2.1_first_module.ipynb 15.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a name=\"top\"></a><img src=\"images/chisel_1024.png\" alt=\"Chisel logo\" style=\"width:480px;\" />"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "# Module 2.1: Your First Chisel Module\n",
    "**Prev: [Introduction to Scala](1_intro_to_scala.ipynb)**<br>\n",
    "**Next: [Combinational Logic](2.2_comb_logic.ipynb)**\n",
    "\n",
    "## Motivation\n",
    "Now that you are familiar with Scala, let's start carving out some hardware! Chisel stands for **C**onstructing **H**ardware **I**n a **S**cala **E**mbedded **L**anguage. That means it is a DSL in Scala, allowing you to take advantage of both Scala and Chisel programming within the same code. It is important to understand which code is \"Scala\" and which code is \"Chisel\", but we will discuss that more later. For now, think of Chisel and the code in Module 2 as a better way to write Verilog. This module throws an entire Chisel `Module` and tester at you. Just get the gist of it for now. You'll see plenty more examples later.\n",
    "\n",
    "## Setup\n",
    "The following cell downloads the dependencies needed for Chisel. You will see it in all future notebooks. Run it now."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val path = System.getProperty(\"user.dir\") + \"/source/load-ivy.sc\"\n",
    "interp.load.module(ammonite.ops.Path(java.nio.file.FileSystems.getDefault().getPath(path)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As mentioned in the last module, these statements are needed to import Chisel. Run them before running any future code blocks."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import chisel3._\n",
    "import chisel3.util._\n",
    "import chisel3.iotesters.{ChiselFlatSpec, Driver, PeekPokeTester}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "# Your First Module\n",
    "This section will present your first hardware module, a test case, and how to run it. It will contain many things that you will not understand, and that is OK. We want you to take away the broad strokes, so you can continually return to this complete and working example to reinforce what you've learned.\n",
    "\n",
    "<span style=\"color:blue\">**Example: A Module**</span><br>\n",
    "Like Verilog, we can declare module definitions in Chisel. The following example is a Chisel `Module`, `Passthrough`, that has one 4-bit input, `in`, and one 4-bit output, `out`. The module combinationally connects `in` and `out`, so `in` drives `out`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "// Chisel Code: Declare a new module definition\n",
    "class Passthrough extends Module {\n",
    "  val io = IO(new Bundle {\n",
    "    val in = Input(UInt(4.W))\n",
    "    val out = Output(UInt(4.W))\n",
    "  })\n",
    "  io.out := io.in\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There's a lot here! The following explains how to think of each line in terms of the hardware we are describing.\n",
    "\n",
    "```scala\n",
    "class Passthrough extends Module {\n",
    "```\n",
    "We declare a new module called `Passthrough`. `Module` is a built-in Chisel class that all hardware modules must extend.\n",
    "\n",
    "```scala \n",
    "val io = IO(...)\n",
    "```\n",
    "We declare all our input and output ports in a special `io` `val`. It must be called `io` and be an `IO` object or instance, which requires something of the form `IO(_instantiated_bundle_)`.\n",
    "\n",
    "```scala\n",
    "new Bundle {\n",
    "    val in = Input(...)\n",
    "    val out = Output(...)\n",
    "}\n",
    "```\n",
    "We declare a new hardware struct type (Bundle) that contains some named signals `in` and `out` with directions Input and Output, respectively.\n",
    "\n",
    "```scala\n",
    "UInt(4.W)\n",
    "```\n",
    "We declare a signal's hardware type. In this case, it is an unsigned integer of width 4.\n",
    "\n",
    "```scala\n",
    "io.out := io.in\n",
    "```\n",
    "We connect our input port to our output port, such that `io.in` *drives* `io.out`. Note that the `:=` operator is a ***Chisel*** operator that indicates that the right-hand signal drives the left-hand signal. It is a directioned operator.\n",
    "\n",
    "The neat thing about hardware construction languages (HCLs) is that we can use the underlying programming language as a scripting language. For example, after declaring our Chisel module, we then use Scala to call the Chisel compiler to translate Chisel `Passthrough` into Verilog `Passthrough`. This process is called ***elaboration***."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "// Scala Code: Elaborate our Chisel design by translating it to Verilog\n",
    "// Don't worry about understanding this code; it is very complicated Scala\n",
    "println(getVerilog(new Passthrough))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that the Name of our module is `cmd<#>WrapperHelperPassthrough`, which is an artifact of running this tutorial in Jupyter. In your normal code, its name should just be `Passthrough`. This is an important lesson though - although Chisel does its best to preserve the names of your modules and other hardware components, sometimes it fails to do so.\n",
    "\n",
    "<span style=\"color:blue\">**Example: A Module Generator**</span><br>\n",
    "If we apply what we learned about Scala to this example, we can see that a Chisel module is implemented as a Scala class. Just like any other Scala class, we could make a Chisel module take some construction parameters. In this case, we make a new class `PassthroughGenerator` which will accept an integer `width` that dictates the widths of its input and output ports:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "// Chisel Code, but pass in a parameter to set widths of ports\n",
    "class PassthroughGenerator(width: Int) extends Module { \n",
    "  val io = IO(new Bundle {\n",
    "    val in = Input(UInt(width.W))\n",
    "    val out = Output(UInt(width.W))\n",
    "  })\n",
    "  io.out := io.in\n",
    "}\n",
    "\n",
    "// Let's now generate modules with different widths\n",
    "println(getVerilog(new PassthroughGenerator(10)))\n",
    "println(getVerilog(new PassthroughGenerator(20)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notice that the generated Verilog uses different bitwidths for the input/output depending on the value assigned to the `width` parameter. Let's dig into how this works. Because Chisel Modules are normal Scala classes, we can use the power of Scala's class constructors to parameterize the elaboration of our design.\n",
    "\n",
    "You may notice that this parameterization is enabled by *Scala*, not *Chisel*; Chisel has no extra APIs for parameterization, but a designer can simply leverage Scala features to parameterize his/her designs.\n",
    "\n",
    "Because `PassthroughGenerator` no longer describes a single Module, but instead describes a family of modules parameterized by `width`, we refer to this `Passthrough` as a ***generator***."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "# Testing Your Hardware\n",
    "\n",
    "No hardware module or generator should be complete without a tester. Chisel has built-in test features that you will explore throughout this bootcamp. The following example is a Chisel test harness that passes values to an instance of `Passthrough`'s input port `in`, and checks that the same value is seen on the output port `out`.\n",
    "\n",
    "<span style=\"color:blue\">**Example: A Tester**</span><br>\n",
    "There is a ***LOT*** of crazy Scala going on here, so no need to understand anything except the `poke` and `expect` commands. You can think of the rest of the code as simply boilerplate to write these simple tests."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "// Scala Code: Calling Driver to instantiate Passthrough + PeekPokeTester and execute the test.\n",
    "// Don't worry about understanding this code; it is very complicated Scala.\n",
    "// Think of it more as boilerplate to run a Chisel test.\n",
    "val testResult = Driver(() => new Passthrough()) {\n",
    "  c => new PeekPokeTester(c) {\n",
    "    poke(c.io.in, 0)     // Set our input to value 0\n",
    "    expect(c.io.out, 0)  // Assert that the output correctly has 0\n",
    "    poke(c.io.in, 1)     // Set our input to value 1\n",
    "    expect(c.io.out, 1)  // Assert that the output correctly has 1\n",
    "    poke(c.io.in, 2)     // Set our input to value 2\n",
    "    expect(c.io.out, 2)  // Assert that the output correctly has 2\n",
    "  }\n",
    "}\n",
    "assert(testResult)   // Scala Code: if testResult == false, will throw an error\n",
    "println(\"SUCCESS!!\") // Scala Code: if we get here, our tests passed!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What's going on? The test accepts a `Passthrough` module, assigns values to the module's inputs, and checks its outputs. To set an input, we call `poke`. To check an output, we call `expect`. If we don't want to compare the output to an expected value (no assertion), we can `peek` the output instead.\n",
    "\n",
    "If all `expect` statements are true, then our boilerplate code will return true (see `testResult`)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<span style=\"color:red\">**Exercise: Writing Your Own Testers**</span><br>\n",
    "Write and execute two tests, one that tests `PassthroughGenerator` for a width of 10 and a second that tests `PassthroughGenerator` for a width of 20. Check at least two values for each: zero and the maximum value supported by the specified width. Note that the triple question mark has a special meaning in Scala. You may see it frequently in these bootcamp exercises. Running code with the `???` will produce the `NotImplementedError`. Replace `???` with your testers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "val test10result = ???\n",
    "\n",
    "val test20result = ???\n",
    "\n",
    "assert((test10result == true) && (test20result == true))\n",
    "println(\"SUCCESS!!\") // Scala Code: if we get here, our tests passed!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div id=\"container\"><section id=\"accordion\"><div>\n",
    "<input type=\"checkbox\" id=\"check-1\" />\n",
    "<label for=\"check-1\"><strong>Solution</strong> (click to toggle displaying it)</label>\n",
    "<article>\n",
    "<pre style=\"background-color:#f7f7f7\">\n",
    "val test10result = Driver(() => new PassthroughGenerator(10)) {\n",
    "  c => new PeekPokeTester(c) {\n",
    "    poke(c.io.in, 0)\n",
    "    expect(c.io.out, 0)\n",
    "    poke(c.io.in, 1023)\n",
    "    expect(c.io.out, 1023)\n",
    "  }\n",
    "}\n",
    "\n",
    "val test20result = Driver(() => new PassthroughGenerator(20)) {\n",
    "  c => new PeekPokeTester(c) {\n",
    "    poke(c.io.in, 0)\n",
    "    expect(c.io.out, 0)\n",
    "    poke(c.io.in, 1048575)\n",
    "    expect(c.io.out, 1048575)\n",
    "  }\n",
    "}\n",
    "\n",
    "</pre></article></div></section></div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "# Looking at Generated Verilog/FIRRTL\n",
    "\n",
    "If you are having trouble understanding the generated hardware and are comfortable with reading structural Verilog and/or FIRRTL (Chisel's IR which is comparable to a synthesis-only subset of Verilog), then you can try looking at the generated Verilog to see the result of Chisel execution.\n",
    "\n",
    "Here is an example of generating the Verilog (which you've seen already) and the FIRRTL."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "// Viewing the Verilog for debugging\n",
    "println(getVerilog(new Passthrough))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "// Viewing the firrtl for debugging\n",
    "println(getFirrtl(new Passthrough))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "# You're done!\n",
    "\n",
    "[Return to the top.](#top)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## <span style=\"color:red\"> Appendix: A Note on \"printf\" Debugging</span>\n",
    "[Debugging with print statements](https://stackoverflow.com/a/189570) is not always the best way to debug, but is often an easy first step to see what's going on when something doesn't work the way you expect.\n",
    "Because Chisel generators are programs generating hardware, there are some extra subtleties about printing generator and circuit state.\n",
    "It is important to remember when your print statement executes and what is being printed.\n",
    "The three common scenarios where you might want to print have some important differences:\n",
    "* Chisel generator prints during circuit generation\n",
    "* Circuit prints during circuit simulation\n",
    "* Tester prints during testing\n",
    "\n",
    "`println` is a built-in Scala function that prints to the console. It **cannot** be used to print during circuit simulation because the generated circuit is FIRRTL or Verilog- not Scala.\n",
    "\n",
    "The following code block shows different styles of printing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class PrintingModule extends Module {\n",
    "    val io = IO(new Bundle {\n",
    "        val in = Input(UInt(4.W))\n",
    "        val out = Output(UInt(4.W))\n",
    "    })\n",
    "    io.out := io.in\n",
    "\n",
    "    printf(\"Print during simulation: Input is %d\\n\", io.in)\n",
    "    // chisel printf has its own string interpolator too\n",
    "    printf(p\"Print during simulation: IO is $io\\n\")\n",
    "\n",
    "    println(s\"Print during generation: Input is ${io.in}\")\n",
    "}\n",
    "\n",
    "class PrintingModuleTester(c: PrintingModule) extends PeekPokeTester(c) {\n",
    "    poke(c.io.in, 3)\n",
    "    step(5) // circuit will print\n",
    "    \n",
    "    println(s\"Print during testing: Input is ${peek(c.io.in)}\")\n",
    "}\n",
    "chisel3.iotesters.Driver( () => new PrintingModule ) { c => new PrintingModuleTester(c) }"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Scala",
   "language": "scala",
   "name": "scala"
  },
  "language_info": {
   "codemirror_mode": "text/x-scala",
   "file_extension": ".scala",
   "mimetype": "text/x-scala",
   "name": "scala211",
   "nbconvert_exporter": "script",
   "pygments_lexer": "scala",
   "version": "2.11.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}