<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hassu on Medium]]></title>
        <description><![CDATA[Stories by Hassu on Medium]]></description>
        <link>https://medium.com/@hassu20083?source=rss-1376dfe8a7f7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*4WcYod45yk61AM6B</url>
            <title>Stories by Hassu on Medium</title>
            <link>https://medium.com/@hassu20083?source=rss-1376dfe8a7f7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:54:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hassu20083/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Hardware Design — RISC-V — Single Cycle Datapath — part-03]]></title>
            <link>https://medium.com/@hassu20083/hardware-design-risc-v-single-cycle-datapath-part-03-b299fb95403d?source=rss-1376dfe8a7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b299fb95403d</guid>
            <category><![CDATA[verilog-hdl]]></category>
            <category><![CDATA[risc-v]]></category>
            <category><![CDATA[computer-architecture]]></category>
            <category><![CDATA[verilog]]></category>
            <category><![CDATA[computer-hardware]]></category>
            <dc:creator><![CDATA[Hassu]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 15:25:37 GMT</pubDate>
            <atom:updated>2024-12-04T08:41:10.130Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hardware Design — RISC-V — Single Cycle Datapath — part-03</h3><p>We have already discussed different components and instruction datapath of RISC-v, and this article focuses on integrating everything into a <strong>unified datapath for R, I, and J-type instructions</strong>. With the control unit managing and controlling those components, we also demonstrate how this design handles a practical program, such as computing the Fibonacci series. If you’re new to the series, ensure you review earlier articles to understand the foundational concepts before proceeding.</p><blockquote>1. <a href="https://medium.com/@hassu20083/instruction-set-architecture-risc-v-single-cycle-datapath-8277381b87da">Instruction Set Architecture — RISC-v — Single Cycle Datapath</a><br>2. <a href="https://medium.com/@hassu20083/hardware-design-risc-v-single-cycle-datapath-part-01-235e9f060733">Hardware Design — RISC-V — Single Cycle Datapath — part-01</a><br>3. <a href="https://medium.com/@hassu20083/hardware-design-risc-v-single-cycle-datapath-part-02-3aa48cee4284">Hardware Design — RISC-V — Single Cycle Datapath — part-02</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*8Dx25ZGC_lCjgNPB_CfMvA.png" /><figcaption>The complete picture of Single Cycle Datapath (RISC-v)</figcaption></figure><h3>Table of Contents:</h3><blockquote><a href="#bc8d">Datapath for R, I, and J type instruction<br></a><a href="#525f">Control Unit</a><br><a href="#00fb">Complete Datapath</a><a href="#0398"><br></a><a href="#0e97">Fibonacci Series Example</a><br><a href="#efda">Final Words</a></blockquote><h3>Datapath for R, I, and J type instructions :</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nHSkIpPbB6mF2-igiX0tQg.png" /><figcaption>Complete Datapath except for control Units</figcaption></figure><p>Unified datapath for R-type and memory-type instruction requires three muxes to select between multiple components, and datapath for control transfer requires the logic to calculate addresses and two muxes to select the suitable next address. To make a unified version of two, we do not require any extra logic but use modified instruction fetch rather than the old one. Although I haven’t included control units, for the testing I will use the whole datapath with control units.</p><p>The test program, Verilog code, testbench, and waveform are given below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*Wmg_pYX3XX1iUNRXZvgLuA.png" /><figcaption>R, I, and J type instructions for testing the design</figcaption></figure><pre>module SCDP_without_control_unit(<br>        input clk, reset, RegDst, RegWrite, ALUsrc, memRead, memWrite, MemToReg,branch, jump,<br>        input [2:0] ALUoperation,<br>        output [5:0] opcode,func        <br>    );<br>    <br>    wire zero;<br>    wire [4:0] write_register;<br>    wire [31:0] instruction, read_data_1, read_data_2, ALU_operand2, ALU_to_Mem, operand_32, Mem_or_ALU, AluData, MemData;<br>        <br>    // instantiate instruction fetch<br>        instruction_fetch_with_control_transfer instruction_fetch(<br>            .reset(reset),<br>            .clk(clk),<br>            .zero(zero),<br>            .branch(branch),<br>            .jump(jump),<br>            .offset(operand_32),<br>            .instruction(instruction)<br>        );<br>        <br>    assign opcode = instruction[31:26];<br>    assign func = instruction[5:0];<br>    <br>    // Reg Dst<br>    assign write_register = (~RegDst)? instruction[20:16] : instruction[15:11];<br>        <br>    // instantiate register file<br>    register_file register_file(<br>        .register_read_1(instruction[25:21]), <br>        .register_read_2(instruction[20:16]), <br>        .write_register(write_register), <br>        .write_data(Mem_or_ALU), <br>        .reg_write(RegWrite),  <br>        .clk(clk), <br>        .reset(reset),<br>        .read_data_1(read_data_1),  // register-1<br>        .read_data_2(read_data_2)   // register-2<br>    );<br>    <br>    // instantiate sign extension<br>    sign_extension sign_extension(<br>            .input_16(instruction[15:0]),<br>            .output_32(operand_32)<br>    );<br>    // ALU mux<br>    assign ALU_operand2 = (~ALUsrc)? read_data_2 : operand_32;<br>    <br>    // instantiate ALU<br>    alu_unit alu_unit(<br>        .A(read_data_1),<br>        .B(ALU_operand2),<br>        .ALU_operation(ALUoperation), <br>        .zero(zero), // unused<br>        .result(AluData)<br>    );<br>    <br>    data_memory data_memory(<br>        .address(AluData),<br>        .write_data(read_data_2),<br>        .mem_read(memRead),<br>        .clk(clk),<br>        .mem_write(memWrite),<br>        .read_data(MemData)<br>     );<br>     <br>     // register write mux<br>     assign Mem_or_ALU = MemToReg?  MemData: AluData;<br>     <br>endmodule</pre><p><strong>Testbench:<br></strong>It initializes all registers with the value of “0” and instruction memory with the test code. After that, it runs the clock cycle for 850ns with a width of 100ns to run all instructions. All control signals are applied through control units.</p><pre>module RISC_v_datapath_tb;<br>    reg clk, reset;<br>    <br>    RISC_v_datapath uut(<br>        .clk(clk),<br>        .reset(reset)<br>    );<br>    <br>    initial begin<br>        clk &lt;= 0;<br>        reset &lt;= 0;<br>        # 10<br>        reset &lt;= 1;<br>        # 850<br>        reset &lt;= 0;<br>        $finish;<br>    end<br>    <br>    always #50 clk = ~clk;<br>    <br>    // value initialization<br>    initial begin : value_initialization<br>        // initialize registers<br>        integer i;<br>        for (i = 0; i &lt; 32; i = i + 1) begin<br>            uut.SCDP.register_file.Registers[i] = 0;<br>        end <br>        <br>        // initialize instructions<br>        // addi: r1 = r1 + 10 = 0 + 10 = 10<br>        uut.SCDP.instruction_fetch.instruction_memory.Memory[1] = 32&#39;b001000_00001_00001_0000000000001010; <br>        // addi: r2 = r2 + 10 = 0 + 10 = 10<br>        uut.SCDP.instruction_fetch.instruction_memory.Memory[2] = 32&#39;b001000_00010_00010_0000000000001010; <br>        // add: r3 = r1 + r2; 10 + 10 = 20<br>        uut.SCDP.instruction_fetch.instruction_memory.Memory[3] = 32&#39;b000000_00001_00010_00011_00000_100000; <br>        // sw: Memory[r0+0] = r3; Memory[0] = 20<br>        uut.SCDP.instruction_fetch.instruction_memory.Memory[4] = 32&#39;b101011_00000_00011_0000000000000000; <br>        // beq: r1 == r2? jump to +3<br>        uut.SCDP.instruction_fetch.instruction_memory.Memory[5] = 32&#39;b000100_00001_00010_0000000000000011; <br>        // j: jump to 100x4<br>        uut.SCDP.instruction_fetch.instruction_memory.Memory[9] = 32&#39;b000010_00000000000000000001100100; <br>        // lw: r4 = Memory[r0+0] = Memory[0] = 20<br>        uut.SCDP.instruction_fetch.instruction_memory.Memory[100] = 32&#39;b100011_00000_00100_0000000000000000; <br>        // and: r5 = r3 &amp; r4 = 20 &amp; 20 = 20<br>        uut.SCDP.instruction_fetch.instruction_memory.Memory[101] = 32&#39;b000000_00011_00100_00101_00000_100100;<br>        <br>        // initialize PC<br>        uut.SCDP.instruction_fetch.program_counter.PC = 0;<br>    end<br>endmodule</pre><p>Since I am using Vivado as IDE, which allows generating the schematic of written RTL, so here is the schematic view,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3mMXosscFtnUoqfscf58Pg.png" /><figcaption>Schematic view of the above RTL</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JAX88BzR1ZTEhql927gwgA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yXuBwnSrAgcv0EGongdouA.png" /><figcaption>The waveform of the above testbench</figcaption></figure><p>It is clear from the above waveform that the first two instructions (50ns to 250ns) were addi with the registers r1 &amp; r2, respectively. The offset value was 10 in both instructions, added with 0, and written back to respective registers. The third instruction from 250ns to 350ns was add-instruction, which read r1 and r2, then added to form 20, which then stored to r3. Fourth instruction from 350ns to 450ns stored r3 to memory location 0. The fifth instruction was of branch, compared r1 and r2, and changed the PC value from 0x000014 to 0x00000024. The sixth instruction was jump, that’s why it changed the PC value from 0x000024 to 0x00000190. You can cross-verify each instruction with generated control signals.</p><h3>Control Units:</h3><p>Just think of having a mentor who gives you all the directives, and you will become successful just by following him, the control unit is more like that mentor. We were always taught the CPU is the brain of the computer but, it is not wrong to say that the real brain is a control unit rather than a whole chip — the Control Unit is responsible for making all decisions in the CPU. The control unit generates control signals based on the instruction being executed, guiding data flow, memory access, ALU operations, and program counter updates.</p><h4>Main Control Unit:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*F3fQ05NIYWTQDYmtcd5Uxw.png" /><figcaption>Datapath of Main Control Unit</figcaption></figure><p>The control signals generated by the Control Unit can be categorized as:</p><ul><li><strong>ALU op:</strong> Input to the ALU control unit.</li><li><strong>Register Write Enable:</strong> Enables writing data to a register.</li><li><strong>Memory Read/Write:</strong> Controls memory access during load and store instructions.</li><li><strong>Multiplexer Select Lines:</strong> Direct inputs and outputs within the datapath.</li><li><strong>PC Write Enable:</strong> Updates the Program Counter for sequential execution.</li><li><strong>Branch/Jump Signals:</strong> Directs the flow of execution for control transfer instructions.</li></ul><p>The main control unit is a combinational circuit that accepts the opcode of the fetched instruction and generates control signals as follows,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*19-DdbzdW_h9dxQhmauvLg.png" /><figcaption>Control Signals generated by the Control Unit</figcaption></figure><p>Let’s consider the example of <em>beq</em> instruction first of all both registers will serve as the operands of ALU since the <em>ALUSrc</em> is 0, then subtraction will be performed since <em>ALUsrc</em> is 01, after which <em>PCsrc</em> is calculated as zero &amp; branch and the address at <em>PCnext</em> will get changed if the <em>PCsrc</em> would 1 otherwise instruction will run sequentially. <em>RegWrite</em> must be 0 in <em>beq</em>, since we don’t write back anything and that’s why <em>RegDst</em> and <em>MemToReg</em> signals are 1&#39;bx (x represents don’t care — it could be 0 or 1). The Verilog code of the control unit is given as follows,</p><pre>module control_unit_datapath(input    [5:0] opcode,   // (instr_addr[31:26])<br>      <br>     output  reg    RegWrite,  <br>     output  reg    MemToReg, <br>     output  reg    RegDst,<br>     output  reg    ALUsrc,  <br>     output  reg    branch,   <br>     output  reg    jump, <br>     output  reg    memWrite,  <br>     output  reg    memRead,<br>     output reg  [1:0] ALUop<br>);<br>    always @(*) begin <br>    <br>         case (opcode)<br>          <br>              6&#39;b000000 : begin // R_Type instruction<br>            <br>                   RegWrite = 1;  <br>                   MemToReg = 0; <br>                   RegDst = 1; <br>                   ALUsrc = 0;  <br>                   branch = 0;    <br>                   memWrite = 0;  <br>                   ALUop = 2&#39;b10;  <br>                   memRead = 0;  <br>                   jump = 0;<br>            <br>              end <br>              <br>              6&#39;b100011 : begin  // load (lw) instruction<br>            <br>                   RegWrite = 1;  <br>                   MemToReg = 1; <br>                   RegDst = 0; <br>                   ALUsrc = 1;  <br>                   branch = 0;    <br>                   memWrite = 0;  <br>                   ALUop = 2&#39;b00;  <br>                   memRead = 1;  <br>                   jump = 0;<br>                <br>              end <br>              <br>              6&#39;b101011 : begin  // store (sw) instruction<br>            <br>                   RegWrite = 0;  <br>                   MemToReg = 1&#39;bx; <br>                   RegDst = 1&#39;bx; <br>                   ALUsrc = 1;  <br>                   branch = 0;    <br>                   memWrite = 1;  <br>                   ALUop = 2&#39;b00;  <br>                   memRead = 0;  <br>                   jump = 0;<br>            <br>              end <br>              <br>              6&#39;b000100 : begin  // beq instruction<br>            <br>                   RegWrite = 0;  <br>                   MemToReg = 1&#39;bx; <br>                   RegDst = 1&#39;bx; <br>                   ALUsrc = 0;  <br>                   branch = 1;    <br>                   memWrite = 0;  <br>                   ALUop = 2&#39;b01;  <br>                   memRead = 0;  <br>                   jump = 0;<br>            <br>              end <br>              <br>              6&#39;b001000 : begin  // addi instruction<br>            <br>                   RegWrite = 1;  <br>                   MemToReg = 0; <br>                   RegDst = 0; <br>                   ALUsrc = 1;  <br>                   branch = 0;    <br>                   memWrite = 0;  <br>                   ALUop = 2&#39;b00;  <br>                   memRead = 0;  <br>                   jump = 0;<br>            <br>              end <br>            <br>              6&#39;b000010 : begin  // jump instruction<br>            <br>                   RegWrite = 0;  <br>                   MemToReg = 1&#39;bx; <br>                   RegDst = 1&#39;bx; <br>                   ALUsrc = 1&#39;bx;  <br>                   branch = 0;    <br>                   memWrite = 0;  <br>                   ALUop = 2&#39;bxx;  <br>                   memRead = 0;  <br>                   jump = 1;<br>                   <br>              end <br>            <br>              default : begin<br>            <br>                   RegWrite = 0;  <br>                   MemToReg = 1&#39;bx; <br>                   RegDst = 1&#39;bx; <br>                   ALUsrc = 1&#39;bx;  <br>                   branch = 0;    <br>                   memWrite = 0;  <br>                   ALUop = 2&#39;bxx;  <br>                   memRead = 0;  <br>                   jump = 0;<br>                   <br>              end<br>         endcase<br>    end<br>endmodule</pre><h4>ALU Control Unit:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*2VLWuTwQjPBKky6EHb_rFw.png" /><figcaption>Datapath of ALU Control Unit</figcaption></figure><p>The ALU control unit is a combinational circuit that accepts <em>ALUop</em> (from the main control unit) and <em>func</em> (valid only for R-type instruction) and generates <em>ALU </em>operation as given below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*AOjtJnBB3XX1QI32v1pMPg.png" /><figcaption>Control signal generated by ALU control unit</figcaption></figure><p>The Verilog code of the ALU control unit is given as follows,</p><pre>module alu_control_datapath(<br> <br>     input   [1:0] ALUop,<br>     input   [5:0] func, // funct field (instr_addr[5:0])<br>     <br>     output  reg [2:0] ALUoperation<br>);<br>      <br>     always @(*) begin <br>     <br>         casex (ALUop)<br>          <br>          2&#39;b00 : begin <br>                ALUoperation = 3&#39;b010; // add<br>          end<br>          <br>          2&#39;b01 : begin /* i change it*/<br>                ALUoperation = 3&#39;b110; // subtract<br>          end<br>          <br>          2&#39;b10 : begin<br>           <br>               case (func)<br>               <br>                  6&#39;b100000 : begin<br>                      ALUoperation = 3&#39;b010; // add<br>                  end  <br>                  <br>                  6&#39;b100010 : begin<br>                      ALUoperation = 3&#39;b110; // subtract<br>                  end  <br>                  <br>                  6&#39;b100100 : begin<br>                      ALUoperation = 3&#39;b000; // and<br>                  end  <br>                  <br>                  6&#39;b100101 : begin<br>                      ALUoperation = 3&#39;b001; // or<br>                  end  <br>                  <br>                  6&#39;b101010 : begin<br>                      ALUoperation = 3&#39;b111; // set less than (SLT)<br>                  end <br>                <br>                default : ALUoperation = 3&#39;bxxx;<br>               endcase<br>          end<br>         <br>          default : ALUoperation = 3&#39;bxxx;<br>         endcase<br>    end<br>endmodule</pre><h3>Complete Datapath:</h3><p>At the very start of this article, we created the unified R, I, and J type datapath, and After that, we defined both types of control units. It’s a time to utilize both datapaths and create the complete Single Cycle RISC-v architecture. <br>It manages R-type, I-type, and J-type operations by dynamically routing data and control signals. At its core, the complete datapath includes essential elements such as the instruction memory, register file, sign extender, ALU, data memory, and control unit. Each of these components plays a specific role, and their interaction ensures that the processor can execute various types of instructions without errors. The Verilog code of the complete datapath is given below,</p><pre>module RISC_v_datapath(<br>      input clk,<br>      input reset<br>    );<br>    <br>    wire RegDst, RegWrite, ALUsrc, memRead, memWrite, MemToReg,branch, jump;<br>    wire [5:0] opcode, func;<br>    wire [2:0] ALUoperation;<br>    wire [1:0] ALUop;<br>    <br>    // instantiate Main Control Unit<br>    control_unit_datapath control_unit(<br>         .opcode(opcode),<br>         .RegWrite(RegWrite),  <br>         .MemToReg(MemToReg), <br>         .RegDst(RegDst),<br>         .ALUsrc(ALUsrc),  <br>         .branch(branch),   <br>         .jump(jump), <br>         .memWrite(memWrite),  <br>         .memRead(memRead),<br>         .ALUop(ALUop)<br>    );<br>    <br>    // instantiate ALU Control Unit<br>    alu_control_datapath alu_control(<br>         .ALUop(ALUop),<br>         .func(func), <br>         .ALUoperation(ALUoperation)<br>    );<br>    <br>    // instantiate RISC-v SCDP<br>    SCDP_without_control_unit SCDP(<br>        .clk(clk), <br>        .reset(reset), <br>        .RegDst(RegDst), <br>        .RegWrite(RegWrite), <br>        .ALUsrc(ALUsrc), <br>        .memRead(memRead), <br>        .memWrite(memWrite), <br>        .MemToReg(MemToReg),<br>        .branch(branch), <br>        .jump(jump),<br>        .ALUoperation(ALUoperation),<br>        .opcode(opcode),<br>        .func(func)<br>    );<br>    <br>endmodule</pre><h3>Fibonacci Series Example:</h3><p>Under this heading, we are going to generate the Fibonacci series using our datapath. Fibonacci numbers follow a predictable pattern where each number is the sum of the two preceding ones. By designing RISC-V instructions to calculate this series, we can showcase the real-world application of the datapath.</p><p>The Python code of the Fibonacci series is given below, which I believe is self-explanatory.</p><pre># Fibonacci Series<br>A[0] = 0<br>A[1] = 1<br>for i in range(2,31): <br>    A[i] = A[i-1] + A[i-2]</pre><h4><strong>Assembly Code:</strong></h4><pre>addi r0, r0, 0        // initialize 0<br>addi r1, r1, 1        // initialize 1<br>addi r31, r31, 0      // address = 0<br>sw r0, r31(0)         // A[0] = 0<br>addi r31, r31, 4      // next base address<br>sw r1, r31(0)         // A[1] = 1<br>addi r3, r3, 0        // i = 0<br>addi r4, r4, 31       // since we don&#39;t have slti<br>for:<br>    beq r3, r4, end_loop  // loop while i &lt; 31<br>    add r5, r0, r1        // r5 = A[i-1] + A[i-2]<br>    addi r31, r31, 4      // next base address<br>    sw r5, r31(0)         // A[i] = r5<br>    addi r0, r1, 0        // r0 = r1<br>    addi r1, r5, 0        // r1 = r5<br>    addi r3, r3, 1        // i += 1<br>    j for                 // next interation<br>end_loop</pre><ol><li><strong>Initialization</strong>:<br>The registers are set up with initial values. <strong><em>r0</em></strong> is assigned<strong><em> 0</em></strong>, and <strong><em>r1 </em></strong>is assigned <strong><em>1</em></strong>, representing the first two Fibonacci numbers. Additionally, <strong><em>r31</em></strong> is initialized as the base memory address for storing the series, starting at address <strong><em>0</em></strong>.</li><li><strong>Storing Initial Values</strong>:<br>The values <strong><em>A[0] = 0</em></strong> and <strong><em>A[1] = 1</em></strong> are then stored in memory. After storing each value, the memory address in <strong><em>r31</em></strong> is incremented by <strong><em>4</em></strong> to prepare for the next term.</li><li><strong>Loop Initialization</strong>:<br>A loop counter, <strong><em>i</em></strong> , is initialized in <strong><em>r3</em></strong> as <strong><em>0</em></strong>. The register <strong><em>r4</em></strong> is set to <strong><em>31</em></strong>, representing the maximum number of iterations (excluding the initial two values).</li><li><strong>Fibonacci Calculation</strong>:<br>The program enters a loop, where it computes the next Fibonacci number as the sum of the previous two terms <strong><em>r0</em></strong> and <strong><em>r1, </em></strong>and stores it into<strong><em> r5</em></strong>. The result is stored in memory at the address pointed to by <strong><em>r31</em></strong>.</li><li><strong>Updating Values</strong>:<br>After storing the computed value, the previous terms are updated. <strong><em>r0</em></strong> takes the value of <strong><em>r1</em></strong>, and <strong><em>r1</em></strong> takes the value of the newly computed Fibonacci number <strong><em>r5</em></strong>.</li><li><strong>Incrementing the Counter</strong>:<br>The loop counter <strong><em>r3</em></strong> is incremented to keep track of the current iteration. If the counter reaches the limit (<em>31</em> terms in total), the loop terminates.</li><li><strong>Jumping to the Next Iteration</strong>:<br>If the loop has not yet reached the limit, the program jumps back to the start of the loop to calculate the next Fibonacci term.</li></ol><h4>Machine Language Translation:</h4><pre>instruction_memory.Memory[1] = 32&#39;b001000_00000_00000_0000000000000000;<br>instruction_memory.Memory[2] = 32&#39;b001000_00001_00001_0000000000000001;<br>instruction_memory.Memory[3] = 32&#39;b001000_11111_11111_0000000000000000;<br>instruction_memory.Memory[4] = 32&#39;b101011_11111_00000_0000000000000000;<br>instruction_memory.Memory[5] = 32&#39;b001000_11111_11111_0000000000000100;<br>instruction_memory.Memory[6] = 32&#39;b101011_11111_00001_0000000000000000;<br>instruction_memory.Memory[7] = 32&#39;b001000_00011_00011_0000000000000000;<br>instruction_memory.Memory[8] = 32&#39;b001000_00100_00100_0000000000011111;<br>instruction_memory.Memory[9] = 32&#39;b000100_00011_00100_0000000000000111;<br>instruction_memory.Memory[10] = 32&#39;b000000_00000_00001_00101_00000_100000;<br>instruction_memory.Memory[11] = 32&#39;b001000_11111_11111_0000000000000100;<br>instruction_memory.Memory[12] = 32&#39;b101011_11111_00101_0000000000000000;<br>instruction_memory.Memory[13] = 32&#39;b001000_00001_00000_0000000000000000;<br>instruction_memory.Memory[14] = 32&#39;b001000_00101_00001_0000000000000000;<br>instruction_memory.Memory[15] = 32&#39;b001000_00011_00011_0000000000000001;<br>instruction_memory.Memory[16] = 32&#39;b000010_00000000000000000000001001;</pre><h4>Waveform of Fibonacci Series:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lY6LpCb9LKzFhqCCTUlF5g.png" /><figcaption>Waveform of fibonacci series</figcaption></figure><p>The above waveform is self-explanatory, you can easily see from the bottom of the waveform that each location of data memory contains the sum of values at previous two locations except the <em>memory[0]</em> and <em>memory[1]</em>, which we stored manually as the first two values of series.</p><h3>Final Words:</h3><p>This article highlighted the integration of R, I, and J-type instruction handling into a complete datapath, and emphasized the importance of control signals and modular design. As an example, run practical programs like the Fibonacci series to demonstrate how the architecture operates in real-world scenarios.</p><p>For all the code and diagrams discussed, check out my <a href="https://github.com/Hassu083/RISC-v_SCDP_Verilog_implementation">GitHub repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b299fb95403d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hardware Design — RISC-V — Single Cycle Datapath — part-02]]></title>
            <link>https://medium.com/@hassu20083/hardware-design-risc-v-single-cycle-datapath-part-02-3aa48cee4284?source=rss-1376dfe8a7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/3aa48cee4284</guid>
            <category><![CDATA[verilog-hdl]]></category>
            <category><![CDATA[verilog]]></category>
            <category><![CDATA[computer-hardware]]></category>
            <category><![CDATA[risc-v]]></category>
            <category><![CDATA[computer-architecture]]></category>
            <dc:creator><![CDATA[Hassu]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 15:18:04 GMT</pubDate>
            <atom:updated>2024-12-04T08:37:58.371Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hardware Design — RISC-V — Single Cycle Datapath — part-02</h3><p>Processors manage diverse instruction types — arithmetic, memory access, and control transfer — each requiring specific datapath designs. This article continues from the foundational concepts of RISC architecture, explaining the <strong>datapaths for R-type, Memory, and I-type instructions</strong>, alongside control transfer mechanisms. If you haven’t reviewed the general RISC ISA or datapath basics, revisit the earlier articles for context.</p><blockquote>1. <a href="https://medium.com/@hassu20083/instruction-set-architecture-risc-v-single-cycle-datapath-8277381b87da">Instruction Set Architecture — RISC-v — Single Cycle Datapath</a><br>2. <a href="https://medium.com/@hassu20083/hardware-design-risc-v-single-cycle-datapath-part-01-235e9f060733">Hardware Design — RISC-V — Single Cycle Datapath — part-01</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*8Dx25ZGC_lCjgNPB_CfMvA.png" /><figcaption>The complete picture of Single Cycle Datapath (RISC-v)</figcaption></figure><h3>Table of Contents:</h3><blockquote><a href="#d2a3">Datapath for R-type instruction</a><br><a href="#7586">Datapath for Memory instruction<br></a><a href="#9f93">Datapath for R and I type instruction<br></a><a href="#5df6">Datapath for Control Transfer instruction</a><a href="#00fb"><br></a><a href="#c5d0">Final Words</a></blockquote><h3>Datapath for R-type instruction:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*74NqJtXBmuNEV3MkIPhKCw.png" /><figcaption>Datapath for R-type instructions</figcaption></figure><p>The datapath for an R-type instruction consists of instruction fetch, register file, and ALU since each instruction is fetched from instruction memory and decoded (wires mapping) to read the specified registers, after which the ALU performs the required operation on those operands, then the resultant value would be written back to the specified write register. The wire mapping of R-type instruction is given as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*rVgT_NpOGU7F98GNqwi69Q.png" /><figcaption>R-type instruction format</figcaption></figure><p>Currently, since we don’t have any type of control unit, and it is necessary to provide <strong><em>reg_write</em></strong> and <strong><em>ALU_operation</em></strong> control signals for the sake of compulsion, I am using <em>1</em> and <em>instruction[2:0]</em> for respective signals.<br><strong>Assumption:</strong> All registers’ value is one<br> The program, Verilog code, testbench, and waveform for r-type instruction datapath are given below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*DgRvv_Sg8vmxskLdlNKjEQ.png" /><figcaption>R-type instructions for testing the design</figcaption></figure><pre>module r_type_datapath(<br>    input clk,<br>    input reset<br>    );<br>    <br>    wire [31:0] read_data_1, read_data_2, ALU_to_reg, instruction;<br>    <br>    instruction_fetch instruction_fetch(<br>        .reset(reset),<br>        .clk(clk),<br>        .instruction(instruction)<br>    );<br>    <br>    register_file register_file(<br>        .register_read_1(instruction[25:21]), // rs<br>        .register_read_2(instruction[20:16]), // rt<br>        .write_register(instruction[15:11]),  // rd<br>        .write_data(ALU_to_reg), <br>        .reg_write(1&#39;b1),  // for now control signal is 1 to ever write <br>        .clk(clk), <br>        .reset(reset),<br>        .read_data_1(read_data_1),  // ALU operand 1<br>        .read_data_2(read_data_2)   // ALU operand 2<br>    );<br>    <br>    alu_unit alu_unit(<br>        .A(read_data_1),<br>        .B(read_data_2),<br>        .ALU_operation(instruction[2:0]), // for now operation will be select from func bits<br>        .zero(), // unused<br>        .result(ALU_to_reg)<br>    );<br>    <br>    integer i;<br>    initial begin<br>        // initialize registers with 1<br>        for (i = 0; i &lt; 32; i = i + 1) begin<br>            register_file.Registers[i] = 1;<br>        end<br>        // initialize memory<br>        // add r2 = r0 + r1 = 1 + 1 = 2<br>        instruction_fetch.instruction_memory.Memory[0] = 32&#39;b000000_00000_00001_00010_00000_000010;  <br>        // sub r3 = r2 - r1 = 2 - 1 = 1<br>        instruction_fetch.instruction_memory.Memory[1] = 32&#39;b000000_00010_00001_00011_00000_000110; <br>        // or  r4 = r2 | r3 = 2 | 1 = 3 <br>        instruction_fetch.instruction_memory.Memory[2] = 32&#39;b000000_00010_00011_00100_00000_000001;  <br>        // and r5 = r3 &amp; r4 = 1 &amp; 3 = 1<br>        instruction_fetch.instruction_memory.Memory[3] = 32&#39;b000000_00011_00100_00101_00000_000000; <br>        // PC counter <br>        instruction_fetch.program_counter.PC = 0;<br>    end<br>    <br>endmodule</pre><p><strong>Testbench:<br></strong>All registers with “1” and instruction memory with instructions are already initialized. This testbench runs the clock cycle for 400ns with a width of 100ns to run all four instructions. All control signals are part of the instruction itself.</p><pre>module r_type_datapath_tb;<br>    reg clk, reset;<br>    <br>    // instantiate unit under test<br>    r_type_datapath uut(<br>        .clk(clk),<br>        .reset(reset)<br>    );<br>    <br>    initial begin<br>        // start execution<br>        clk &lt;= 0;<br>        reset &lt;= 0;<br>        # 50<br>        reset = 1;<br>        # 400<br>        // stop execution<br>        reset = 0; <br>        $finish;<br>    end<br>    <br>    always # 50 clk &lt;= ~clk;<br>endmodule</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rbFr4UyJVNwAbMgJUUX_JQ.png" /><figcaption>Waveform of above testbench</figcaption></figure><p>From the above waveform, we can see that all four instructions are working correctly. For example, from time <em>50ns</em> to <em>150ns </em>(instruction number-1), the <em>PC</em> value was 4 — which translated to 1 according to our logic — instruction for addition was read from the instruction memory. Meanwhile, registers 0 and 1 were read — both have the value of 1 — , after which ALU added both operands, and then the resulting value of 2 was saved to register 2. All results from the ALU (2, 1, 3, and 1 ) are according to the explanation table above.</p><h3>Datapath for Memory instruction:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DaEMy87Hxu1s1jvu-B2Brw.png" /><figcaption>Datapath for memory transfer instruction</figcaption></figure><h4>Sign Extension:</h4><p>It will accept 16-bit wide immediate/offset and return its 32-bit wide version by taking care of the sign.</p><pre>module sign_extension(<br>    input [15:0] input_16,<br>    output [30:0] output_32<br>    );<br>    // sign extended output<br>    assign output_32 = (input_16[15] == 1&#39;b1)? {{16{1&#39;b1}},input_16} :{{16{1&#39;b0}},input_16};<br>     <br>endmodule</pre><p>It is clear from the diagram that the execution of memory instructions requires four stages: instruction fetch, decode (register read ), ALU, and Data memory — in case of <strong><em>lw,</em></strong> stages are 5 because of writing back to the register. The base address (<strong><em>$rs</em></strong>) and offset of both instructions would be read from <em>read-register-1</em> and <em>[15:0]</em> bits, respectively, and are then added to form the <em>Address</em> of date memory. But there are some differences among both instructions that we need to take care of,<br> <strong>— lw:</strong> load data from memory to destination register <em>$rt</em><br> <strong>— sw:</strong> store data in memory, use <em>$rt</em> as a source register<br> The wire mapping of I-type instruction is given as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*FjNwJymmvThNT2y59rWWfg.png" /><figcaption>I-type instruction format</figcaption></figure><p>Since we don’t have any type of control unit, and it is necessary to provide <strong><em>reg_write, memRead, memWrite, </em></strong>and <strong><em>ALU_operation</em></strong> control signals for the sake of easiness, I am using <em>instruction[31], instruction[30], instruction[29] and instruction[28:26] </em>bits for respective signals. <br><strong>Assumption:</strong> <em>r2 = 22, r0 = 0</em><br>The program, Verilog code, testbench, and waveform for r-type instruction datapath are given below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*D8jwakCBUmXuwRwquODQ4A.png" /><figcaption>Memory-type instructions for testing the design</figcaption></figure><pre>module memory_transfer_datapath(<br>    input clk,<br>    input reset<br>    );<br>    <br>    wire [31:0] instruction, read_data_1, read_data_2, ALU_to_Mem, operand_2, Mem_to_ALU;<br>    <br>    // instantiate instruction fetch<br>        instruction_fetch instruction_fetch(<br>            .reset(reset),<br>            .clk(clk),<br>            .instruction(instruction)<br>        );<br>        <br>        // instantiate register file<br>        register_file register_file(<br>            .register_read_1(instruction[25:21]), // rs base address<br>            .register_read_2(instruction[20:16]), // rt for se<br>            .write_register(instruction[20:16]),  // rd for lw<br>            .write_data(Mem_to_ALU), <br>            .reg_write(instruction[31]),  // for now control signal is 1 to ever write <br>            .clk(clk), <br>            .reset(reset),<br>            .read_data_1(read_data_1),  // register-1<br>            .read_data_2(read_data_2)   // register-2<br>        );<br>        <br>        // instantiate sign extension<br>        sign_extension sign_extension(<br>                .input_16(instruction[15:0]),<br>                .output_32(operand_2)<br>        );<br>        <br>        // instantiate ALU<br>        alu_unit alu_unit(<br>            .A(read_data_1),<br>            .B(operand_2),<br>            .ALU_operation(instruction[28:26]), <br>            .zero(), // unused<br>            .result(ALU_to_Mem)<br>        );<br>        <br>        // instantiate data memory<br>        data_memory data_memory(<br>            .address(ALU_to_Mem),<br>            .write_data(read_data_2),<br>            .mem_read(instruction[30]),<br>            .clk(clk),<br>            .mem_write(instruction[29]),<br>            .read_data(Mem_to_ALU)<br>         );<br>         <br>         // value initialization<br>         integer i;<br>         initial begin<br>            // register initialization<br>            register_file.Registers[0] = 32&#39;d0;<br>            register_file.Registers[2] = 32&#39;d22;<br>            // instruction initialization<br>            // Memory[r0+0] = r2; Memory[0] = 22<br>            instruction_fetch.instruction_memory.Memory[0] = 32&#39;b001010_00000_00010_0000000000000000;    <br>            // r31 = Memory[r0+0]; r31 = 22<br>            instruction_fetch.instruction_memory.Memory[1] = 32&#39;b110010_00000_11111_0000000000000000;    <br>            // PC counter <br>            instruction_fetch.program_counter.PC = 0;<br>         end<br>    <br>endmodule</pre><p><strong>Testbench:<br></strong>Registers r0 &amp; r2 with “0” &amp; “22”, and instruction memory with instructions are already initialized. This testbench runs the clock cycle for 200ns with a width of 100ns to run both instructions. All control signals are part of the instruction itself.</p><pre>module memory_transfer_datapath_tb;<br>    reg clk, reset;<br>    <br>    // instantiate unit under test<br>    memory_transfer_datapath uut(<br>        .clk(clk),<br>        .reset(reset)<br>    );<br>    <br>    initial begin<br>        // start execution<br>        clk &lt;= 0;<br>        reset &lt;= 0;<br>        # 50<br>        reset = 1;<br>        # 200<br>        // stop execution<br>        reset = 0; <br>        $finish;<br>    end<br>    <br>    always # 50 clk &lt;= ~clk;<br>endmodule</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LKjSIG-rhF9CPWhGXG-oKQ.png" /><figcaption>Waveform of the above testbench</figcaption></figure><p>From the above waveform, we can see that both instructions are working correctly. For example, from time <em>50ns</em> to <em>150ns </em>(instruction number-1), the <em>PC</em> value was 4 — which translated to 1 according to our logic — store instruction was read from the instruction memory and stored <em>r2 = 22</em> at data memory location 0. Meanwhile, signal <em>memWrite</em> is 1. Then, the load-word instruction loaded the same address’s value to the r31, while the control signals including <em>memRead</em>, and <em>regWrite</em> were asserted.</p><h3>Datapath for R and I type instructions:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*327tgRLwb3K2g5aJdR_Tgw.png" /><figcaption>Datapath for R &amp; I type instructions</figcaption></figure><p>The datapath for an R &amp; I type instruction consists of 4 units — instruction fetch, register file, ALU, and Data memory — since each instruction is fetched from instruction memory and decoded (wires mapping) to read the specified registers, after which the ALU performs the required operation on those operands, then the calculated value would be applied to address terminal of Data memory. Lastly, the value (depending upon instruction) will then be written back to the write register. But this is not as easy as I said, some conflicts need to be resolved,</p><p><strong>Conflicts:<br></strong> — <strong>Write Register: </strong>In <em>R-type</em> instruction <em>rd</em> value is <em>instruction[15:11]</em> different from <em>lw &amp; addi</em>, which is <em>instruction[20:16]</em>.<br> — <strong>ALU operand-2:</strong> In <em>R-type</em> instruction, <em>operand-2</em> is the same as <em>register-read-2</em>, while in <em>I-type</em> instruction it is a <em>sign-extended</em> value (immediate or offset).<br> — <strong>Write Data: </strong>In <em>R-type</em> instructions &amp; addi, the ALU result is directly saved to the rd register while lw reads the memory value and saves it back to the register.</p><p><strong>Conflicts Resolution:<br></strong>All conflicts can easily be resolved by utilizing <strong><em>MUX — </em></strong>It is a combinational circuit that accepts <strong>m-bit-wide 2^n</strong> inputs and <strong>n-bit </strong>select line and outputs the selected input line — at the place of each conflict since we have to choose only one value from two in each conflict.</p><p>Currently, we don’t have any control unit, and it is necessary to provide <strong><em>RegDst, RegWrite, ALUsrc, memRead, memWrite, MemToReg, </em></strong>and <strong><em>ALU_operation</em></strong> control signals, so I will provide these signals as input in the testbench. The test program, Verilog code, testbench, and waveform are given below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*4pWNeGcHLJ7VGKgmPmCcvg.png" /><figcaption>R and I type instructions for testing the design</figcaption></figure><pre>module r_i_type_datapath(<br>        input clk, reset, RegDst, RegWrite, ALUsrc, memRead, memWrite, MemToReg,<br>        input [2:0] ALUoperation<br>    );<br>    <br>    wire [4:0] write_register;<br>    wire [31:0] instruction, read_data_1, read_data_2, ALU_operand2, ALU_to_Mem, operand_2, Mem_or_ALU, AluData, MemData;<br>        <br>    // instantiate instruction fetch<br>    instruction_fetch instruction_fetch(<br>        .reset(reset),<br>        .clk(clk),<br>        .instruction(instruction)<br>    );<br>    <br>    // Reg Dst<br>    assign write_register = RegDst? instruction[20:16] : instruction[15:11];<br>        <br>    // instantiate register file<br>    register_file register_file(<br>        .register_read_1(instruction[25:21]), <br>        .register_read_2(instruction[20:16]), <br>        .write_register(write_register), <br>        .write_data(Mem_or_ALU), <br>        .reg_write(RegWrite),  <br>        .clk(clk), <br>        .reset(reset),<br>        .read_data_1(read_data_1),  // register-1<br>        .read_data_2(read_data_2)   // register-2<br>    );<br>    <br>    // instantiate sign extension<br>    sign_extension sign_extension(<br>            .input_16(instruction[15:0]),<br>            .output_32(operand_2)<br>    );<br>    // ALU mux<br>    assign ALU_operand2 = ALUsrc? read_data_2 : operand_2;<br>    <br>    // instantiate ALU<br>    alu_unit alu_unit(<br>        .A(read_data_1),<br>        .B(ALU_operand2),<br>        .ALU_operation(ALUoperation), <br>        .zero(), // unused<br>        .result(AluData)<br>    );<br>    <br>    data_memory data_memory(<br>        .address(AluData),<br>        .write_data(read_data_2),<br>        .mem_read(memRead),<br>        .clk(clk),<br>        .mem_write(memWrite),<br>        .read_data(MemData)<br>     );<br>     <br>     // register write mux<br>     assign Mem_or_ALU = MemToReg?  MemData: AluData;<br>     <br>     // value initialization<br>     integer i;<br>     initial begin<br>        // register initialization<br>        for (i = 0; i &lt; 32; i = i + 1) begin<br>            register_file.Registers[i] = 0;<br>        end<br>        // instruction initialization<br>        // addi: r0 = r0 + 4 = 0 + 4 = 4<br>        // RegDst = 1, RegWrite = 1, ALUsrc = 0, ALUoperation = 010, memRead = 0, memWrite = 0, MemToReg = 0<br>        instruction_fetch.instruction_memory.Memory[1] = 32&#39;b000000_00000_00000_0000000000000100; <br>                                //   ------_  r0 _  r0 _       4<br>        // sw: Memory[r1+0] = r0; Memory[0] = 4<br>        // RegDst = x, RegWrite = 0, ALUsrc = 0, ALUoperation = 010, memRead = 0, memWrite = 1, MemToReg = x<br>        instruction_fetch.instruction_memory.Memory[2] = 32&#39;b000000_00001_00000_0000000000000000;<br>                                //   ------_  r1 _  r0 _       0<br>        // lw: r1 = Memory[r1+0] = Memory[0] = 4<br>        // RegDst = 1, RegWrite = 1, ALUsrc = 0, ALUoperation = 010, memRead = 1, memWrite = 0, MemToReg = 1<br>        instruction_fetch.instruction_memory.Memory[3] = 32&#39;b000000_00001_00001_0000000000000000;<br>                                //   ------_  r1 _  r1 _       0<br>        // add: r2 = r0 + r1 = 4 + 4 = 8<br>        // RegDst = 0, RegWrite = 1, ALUsrc = 1, ALUoperation = 010, memRead = 0, memWrite = 0, MemToReg = 0<br>        instruction_fetch.instruction_memory.Memory[4] = 32&#39;b000000_00000_00001_00010_00000_000000;<br>                                //   ------_  r0 _  r1 _  r2 _ -----------<br>  <br>        // PC counter <br>        instruction_fetch.program_counter.PC = 0;<br>     end<br>             <br>endmodule</pre><p><strong>Testbench:</strong><br>All registers with “0” and instruction memory with instructions are already initialized. This testbench generates “4” clock cycles and applies all “7” control signals according to the type of instruction since the control unit is not present.</p><pre>module r_i_type_datapath_tb;<br>    <br>    reg clk, reset, RegDst, RegWrite, ALUsrc, memRead, memWrite, MemToReg;<br>    reg [2:0] ALUoperation;<br>    <br>    // initialize uut<br>    r_i_type_datapath uut(<br>           .clk(clk), <br>           .reset(reset), <br>           .RegDst(RegDst), <br>           .RegWrite(RegWrite), <br>           .ALUsrc(ALUsrc), <br>           .memRead(memRead), <br>           .memWrite(memWrite), <br>           .MemToReg(MemToReg), <br>           .ALUoperation(ALUoperation)<br>        );<br>    <br>    <br>    <br>    initial begin<br>        clk &lt;= 0;<br>            reset &lt;= 0;<br>            # 50<br>            reset &lt;= 1;<br>            // clock cycle 1<br>                clk &lt;= 1;<br>                // signals for addi<br>                    RegDst &lt;= 1; <br>                    RegWrite &lt;= 1; <br>                    ALUsrc &lt;= 0;<br>                    ALUoperation &lt;= 3&#39;b010;<br>                    memRead &lt;= 0;<br>                    memWrite &lt;= 0;<br>                    MemToReg &lt;= 0;<br>                # 50<br>                clk &lt;= 0;<br>                # 50<br>        // clock cycle 2<br>            clk &lt;= 1;<br>            # 5<br>            // signals for sw<br>                RegDst &lt;= 1&#39;bx; <br>                RegWrite &lt;= 0; <br>                ALUsrc &lt;= 0;<br>                ALUoperation &lt;= 3&#39;b010;<br>                memRead &lt;= 0;<br>                memWrite &lt;= 1;<br>                MemToReg &lt;= 1&#39;bx;<br>            # 50<br>            clk &lt;= 0;<br>            # 50<br>        // clock cycle 3<br>            clk &lt;= 1;<br>            # 5<br>            // signals for lw<br>                RegDst &lt;= 1; <br>                RegWrite &lt;= 1; <br>                ALUsrc &lt;= 0;<br>                ALUoperation &lt;= 3&#39;b010;<br>                memRead &lt;= 1;<br>                memWrite &lt;= 0;<br>                MemToReg &lt;= 1;<br>            # 50<br>            clk &lt;= 0;<br>            # 50<br>        // clock cycle 4<br>            clk &lt;= 1;<br>            # 5<br>            // signals for add<br>                RegDst &lt;= 0; <br>                RegWrite &lt;= 1; <br>                ALUsrc &lt;= 1;<br>                ALUoperation &lt;= 3&#39;b010;<br>                memRead &lt;= 0;<br>                memWrite &lt;= 0;<br>                MemToReg &lt;= 0;<br>            # 50<br>            clk &lt;= 0;<br>            # 50<br>        $finish;<br>    end<br>    <br>endmodule</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GYwY_3F_ABhkihrD77sdTw.png" /><figcaption>Waveform of the above testbench</figcaption></figure><p>The first instruction is <em>addi</em>, which runs from <em>50ns to 150ns</em>. Initially, the value of <em>r0</em> was 0, and the immediate value was 4 (<em>A</em> and <em>B</em> operands, respectively) both were added to form 4 as an output of <em>ALU</em>, and then this value was written back to <em>r0</em> register. Then, the next instruction that was run on the CPU was <em>sw</em>, which stores that calculated 4 from <em>r0</em> to the data memory’s <em>0th</em> location. After that, the third instruction was lw, which read the data from <em>memory[0]</em> (available at <em>read_data</em>) and then wrote back this data to <em>r1</em> register. Lastly, the instruction was of <em>add</em>, which simply read <em>r0</em> and <em>r1</em>, then stored the addition of those values to <em>r2</em>.</p><h3>Datapath for Control Transfer instruction:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5KrgOsVezoQdApfBdyFteQ.png" /><figcaption>Datapath for control Transfer instruction</figcaption></figure><p>Control of Transfer means the next instruction could be different from the sequential one since this kind of instruction changes the address of <em>PC_next</em>. These instructions help to form <em>if_else</em> and <em>for_loop</em> in a high-level language. This only involves instruction fetch, register file, and ALU and is divided into two types:<br>1. <strong>Conditional</strong> which involves I-format and the new address is calculated as, <strong><em>BTA = PC_next + 4 x offset</em></strong><br>2. <strong>Unconditional</strong> which utilizes J-format and next address is given by, <br><strong><em>JTA = PC_next[31:38] || (address &lt;&lt; 2)</em></strong></p><h4>Conditional:</h4><p><strong>Beq: (branch if equal)</strong><br>Conditional instruction could be <em>beq</em> and <em>bne</em>, let first only consider <em>beq</em>. First of all, the instruction would be fetched from instruction memory and then divided into three separate entities: <em>rs, rt, and offset</em>. After that, the specified register would serve as the operands of <em>ALU</em>; it will perform subtraction because <em>A-B = 0</em> if <em>A</em> is equal to <em>B</em>, and assert the zero flag. <em>Beq</em> instruction changes the execution sequence only if <em>zero == 1</em> but <em>zero</em> could be 1 in the case of <em>R-type sub-instruction</em>, so just to make a difference between the two we can use <em>branch</em> control signal with zero <em>flag</em> as <strong><em>PCsrc = zero &amp; branch</em></strong>. <br><strong>Bne: (branch if not equal)</strong><br>But the same equation will not work in <em>bne</em> (branch if not equal) since it will jump only if the operands are not equal, so we need one more signal for <em>bne</em> (<em>branch_bne</em>), and the equal for <em>bne</em> would be <strong><em>branch_bne &amp; ~zero</em></strong>. Since operations before and after calculating <em>PCsrc</em> are the same in both instructions, so we can change the equation of <em>PCsrs</em> as <strong><em>((branch_beq &amp; zero) |(branch_bne &amp; ~zero)</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*RlQ-l5nzdqd3IknxmjBrqQ.png" /><figcaption>To incorporate bne, we need to change PCSrc</figcaption></figure><h4>Unconditional:</h4><p>From its name, one can easily perceive that it transfers the control to some insequential instruction without checking any condition. The important unconditional instruction in our case is only<em> j</em> instruction where we specify its opcode and the address of the new instruction. It also requires <em>jump</em> control signal to jump to the next instruction. The wire mapping of <em>j</em> instruction is given below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*VX9l9b9Bbnst3hI6KSbmgQ.png" /><figcaption>J-type instruction format</figcaption></figure><p><strong>Conflict:<br></strong>Previously, the next address would be calculated as <em>PC_next = PC + 4</em> but now we have two more candidates for <em>PC_next</em> one is <strong>BTA</strong> (Branch Target Address) and another one is <strong>JTA</strong> (Jump Target Address).<br><strong><em>PC_next = (PC + 4) or BTA or JTA</em></strong></p><p><strong>Conflict Resolution:<br></strong>Do you remember the rule of selecting one candidate out of many? Utilizing MUX. This is what we will do. We can make a selection between <em>PC + 4</em> and <em>BTA</em> with <em>PCsrc</em> signal as <em>tempAddress</em> and then one will be selected <em>tempAddress</em> and <em>JTA</em> with jump control signal.</p><p>Currently, we don’t have any control unit, and it is necessary to provide <strong><em>branch, jump, </em></strong>and <strong><em>ALU_operation</em></strong> control signals, so I will provide these signals as input in the testbench. The test program, Verilog code, testbench, and waveform are given below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*1t37BkA-TiYNQjSzLkQc7Q.png" /><figcaption>Branch instructions for testing the design</figcaption></figure><h4>Modified Instruction Fetch Unit:</h4><p>Previously, the instruction fetch unit was only reading instructions sequentially, but now we have to incorporate JTA and BTA as well and select one address among three candidates. A modified version of it would accept zero, branch, jump, and offset as input, then process it to form a new address, and lastly, output instruction at that address. For selecting a new address, we have two muxes here. The first one is used to select between PC_plus_4 and BTA and the second one is to select between previously selected and JTA. The Verilog code of modified instruction fetch is given below,</p><pre>module instruction_fetch_with_control_transfer(<br>    input reset,clk,zero,branch,jump,<br>    input [31:0] offset,<br>    output [31:0] instruction<br>    );<br>    <br>    wire [31:0] JTA, BTA, PC_plus_4;<br>    wire [31:0] PC_address, Actual_PC_Address, Branch_Address;<br>    <br>    // instantiate PC<br>    program_counter program_counter(<br>        .PC_next(Actual_PC_Address),<br>        .clk(clk),<br>        .reset(reset),<br>        .PC(PC_address)<br>    );<br>    <br>    // instantiate counter <br>    pc_counter pc_counter(<br>        .PC_address(PC_address),<br>        .PC_plus_4(PC_plus_4)<br>        );<br>        <br>    // instantiate memory<br>    instruction_memory instruction_memory(<br>        .address(PC_address),<br>        .reset(reset),<br>        .instruction(instruction)<br>    );<br>    <br>    // Calculate BTA<br>    assign BTA = PC_plus_4 + (offset &lt;&lt; 2);<br>    <br>    // Calculate JTA<br>    assign JTA = {PC_plus_4[31:28], {instruction[25:0], 2&#39;b00}};<br>    <br>    // Branch MUX<br>    assign Branch_Address = (zero &amp; branch)? BTA : PC_plus_4;<br>    <br>    // Jump MUX<br>    assign Actual_PC_Address = jump? JTA : Branch_Address;<br>   <br>endmodule</pre><pre>module control_transfer_datapath(<br>        input clk, reset, branch, jump,<br>        input [2:0] ALUoperation<br>    );<br> <br>    wire zero;<br>    wire [31:0] instruction, read_data_1, read_data_2, operand_32;<br>        <br>    // instantiate instruction fetch<br>    instruction_fetch_with_control_transfer instruction_fetch_with_control_transfer(<br>        .reset(reset),<br>        .clk(clk),<br>        .zero(zero),<br>        .branch(branch),<br>        .jump(jump),<br>        .offset(operand_32),<br>        .instruction(instruction)<br>    );<br>            <br>    // instantiate register file<br>    register_file register_file(<br>        .register_read_1(instruction[25:21]), <br>        .register_read_2(instruction[20:16]), <br>        .write_register(),  // unused<br>        .write_data(),  // unused<br>        .reg_write(1&#39;b0),  <br>        .clk(clk), <br>        .reset(reset),<br>        .read_data_1(read_data_1),  // register-1<br>        .read_data_2(read_data_2)   // register-2<br>    );<br>    <br>    // instantiate sign extension<br>    sign_extension sign_extension(<br>            .input_16(instruction[15:0]),<br>            .output_32(operand_32)<br>    );<br>    <br>    // instantiate ALU<br>    alu_unit alu_unit(<br>        .A(read_data_1),<br>        .B(read_data_2),<br>        .ALU_operation(ALUoperation), <br>        .zero(zero),<br>        .result()  // unused<br>    );<br>    <br>      <br>     // value initialization<br>     initial begin<br>        // register initialization<br>        register_file.Registers[0] = 0;<br>        register_file.Registers[1] = 0;<br>        // instruction initialization<br>        <br>        // jump: to address 22*4<br>        // jump = 1&#39;b1; branch = 1&#39;b0; ALUoperation = 3&#39;bxxx<br>        instruction_fetch_with_control_transfer.instruction_memory.Memory[0] = 32&#39;b000000_00000000000000000000010110; <br>        <br>        // beq: r0 == r1? jump to +3<br>        // jump = 1&#39;b0; branch = 1&#39;b1; ALUoperation = 3&#39;b110<br>        instruction_fetch_with_control_transfer.instruction_memory.Memory[22] = 32&#39;b000000_00000_00001_0000000000000011; <br>        <br>        // PC counter <br>        instruction_fetch_with_control_transfer.program_counter.PC = 0;<br>     end<br>             <br>endmodule</pre><p><strong>Testbench:<br></strong>Registers r0 &amp; r1 with “0”, and instruction memory with instructions are already initialized. This testbench generates “2” clock cycles and applies “3” control signals according to the type of instruction since the control unit is not present.</p><pre>module control_transfer_datapath_tb;<br>    reg branch, jump, clk, reset;<br>    reg [2:0] ALUoperation;<br>    <br>    control_transfer_datapath uut(<br>        .clk(clk),<br>        .reset(reset),<br>        .branch(branch),<br>        .jump(jump),<br>        .ALUoperation(ALUoperation)<br>    );<br>    <br>    initial begin<br>        reset &lt;= 0;<br>        clk &lt;= 0;<br>        # 50<br>        // clock cycle 1<br>            clk &lt;= 1;<br>            # 1<br>            reset &lt;= 1;<br>                // Control signals for jump<br>                jump = 1&#39;b1; <br>                branch = 1&#39;b0; <br>                ALUoperation = 3&#39;bxxx;<br>            # 49<br>            clk &lt;= 0;<br>            # 50<br>        // clock cycle 2<br>            clk &lt;= 1;<br>            # 1<br>                // Control signals for beq<br>                jump = 1&#39;b0; <br>                branch = 1&#39;b1; <br>                ALUoperation = 3&#39;b110;<br>            # 49<br>            clk &lt;= 0;<br>            # 50<br>        $finish;<br>    end<br>endmodule</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sqoD8C-2Ag_z3SzqVibvBg.png" /><figcaption>wave form of the above testbench</figcaption></figure><p>It is clear from the above waveform from <em>50ns to 150ns</em> that the first instruction which was <strong><em>j</em></strong>, since <em>jump</em> signal was asserted, changed the PC value to JTA <strong>(<em>0x00000000 to 0x00000058</em>)</strong> and the second instruction which was <strong><em>beq</em></strong>, branch signal was asserted, changed the PC next to BTA <strong>(<em>0x00000058 to 0x00000068</em>)</strong>.</p><h3>Final Words:</h3><p>The modularity of the datapath ensures the smooth handling of diverse instructions, from arithmetic operations to memory access and control flow. Each instruction type demands unique design considerations, and sometimes may become a reason for conflict, This article discussed each aspect of every type of instruction alone as well as together.</p><p>In the next article, we will focus on creating a <strong>unified datapath for R, I, and J-type instructions</strong>, integrating the control unit, and demonstrating the full architecture with a practical example: Fibonacci series computation. This will showcase how concepts come together in a complete processor design.</p><blockquote><a href="https://medium.com/@hassu20083/hardware-design-risc-v-single-cycle-datapath-part-03-b299fb95403d">Hardware Design — RISC-V — Single Cycle Datapath — part-03</a></blockquote><p>Visit my <a href="https://github.com/Hassu083/RISC-v_SCDP_Verilog_implementation">GitHub repository</a> to review the designs and code discussed here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3aa48cee4284" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hardware Design — RISC-V — Single Cycle Datapath — part-01]]></title>
            <link>https://medium.com/@hassu20083/hardware-design-risc-v-single-cycle-datapath-part-01-235e9f060733?source=rss-1376dfe8a7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/235e9f060733</guid>
            <category><![CDATA[verilog]]></category>
            <category><![CDATA[verilog-hdl]]></category>
            <category><![CDATA[risc-v]]></category>
            <category><![CDATA[computer-architecture]]></category>
            <category><![CDATA[computer-organization]]></category>
            <dc:creator><![CDATA[Hassu]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 15:10:24 GMT</pubDate>
            <atom:updated>2024-12-04T08:29:41.603Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hardware Design — RISC-V — Single Cycle Datapath — part-01</h3><p>To understand any processor’s organization (Datapath), the prerequisite is to be aware of its <strong>ISA (I</strong>nstruction <strong>S</strong>et <strong>A</strong>rchitecture<strong>) </strong>first. If you already know RISC-v’s ISA, then you are at the right place; otherwise, I would recommend you to first look at the preceding articles of this series.</p><ol><li><a href="https://medium.com/@hassu20083/instruction-set-architecture-risc-v-single-cycle-datapath-8277381b87da"><strong><em>Instruction Set Architecture — RISC-v — Single Cycle Datapath</em></strong></a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*8Dx25ZGC_lCjgNPB_CfMvA.png" /><figcaption>The complete picture of Single Cycle Datapath (RISC-v)</figcaption></figure><h3>Table of Contents:</h3><blockquote><a href="#b30d">RISC — Design Principles<br></a><a href="#698d">Processor Design — Datapath<br></a><a href="#95cd">Memory</a><a href="#b2f2"><br></a><a href="#c936">Datapath for Instruction Fetch</a><br><a href="#c3b4">Register File<br></a><a href="#2d7b">Arithmetic and Logic Unit</a><a href="#00fb"><br></a><a href="#efda">Final Words</a></blockquote><h3>RISC — Design Principles:</h3><p>The selection of an instruction set that the machine can execute is a crucial part of the processor design — it requires planning for a number of instructions to execute the program, the number of clock cycles to execute each instruction, and the speed of the clock cycle — since its efficiency is highly dependent. These are the design principles of RISC:</p><ol><li><strong>Simplicity favors regularity: <br></strong>All instructions in the instruction set use a 6-bit opcode and all instructions of RISC-v are 32-bit wide — fixed-length instructions. Keeping all instructions of size allows us to keep register fields and opcodes at the same location in each format.<br> — Easy to decode<br> — Easy to generate address, increment by 4</li><li><strong>Smaller is faster:</strong><br>The processor has fewer registers because smaller pieces of hardware are generally quicker than larger pieces. Smaller size means,<br> — Electronic signal travels through the smaller distances<br> — We can utilize small memories that are faster than larger one</li><li><strong>Good design demands good compromises:<br></strong>Since all instructions are of the same size, we need different formats to differentiate the types of instruction.<br> — R, I &amp; J –Formats</li><li><strong>Make the common case fast:<br></strong>Improve the efficiency of frequently used hardware — favor the frequent cases over the infrequent cases. <br> — Constants are made a part of arithmetic instructions because the addition of constants is a very common operation e.g. <em>addi, slti, etc.</em></li></ol><h3>Processor Design — Datapath:</h3><p>A processor comprises three parts:</p><ol><li><strong>Functional Units: </strong>Any components that accept input, process it — not necessarily — , and produce some output. For example ALU, Adders, etc.</li><li><strong>Datapath:</strong> The interconnection of various functional units that move data between these components</li><li><strong>Control unit:</strong> It generates control signals, supervises and manages the movement and processing of data to execute instructions</li></ol><h4>Steps of Processor Design</h4><ol><li>Extract the datapath requirements (by exploring the <strong>ISA</strong> of the processor)</li><li>Design of datapath elements</li><li>Interconnecting datapath elements &amp; deciding which control signals are to be generated by the control unit</li><li>Design of control unit</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*lD6L39vX6tRfi3TNhL65nA.png" /><figcaption>Instructions we are going to implement</figcaption></figure><h3>Memory:</h3><p>There are two types of memory architecture:<br><strong>1.</strong> <strong><em>Princeton Memory Architecture:</em></strong> Where instruction and data are held in the same memory.<br><strong>2.</strong> <strong><em>Harvard Memory Architecture: </em></strong>Uses different memory for data and instructions.</p><blockquote>We will use Harvard Memory Architecture in the design of RISC-v.</blockquote><h4>1. Instruction Memory:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*x8QDnGellOc76Qg0_CyRJA.png" /><figcaption>RISC-v instruction memory</figcaption></figure><p>In this memory, we will store the machine code to execute. This memory will accept a 32-bit-wide address and return 32-bit-wide machine instruction. There is no control (read/write) signal other than reset. The Verilog code of instruction memory and testbench is given below,</p><pre>module instruction_memory(<br>    input [31:0] address,<br>    input reset,<br>    output [31:0] instruction<br>    );<br><br>    // stack of 1024 32-bit wide registers  <br>    reg [31:0] Memory [1023:0];<br>    // If reset is 0 then the output would be 0 otherwise instruction <br>    // at the location. I will explain reason behind using <br>    // address[31:2] later.<br>    assign instruction = (reset == 1&#39;b0) ? 32&#39;h00000000 : Memory[address[31:2]];<br><br>endmodule</pre><p><strong>Testbench:</strong><br>This testbench first initializes the ith address of memory with the value of ix4, then performs some read queries with some amount of delay (within the initial block).</p><pre>module instruction_memory_tb;<br><br>    reg [31:0] address;<br>    reg reset;<br>    wire [31:0] instruction;<br><br>    instruction_memory uut (<br>        .address(address),<br>        .reset(reset),<br>        .instruction(instruction)<br>    );<br><br>    integer i;<br><br>    initial begin<br>        // Initialize inputs<br>        reset = 0;<br>        address = 0;<br><br>        // Initialize memory with test data<br>        for (i = 0; i &lt; 1024; i = i + 1) begin<br>            uut.Memory[i] = i * 4; // Example initialization<br>        end<br><br>        // Wait for the initial reset state<br>        #10;<br>        <br>        <br>        // Test reset behavior<br>        #10 reset = 0; address = 32&#39;h00000004; #10;<br>        #10 reset = 0; address = 32&#39;h00000008; #10;<br><br>        // Test active state behavior<br>        reset = 1; #10;<br>        address = 32&#39;h00000000; #10;<br>        address = 32&#39;h00000004; #10;<br>        address = 32&#39;h00000008; #10;<br><br>        // Finish simulation<br>        $finish;<br>    end<br><br>endmodule</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G4DoDucY4EuarD4ywwhURg.png" /><figcaption>waveform of the above testbench</figcaption></figure><p>There are four waves, and the first three are important: the first one is of address — which is changing with time, the second one is of reset — which is 0 for half of the time, and 1 for the rest, and the third waveform is the instruction — which is <em>32&#39;h00000000</em> when reset is 0, then starts changing with address.</p><h4>2. Data Memory:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*GT2eHFqpf48tUIrpAXCVlQ.png" /><figcaption>RISC-v data memory</figcaption></figure><p>This memory is for storing data. It will accept a 32-bit-wide address and 1-bit <em>memRead </em>or <em>memWrite,</em> upon <em>memRead </em>it will return 32-bit-wide data, and on <em>memWrite</em>, it will write 32-bit <em>writeData</em> on a specified location. The Verilog code of instruction memory and testbench is given below,</p><pre>module data_memory(<br>    input [31:0] address,<br>    input [31:0] write_data,<br>    input mem_read, clk,<br>    input mem_write,<br>    output [31:0] read_data<br>    );<br>    reg [31:0] Memory [1023:0];<br>    assign read_data = (mem_read)? Memory[address[31:2]] : 32&#39;h00000000;<br>    always @(posedge clk) begin<br>        if (mem_write) begin<br>            Memory[address[31:2]] &lt;= write_data;<br>        end<br>    end<br>    <br>endmodule</pre><h3>Datapath for Instruction Fetch:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*6SjfTsuKf0NAl_SfbFcOGQ.png" /><figcaption>Datapath for instruction fetch</figcaption></figure><p>It involves instruction memory, a program counter (Special-purpose register), and one adder, which increments the current address by 4. At this point, one question arises: why <strong><em>next-address = address + 4</em></strong>? Since byte-addressable memory is used in actual architecture, 4 bytes combined to form 32-bit wide instruction.<br>But in our case, the memory is 4-byte-addressable that’s why we neglected the first 2 bits of address and used <strong><em>Memory[address[31:2]] </em></strong>instead of<strong><em> Memory[address], </em></strong>in other words,<strong><em> address[31:2] </em></strong>is equal to<strong><em> address/4. </em></strong>The given table will help you to understand intuition,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*ZjzAA8zhEAi4wGphAvPQrg.png" /><figcaption>Address vs Address[31:2]</figcaption></figure><h4>Program Counter:</h4><p>It is a 32-bit special-purpose register. Its output — <strong>PC</strong> points to the address of the current instruction, while its input — <strong>PCnext</strong> indicates the address of the next instruction.</p><pre>module program_counter(<br>    input [31:0] PC_next,<br>    input clk,reset,<br>    output reg [31:0] PC<br>    );<br>    <br>    always @(posedge clk)<br>    begin<br>        PC &lt;= (reset == 1&#39;b0)? 32&#39;h00000000 : PC_next;<br>    end<br>    <br>endmodule</pre><p><strong>PC Adder:</strong><br>It is the combinational circuit that accepts the current address and outputs the next address by adding 4 to the current address.</p><pre>module pc_counter(<br>    input [31:0] PC_address,<br>    output [31:0] PC_plus_4<br>    );<br>    // PC increment by 4<br>     assign PC_plus_4 = PC_address + 32&#39;d4;<br>endmodule</pre><h4>Instruction Fetch:</h4><p>Instruction fetch datapath, The program counter has some initial address, which is then incremented by 4, and at the same time, it will read the instruction from the specified address. This cycle will run until the reset signal is 1. The Verilog code, testbench, and waveform are given below,</p><pre>module instruction_fetch(<br>    input reset,clk,<br>    output [31:0] instruction<br>    );<br>    <br>    wire [31:0] PC_address, PC_plus_4;<br>    <br>    // instantiate PC<br>    program_counter program_counter(<br>        .PC_next(PC_plus_4),<br>        .clk(clk),<br>        .reset(reset),<br>        .PC(PC_address)<br>    );<br>    <br>    // instantiate counter <br>    pc_counter pc_counter(<br>        .PC_address(PC_address),<br>        .PC_plus_4(PC_plus_4)<br>        );<br>        <br>    // instantiate memory<br>    instruction_memory instruction_memory(<br>        .address(PC_address),<br>        .reset(reset),<br>        .instruction(instruction)<br>    );<br>    <br>    // initialize memory and PC counter<br>    integer i;<br>    initial begin<br>        for (i = 0; i &lt; 1024; i = i + 1) begin<br>            instruction_memory.Memory[i] = i*2;<br>        end<br>        program_counter.PC = 0;<br>    end<br>    <br>endmodule</pre><p><strong>Testbench:</strong><br>Instruction memory is already initialized with random instructions. Testbench runs the clock with some time, since instruction fetch only accepts the clock and generates addresses by itself with each clock.</p><pre>module instruction_fetch_tb;<br>    reg clk, reset;<br>    wire [31:0] instruction;<br>    <br>    // instantiate instruction fetch unit<br>    instruction_fetch uut(<br>        .reset(reset),<br>        .clk(clk),<br>        .instruction(instruction)<br>        );<br>        <br>    initial begin<br>        clk &lt;= 0;<br>        reset &lt;= 0;<br>        #10<br>        reset &lt;= 1;        <br>    end<br>    always #50 clk = ~clk;<br>endmodule</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hPoui0426GbsAlP5R8w7Lw.png" /><figcaption>waveform of the above testbench; You can clearly see that new instruction is reading with each clock cycle.</figcaption></figure><h3>Register File:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*P4v0VJjqQlmrYDACfpFOFA.png" /><figcaption>RISC-v register file</figcaption></figure><p>In RISC architecture, <strong>registers</strong> play a crucial role in reducing memory access latency. Register access time is much less than memory access time. The register file is a collection of 32 32-bit registers. At most, an instruction performs two reads &amp; one write operation (e.g. arithmetic &amp; logic instructions), so it has two reading ports and one writing port. It has a total seven ports: <br>- <strong>Read register number</strong> <strong>1 &amp; 2 </strong>are the address ports for reading registers<br>- Read data will be available at <strong>Read Data 1 </strong>and <strong>2</strong><br>- <strong>Write register</strong> is an address port for writing on the register <br>- <strong>Write Data</strong> is the actual data to write<br>- <strong>RegWrite</strong> is a 1-bit write control signal — if enabled, the register file writes the data into a specified register<br>The Verilog code of the register file and testbench is given below,</p><pre>module register_file(<br>    input [4:0] register_read_1,<br>    input [4:0] register_read_2,<br>    input [4:0] write_register,<br>    input [31:0] write_data,<br>    input reg_write, clk, reset,<br>    output [31:0] read_data_1,<br>    output [31:0] read_data_2<br>    );<br>    <br>    reg [31:0] Registers [31:0];<br>    <br>    assign read_data_1 = (!reset)? 32&#39;h00000000  : Registers[register_read_1];<br>    assign read_data_2 = (!reset)? 32&#39;h00000000  : Registers[register_read_2];<br>    <br>    always @(posedge clk)<br>    begin<br>        if( reg_write == 1&#39;b1 )<br>        begin<br>            Registers[write_register] &lt;= write_data;<br>        end<br>    end<br>endmodule</pre><p><strong>Testbench:</strong><br>This testbench first writes the data to the first five registers and then reads data from both terminals in forward and reverse order, respectively.</p><pre>module register_file_tb;<br><br>    // Inputs<br>    reg [4:0] register_read_1, register_read_2, write_register, address, address2;<br>    reg reg_write, clk, reset;<br>    reg [31:0] write_data;<br><br>    // Outputs<br>    wire [31:0] read_data_1, read_data_2;<br><br>    // Instantiate the Unit Under Test (UUT)<br>    register_file uut (<br>        .register_read_1(register_read_1),<br>        .register_read_2(register_read_2),<br>        .write_register(write_register),<br>        .write_data(write_data),<br>        .reg_write(reg_write),<br>        .clk(clk),<br>        .reset(reset),<br>        .read_data_1(read_data_1),<br>        .read_data_2(read_data_2)<br>    );<br><br>    integer i;<br><br>    // Initialize values<br>    initial begin<br>        // Initialize inputs<br>        clk = 0;<br>        reset = 1;<br>        reg_write = 0;<br>        address = 0;<br>        address2 = 0;<br><br>        // Apply reset pulse<br>        #5 reset = 0; // Assert reset<br>        #20 reset = 1; // Deassert reset<br><br>        // Write zero to all registers (if not handled by reset in module)<br>        for (i = 0; i &lt; 32; i = i + 1) begin<br>            uut.Registers[i] = 32&#39;h00000000; // Optional if reset logic is implemented<br>        end<br><br>        // Write to registers<br>        for (i = 0; i &lt; 5; i = i + 1) begin<br>            write_register = i;<br>            write_data = i * 10; // Example data<br>            reg_write = 1;<br>            #10; // Wait for a clock cycle<br>        end<br>        reg_write = 0; // Disable write<br><br>        // Read from registers<br>        for (i = 0; i &lt; 5; i = i + 1) begin<br>            register_read_1 = i;<br>            register_read_2 = 4 - i;<br>            #10; // Wait for a clock cycle<br>        end<br><br>        // End simulation<br>        #100;<br>        <br>    end<br><br>    // Clock generation<br>    always #5 clk = ~clk;<br><br>endmodule</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2DDxR7vTA5SChyy739Ew3g.png" /><figcaption>waveform of the above testbench</figcaption></figure><p>According to testbench logic, the first half simulation till 75ns is for writing on the register, and from 75ns to 115ns is for reading from registers — when <em>register_read</em> signal is changing, which is the address of the register, <em>read_data </em>signal is also changing.</p><h3>Arithmetic and Logic Unit:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*nX-VxYUuoL5eybQglRdgwA.png" /><figcaption>Datapath of ALU</figcaption></figure><p>The ALU is a combinational circuit with the sole purpose of performing arithmetic or logic operations on two operands. It will accept two 32-bit wide operands <strong>A</strong> and <strong>B </strong>and<strong> </strong>one 3-bit wide control signal <strong>ALU operation — </strong>select bits of mux inside the ALU<strong> — </strong>and generate results of 32-bit and one 1-bit flag signal <strong>zero</strong>. The Verilog code, testbench, and waveform of ALU are given below,</p><pre>module alu_unit(<br>    input [31:0] A,<br>    input [31:0] B,<br>    input [2:0] ALU_operation,<br>    output reg zero,<br>    output reg [31:0] result<br>    );<br>    // If any input change<br>    always @(*) begin<br>        // MUX based on ALU_operation<br>        case (ALU_operation)<br>            // and operation<br>            3&#39;b000: begin<br>                result &lt;= A &amp; B;<br>            end<br>            // or operation<br>            3&#39;b001: begin<br>                result &lt;= A | B;<br>            end<br>            // addition operation<br>            3&#39;b010 : begin <br>                result &lt;= A + B;<br>            end<br>            // subtraction operation<br>            3&#39;b110 : begin<br>                result &lt;= A - B;<br>            end<br>            // less than operation<br>            3&#39;b111 : begin<br>                result &lt;= (A &lt; B) ? 32&#39;d1 : 32&#39;d0;<br>            end<br>            // no operation<br>            default: begin<br>                result &lt;= 0;<br>            end<br>        endcase<br>        <br>        // zero flag for bne and beq<br>        if (result == 0) begin<br>            zero &lt;= 1;<br>        end<br>        else begin<br>            zero &lt;= 0;<br>        end<br>    end<br>    <br>endmodule</pre><p><strong>Testbench:</strong><br>The given testbench first initializes both operands of ALU with some value then changes the ALU operation after some delays. It does not require any clock since ALU is a combinational circuit.</p><pre>module alu_unit_tb;<br>    reg [31:0] A, B;<br>    reg [2:0] ALU_operation;<br>    wire [31:0] result;<br>    wire zero;<br>    <br>    alu_unit uut(<br>        .A(A),<br>        .B(B),<br>        .ALU_operation(ALU_operation),<br>        .zero(zero),<br>        .result(result)<br>    );<br>    <br>    initial begin<br>        // initialize values<br>        A &lt;= 32&#39;d200;<br>        B &lt;= 32&#39;d100;<br>        // and operation<br>        ALU_operation &lt;= 0;<br>        # 20<br>        // or operation<br>        ALU_operation &lt;= 1;<br>        # 20<br>        // add operation<br>        ALU_operation &lt;= 2;<br>        # 20<br>        // sub operation<br>        ALU_operation &lt;= 6;<br>        # 20<br>        // less than operation<br>        ALU_operation &lt;= 7;<br>        # 20<br>        // nothing<br>        ALU_operation &lt;= 3;<br>    end<br>    <br>endmodule</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rlRMqT89how0w_ehySR7JA.png" /><figcaption>waveform of the above testbench</figcaption></figure><p>It is clear from the above waveform that our ALU is functionally correct, values of A and B are 200 and 100, respectively, for the whole simulation. The operations are “and”, “or”, “addition”, “subtraction”, “less than”, and “nothing”, and the results are <em>200&amp;100 = 64, 200|100 = 236, 200+100 = 300, 200-100 = 100, 200&lt;100 = 0,</em> and <em>0</em>, respectively.</p><h3>Final Words:</h3><p>This article introduced the fundamental components of the RISC-V single-cycle datapath. By understanding how each piece fits together, you can appreciate the elegance and efficiency of RISC-V architecture.</p><p>In the next articles of this series, we will take this foundation further by diving into datapaths for specific instruction types, such as R-type, memory-related instructions, and control transfers.</p><blockquote><a href="https://medium.com/@hassu20083/hardware-design-risc-v-single-cycle-datapath-part-02-3aa48cee4284">Hardware Design — RISC-V — Single Cycle Datapath — part-02</a></blockquote><p>You can also explore the code and examples used in this article on my <a href="https://github.com/Hassu083/RISC-v_SCDP_Verilog_implementation">GitHub repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=235e9f060733" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Instruction Set Architecture — RISC-v— Single Cycle Datapath]]></title>
            <link>https://medium.com/@hassu20083/instruction-set-architecture-risc-v-single-cycle-datapath-8277381b87da?source=rss-1376dfe8a7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8277381b87da</guid>
            <category><![CDATA[risc-v]]></category>
            <category><![CDATA[computer-architecture]]></category>
            <category><![CDATA[isa]]></category>
            <category><![CDATA[computer-hardware]]></category>
            <category><![CDATA[instruction-set]]></category>
            <dc:creator><![CDATA[Hassu]]></dc:creator>
            <pubDate>Tue, 26 Nov 2024 13:58:05 GMT</pubDate>
            <atom:updated>2024-11-26T13:58:05.729Z</atom:updated>
            <content:encoded><![CDATA[<h3>Instruction Set Architecture — RISC-v— Single Cycle Datapath</h3><p>As a programmer, you must have wondered how instructions/code/ programs run on hardware. Let’s dive into this article to answer those questions.</p><h3>Table of Contents:</h3><blockquote><a href="#b6a7">Instruction Set Architecture<br></a><a href="#5110">CISC vs RISC<br></a><a href="#0497">RISC Registers<br></a><a href="#17f2">R-format Instructions<br></a><a href="#bbe1">I-format Instructions<br></a><a href="#b1c2">J-format Instructions<br></a><a href="#a9b8">For loop</a><br><a href="#4d12">Functional Units Used<br></a><a href="#b5fd">Final Words</a></blockquote><h3>Instruction Set Architecture: (ISA)</h3><p>An ISA is an interface between software and hardware that defines how high-level code is translated into machine code, how assembly code is represented in the forms of 0s and 1s, and where and how data or instructions are loaded or stored; in short, it defines programmer’s view of hardware. By definition,</p><blockquote>A set of machine attributes that a system programmer needs to know to develop system software or a compiler required for translating high-level language (HLL) code into machine language.</blockquote><ul><li><strong>Instruction Set: </strong>A set of instructions that a machine can execute such as add (addition), sub (subtraction), etc.</li><li><strong>Programmer Accessible Registers: </strong>There are two kinds of registers: one is general-purpose registers that can be accessed and used within code, and another one is special-purpose registers such as program counter — Its use case can not be modified.</li><li><strong>Instruction Format: </strong>Every instruction contains some meaningful information, like address, register, data, control signal, etc. Instruction format defines the position of that meaningful information.</li><li><strong>Addressing Modes: </strong>Data plays a major role in instruction execution since arithmetic and logical operations are useless without operands. Addressing modes defines ways to access data. These are some modes I will mention the definition and use case of each mode while discussing instruction formats.<br> — <strong>Immediate Mode<br> — Register-Direct Mode<br> — Register-Indirect Mode<br> — Direct Mode<br> — Indirect Mode</strong></li></ul><h3>CISC vs. RISC</h3><p>Both are two different paradigms of computers with different purposes. CISC is more popular for designing high-end computing devices such as laptops, PCs, and servers, while RISC for embedded systems.</p><ul><li><strong>CISC</strong> (<strong>C</strong>omplex <strong>I</strong>nstruction <strong>S</strong>et <strong>C</strong>omputers)<br>It provides a large number and many types of instructions, with every instruction performing multiple tasks. You can imagine it as a very huge and complex circuit. Although it is easy for a programmer to use CISC and write algorithms with fewer instructions, it is difficult to design.</li><li><strong>RISC</strong> (<strong>R</strong>educed <strong>I</strong>nstruction <strong>S</strong>et <strong>C</strong>omputers)<br>It focuses on a smaller, simpler set of instructions with straightforward and single tasks, like addition, subtraction, and comparison. Nightmare for any programmers to write code in RISC’s assembly since simple loops require 4–5 different instructions, but it is easy to design. It can be converted into CISC by adding more functional units.</li></ul><p>In layman’s terms, CISC is a circuit with many wires, less vacant space, or a congested design. Admittedly, CISC is more power-hungry in comparison to RISC, as it is simple with less number of functional units, wires, and more free space.</p><h3>RISC Registers:</h3><p>In RISC architecture, <strong>registers</strong> play a crucial role in reducing memory access latency. Register access time is much less than memory access time. RISC ISA includes thirty-two 32-bit registers which are given as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*0NjwZtesiPsUTX_HeZ7XwQ.png" /><figcaption>Registers in RISC-v</figcaption></figure><p><strong>Where,<br><em>$ symbol:</em> </strong>It is used before the name of some register<br><strong><em>Register Name:</em></strong><em> </em>These are used in assembly code<br><strong><em>Number:</em> </strong>They are used in machine code</p><h3>R-format Instructions:</h3><p>R-instructions include all arithmetic and logical instructions such as addition, subtraction, and (bit-wise), or, etc. The format of writing assembly code is given as follows,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*wZe-iMImgM12wInB3e_Gaw.png" /><figcaption>Assembly code of addition</figcaption></figure><pre><strong>add</strong> <em>$s0, $s1, $s2</em>  #  s0 = s1 + s2<br><strong>sub</strong> <em>$s0, $s1, $s2</em>  #  s0 = s1 - s2<br><strong>and</strong> <em>$s0, $s1, $s2</em>  #  s0 = s1 &amp; s2<br><strong>or</strong>  <em>$s0, $s1, $s2</em>  #  s0 = s1 | s2<br><strong>slt</strong> <em>$s0, $s1, $s2</em>  #  s0 = s1 &lt; s2<br>... and so on.</pre><p><strong>Register-Direct Mode: </strong>These above instructions are the best examples of register-direct addressing since the operand is stored in the register specified in the instructions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*nEgg7p7ly92ZvQI2AgTAaA.png" /><figcaption>Register-direct addressing mode</figcaption></figure><h4><strong>Format:</strong></h4><p>These formats are important in translating the assembly code to machine-level code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*rVgT_NpOGU7F98GNqwi69Q.png" /><figcaption>R-format</figcaption></figure><p><strong>Where,<br></strong><em>op:</em> opcode (identifies different instructions) (0 in R-format) (6 bits)<br><em>rs: </em>1st register operand (register source) (5 bits)<br><em>rt: </em>2nd register operand (5 bits)<br><em>rd: </em>destination register (5 bits)<br><em>shamt: </em>shift amount (0 when N/A) (5 bits)<br><em>func: </em>function code (identifies the specific R-format instruction) (6 bits)</p><p>Let’s write the code for the equation, <strong><em>a = (b + c)-(d + e)</em></strong></p><pre>Let&#39;s assume the following variable-register associations,<br><em>a </em><strong><em>=</em></strong><em> $s0, b </em><strong><em>=</em></strong><em> $s1, c </em><strong><em>=</em></strong><em> $s3, d </em><strong><em>=</em></strong><em> $s4, e </em><strong><em>=</em></strong><em> $s5</em><br>Code is written as,<br><strong>add</strong> <em>$t0, $s1, $s2 </em>    # <strong>$t0 &lt;- b + c</strong><br><strong>add</strong> <em>$t1, $s3, $s4</em>     # <strong>$t1 &lt;- d + e</strong><br><strong>sub</strong> <em>$s0, $t0, $t1</em>     # <strong>a</strong> <strong>&lt;- (b + c) – (d + e)</strong></pre><h4>Assembly to Machine Language Translation:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*90OQBIU_7YQKW-nEP5Pn2g.png" /></figure><h3>I-format Instructions:</h3><p>In R-instruction, we assumed that registers already have operand values but in actual data is always present in memory. Now we need instructions that load data from memory and store it in memory.</p><ul><li><strong>Load Operation: </strong>Transferring data from main memory to the processor registers.<br> — <strong>lw</strong> <em>$rt, offset ($rs) — lw is load word<br>$rt ← Mem[$rs + offset]</em></li><li><strong>Store Operation:</strong> Transferring data from processor registers to main memory.<br> — <strong>sw</strong> <em>$rt, offset ($rs) — sw is store word<br>Mem[$rs + offset] ← $rt</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*qVF3Sv0nG19S9xQVp8jI0w.png" /><figcaption>load and store operation</figcaption></figure><ul><li>Set Less than Immediate:<br> — <strong>slti</strong> <em>$rt, $rs, imm<br>$rt ← $rs &lt; imm</em></li><li><strong>Immediate Addition: </strong>What if we want to initiate a register with some immediate value like <em>a = 10</em>? For that, we have <strong>addi</strong> instruction.<br> — <strong>addi</strong> <em>$rt, $rs, imm</em><br><em>$rt ← $rs + imm</em></li></ul><p><strong>Where,</strong><br><strong><em>offset or imm:</em></strong> it is the 16-bit immediate value <br><strong><em>$rs:</em></strong> contains the base address for lw and sw, while operand for the addi<br><strong><em>$rt:</em></strong> is the destination register in case of load, and addi; while source for store word<br><strong><em>word:</em></strong> Maximum number of bits that can be simultaneously accessed from main memory</p><p><strong>Register-indirect Mode: </strong>These above instructions are the best examples of register-indirect addressing since the register mentioned in the instruction contains the address of the operand. This time you need content of content of $rs given by <em>[[$rs]].</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*J-mkH-Veam2KnfgWu-HiEQ.png" /><figcaption>Register-indirect addressing mode</figcaption></figure><h4>Format:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*FjNwJymmvThNT2y59rWWfg.png" /><figcaption>I-format</figcaption></figure><p>Let’s write the code for the equation,<br><strong><em> A[25] = A[15]-A[20]; <br>A[30] = b -2;</em></strong></p><pre><em>Assuming that variable </em><strong><em>b</em></strong><em> is associated with register </em><strong><em>$16</em></strong><em> <br></em><strong><em>(or $s0)</em></strong><em> &amp; </em><strong><em>A</em></strong><em> is an array of words with base address in the register <br></em><strong><em>$17</em></strong><em>.<br>Code is written as,</em><br><strong>lw</strong> <em>$8, 60($17)</em>    # <strong>$8 &lt;- A[15] (15x4=60) </strong>(remember word length is 4 byte)<br><strong>lw</strong> <em>$9, 80($17)</em>    # <strong>$9 &lt;- A[20]</strong><br><strong>sub</strong> <em>$10, $8, $9 </em>  # <strong>$10 &lt;- A[15] – A[20] </strong><br><strong>sw</strong> <em>$10, 100 ($17)</em> # <strong>A[25] &lt;- $10</strong><br><strong>addi</strong> <em>$11, $16, -2</em> # <strong>$11 &lt;- b – 2</strong><br><strong>sw</strong> <em>$11, 120($17)</em>  # <strong>A[30] &lt;-$11<br></strong>One important thing to notice here is that we can use the register number <br>in place of it&#39;s name.</pre><h4>Assembly to Machine Language Translation:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*2rYA0u1OHrOSffyiflx0GA.png" /></figure><h4>Transfer of Control Instruction:</h4><p>If you are following the article, you must be thinking that we have only covered sequential instructions — which execute sequentially. What about if — else if — else type of instruction? Don’t need to worry, now we are discussing those. <em>A </em><strong><em>branch</em></strong><em> is an instruction that transfers control to an instruction that does not follow it in the program sequence. <br> — </em>These instructions modify the contents of PC (Program Counter)<br> — Also known as <strong>Branch Instructions<br></strong>There are two kinds of it,<br> <strong>— Conditional:</strong> Check the condition first, then jump to the new address.<br> <strong>— Unconditional: </strong>Directly jumps to the new address.</p><ul><li><strong>Branch-if-Equal:</strong> It compares registers <strong>$rs </strong>&amp;<strong> $rt</strong> and transfers control to label in the program if the contents of registers <strong>$rs </strong>&amp;<strong> $rt</strong> are equal.<br> — <strong>beq</strong> <em>$rs, $rt, label</em></li><li><strong>Branch-if-Not-Equal:</strong> It compares registers <strong>$rs </strong>&amp;<strong> $rt</strong> and transfers control to label in the program if the contents of registers <strong>$rs </strong>&amp;<strong> $rt</strong> are not equal.<br> — <strong>bne</strong> <em>$rs, $rt, label</em></li></ul><p><strong>Where,<br><em>label:</em></strong> it is the address of the new instruction</p><p><strong>Note:</strong> One important thing to remember before using these instructions is to always use the opposite condition I meant that if in HLL condition is equal, then try to implement code not equal condition.<br>Let’s write the assembly code for the Program,</p><pre>if (a == b):<br>    a = a + 1<br>b = b - 1</pre><pre><em>Let&#39;s assume the following variable-register associations,</em><br><em>a = $16, b = $17</em><br>Code is written as,<br><br><strong>bne</strong> <em>$16, $17, </em><strong><em>there</em></strong> (false) # <strong>compare registers $16 and $17</strong><br><strong>addi</strong> <em>$16, $16, 1  </em>          # <strong>if a = b then $16 = $16 + 1</strong><br><strong><em>there:</em></strong> <strong>addi</strong> <em>$17, $17, -1 </em>   # <strong>if a ≠ b then $17 = $17 – 1</strong></pre><h4>Dry Run Steps:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*CwIS5rF-qK8HP6s-4FyCgg.gif" /><figcaption>The above addressing mode is called PC relative addressing, where the new address is calculated with the help of the program counter</figcaption></figure><h3>J-format Instructions:</h3><p>It’s time to talk about <strong>Unconditional branch instruction— </strong>it transfers control to another instruction without testing any condition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*VX9l9b9Bbnst3hI6KSbmgQ.png" /><figcaption>J-format</figcaption></figure><ul><li><strong>Jump:</strong> This unconditional branch instruction transfers control to a program label mentioned as part of the instruction.<br> — <strong>j</strong> <em>label </em>(<strong><em>label:</em></strong><em> </em>shows the new address called JTA)<br><strong>JTA </strong>— <strong>J</strong>ump <strong>T</strong>arget <strong>A</strong>ddress<br><strong><em>JTA = PC [31:28] || ( address &lt;&lt; 2 )</em></strong></li></ul><p>Let’s write the assembly code for the Program,</p><pre>if (a == b):<br>    b = b + 1<br>else:<br>    b = b - 1</pre><pre><em>Let&#39;s assume the following variable-register associations,<br>a = $16, b = $17<br><br></em>Code is written as,<br><strong><em># compare registers $16 and $17</em></strong><br><strong>bne</strong> <em>$16, $17, </em><strong><em>else</em></strong><em>               </em># false means run else <br><br><strong><em># if a = b then $17 = $17 + 1</em></strong><br><strong>addi</strong> <em>$17, $17, 1 </em>                # if body<br><br><strong>j</strong> <strong><em>end_if</em></strong>                         # jump over the else part <br><br><strong><em>#</em> <em>if a ≠ b then $17 = $17 – 1</em></strong><br><strong><em>else:</em> addi</strong> <em>$17, $17, -1</em>          # else body<br><br><strong><em>end_if<br><br>You can dry run it with yourself.</em></strong></pre><ul><li><strong>Jump and Link:</strong> This instruction is used in function calling that’s why it performs two operations:<br>1. First, it saved the current address since after the function is completed, the program counter must return to the place where the function was called.<br>2. Second, it performs unconditional jump operation<br> — <strong>jal</strong> <em>label</em></li></ul><h3>For loop:</h3><p>The loop is an essential part of any programming language since it works according to the <strong>DRY</strong> rule (<strong>D</strong>on&#39;t <strong>R</strong>epeat <strong>Y</strong>ourself) and allows coder to perform a repetitive task without repeating code. Let’s write assembly for the given program and dry run it,</p><pre>int s = 0;<br>for(int i = 0; i &lt; 10; i++){<br>    s = s + i;<br>}</pre><pre>add $16, $0, $0       # i = 0 <br>add $17, $0, $0       # s = 0<br>for: <br>slti $8, $16, 10      # $8 = i &lt; 10? 1 : 0<br>beq $8, $0, end_loop  # if condition is false end_loop<br>add $17, $17, $16     # s = s + i<br>addi $16, $16, 1      # i += 1<br>j for                 # next iteration<br>end_loop:             # exit loop</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*H584MQM0cCm1OCQeDUon7Q.gif" /><figcaption>Dry Run</figcaption></figure><h3>Functional Units Used</h3><p>A RISC processor’s single-cycle datapath executes one instruction per clock cycle. Key components include:</p><h4>Arithmetic Logic Unit (ALU):</h4><p>Performs arithmetic (e.g., addition, subtraction) and logical (e.g., AND, OR) operations.</p><h4>Register File:</h4><p>Stores operands and results, ensuring fast access compared to accessing memory.</p><h4>Memory Unit:</h4><p>Supports von Neuman’s architecture. Instruction memory handles fetching instructions and Data memory for reading/writing data.</p><h4>Control Unit:</h4><p>Takes opcode as input and generates control signals to direct data flow and operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*SA3vbchBYfw91hOnw9_oog.png" /><figcaption>Functional Units used by each type of instruction in sequence</figcaption></figure><h4>Visualizing the Datapath:</h4><p>A typical single-cycle datapath includes:</p><ol><li><strong><em>Instruction Fetch:</em></strong> Retrieve instruction from memory.</li><li><strong><em>Decode:</em></strong> Identify the instruction type and operands.</li><li><strong><em>Execute:</em></strong> Perform the operation using the ALU.</li><li><strong><em>Memory Access:</em></strong> Load/store data if needed.</li><li><strong><em>Write Back:</em></strong> Save results in the register file.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SSqTixZk5mHpO-y57i8CPA.png" /><figcaption>The complete picture of Single Cycle Datapath (RISC-v)</figcaption></figure><h3>Final Words:</h3><p>RISC’s simplicity and focus on efficiency have made it a cornerstone of modern computer architecture. Its principles influence advanced ISAs like ARM and RISC-V, which power everything from smartphones to servers. Understanding RISC and the single-cycle datapath is just the beginning. For deeper insights, explore concepts like pipelining, multi-cycle datapaths, and out-of-order execution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8277381b87da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why 0.2+0.3 != 0.5? IEEE Standard 754 Floating Point Number]]></title>
            <link>https://medium.com/@hassu20083/why-0-2-0-3-0-5-ieee-standard-754-floating-point-number-fb5e58e386be?source=rss-1376dfe8a7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb5e58e386be</guid>
            <category><![CDATA[binary]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[binary-concept]]></category>
            <category><![CDATA[ieee754]]></category>
            <category><![CDATA[ieee]]></category>
            <dc:creator><![CDATA[Hassu]]></dc:creator>
            <pubDate>Wed, 23 Oct 2024 05:36:31 GMT</pubDate>
            <atom:updated>2024-10-23T06:01:18.494Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why 0.1+0.2 != 0.3? IEEE Standard 754 Floating Point Number</h3><p>Imagine you get this question in your future interview. What would be your answer?</p><pre>if (0.1 + 0.2 == 0.3):<br>    print(&quot;YES&quot;)<br>else:<br>    print(&quot;NO&quot;)</pre><p>If your answer is “YES”, it’s the right time to dive into a floating-point number representation.</p><h3>Table Of Content</h3><blockquote>—<a href="#0025"> What is a Floating-point Number?</a><br> — <a href="#3079">IEEE 754 Floating-Point Number</a><br> — <a href="#17fa">Structure of IEEE 754</a><br> — <a href="#d302">Biased Exponent</a><br> — <a href="#d7d8">How Encoding Works in IEEE-754</a><br> — <a href="#842b">How Decoding Works in IEEE-754</a><br> — <a href="#a4a1">Identification of Ranges</a><br> — <a href="#1356">Interesting Insights from Range</a><br> — <a href="#40ba">Special Numbers</a><br> — <a href="#0a0d">Identification of Problem</a><br> — <a href="#a012">Solution (Denormalized or Subnormal Number)</a><br> — <a href="#49ce">Final words</a></blockquote><h3>1. What is a Floating-point Number?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g2SputbWVRdgBh_glSl_iQ.png" /></figure><p>A floating-point number is a way to represent a real number that can handle a wide range of values — not only integer numbers like 1 &amp; 2 but also the numbers between them.</p><p><strong>For example:</strong> 1.2345 (in decimal) and 1.010101 (fixed-point binary number) are examples of floating-point numbers.</p><h3>2. IEEE 754 Floating-Point Number</h3><p>It is the standard for floating-point number representation and is used in almost every computing system to manipulate real numbers. It has 3 basic components:</p><ul><li><strong>Sign bit: </strong>1 bit used to represent the sign of the number. <em>0 </em>for positive and<em> 1 </em>is used for negative numbers<em>.</em></li><li><strong>Biased Exponent</strong>: Multiple bits used to present a power of 2. The exponent could be positive or negative, but its biased version is always positive.</li><li><strong>Mantissa: </strong>Again multiple bits are used to represent the fractional part of the number.</li></ul><pre>if Number = -1.01010101x2^-23 then<br>sign_bit = 1 (since it&#39;s a negative number)<br>exponent = -23 (biased_exponent depends upon the version of IEEE)<br>mantissa = 01010101</pre><h3>3. Structure of IEEE 754</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*eJwRltR9HVcQxLuvfyollQ.png" /><figcaption><strong>Single Precision (32-bits)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*IxqAJrpXBZHkrtEj_uEY2g.png" /><figcaption><strong>Double Precision (64-bit)</strong></figcaption></figure><h3>4. Biased Exponent</h3><p>If we could present the exponent as 2’s complement (both positive and negative integer) what is the need to make it positive by adding bias? Well, the biased approach offers several advantages,</p><ul><li>Easy to sort. In decimal 1 is greater than -1 but in binary 0b001 &lt; 0b111 (since 1 &lt; 7). We can deal with such anomaly either by using custom comparators (tuned to handle 2’s complement) or by bias approach.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/129/1*FFg9Jo03cznc1KKAqj1YrQ.png" /><figcaption>where k is the number of bits in exponents</figcaption></figure><pre>Bias for Single Precision number = 2^(8-1) - 1 = 127<br>Bias for Double Precision number = 2^(11-1) - 1 = 1023</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*gwGzzecKZWKoF4iCGTkclg.png" /></figure><pre>Number = -1.01010101x2^-23<br>biased_exponent = -23 + 127 = 104 (single precision)<br>biased_exponent = -23 + 1023 = 1000 (double precision)</pre><h3>5. How Encoding Works in IEEE-754</h3><ul><li><strong>Step 1:</strong> Convert the Decimal to Binary</li><li><strong>Step 2:</strong> Normalize the Binary Number. Shifting the floating point to the left until only one bit remains on the left side, let’s say the given binary number is 1010101 → 101010.1x2¹ → 10101.01x2² … → 1.010101x2⁶ is the normalized binary number</li><li><strong>Step 3:</strong> Calculate the Exponent and Apply Bias</li><li><strong>Step 4:</strong> Encode the Sign, Exponent, and Mantissa</li><li><strong>Step 5:</strong> Final IEEE 754 Representation</li></ul><h4>Example</h4><pre>number = 12345<br><strong>Step 1:</strong><br><em>binary</em> = 11000000111001<br><strong>Step 2:</strong><br><em>normalized_binary_number</em> = 1.1000000111001x2^13<br><strong>Step 3:</strong><br><em>exponent</em> = 13<br><em>biased_exponent</em> = 13 + 127 = 140 <br><strong>Step 4:</strong><br><em>sign</em> = 0 (since it is positive)<br><em>biased_exponent</em> = 10001100 (8 bits)<br><em>mantissa</em> = 00000000001000000111001 (23 bits)<br><strong>Step 5:<br></strong><em>The final representation of IEEE 754 Single Precision is given by,<br></em>0 10001100 00000000001000000111001</pre><pre>number = 12.25<br><strong>Step 1:</strong><br><em>binary</em> = 1100.01<br><strong>Step 2:</strong><br><em>normalized_binary_number</em> = 1.10001x2^3<br><strong>Step 3:</strong><br><em>exponent</em> = 3<br><em>biased_exponent</em> = 3 + 127 = 130 <br><strong>Step 4:</strong><br><em>sign</em> = 0 (since it is positive)<br><em>biased_exponent</em> = 10000010(8 bits)<br><em>mantissa</em> = 00000000000000000010001 (23 bits)<br><strong>Step 5:<br></strong><em>The final representation of IEEE 754 Single Precision is given by,<br></em>0 10000010 00000000000000000010001</pre><pre>number = 0.1<br><strong>Step 1:</strong><br><em>binary</em> = 0.0001100110011001100110011001100... (number very close to 0.1)<br><strong>Step 2:</strong><br><em>normalized_binary_number</em> = 1.100110011001100110011001100​x2^-4<br><strong>Step 3:</strong><br><em>exponent</em> = 3<br><em>biased_exponent</em> = -4 + 127 = 123<br><strong>Step 4:</strong><br><em>sign</em> = 0 (since it is positive)<br><em>biased_exponent</em> = 01111011(8 bits)<br><em>mantissa</em> = 10011001100110011001100 (23 bits)<br><strong>Step 5:</strong><br><em>The final representation of IEEE 754 Single Precision is given by,</em><br>0 01111011 10011001100110011001100</pre><h3>6. How Decoding Works in IEEE-754</h3><p>Decoding requires steps to be repeated in the reverse direction, but we could make it easier by given formula,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*G0EL4Mq9im1l9LKYVp2how.png" /><figcaption><strong>here</strong>, (1+mantissa) means (1+0.mantissa)</figcaption></figure><pre>original_number = 0.1<br><strong>Its IEEE representation is given by,</strong><br>0 01111011 10011001100110011001100<br><strong>Here,</strong> <br><em>sign</em> = 0<br><em>biased_exponent</em> = 01111011 = 123<br><em>mantissa</em> = 10011001100110011001100<br><strong>Let&#39;s apply the formula,</strong><br><em>number</em> = ((-1)^0)x(1.10011001100110011001100)x2^(123-127)<br><strong>The final number is given by,</strong><br><em>number</em> = 0.09999999403953552246125 (very close to 0.1)<br><strong>Similarly, </strong><br>0.2 <strong><em>changed to</em></strong> 0.20000000298023223876953125<br>0.3 <strong><em>to</em></strong> 0.300000011920928955078125</pre><blockquote>I hope now you can explain to your interviewer why 0.1 + 0.2 != 0.3, since <strong>0.09999999403953552246125 + 0.20000000298023223876953125 == 0.29999999701976776123046875</strong></blockquote><h3>7. Identification of Ranges</h3><p>You must be thinking of a range of numbers that we can represent with IEEE since this is a curse of a limited number of bits similar to 2’s and 1’s complement but a little bit more complex in terms of intuition.</p><ul><li><strong>Exponent bits</strong>: 8</li><li><strong>Exponent range</strong>: 1 to 254 (0 and 255 are for some special cases)</li></ul><h4>Smallest Positive Number and Largest Negative Number</h4><pre><em>sign</em> = 0 (since it is a positive number)<br><em>mantissa</em> = 0 (since number is smallest positive)<br><em>smallest_exponent</em> = 1<br><strong>Let&#39;s apply the formula,</strong><br><em>number</em> = ((-1)^0)x(1.00000000000000000000000)x2^(1-127)<br><strong>The final number is given by,</strong><br><em>number</em> = 1x2^-126<br><strong>In decimal,</strong><br><em>number</em> = 1.18x10^-38<br><strong>Similarly, largest negative number is given by,</strong><br>number = -1.18x10^-38</pre><h4>Largest Positive Number and Smallest Negative Number</h4><pre><em>sign</em> = 0 (since it is a positive number)<br><em>mantissa</em> = 11111111111111111111111 (since the number is the largest positive)<br><em>largest_exponent</em> = 254<br><strong>Let&#39;s apply the formula,</strong><br><em>number</em> = ((-1)^0)x(1.11111111111111111111111)x2^(254-127)<br><strong>The final number is given by,</strong><br><em>number</em> = (2^128 - 2^104)<br><strong>In decimal,</strong><br><em>number</em> = 3.4x10^38<br><strong>Similarly, the smallest negative number is given by,</strong><br><em>number</em> = -3.4x10^38</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*3VS2E11xQBaTF7uhJpgi-w.png" /><figcaption>range of normalized IEEE-754 single-precision</figcaption></figure><h3>8. Interesting Insights from Range</h3><p>Now you know the 1st smallest number. If I ask you a question, what would be the 2nd smallest number? Yes I know we can simply calculate it with some changes in mantissa.</p><h4>The second Smallest Positive Number</h4><pre><em>sign</em> = 0 (since it is a positive number)<br><em>mantissa</em> = 00000000000000000000001 (since number is 2nd smallest positive)<br><em>smallest_exponent</em> = 1<br><strong>Let&#39;s apply the formula,</strong><br><em>number</em> = ((-1)^0)x(1.00000000000000000000001)x2^(1-127)<br><strong>The final number is given by,</strong><br><em>number</em> = 2^-126 + 2^-149<br><strong>What would be 3rd smallest positive number?</strong><br><em>number</em> = 2^-126 + 2*2^-149</pre><blockquote>Can we conclude that if “a” and “b” are two consecutive numbers then | a — b | must be equal to 2^-149</blockquote><h3>9. Special Numbers</h3><ul><li><strong>Zero: </strong>In IEEE 754 we have two different representations of +0 and -0</li><li><strong>Infinity: </strong>For overflow case, we have positive as well as negative infinity</li><li><strong>Not a Number (NaN): </strong>Numbers that aren’t real numbers, for example, complex numbers, can be represented with Nan</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*Jvb4wl8Cni4weHcgWZWbrQ.png" /></figure><h3>10. Identification of Problem</h3><p>Do you remember the conclusion that we have drawn about two consecutive numbers, at that time we didn’t have any representation of zero, but now since we can represent 0 as well let’s check the validity of the formula,</p><pre><strong>|a-b| == 2^-149</strong><br><em>a</em> = 0<br><em>b</em> = 2^-126<br>|0-2^-126| = 2^-126<br><strong>which is greater that 2^-149<br>Loss of precision near zero</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*IzPSwY1dvaH7H_8pCOSWoA.png" /><figcaption>problem with formula<strong> |a-b| == 2^-149</strong></figcaption></figure><h3>11. Solution (Denormalized or Subnormal Number)</h3><p>Now we need some special type of number to continue the smooth transition from <em>-2^-126 to 0</em> and <em>0 to 2^-126 </em>(between 0 and normalized numbers) and to ensure that our conclusion regarding consecutive numbers holds.</p><h4>Denormalized Number:</h4><p>If the exponent is all zeros <em>( exponent == 0 )</em>, but the mantissa is not <em>( mantissa != 0 )</em> then the value is a denormalized number. This means this number has no assumed leading one before the binary point. For this number, we have a special formula which is given as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*fh0o6mBgfGJMmsDsbLU6Vg.png" /></figure><h4>Smallest Positive Number and Largest Negative Number (Subnormal)</h4><pre><em>sign</em> = 0 (since it is a positive number)<br><em>mantissa</em> = 00000000000000000000001 (since the number is the smallest positive)<br><em>exponent</em> = 0<br><strong>Let&#39;s apply the formula,</strong><br><em>number</em> = ((-1)^0)x(0.00000000000000000000001)x2^(1-127)<br><strong>The final number is given by,</strong><br><em>number</em> = 1x2^-149<br><strong>Similarly, the largest negative number is given by,</strong><br><em>number</em> = -1x2^-149</pre><h4>Largest Positive Number and Smallest Negative Number (Subnormal)</h4><pre><em>sign</em> = 0 (since it is a positive number)<br><em>mantissa</em> = 11111111111111111111111 (since the number is the largest positive)<br><em>exponent</em> = 0<br><strong>Let&#39;s apply the formula,</strong><br><em>number</em> = ((-1)^0)x(0.11111111111111111111111)x2^(1-127)<br><strong>The final number is given by,</strong><br><em>number</em> = (2^-126 - 2^-149)<br><strong>Similarly, the smallest negative number is given by,</strong><br><em>number</em> = -(2^-126 - 2^-149)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*oA6W6NH1-sJ1qMaX_ja1RA.png" /></figure><h3>12. Final Words</h3><p>Congratulations! You can now impress your interviewer with a detailed and accurate explanation. Jokes aside, now there is one question about the drawn conclusion of <strong>|a-b| == 2^-149, </strong>don’t you think this small distance/error is a curse of bits? Yes, it could be reduced by increasing the number of bits but we cannot eliminate this error completely within a conventional binary system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb5e58e386be" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>