How does instruction after Load, execute? - pipeline

There are 5 stages in pipeline.
IF - Instruction fetch
ID - Instruction Decode, read the register
EX - On a memeory reference add up base and offset,
and for arithmetic instruction do the math.
MEM - If load or store access memory
WB - Place the result in appropriate register.
I1 : R0 <- M[loc] IF | ID | EX | MEM | WB |
I2 - R0 <- R0 + R0 | IF | ID | EX | MEM | WB |
I3 - R2 <- R2 - R0 | IF | ID | EX | MEM | WB |
Consider that "Operand Forwarding " has been used.
Solution says :-
Instruction I1 is a Load instruction. So the next instruction ( I2) cannot fetch until I1 finishes its EXE stage.
But I think: in MEM stage, the processor accesses the memory and picks the desired word. And in WB stage it updates Registry of Register.
So until MEM stage the processor holds the control of Memory, so I2 will start fetching after MEM of I1.
Which one is correct?
Description of stages has not been given, it is written as per my knowledge.

Convention:
I denote a generic instruction.
I1, I2, I3, ... denote specific instructions.
S denote a generic stage of the pipeline.
IF, ID, EX, MEM, WB denote a specific stages of the pipeline.
I.S denote the cycle in which the instruction I was in the stage S.
The instruction I2 needs R0 but that register won't be ready from I1 until I1.WB has finished, assuming a basic pipeline.
With operand forwarding present, I2 can read the result while I1 is writing it back into the register file, that is during I1.WB.
Since the operand is read in the ID stage, I2.ID and I1.WB must happen at the same time.
That means that I2.IF must happen at the same time of I1.MEM.
Now you are rightfully dubious about the ability of the CPU to perform two reads (one for the instruction fetching and one for the load) in the same clock.
Very simple CPUs actually stalls on such conflict (in your example the I2.IF would happen at I1.WB).
The simplest approach to avoid a stall is the Harvard architecture, where the CPU fetches instructions from a different memory.
The Harvard architecture has been modified through the use of caches and pre-fetching of data and instructions.
In this context a stall occurs only if both the load and the instruction fetching need to access the memory (and not the caches).
Modern desktop architectures have L1 data cache that can handle more that one access at a time and the CPU is tightly coupled with them so that two or more loads/stores can be executed at the same time, in parallel with loads from L1 instruction cache.
Finally some of the modern CPUs decode more than one instruction at a time, alleviating the problem of the stall (but not eliminating it).
It is the cache that provide the greatest benefit in avoiding stalls though.

Related

Arguing whether a situation leads to data hazard or not

I was going through the section of pipelining from the text Computer Organization [5e] by Hamacher et. al.. There I came across a situation which the authors claim causes data hazard.
The situation is shown below:
For example, stage E in the four-stage pipeline of Figure 8.2b is responsible for arithmetic and logic operations, and one clock cycle is assigned for this task. Although this may be sufficient for most operations, some operations, such as divide, may require more time to complete. Figure 8.3 shows an example in which the operation specified in instruction I2 requires three cycles to complete, from cycle 4 through cycle 6. Thus, in cycles 5 and 6, the Write stage must be told to do nothing, because it has no data to work with. †: Meanwhile, the information in buffer B2 must remain intact until the Execute stage has completed its operation. This means that stage 2 and, in turn, stage 1 are blocked from accepting new instructions because the information in B1 cannot be overwritten. Thus, steps D4 and F5 must be postponed as shown.
... Any condition that causes the pipeline to stall is called a hazard. We have just seen an example of a data hazard. A data hazard is any condition in which either the source or the destination operands of an instruction are not available at the time expected in the pipeline.
In the example above, the authors assume that a data hazard has occurred, and two stall cycles are introduced into the pipeline. The main reason that they give for this data hazard is that, since the execute phase requires 2 more cycles than the usual need for instruction 2, so the data on which the write back stage should work has to wait for 2 cycles...
But I am having a little difficulty in accepting this analysis. Usually, the books give examples of data hazards in situations, where there is data dependency (the usual RAW, WAR, etc..). But here there is no such thing. And I thought this to be a structural hazard assuming that I2 cannot use the EX stage as I1 is using it.
Moreover, the text assumes that there is no queuing of the results of the stages in the buffer. Clear from the statement marked with †, Meanwhile, the information in the buffer..., (where there is a little flaw as well, because, if no queuing is there, then the output of D3 in cycle 4 shall overwrite the value in buffer B2 on which the EX stage is working, a contradiction to their own assumption).
I thought that the stalls are introduced due to this no queuing condition... and structural hazard, and if things are properly managed as shown below, no stalls shall be there.
This is what I assume:
I assume that the execute stage has more than one separate functional units (e.g. one where calculations of instruction 1 are performed. [basic ALU requiring 1 cycle duration], one for integer division, another for integer multiplication etc.) [So structural hazard is out of the way now.]
I also assume that the pipeline buffers can store the results produced in the stages in a queue. [So that the problem in statement marked with † is no longer there.]
This being said, the situation is now as follows:
However hard I tried with the assumptions, I could not remove the bubbles shown in blue. [Even if queuing is assumed in buffers, the buffers cannot give the result out of order, so those stalls remain].
With this exercise of mine, I feel that the example shown in the text is indeed a hazard and that too data hazard (even though there was no data dependencies ?), as in my exercise there was no chance of structural hazard...
Am I correct?
And I thought this to be a structural hazard assuming that I2 cannot use the EX stage as I1 is using it.
Yup, that's the terminology I'd use, based on wikipedia: https://en.wikipedia.org/wiki/Hazard_(computer_architecture).
That article restricts data hazards to only RAW, WAR, and WAW. As such, they're only visible when you consider which operands are being used.
e.g. an independent multiply (result not read by the next few insns) could be allowed to complete out of order, after executing in a separate multi-cycle or pipelined multiplier unit.
Write-back conflicts would be a problem if the slow ALU instruction needed to write a GPR in the same cycle as a later add or something. Also data hazards like WAW, since mul r3, r2, r1 / sw r3, (r4) / add r3, r2, r1 should leave r3 = r2+r1 not r2*r1.
MIPS solved all that with the special hi:lo reg pair for mult/div, allowing the mul and div units to be loosely coupled to the 5-stage pipeline. And the ISA had pretty relaxed rules about what was allowed to happen to those registers, e.g. writing one with mthi r3 destroys the previous value of the other, so mflo r2 would give unpredictable results after mthi. Raymond Chen's article.
An "in-order pipeline" means instructions start execution in program order, no necessarily that they complete in program order. It's very common for modern in-order pipelines to allow memory operations to complete out of order, allowing memory-level parallelism and allowing instruction scheduling to hide load-use latency of L1d cache hits. It's also possible to pipeline higher-latency ALU operations as long as hazards are detected and handled somehow.
Do these authors use the term "structural hazard" at all, or do they consider all (non-control?) hazards to be data hazards?
At this point it seems like primarily a terminology issue. IDK if they're on their own in using terminology this way, or if there is another convention with any popularity other than the one Wikipedia describes.
Separate from your main question, In clock cycles 4 and 5, you have two instructions in the E stage at the same time. If something stalls in the E stage, the stall bubbles need to come before the E stage in later instructions, like in the Fig 8.3 image you linked from the book.
And yeah, it's weird that they talk about the pipeline register between stages needing to stay constant. If a multi-cycle non-pipelined execution unit needs to keep values around, it could snapshot them.
Unless maybe the stall signal makes the Decode stage keep generating that output repeatedly until the stall signal is de-asserted and the pipeline register will finally latch the output of the previous stage instead of ignoring it. There are latches / flip-flops that have a control signal separate from the clock that makes them ignore their input and keep outputting what they were already outputting.

Why is this jump instruction so expensive when performing pointer chasing?

I have a program that performs pointer chasing and I'm trying to optimize the pointer chasing loop as much as possible.
I noticed that perf record detects that ~20% of execution time in function myFunction() is spent executing the jump instruction (used to exit out of the loop after a specific value has been read).
Some things to take note:
the pointer chasing path can comfortably fit in the L1 data cache
using __builtin_expect to avoid the cost of branch misprediction had no noticeable effect
perf record has the following output:
Samples: 153K of event 'cycles', 10000 Hz, Event count (approx.): 35559166926
myFunction /tmp/foobar [Percent: local hits]
Percent│ endbr64
...
80.09 │20: mov (%rdx,%rbx,1),%ebx
0.07 │ add $0x1,%rax
│ cmp $0xffffffff,%ebx
19.84 │ ↑ jne 20
...
I would expect that most of the cycles spent in this loop are used for reading the value from memory, which is confirmed by perf.
I would also expect the remaining cycles to be somewhat evenly spent executing the remaining instructions in the loop. Instead, perf is reporting that a large chunk of the remaining cycles are spent executing the jump.
I suspect that I can better understand these costs by understanding the micro-ops used to execute these instructions, but I'm a bit lost on where to start.
Remember that the cycles event has to pick an instruction to blame, even if both mov-load and the macro-fused cmp-and-branch uops are waiting for the result. It's not a matter of one or the other "costing cycles" while it's running; they're both waiting in parallel. (Modern Microprocessors
A 90-Minute Guide! and https://agner.org/optimize/)
But when the "cycles" event counter overflows, it has to pick one specific instruction to "blame", since you're using statistical-sampling. This is where an inaccurate picture of reality has to be invented by a CPU that has hundreds of uops in flight. Often it's the one waiting for a slow input that gets blamed, I think because it's often the oldest in the ROB or RS and blocking allocation of new uops by the front-end.
The details of exactly which instruction gets picked might tell us something about the internals of the CPU, but only very indirectly. Like perhaps something to do with how it retires groups of 4(?) uops, and this loop has 3, so which uop is oldest when the perf event exception is taken.
The 4:1 split is probably significant for some reason, perhaps because 4+1 = 5 cycle latency of a load with a non-simple addressing mode. (I assume this is an Intel Sandybridge-family CPU, perhaps Skylake-derived?) Like maybe if data arrives from cache on the same cycle as the perf event overflows (and chooses to sample), the mov doesn't get the blame because it can actually execute and get out of the way?
IIRC, BeeOnRope or someone else found experimentally that Skylake CPUs would tend to let the oldest un-retired instruction retire after an exception arrives, at least if it's not a cache miss. In your case, that would be the cmp/jne at the bottom of the loop, which in program order appears before the load at the top of the next iteration.

Understanding STM8 pipelining

I’m trying to understand STM8 pipelining to be able to predict how much cycles my code will need.
I have this example, where I toggle a GPIO pin for 4 cycles each.
Iff loop is aligned at 4byte-boundary + 3, the pin stays active for 5 cycles (i.e. one more than it should). I wonder why?
// Switches port D2, 5 cycles high, 4 cycles low
void main(void)
{
__asm
bset 0x5011, #2 ; output mode
bset 0x5012, #2 ; push-pull
bset 0x5013, #2 ; fast switching
jra _loop
.bndry 4
nop
nop
nop
_loop:
nop
bset 0x500f, #2
nop
nop
nop
bres 0x500f, #2
jra _loop
__endasm;
}
A bit more context:
bset/bres are 4 byte instructions, nop 1 byte.
The nop/bset/bres instructions take 1 cycle each.
The jra instruction takes two cycles. I think in the first cycle, the instruction cache is filled with the next 32bit value, i.e. in this case the nop instruction only. And the 2nd cycle is actually just the CPU being stalled while decoding the next instruction.
So in cycles:
bres clears the pin
jra, pipeline flush, nop fetch
nop decode, bset fetch
nop execute, bset decode, next nop fetch
bset execute sets the pin
nop, bres fetch
nop
nop, bres decode
bres execute clears the pin
According to this, the pin should stay LOW for 4 cycles and HIGH for 4 cycles, but it’s staying HIGH for 5 cycles.
In any other alignment case, the pin is LOW/HIGH for 4 cycles as expected.
I think, if the PIN stays high for an extra cycle that must mean that the execution pipeline is stalled after the bset instruction (the nops thereafter provide enough time to make sure that bres later is ready to execute immediately). But according to my understanding nop (for 6.) would already be fetched in 4.
Any idea how this behavior can be explained? I couldn’t find any hints in the manual.
It is explained in section 5.4, which basically says that throughout the programming manual, "a simplified convention providing a good match with reality" will be used. From my experience, this simplified convention is indeed a good approximate for a longer sequence, but unusable for exact per-instruction timing, even if you're working on assembly level and control alignment. Take "SLA addr" as an example. It is documented to use 1 cycle. Put three of them in sequence to implement the C equivalent of "*(addr) << 3", and you'll clock up 5-6 cycles.
Actual cycles used for decoding and execution are undocumented. Apart from the obvious reasons, there is no comprehensive documentation about what causes pipeline stalls. I was able to get some insight into this by configuring TIM2 with a prescaler of /1 and reload values of 0xFFFF while using ST-LINK/V2 to step through my code. You can then keep a watch on TIM2_CNTRL to see cycles consumed (== the aggregate value of executing the previous and decoding the current instruction).
Things to keep an eye on are obviously instructions spanning 32-bit boundaries. There were also cases where loading instructions from the next 32-bit word caused an unexpected additional cycle in a sequence of NOPs, suggesting that any fetch (even if not necessary for the current or next instruction) costs 1 cycle? I've seen CALLs to targets aligned to 32 bit boundaries taking 4-7 cycles, suggesting that the CPU was still busy executing the previous instruction or stalling the call for unknown reason. Modifying the SP (push/pop or direct add/sub) seems to be causing stalls under certain conditions.
Any additional insight appreciated!

Pipeline and branch instructions

Lets suppose that 20 percent of the instructions in a program are branch instructions.The static prediction of the jumps supposes that the jumps don't happen.
I should find the execution time in two cases : When 30 percent of the branches happen and when 70 percent of the branches happen
I also should find the speedup of one case compared to the other and express it in percentage.
Thing is,how do I find the execution time here ? I usually find the execution time where the pipeline is separated in different phases and there is given the time for each phase ....
Edit : This is NOT homework.I found this in my computer architecture textbook and its not a familiar exercise.
This question sounds like homework but the matter is worth some discussion.
We assume to have a static branch predictor that always predicts NOT TAKEN. This was the type of branch predictor of early SPARC and MIPS implementations. Such a branch predictor always fetches the next sequential instruction in the program.
Let me also assume that we have a simplified 4 stage pipeline made of Fetch (F), Decode (D), Execute (E) and Write Back (W). Consider the following simplified assembly program:
...
0xF1: JUMP <condition>, 0xF4
0xF2: ADD r1, r2, r3
0xF3: ADD r3, r4, r1
0xF4: ADD r1, r2, r3
When a branch is correctly predicted the pipeline behaves normally. The question is what happens to the pipeline when a branch is mis-predicted. Which in our case corresponds to the case when the condition of the JUMP instruction (0xF1) is verified.
0xF1: F D E W
0xF2: F D X
0xF3: F X
0xF4: F
cycle 1 2 3 4
In the Execute stage of the JUMP instruction we evaluate the condition and detect that the branch has to be taken. Due to the branch predictor policy, however, we already fetched instructions 0xF2 and 0xF3 and decoded 0xF2. The pipeline is flushed and at the next clock cycle the branch target is correctly fetched. As you can see from the pipeline we wasted 2 clock cycles fetching and decoding instructions that will not be executed. This 2 clock cycles are known as branch penalties and you must take them into account when calculating the program's execution time.
The world of branch predictors is much more complex in reality. More elaborated static branch predictors exist that, for instance, always predict as TAKEN a forward jump and as NOT TAKEN backward ones. To reduce the branch penalty cycles processors often employ a Branch Target Buffer (BTB) that is a small cache that stores the target of recently executed JUMP instructions. Without a BTB, to predict a branch as TAKEN we have to wait until the Decode stage, where the instruction is identified as a JUMP and the target address is decoded. In the meantime we have fetched an instruction that will then be flushed. With a BTB, on the other hand, we can do branch prediction in the Fetch stage: if the Program Counter is in the BTB we know 2 that
The fetched instruction is a branch
We have its target address
So if can predict the branch and if predicted as TAKEN we can fetch its target without any penalty.
Modern processors also adopt dynamic branch predictors that use complex policies as well as some additional buffers to avoid mis-predictions.

pipeline stalling and bypassing examples

I am taking a course on Computer Architecture. I found this website from another University which has notes and videos which are helping me thus far: CS6810, Univ of Utah. I am working through these series of notes but am in need of some explanation on some of the example problems. I am currently looking at Problem 7, on page 17-18. The solutions are given in the notes on page 18 but I am somewhat unsure of how the professor is reaching the conclusions. He states on his class webpage that he does not provide solutions to anything, so that is out of the picture.
For those that cannot view the pdf, the problem is as follows:
Consider an 8-stage pipeline where Register Read (RR) and Register Write (RW) take a full cycle. Key: Instruction Fetch = IF, Decode = DE, ALU = AL, Data Memory = DM, Latch # = L#
L1-->IF-->L2-->DE-->L3-->RR-->L4-->AL-->L5-->AL-->L6-->DM-->L7-->DM-->L8-->RR-->L9
Given the following series of instructions, determine the number of stalls for the 2nd instruction, with and without bypassing
ADD R1 + R2 -> R3, ADD R3 + R4 -> R5 : without bypassing 5, with bypassing 1
LD[R1] -> R2, ADD R2 + R3 -> R4 : without bypassing 5, with bypassing 3
LD[R1] -> R2, SD[R2] -> R3 : without bypassing 5, with bypassing 3
LD[R1] -> R2, SD[R3] -> R2 : without bypassing 5, with bypassing 1
I understand how each of them will generate 5 stalls without bypassing, and I understand how the first one will only generate 1 stall with bypassing, but I am uncertain of how the stalls with bypassing are generated with 2-4.
Any help would be appreciated.
edit (for further clarification, my understanding of how the cases would look):
ST = Stall, latches are implied
1.
IF-->DE-->RR-->AL-->AL-->DM-->DM-->RW
IF-->DE-->ST-->ST-->ST-->ST-->ST-->RR-->AL-->AL-->DM-->DM-->RW (without)
IF-->DE-->RR-->ST-->AL-->AL-->DM-->DM-->RW (with)
Without bypassing, I2 stalls before entering RR and has to wait until R3 is written before it can enter RR; this understanding is universal amongst all the cases. With bypassing, I2 can enter RR but stalls until the arithmetic is done by I1, which is after the second ALU stage.
2.
IF-->DE-->RR-->AL-->AL-->DM-->DM-->RW
IF-->DE-->ST-->ST-->ST-->ST-->ST-->RR-->AL-->AL-->DM-->DM-->RW (without)
IF-->DE-->RR-->ST-->ST-->ST-->AL-->AL-->DM-->DM-->RW (with)
With bypassing, I2 can enter RR but must wait until R2 processed and this occurs after the second DM stage of I1.
3.
IF-->DE-->RR-->AL-->AL-->DM-->DM-->RW
IF-->DE-->ST-->ST-->ST-->ST-->ST-->RR-->AL-->AL-->DM-->DM-->RW (without)
IF-->DE-->RR-->ST-->ST-->ST-->AL-->AL-->DM-->DM-->RW (with)
With bypassing, I2 can enter RR but must wait until R2 is processed and this occurs after the second DM stage of I1.
4.
IF-->DE-->RR-->AL-->AL-->DM-->DM-->RW
IF-->DE-->ST-->ST-->ST-->ST-->ST-->RR-->AL-->AL-->DM-->DM-->RW (without)
IF-->DE-->RR-->AL-->AL-->ST-->DM-->DM-->RW (with)
With bypassing, I2 can continue along the pipeline until the second ALU stage and it must wait here until it can pull R2, which isn't processed by I1 until after its second DM stage.
And one more, just to make sure I understand everything:
I1: R1+R2-->R3, I2: SD[R4]<--R3
IF-->DE-->RR-->AL-->AL-->DM-->DM-->RW
IF-->DE-->ST-->ST-->ST-->ST-->ST-->RR-->AL-->AL-->DM-->DM-->RW (without)
IF-->DE-->RR-->AL-->AL-->DM-->DM-->RW (with)
It is my understanding that without bypassing, it would stall in the same place for the same number of stalls (5). With bypassing, however, there would be 0 stalls because I2 would use the ALU stages to calculate the register address and when it came time to make the store, it could take the information from the 2nd ALU stage in I1.
The stalls in cases 2 and 3 come from the second instruction depending in its first ALU stage on the result of the load in the previous instruction (which is not available until after the second Data Memory stage, so the stall if for the earlier instruction's second ALU stage and the two Data Memory stages). (L8 of the first instruction lines up with L4 of the second.)
L1-->IF-->L2-->DE-->L3-->RR-->L4-->AL-->L5-->AL-->L6-->DM-->L7-->DM-->L8-->RW-->L9
L1-->IF-->L2-->DE-->L3-->RR-->STALL---->STALL---->STALL---->L4-->AL-->L5-->AL-->L6-->DM-->L7-->DM-->L8-->RW-->L9
For case 4, the value stored in memory by the second instruction is (presumably) not needed until the first Data Memory stage and the address generation part of the second instruction has no dependency on the first instruction. (L8 of the first instruction lines up with L6 of the second.)
L1-->IF-->L2-->DE-->L3-->RR-->L4-->AL-->L5-->AL-->L6-->DM-->L7-->DM-->L8-->RW-->L9
L1-->IF-->L2-->DE-->L3-->RR-->L4-->AL-->L5-->AL-->STALL---->L6-->DM-->L7-->DM-->L8-->RW-->L9
(Since the writing to memory is a commitment of architectural state similar to writing the register, it might be more typical for a pipeline not to require the stored value until the RW stage.)
Without bypassing all register source operands are retrieved from the register file in the Register Read stage. Since a new value is written to the register file in the Register Write stage, without bypassing the given 8-stage pipeline will require 5 cycles of stall for such dependent cases.
L1-->IF-->L2-->DE-->L3-->RR-->L4-->AL-->L5-->AL-->L6-->DM-->L7-->DM-->L8-->RW-->L9
L1-->IF-->L2-->DE-->STALL---->STALL---->STALL---->STALL---->STALL---->L3-->RR-->L4-->AL-->L5-->AL-->L6-->DM-->L7-->DM-->L8-->RW-->L9
With bypassing, a dependent value can be communicated from the earliest stage it is available (the end of the second ALU stage for arithmetic instructions, the end of the second Data Memory stage for load instructions)--rather than the Register Write stage--to the earliest stage of the dependent instruction in which the value is needed (before the ALU stages for arithmetic instructions and address computation, before the Data Memory stages for stores if stores require the stored value early as seems to be the case in this pipeline)--rather than the Register Read stage.
(Aside: Some pipelines perform the register write in the first half of the cycle and the register read in the second half of the cycle. Not only can this reduce the number of access ports needed for the register file, but it also allows values to be available from the register file one cycle earlier since the read of a newly written value can occur in the later half of the same cycle as the write. This reduces the amount of bypassing needed.)

Resources