How to Optimize for the Pentium Family of MicroProcessors
Copyright © 1996, 2000 by Agner Fog. Last Modified 2000-07-03.
Contents
Introduction Literature Calling assembly functions from high level language Debugging and verifying Memory model Alignment Cache First time versus repeated execution Address generation interlock (PPlain and PMMX) Pairing integer instructions (PPlain and PMMX)
Perfect pairing Imperfect pairing Splitting complex instructions into simpler ones (PPlain and PMMX) Prefixes (PPlain and PMMX) Overview of PPro, PII and PIII pipeline Instruction decoding (PPro, PII and PIII) Instruction fetch (PPro, PII and PIII) Register renaming ( PPRO, PII and PIII)
Eliminating Dependencies Register Read Stalls Out of Order Execution (PPRO, PII AND PIII) Retirement (PPRO, PII AND PIII) Partial Stalls (PPRO, PII and PIII)
Partial register stalls Partial flags stalls Flags stalls after shifts and rotates Partial memory stalls Dependency chains (PPro, PII and PIII) Searching for bottlenecks (PPro, PII and PIII) Jumps and branches (all processors)
Branch prediction in PPlain Branch prediction in PMMX, PPro, PII and PIII Avoiding jumps (all processors) Avoiding conditional jumps by using flags (all processors) Replacing conditional jumps by conditional moves (PPro, PII and PIII) Reducing code size (all processors) Scheduling floating point code (PPLAIN AND PMMX) Loop Optimization (All Processors)
LOOPS in Pplain and Pmmx Loops in PPRO, PII AND PIII PROBLEMATIC INSTRUCTIONS
XCHG (all processors) Rotates through carry (all processors) String instructions (all processors) Bit test (all processors) Integer multiplication (all processors) WAIT instruction (all processors) FCOM FSTSW AX (all processors) FPREM (all processors) FRNDINT (all processors) FSCALE and exponential function (all processors) FPTAN (all processors) FSQRT (PIII) MOV [MEM], ACCUM (PPlain and PMMX) TEST instruction (PPlain and PMMX) Bit scan (PPlain and PMMX) FLDCW (PPro, PII and PIII) Special topicsLEA instruction (all processors) Division (all processors) Freeing floating point registers (all processors) Transitions between floating point and MMX instructions PMMX, PII and PIII) Converting from floating point to integer (All processors) Using integer instructions to do floating point operations (All processors) Using floating point instructions to do integer operations (PPlain and PMMX) Moving blocks of data (All processors) Self-modifying code (All processors) Detecting processor type (All processors) list of instruction Timings for PPLAIN AND PMMX
Integer INSTRUCTIONS FLOATING POINT INSTRUCTIONS MMX INSTRUCTIONS (PMMX) List of instruction Timings and Micro-Op Breakdown for PPRO, PII AND PIII
INTEGER INSTRUCTIONS FLOATING POINT INSTRUCTIONS MMX Instructions (PII and PIII) XMM Instructions (PIII) Testing Speed Comparison of The Different Microprocessors
INTRODUCTION
This Manual Describes in detail how to write Optimized Assembly Language Code, with Particular Focus on the Pentium® Family of Microprocessors.
Most of the information herein is based on my own research. Many people have sent me useful information and corrections for this manual, and I keep updating it whenever I have new important information. This manual is therefore more accurate, detailed, comprehensive and exact than any other source of information, and it contains many details not found anywhere else. This information will enable you in many cases to calculate exactly how many clock cycles a piece of code will take. I do not claim, though, that all information in this manual is exact: Some timings etc. can be difficult or impossible to measure exactly, and I do not have access to the inside information on technical implementations that the writers of Intel manuals have.The following versions of Pentium processors are discussed in this manual:
AbbreviationNamepplainPlain Old Pentium (WITHOUT MMX) PMMXPENTIUM WITH MMXPROPENTIUM PROPIIPENTIUM II (Including Celeron and Xeon) PiiIpendium III (Including Variants)
The assembly language syntax used in this manual is MASM 5.10 syntax. There is no official standard for X86 assembly language, but this is the closest you can get to a de facto standard since most assemblers have a MASM 5.10 compatible mode. (I do not Recommend Using Masm Version 5.10 Though, Because IT Has A Serious Bug in 32 bit mode. Use tasm or a later version of masm).
Some of the remarks in this manual may seem like a criticism of Intel. This should not be taken to mean that other brands are better. The Pentium family of microprocessors compare well with competing brands, they are better documented, and have better testability features. For these reasons, no competing brand has been subjected to the same level of independent research by me or by anybody else.Programming in assembly language is much more difficult than high level language. Making bugs is very easy, and finding them is very difficult. Now you have been warned! It is assumed that the reader is already experienced in assembly programming. If not, then please read some books on the subject and get some programming experience before you begin to do complicated optimizations.
The hardware design of the PPlain and PMMX chips has many features which are optimized specifically for some commonly used instructions or instruction combinations, rather than using general optimization methods. Consequently, the rules for optimizing software for this design are complicated and have many exceptions, but the possible gain in performance may be substantial. The PPro, PII and PIII processors have a very different design where the processor takes care of much of the optimization work by executing instructions out of order, but the more complicated design of these processors generate many potential bottlenecks, so there may be a lot to gain by optimizing manually for these processors The Pentium 4 processor has yet another design, and the optimization guidelines for Pentium 4 are quite different from previous versions This manual does not cover the Pentium 4 -.. the Reader is refered to manuals from intel.
Before you start to convert your code to assembly, make sure that your algorithm is optimal. Often you can improve a piece of code much more by improving the algorithm than by converting it to assembly code.Next, you have to identify the critical parts of your program. Often more than 99% of the CPU time is spent in the innermost loop of a program. in this case you should optimize only this loop and leave everything else in high level language. Some assembly programmers waste a lot of energy optimizing the Wrong Parts of Their Programs, The Only Significant Effect of Their Effort Being That The Programs Become More Difficult To Debug and Maintain!
If it is not obvious where the critical parts of your program are then you may use a profiler to find them. If it turns out that the bottleneck is disk access, then you may modify your program to make disk access sequential in order to improve disk .
Some High Level Language Compilers Offer Relative, Good Optimization for Specific Processors, But Further Optimization by Hand CAN Usually Make It Much Better.
Please don't send Your Programming Questions to me. I am Not Gonna Do Your HomeWork for you!
Good luck with your hunt for nanoseconds!
2. LitrateuRe
A lot of useful literature and tutorials can be downloaded for free from Intel's www site or acquired in print or on CD-ROM. It is recommended that you study this literature in order to get acquainted with the microprocessor architecture. However, the documents from Intel are not always accurate -. especially the tutorials have many errors (evidently, they have not tested their own examples) .I will not give the URL's here because the file locations change very often you can find the documents you need by using the search Facilities at: developer.intel.com or folow the links from www.agner.org/assem
Some Documents Are IN .pdf format. If you don't have.com www.adobe.com www.adobe.com
The use of mmx and xmm (simd) instructions for Optimizing Specific Applications Are Described in Several Application Notes. The instruction set is described in Various Manuals and Tutorials.
VTune Is A Software Tool from Intel for Optimizing Code. I have not test it and can there ip at the IT Here.
A Lot of Other Sources Than Intel Also Have Useful Information. Thase Sources Are Listed In The Faq for the newsGroup Comp.lang.asm.x86. For other Internet restources Follow the links from www.agner.org/assem
3. Calling assembly functions from High Level Language
You can either use inline assembly or code a subroutine entirely in assembly language and link it into your project. If you choose the latter option, then it is recommended that you use a compiler which is capable of translating high level code directly to assembly. This Assouting Method Right. MOST C Compilers Can do this.
The way of transferring parameters depends on the calling convention: calling convention parameter order on stack parameters removed by _cdecl first par at low address caller _stdcall first par at low address subroutine _fastcall compiler specific subroutine _pascal first par at high address subroutine...
The methods for function calling and name mangling can be quite complicated. There are many different calling conventions, and the different brands of compilers are not compatible in this respect. If you are calling assembly language subroutines from C , then the best method in terms of consistency and compatibility is to declare your functions extern "C" and _cdecl The assembly code must then have the function name prefixed by an underscore (_) and be assembled with case sensitivity on externals (option -mx) Example..:
; extern "c" INT _CDECL Square (int X);
_SQUARE PROC NEAR; Integer Square Function
Public _square
MOV EAX, [ESP 4]
Imul EAX
RET
_SQUARE ENDP
If you need to make overloaded functions, overloaded operators, methods, and other C specialties then you have to code it in C first and make your compiler translate it to assembly in order to get the right linking information and calling method. These details are different for different brands of compilers and seldom documented. If you want an assembly function with any other calling method than extern "C" and _cdecl to be callable from code compiled with different compilers then you need to give it one public name for each compiler. for Example An Overloaded Square Function:
INT Square (int X);
Square_i proc Near; Integer Square FUNCTION
@ Square $ qi Label Near; Link Name for Borland Compiler? Square @@ yahh @ z label Near; Link Name for Microsoft Compiler
_SQUARE__FI Label Near; Link Name for GNU Compiler
Public @ Square $ qi,? Square @@ yahh @ z, _square__fi
MOV EAX, [ESP 4]
Imul EAX
RET
Square_i endp
Double Square (double x);
Square_d proc Near; Double Precision Float Square Function
@ Square $ qd Label Near; Link Name for Borland Compiler
? Square @@ yann @ z Label Near; Link Name for Microsoft Compiler
_SQUARE__FD Label Near; Link Name for GNU Compiler
Public @ Square $ qd,? Square @@ yann @ z, _square__fd
FLD Qword PTR [ESP 4]
Fmul St (0), ST (0)
RET
Square_d endp
This method works because all these compilers use the _cdecl calling convention by default for overloaded functions. For methods (member functions), however, not even the calling convention is the same for all compilers (Borland and Gnu compilers use _cdecl convention with the 'this 'Pointer First, Microsoft Uses The_stdcall convention with the' this' Pointer IN ECX).
In general, you should not expect different compilers to be compatible on the object file level if you are using any of these constructs: long double, member pointers, virtual methods, new, delete, exceptions, system function calls, or standard library functions .
Register USAGE IN 16 Bit Mode Dos or Windows, C or C : 16-Bit Return Value In DX: AX: AX, FLOATING POINT RETURN VALUE IN ST (0). Registers AX, BX, CX, DX , ES and arithmetic flags may be changed by the procedure; all other registers must be saved and restored A procedure can rely on SI, DI, BP, DS and SS being unchanged across a call to another procedure.Register usage in 32 bit Windows. , C and other programming languages:.. Integer return value in EAX, floating point return value in ST (0) Registers EAX, ECX, EDX (not EBX) may be changed by the procedure; all other registers must be saved and restored Segment registers can not be changed, not even temporarily. CS, DS, ES, and SS all point to the flat segment group. FS is used by the operating system. GS is unused, but reserved. Flags may be changed by the procedure with the following Restrictions: The Direction Flag IS 0 by Default. The Direction Flag May Be set Temporarily, But Must Be Cleared Before Any Call OR return. The interrupt flag can not be cleared. The floating point register stack is empty at the entry of a procedure and must be empty at return, except for ST (0) if it is used for return value. MMX registers may be changed by the procedure and if so cleared by EMMS before returning and before calling any other procedure that may use floating point registers. All XMM registers may be modified by procedures. Rules for passing parameters and return values in XMM registers are described in Intel's application note AP 589. A Procedure Can Rely ON EBX, ESI, EDI, EBP AND All Segment Registers Being Unchanged Across A Call To Another Procedure.
4. Debugging and verifying
Debugging assembly code can be quite hard and frustrating, as you probably already have discovered. I would recommend that you start with writing the piece of code you want to optimize as a subroutine in a high level language. Next, write a test program that will test your subroutine thoroughly. Make sure the test program goes into all branches and boundary cases.When your high level language subroutine works with your test program then you are ready to translate the code to assembly language.
Now you can start to optimize. Each time you have made a modification you should run it on the test program to see if it works correctly. Number all your versions and save them so that you can go back and test them again in case you discover An Error That The Test Program Didn't Catch (SUCH AS WRITIG TO A WRONG Address).
Test the speed of the most critical part of your program with the method described in chapter 30 or with a test program If the code is significantly slower than expected, then the most probable causes are:. Cache misses (chapter 7), misaligned operands ( Chapter 6), First Time Penalty (Chapter 8), Branch Mispredictions (Chapter 22), Instruction Fetch Problems (Chapter 15), Register Read Stalls (16), or Long Dependency Chains (Chapter 20).
Highly optimized code tends to be very difficult to read and understand for others, and even for yourself when you get back to it after some time. In order to make it possible to maintain the code it is important that you organize it into small logical units (Procedures or Macros) with a well-defined interface and appropriate Comments. The More complicated the code is to read, The more important is a good documentation.
5. Memory Model
The Pentiums are designed primarily for 32 bit code, and the performance is inferior on 16 bit code. Segmenting your code and data also degrades performance significantly, so you should generally prefer 32 bit flat mode, and an operating system which supports this mode. The Code Examples Shown in this Manual Assumeth A 32 Bit Flat Memory Model, UNSS OtherWise Specified.6. Alignment
All Data in Ram Should Be Aligned to Addresses Divisible By 2, 4, 8, or 16 According to this scheme:
Alignment Operand Size PPLAIN AND PMMX PPRO, PII AND PIII 1 (Byte) 11 2 (Word) 22 4 (DWORD) 44 6 (FWORD) 48 8 (qword) 88 10 (TBYTE) 816 16 (OWORD) N.A.16
ON PPLAIN AND PMMX, Misaligned Data Will Take At Least 3 Clock Cycles Extra To Access IF A 4 byte Boundary Is Crossed. The Penalty Is Higher When a Cache Line Boundary is crossed.
ON PPRO, PII AND PIII, MISALIGNED DATA WILL COSTYO 6-12 Clocks Extra When a cache line boundary is crossed. Misaligned Operands Smaller Than 16 Bytes That Do Not Cross A 32 byte Boundary Give No Penalty.
Aligning Data By 8 or 16 on a dword size stack may be a problem. A common method is to set up an aligned frame pointer. A Function with aligned local Data May Look Like this:
_FuncWithalign Proc Near
Push EBP; ProLog Code
MOV EBP, ESP
And EBP, -8; Align Frame Pointer by 8
FLD DWORD PTR [ESP 8]; Function Parameter
Sub ESP, Localspace 4; Allocate Local Space
FSTP QWORD PTR [ebp-localspace]; Store Something in Aligned Space
...
Add ESP, LocalSpace 4; Epilog Code. Restore ESP
POP EBP; (AGI Stall on PPLAIN / PMMX)
RET
_Funcwithalign endp
While Aligning Data IS ALWAYS IMPORTANT, Aligning Code Is Not Necessary on the PPLAIN AND PMMX. Principles for Aligning Code on PPRO, PII AND PIII Are Explained in Chapter 15.7. Cache
THE PPLAIN AND PPRO HAVE 8 KB OF ON-Chip Cache (Level One Cache) for Code, AND 8 KB for Data. The PMMX, PII AND PIII HAVE 16 KB for Code and 16 KB for Data. Data in The Level 1 Cache CAN Be Read Or Written to In Just One Clock Cycle, WHEREAS A Cache Miss May Cost Many Clock Cycles. It is the the cache works in Order to Use it..
The data cache consists of 256 or 512 lines of 32 bytes each. Each time you read a data item which is not cached, the processor will read an entire cache line from memory. The cache lines are always aligned to a physical address divisible by 32 . When you have read a byte at an address divisible by 32, then the next 31 bytes can be read or written to at almost no extra cost. you can take advantage of this by arranging data items which are used near each other together into aligned blocks of 32 bytes of memory. If, for example, you have a loop which accesses two arrays, then you may interleave the two arrays into one array of structures, so that data which are used together are also stored together.
If The size of an array or other data structure is a multiple of 32 bytes, the you will preformed Align IT by 32.
The cache is set-associative. This means that a cache line can not be assigned to an arbitrary memory address. Each cache line has a 7-bit set-value which must match bits 5 through 11 of the physical RAM address (bit 0- 4 define the 32 bytes within a cache line). The PPlain and PPro have two cache lines for each of the 128 set-values, so there are two possible cache lines to assign to any RAM address. The PMMX, PII and PIII have four .The consequence of this is that the cache can hold no more than two or four different data blocks which have the same value in bits 5-11 of the address. You can determine if two addresses have the same set-value by the following method : Strip Off The Lower 5 Bits of Each Address To Get A Value Divisible by 32. IF The Difference Between The Two Truncated Addresses IS A Multiple Of 4096 (= 1000H), THE Addresses Have The Same Set-Value.
Let me illustrate this by the folowing piece of code, where esi holds an address divisible by 32:
Again: MOV EAX, [ESI]
MOV EBX, [ESI 13 * 4096 4]
MOV ECX, [ESI 20 * 4096 28]
Dec edx
Jnz Again
The three addresses used here all have the same set-value because the differences between the truncated addresses are multipla of 4096. This loop will perform very poorly on the PPlain and PPro. At the time you read ECX there is no free cache line with the Proper set-value so the processor takes the least all Was, That Is The One Which Was Used for Eax, And Fills It With The Data from [ESI 20 * 4096] To [ESI 20 * 4096 31] and reads ECX. Next, when reading EAX, you find that the cache line that held the value for EAX has now been discarded, so you take the least recently used line, which is the one holding the EBX value, and so ON .. You Have Nothing But Cache Misses and The Loop Takes Something Like 60 Clock Cycles. If The Third Line Is Changd To: Mov ECX, [ESI 20 * 4096 32]
then we have crossed a 32 byte boundary, so that we do not have the same set-value as in the first two lines, and there will be no problem assigning a cache line to each of the three addresses. The loop now takes only 3 clock cycles (except for the first time) -! a very considerable improvement As already mentioned, the PMMX, PII and PIII have 4-way caches so that you have four cache lines with the same set-value (Some Intel documents erroneously say. That the PII Cache IS 2-WAY).
It may be very difficult to determine if your data addresses have the same set-values, especially if they are scattered around in different segments. The best thing you can do to avoid problems of this kind is to keep all data used in the critical part or your program within one contiguous block not bigger than the cache, or two contiguous blocks no bigger than half that size (for example one block for static data and another block for data on the stack). This will make sure that your cache lines are used optimally.If the critical part of your code accesses big data structures or random data addresses, then you may want to keep all frequently used variables (counters, pointers, control variables, etc.) within a single contiguous block of max 4 kbytes so that you have a complete set of cache lines free for accessing random data. Since you probably need stack space anyway for subroutine parameters and return addresses, the best thing is to copy all frequently used static data to dynamic Variables on the stack, and copy the..
Reading a data item which is not in the level one cache causes an entire cache line to be filled from the level two cache, which takes approximately 200 ns (that is 20 clocks on a 100 MHz system or 40 clocks on a 200 MHz system) , but the bytes you ask for first 40-100 ns. if the data item is not in The Level Two Cache Either, The Level Get a Delay of Something Like 200-300 NS. this delay Will Be Somewhat Longer IF you cross A DRAM Page Boundary. (The Size of A DRAM Page IS 1 KB for 4 AND 8 MB 72 PIN RAM MODULES, AND 2 KB FOR 16 and 32 MB MODULES).
When reading big blocks of data from memory, the speed is limited by the time it takes to fill cache lines You can sometimes improve speed by reading data in a non-sequential order:. Before you finish reading data from one cache line start reading the first item from the next cache line This method can increase reading speed by 20 -.. 40% when reading from main memory or level 2 cache on PPlain and PMMX, and from level 2 cache on PPro, PII and PIII A disadvantage of this method is of course that the program code becomes extremely clumsy and complicated. For further information on this trick see www.intelligentfirm.com.When you write to an address which is not in the level 1 cache, then the value will go right through to the level 2 cache or to the RAM (depending on how the level 2 cache is set up) on the PPlain and PMMX. This takes approximately 100 ns. If you write eight or more times to the same 32 byte block of memory without also reading from IT, And The Block is Not in The Level O ne cache, then it may be advantageous to make a dummy read from the block first to load it into a cache line. All subsequent writes to the same block will then go to the cache instead, which takes only one clock cycle. On PPlain and Pmmx, There is Sometimes A Small Penalty for Writing Repeatedly To The Same Address WITHOUTETING IN BETWEEN.
On PPro, PII and PIII, a write miss will normally load a cache line, but it is possible to setup an area of memory to perform differently, for example video RAM (See Pentium Pro Family Developer's Manual, vol 3:. Operating System Writer's ").
Other Ways of Speeding Up Memory Reads and Writes Are Discussed in Chapter 27.8 Below.
The PPlain and PPro have two write buffers, PMMX, PII and PIII have four. On the PMMX, PII and PIII you may have up to four unfinished writes to uncached memory without delaying the subsequent instructions. Each write buffer can handle operands up to 64 bits wide.Temporary data may conveniently be stored on the stack because the stack area is very likely to be in the cache. However, you should be aware of the alignment problems if your data elements are bigger than the stack word size.
If the life ranges of two data structures do not overlap, then they may share the same RAM area to increase cache efficiency. This is consistent with the common practice of allocating space for temporary variables on the stack.
Storing temporary data in registers is of course even more efficient. Since registers is a scarce ressource you may want to use [ESP] rather than [EBP] for addressing data on the stack, in order to free EBP for other purposes. Just don ' t forget that the value of ESP changes every time you do a PUSH or POP. (you can not use ESP under 16-bit Windows because the timer interrupt will modify the high word of ESP at unpredictable places in your code.)
There is a separate cache for code, which is similar to the data cache. The size of the code cache is 8 kb on PPlain and PPro and 16 kb on the PMMX, PII and PIII. It is important that the critical part of your code (the innermost loops) fit in the code cache. Frequently used pieces of code or routines which are used together should preferable be stored near each other. Seldom used branches or procedures should be put away in the bottom of your code or somewhere else.
8. First Time Versus REPEATED EXECUTION
A piece of code usually takes much more time the first time it is executed than when it is repeated The reasons are the following:. Loading the code from RAM into the cache takes longer time than executing it Any data accessed by the code has to. be loaded into the cache, which may take much more time than executing the instructions. When the code is repeated then the data are more likely to be in the cache. Jump instructions will not be in the branch target buffer the first time they execute, and therefore are less likely to be predicted correctly. See chapter 22. In the PPlain, decoding the code is a bottleneck. If it takes one clock cycle to determine the length of an instruction, then it is not possible to decode two instructions per clock cycle, because the processor does not know where the second instruction begins. The PPlain solves this problem by remembering the length of any instruction which has remained in the cache since last time it was executed. As a consequence of this, a set of instructions will not pair in the PPlain the first time they are executed, unless the first of the two instructions is only one byte long. The PMMX, PPro, PII and PIII have no penalty on first time decoding.
Fors the Subsequent Times.
If you have a big loop which does not fit into the code cache then you will get penalties all the time because it does not run from the cache. You should therefore try to reorganize the loop to make it fit into the cache.
IF you have very much one jumps, calls, and branches inside a loop, the you get the pen point the branch target buffer miss.
Likewise, IF a loop refeatedly acfor
It takes one clock cycle to calculate the address needed by an instruction which accesses memory. Normally, this calculation is done at a separate stage in the pipeline while the preceding instruction or instruction pair is executing. But if the address depends on the result of an instruction executing in the preceding clock cycle, then you have to wait an extra clock cycle for the address to be calculated This is called an AGI stall Example:.. ADD EBX, 4 / MOV EAX, [EBX]; AGI stall The stall in This Example Can Be Removed by Putting Some Other Instructions in Between Add Ebx, 4 and Mov EX, [EBX] or by ReWriting The Code To: MOV EAX, [EBX 4] / Add EBX, 4
You can also get an AGI stall with instructions which use ESP implicitly for addressing, such as PUSH, POP, CALL, and RET, if ESP has been changed in the preceding clock cycle by instructions such as MOV, ADD, or SUB. The PPlain and PMMX have special circuitry to predict the value of ESP after a stack operation so that you do not get an AGI delay after changing ESP with PUSH, POP, or CALL. you can get an AGI stall after RET only if it has an immediate operand To Add to ESP.
EXAMPLES:
Add ESP, 4 / POP ESI; AGI STALL
POP Eax / Pop ESI; No Stall, Pair
MOV ESP, EBP / RET; AGI Stall
Call L1 / L1: MOV Eax, [ESP 8]; No Stall
RET / POP EAX; No Stall
RET 8 / POP EAX; AGI Stall
The Lea Instruction is Also Subject To An Agi Stall IT Uses A Base or Index Register Which Has Been Changed In The Preceding Clock Cycle. EXAMPLE: INC ESI / LEA ESI]; AGI Stall
PPRO, PII AND PIII HAVE NO AGI Stalls for Memory Reads and LEA, But They Do Have Agi Stalls for Memory Writes. This is not VERY SIGNIFICANT UNSE Subsequent Code Has to Wait for the Write To Finish.
10. Pairing Integer Instructions (PPLAIN AND PMMX)
10.1 Perfect Pairing
The PPlain and PMMX have two pipelines for executing instructions, called the U-pipe and the V-pipe. Under certain conditions it is possible to execute two instructions simultaneously, one in the U-pipe and one in the V-pipe. This can Almost Double The Speed. It is Therefore Advantageous To Reorder Your Instructions to make them pair.
The Following Instructions Are Pairable In Either Pipe:
Mov Register, Memory, Or Immediate Into Register or Memory Push Register Or Immediate, Pop Register Lea, NOP Inc, DEC, Add, Sub, CMP, AND, OR, XOR, AND Some Forms of Test (See Chapter 26.14)
The Following Instructions Are Pairable in The U-PIPE ONLY:
ADC, SBB SHR, SAR, SHL, SAL with IMMEDIAT ROR, ROL, RCR, RCL with an IMMEDITE COUNT OF 1
The Following Instructions Can Execute In Either Pipe But Are ONLY PAIRABLE WHENIN THE V-PIPE:
Near Call Short and Near Jump Short and Near Conditional Jump.
All Other Integer INSTRUCTIONS CAN EXECUTE IN THE U-PIPE ONLY, AND ARE NOT PAIRABLE.
Two Consecutive Instructions Will Pair When The Following Conditions Are Met:
1. The first instruction is pairable in The U-PIPE AND THE Second Instruction IS Pairable In The V-PIPE.
2. The Second Instruction Does Not Read or Write a Register Which To. Examples: Mov Eax, EBX / MOV ECX, EBX / MOV ECX, EBX / MOV ECX, EBX / MOV ECX, EBX / MOV ECX, EBX / MOV ECX, EBX / MOV ECX, EBX / MOV ECX, EBX / MOV ECX, EBX / MOV EAX
MOV Eax, 1 / Mov Eax, 2; Write After Write, Do Not Pair
MOV EBX, EAX / MOV Eax, 2; Write After Read, Pair OK
MOV EBX, EAX / MOV ECX, EAX; Read after Read, Pair OK
MOV EBX, EAX / Inc Eax; Read and Write After Read, Pair OK
3. In Rule 2 Partial Registers Are Treated As Full Registers. EXAMPLE:
MOV Al, BL / MOV AH, 0
Writes to Different Parts of The Same Register, Do Not Pair
4. Two instructions Which Both Write to Parts of The Flags Register CAN Pair Despite Rule 2 and 3. Example:
SHR EAX, 4 / Inc EBX; Pair OK
5. An Instruction Which Writes to the Flags Can Pair with a Conditional Jump Despite Rule 2. Example:
CMP EAX, 2 / JA Labelbigger; Pair OK
6. The Following Instruction Combinations Can Pair Despite The Fact That Thei Both Modify The Stack Pointer:
Push Push, Push Call, POP POP
7. There Are Restrictions on the Pairing of Instructions with prefix. There Are Several Types of Prefixes:
instructions addressing a non-default segment have a segment prefix. instructions using 16 bit data in 32 bit mode, or 32 bit data in 16 bit mode have an operand size prefix. instructions using 32 bit base or index registers in 16 bit mode have an address size prefix. repeated string instructions have a repeat prefix. locked instructions have a LOCK prefix. many instructions which were not implemented on the 8086 processor have a two byte opcode where the first byte is 0FH. The 0FH byte behaves as a prefix on the PPLAIN, But Not On The Other Versions. The Most Common Instructions with 0fh Prefix Are: Movzx, Movsx, Push Fs, POP FS, PUSH GS, POP GS, LFS, LGS, LSS, SETCC, BT, BTC, BTR, BTS, BSF, BSR, SHLD, SHRD, AND IMUL WITH TWO OPERANDS AND NO IMMEDITERAND.ON THE PPLAIN, A Prefixed Instruction Can Only Except for Conditional Near Jumps.
ON The PMMX, Instructions with Operands, Address Size, or 0FH Prefix CAN Execute IN Either Pipe, WHEREAS INSTRUCTIONS with Segment, Repeat, or Lock Prefix Can Only Execute In The U-PIPE.
8. An Instruction Which Has Both a Displacement and Immediate Data IS Not Pairable On The PPLAIN AND OnLY PAIRABLE IN THE U-PIPE ON THE PMMX:
MOV DWORD PTR DS: [1000], 0; Not Pairable or Only in U-PIPE
CMP BYTE PTR [EBX 8], 1; Not Pairable or Only in U-PIPE
CMP Byte PTR [EBX], 1; Pairable
CMP BYTE PTR [EBX 8], Al; Pairable
(Another problem with instructions which have both a displacement and immediate data on the PMMX is that such instructions may be longer than 7 bytes, which means that only one instruction can be decoded per clock cycle, as explained in chapter 12.)
9. Both Instructions Must Be Preloaded and Decoded. This is expected in chapter 8.10. There Are Special Pairing Rules for MMX Instructions on the PMMX:
MMX shift, pack or unpack instructions can execute in either pipe but can not pair with other MMX shift, pack or unpack instructions. MMX multiply instructions can execute in either pipe but can not pair with other MMX multiply instructions. They take 3 clock cycles and the last 2 clock cycles can overlap with subsequent instructions in the same way as floating point instructions can (see chapter 24). an MMX instruction which accesses memory or integer registers can execute only in the U-pipe and can not pair with a non-MMX instruction.
10.2 Imperfect Pairing
There are situations where the two instructions in a pair will not execute simultaneously, or only partially overlap in time. They should still be considered a pair, though, because the first instruction executes in the U-pipe, and the second in the V- .
Imperfect Pairing Will Happen in The Following Cases:
1. If The Second Instructions Suffers An AGI Stall (See Chapter 9).
. 2. Two instructions can not access the same DWORD of memory simultaneously The following examples assume that ESI is divisible by 4: MOV AL, [ESI] / MOV BL, [ESI 1] The two operands are within the same DWORD, so they can not execute simultaneously. The pair takes 2 clock cycles. MOV AL, [ESI 3] / MOV BL, [ESI 4] Here the two operands are on each side of a DWORD boundary, so they pair perfectly, and take only one Clock Cycle.
3. Rule 2 is extended to the case where bit 2-4 is the same in the two addresses (cache bank conflict) For DWORD addresses this means that the difference between the two addresses should not be divisible by 32. Examples:. MOV [ ESI], EAX / MOV [ESI 32000], EBX; Imperfect Pairing
MOV [ESI], ESI 32004], EBX; Perfect Pairing
Pairable integer instructions which do not access memory take one clock cycle to execute, except for mispredicted jumps. MOV instructions to or from memory also take only one clock cycle if the data area is in the cache and properly aligned. There is no speed penalty for Using Complex Addressing Modes Such as scaled index registers.
A Pairable Integer Instruction Which Reads from Memory, Does Some Calculation, and Stores The Result IN A Register OR Flags, Takes 2 Clock Cycles (Read / Modify Instructions).
A Pairable Integer Instruction Which Reads from Memory, Does Some Calculation, And Writes The Result Back to The Memory, Takes 3 Clock Cycles (Read / Modify / Write Instructions).
4. IF a read / modify / write instruction ispaired with a read / modify or read / modify / write instruction, THEY WILL PAIR IMPERFECTLY.
The Number of Clock Cycles Used is Given In The Following Table:
First INSTRUCOND INSTRUCTION MOV OR Register Only Read / Modify Read / Modify / Write Mov or Register Only 1 2 3 Read / Modify 2 2 3 Read / Modify / Write 3 4 5
Example: Add [Mem1], Eax / Add EBX, [MEM2]; 4 Clock Cycles Add Ebx, [MEM2] / Add [Mem1], EAX; 3 Clock Cycles
5. When Two Paired Instructions Both Take Extra Time Due To Cache Misses, Misalignment, or Jump Misprediction, The Pair Will Take More Time Than Each Instruction, But Less Than Sum of The Two.
6. A pairable floating point instruction followed by FXCH will make imperfect pairing if the next instruction is not a floating point instruction.In order to avoid imperfect pairing you have to know which instructions go into the U-pipe, and which to the V- For one of the rules above.
Imperfect pairing can offten be avoided by reordering your instructions. EXAMPLE:
L1: MOV Eax, [ESI]
MOV EBX, [ESI]
Inc ECX
Here the two MOV instructions form an imperfect pair because they both access the same memory location, and the sequence takes 3 clock cycles. You can improve the code by reordering the instructions so that INC ECX pairs with one of the MOV instructions.
L2: MOV Eax, Offset A
XOR EBX, EBX
Inc EBX
MOV ECX, [EAX]
JMP L1
The pair INC EBX / MOV ECX, [EAX] is imperfect because the latter instruction has an AGI stall. The sequence takes 4 clocks. If you insert a NOP or any other instruction so that MOV ECX, [EAX] pairs with JMP L1 instead .
The next example is in 16 bit mode, Assuming That SP is Divisible By 4:
L3: Push AX
Push BX
PUSH CX
Push dx
Call func
Here the PUSH instructions form two imperfect pairs, because both operands in each pair go into the same dword of memory. PUSH BX could possibly pair perfectly with PUSH CX (because they go on each side of a DWORD boundary) but it does not because it has already been paired with PUSH AX. The sequence therefore takes 5 clocks. If you insert a NOP or any other instruction so that PUSH BX pairs with PUSH CX, and PUSH DX with CALL FUNC, then the sequence will take only 3 clocks. Another way to solve the problem is to make sure that SP is not divisible by 4. Knowing whether SP is divisible by 4 or not in 16 bit mode can be difficult, so the best way to avoid this problem is to use 32 bit mode. 11. Splitting Complex Instructions INTO SIMPLER ANES (PPLAIN and PMMX)
You may split up read / modify and read / modify / write instructions to improve pairing Example:. ADD [mem1], EAX / ADD [mem2], EBX; 5 clock cycles This code may be split up into a sequence which takes only 3 Clock Cycles:
MOV ECX, [MEM1] / MOV EDX, [MEM2] / Add ECX, EAX / Add Edx, EBX
MOV [MEM1], ECX / MOV [MEM2], EDX
LIKEWISE You May Split Up Non-Pairable Instructions Into Pairable Instructions:
Push [MEM1]
Push [MEM2]; non-pairable
Split Up Into:
MOV EAX, [MEM1]
Mov EBX, [MEM2]
Push EAX
Push Ebx; Everything PAIRS
Other examples of non-pairable instructions which may be split up into simpler pairable instructions: CDQ split into: MOV EDX, EAX / SAR EDX, 31 NOT EAX change to XOR EAX, -1 NEG EAX split into XOR EAX, -1 / INC Eax Movzx Eax, Byte Ptr [Mem] split Into xor Eax, Eax / Mov Al, Byte Ptr [MEM] JECXZ Split Into Test ECX, ECX / JZ LOOP SPLIT INTO DEC ECX / JNZ XLAT CHANGE to MOV Al, [EBX EAX ]
If splitting instructions does not improve speed, then you may keep the complex or nonpairable instructions in order to reduce code size.Splitting instructions is not needed on the PPro, PII and PIII, except when the split instructions generate fewer uops.
12. prefixes (PPLAIN AND PMMX)
An Instruction with One or More Prefixes May Not Be Aable To Execute In The V-PIPE (SE Chapter 10, SECT.7), AND IT May Take More Than One Clock Cycle to Decode.
On the PPLAIN, The DECODING DELAY IS One Clock Cycle for Each Prefix Except for the 0fh Prefix of Conditional Near Jumps.
The PMMX has no decoding delay for 0FH prefix. Segment and repeat prefixes take one clock extra to decode. Address and operand size prefixes take two clocks extra to decode. The PMMX can decode two instructions per clock cycle if the first instruction has a segment or repeat prefix or no prefix, and the second instruction has no prefix. Instructions with address or operand size prefixes can only decode alone on the PMMX. Instructions with more than one prefix take one clock extra for each prefix.
Address size prefixes can be avoided by using 32 bit mode. Segment prefixes can be avoided in 32 bit mode by using a flat memory model. Operand size prefixes can be avoided in 32 bit mode by using only 8 bit and 32 bit integers.
Where prefixes are unavoidable, the decoding delay may be masked if a preceding instruction takes more than one clock cycle to execute. The rule for the PPlain is that any instruction which takes N clock cycles to execute (not to decode) can 'overshadow' the decoding delay of N-1 prefixes in the next two (sometimes three) instructions or instruction pairs. in other words, each extra clock cycle that an instruction takes to execute can be used to decode one prefix in a later instruction. This shadowing effect even extends across a predicted branch. Any instruction which takes more than one clock cycle to execute, and any instruction which is delayed because of an AGI stall, cache miss, misalignment, or any other reason except decoding delay and branch misprediction, has a shadowing effect .
The PMMX has a similar shadowing effect, but the mechanism is different. Decoded instructions are stored in a transparent first-in-first-out (FIFO) buffer, which can hold up to four instructions. As long as there are instructions in the FIFO buffer you get no delay. When the buffer is empty then instructions are executed as soon as they are decoded. The buffer is filled when instructions are decoded faster than they are executed, ie when you have unpaired or multi-cycle instructions. The FIFO buffer is emptied when instructions execute faster than they are decoded, ie when you have decoding delays due to prefixes. The FIFO buffer is empty after a mispredicted branch. The FIFO buffer can receive two instructions per clock cycle provided that the second instruction is without prefixes and None of the instructions area longer Than 7 Bytes. The Two Execution Pipelines (U and V) Can Each Receive One Instruction Per Clock Cycle from the FIFFER.EXAMPLES: CLD / Rep Movsd The CLD Installer ruction takes two clock cycles and can therefore overshadow the decoding delay of the REP prefix. The code would take one clock cycle more if the CLD instruction was placed far from the REP MOVSD. CMP DWORD PTR [EBX], 0 / MOV EAX, 0 / SETNZ AL The CMP instruction takes two clock cycles here because it is a read / modify instruction. The 0FH prefix of the SETNZ instruction is decoded during the second clock cycle of the CMP instruction, so that the decoding delay is hidden on the PPlain ( The pmmx has no decoding delay for the 0fh.
Prefix Penalties In PPRO, PII AND PIII Are Described in Chapter 14.
13. Overview of PPRO, PII and PIII PIPELINE
The architecture of the PPro, PII and PIII microprocessors is well explained and illustrated in various manuals and tutorials from Intel. It is recommended that you study this material in order to get an understanding of how these microprocessors work. I will describe the structure briefly here with particular focus on those elements that are important for optimizing code.Instruction codes are fetched from the code cache in aligned 16-byte chunks into a double buffer that can hold two 16-byte chunks. The code is passed on from the double buffer to the decoders in blocks which I will call ifetch blocks (instruction fetch blocks). The ifetch blocks are usually 16 bytes long, but not aligned. The purpose of the double-buffer is to make it possible to decode an instruction that crosses a 16- BYTE Boundary (IE An Address Divisible By 16).
The ifetch block goes to the instruction length decoder, which determines where each instruction begins and ends, and next to the instruction decoders. There are three decoders so that you can decode up to three instructions in each clock cycle. A group of up to three Instructions That Are Decoded In The Same Clock Cycle IS Called A Decode Group.
. The decoders translate instructions into micro-operations, abbreviated uops Simple instructions generate only one uop, while more complex instructions may generate several uops For example, the instruction ADD EAX, [MEM] is decoded into two uops:. One for reading the source .
The three decoders are called D0, D1, and D2. D0 can handle all instructions, while D1 and D2 can handle only simple instructions that generate one uop.The uops from the decoders go via a short queue to the register allocation table (RAT) . The execution of uops work on temporary registers which are later written to the permanent registers EAX, EBX, etc. The purpose of the RAT is to tell the uops which temporary registers to use, and to allow register renaming (see later).
After the RAT, the uops to go the reorder buffer (ROB). The purpose of the ROB is to enable out-of-order execution. A uop stays in the reservation station until the operands it needs are available. If an operand for one Uop is delayed Because A Previous Uop That Genereates The Operand Is Not Finished Yet, The Rob May Find Another Uop Later In The Meantime in Order to Save Time.
The uops that are ready for execution are sent to the execution units, which are clustered around five ports: Port 0 and 1 can handle arithmetic operations, jumps, etc. Port 2 takes care of all reads from memory, port 3 calculates addresses for memory Writes, and port 4 does memory writes.
When an instruction has been executed then it is marked in the ROB as ready to retire. It then goes to the retirement station. Here the contents of the temporary registers used by the uops are written to the permanent registers. While uops can be executed out ORDER, The Must Be Retired in Order.
In The Following Chapters, I Will Describe in detail how to optimize the throughput of each step in the pipeline.
14. Instruction Decoding (PPRO, PII AND PIII)
I am describing instruction decoding before instruction fetching here because you need to know how the decoders work in order to understand the possible delays in instruction fetching.The decoders can handle three instructions per clock cycle, but only when certain conditions are met. Decoder D0 can .
To Summarize The Rules for Decoding Two or Three Instructions in The Same Clock Cycle:
The first instruction (D0) generates no more than 4 uops, The second and third instructions generate no more than 1 uop each, The second and third instructions are no more than 8 bytes long each, The instructions must be contained within the same 16 bytes IFETCH Block (See next chapter).
........................... ..
An Instruction That Genere Than 4 uops Takes Two or More Clock Cycles To Decode, and no Other Instructions Can Decode in Parallel.
It follows from the rules above that the decoders can produce a maximum of 6 uops per clock cycle if the first instruction in each decode group generates 4 uops and the next two generate 1 uop each. The minimum production is 2 uops per clock cycle, which YOU GET WHEN ALL INSTRUCTIONS Generate 2 UOPS EACH, SO THAT D1 and D2 Are Never USED.
For maximum throughput, it is recommended that you order your instructions according to the 4-1-1 pattern: instructions that generate 2 to 4 uops can be interspearsed with two simple 1-uop instructions for free, in the sense that they do not add To the decoding time. EXAMPLE: MOV EBX, [MEM1]; 1 UOP (d0)
INC EBX; 1 UOP (D1)
Add Eax, [MEM2]; 2 UOPS (D0)
Add [MEM3], EAX; 4 UOPS (D0)
THIS Takes 3 Clock Cycles To Decode. You Can Save ONE CLOCK CYCLE BY REORDERING The Instructions Into Two Decode Groups:
Add Eax, [MEM2]; 2 UOPS (D0)
MOV EBX, [MEM1]; 1 UOP (D1)
INC EBX; 1 UOP (D2)
Add [MEM3], EAX; 4 UOPS (D0)
The decoders now generate 8 uops in two clock cycles, which is probably satisfactory. Later stages in the pipeline can handle only 3 uops per clock cycle so with a decoding rate higher than this you can assume that decoding is not a bottleneck. However, complications In The Fetch Mechanism CAN Delay Decoding As Described in The next chapter
You can see How Many Uops Each Instruction Generated IN The Tables in Chapter 29.
Instruction Prefixes Can Also Incoders. Instructions CAN Have Several Kinds of Prefixes:
An operand size prefix is needed when you have a 16-bit operand in a 32-bit environment or vice versa. (Except for instructions that can only have one operand size, such as FNSTSW AX). An operand size prefix gives a penalty of a few clocks if the instruction has an immediate operand of 16 or 32 bits because the length of the operand is changed by the prefix Examples: ADD BX, 9; no penalty because immediate operand is 8 bitsMOV WORD PTR [MEM16], 9;. Penalty Because Operand IS 16 BITS The Last Instruction SHOULD BE CHANGED TO: MOV EAX, 9
MOV WORD PTR [MEM16], AX; no penalty because no immediate An address size prefix is used when you use 32-bit addressing in 16 bit mode or vice versa This is seldom needed and should generally be avoided The address size prefix gives.. a penalty whenever you have an explicit memory operand (even when there is no displacement) because the interpretation of the r / m bits in the instruction code is changed by the prefix. Instructions with only implicit memory operands, such as string instructions, have no penalty with address size prefix. segment prefixes are used when you address data in a non-default data segment. segment prefixes give no penalty on the PPro, PII and PIII. Repeat prefixes and lock prefixes give no penalty in the decoders. There is always A Penalty if you have more Than One Prefix. This Penalty is Usually One Clock Per Prefix.
15. Instruction Fetch (PPRO, PII and PIII)
The code is fetched in aligned 16-bytes chunks from the code cache and placed in the double buffer, which is called so because it can contain two such chunks. The code is then taken from the double buffer and fed to the decoders in blocks which are usually 16 bytes long, but not necessarily aligned by 16. I will call these blocks ifetch blocks (instruction fetch blocks). If an ifetch block crosses a 16 byte boundary in the code then it needs to take from both chunks in the double buffer . So the purpose of the double buffer is to allow instruction fetching across 16 byte boundaries.The double buffer can fetch one 16-bytes chunk per clock cycle and can generate one ifetch block per clock cycle. The ifetch blocks are usually 16 bytes long, But Can Be Shorter if The IS A Predicted Jump In The Block. (See Chapter 22 About Jump PREDIX).
Unfortunately, the double buffer is not big enough for handling fetches around jumps without delay. If the ifetch block that contains the jump instruction crosses a 16-byte boundary then the double buffer needs to keep two consecutive aligned 16-bytes chunks of code in order to generate it. If the first instruction after the jump crosses a 16-byte boundary, then the double buffer needs to load two new 16-bytes chunks of code before a valid ifetch block can be generated. This means that, in the worst case , the decoding of the first instruction after a jump can be delayed for two clock cycles. You get one penalty for a 16-byte boundary in the ifetch block containing the jump instruction, and one penalty for a 16-byte boundary in the first instruction after the jump. you can get bonus if you have more than one decode group in the ifetch block that contains the jump because this gives the double buffer extra time to fetch one or two 16-byte chunks of code in advance for the instructions af ter the jump. The bonuses can compensate for the penalties according to the table below. If the double buffer has fetched only one 16-byte chunk of code after the jump, then the first ifetch block after the jump will be identical to this chunk, that is, aligned to a 16-byte boundary. In other words, the first ifetch block after the jump will not begin at the first instruction, but at the nearest preceding address divisible by 16. If the double buffer has had time to load two 16-Byte Chunks, THE New IFETCH Block Can Cross A 16-Byte Boundary And Beg. These Rules Are Summarized in The Following Table:
Number ofdecode groupsin ifetch-blockcontaining jump16-byteboundary in thisifetch-block16-byteboundary in firstinstruction afterjumpdecoder delayalignment of firstifetch after jump1000by 161011to instruction1101by 161112to instruction2000to instruction2010to instruction2100by 162111to instruction3 or more000to instruction3 or more010to instruction3 or more100to instruction3 or more110to instructionJumps delay the fetching so that a loop Always Takes At Least Two Clock Cycles More Per Itemion Than The Number of 16 Byte Boundaries in the loop.
A further problem with the instruction fetch mechanism is that a new ifetch block is not generated until the previous one is exhausted. Each ifetch block can contain several decode groups. If a 16 bytes long ifetch block ends with an unfinished instruction, then the next ifetch block will begin at the beginning of that instruction. The first instruction in an ifetch block always goes to decoder D0, and the next two instructions go to D1 and D2, if possible. The consequence of this is that D1 and D2 are used less than optimally. If the code is structured according to the recommended 4-1-1 pattern, and an instruction intended to go into D1 or D2 happens to be the first instruction in an ifetch block, then that instruction has to go into D0 with the result that one clock cycle is wasted. This is probably a hardware design flaw. At least it is suboptimal design. The consequence of this problem is that the time it takes to decode a piece of code can vary considerably depending on where the First IFETCH Block Begins.
If decoding speed is critical and you want to avoid these problems then you have to know where each ifetch block begins. This is quite a tedious job. First you need to make your code segment paragraph-aligned in order to know where the 16-byte boundaries are. Then you have to look at the output listing from your assembler to see how long each instruction is. (It is recommended that you study how instructions are coded so that you can predict the lengths of the instructions.) If you know where one ifetch block begins then you can find where the next ifetch block begins in the following way:.. Make the block 16 bytes long If it ends at an instruction boundary then the next block will begin there If it ends with an unfinished instruction then the next block will begin at the beginning of this instruction. (Only the lengths of the instructions counts here, it does not matter how many uops they generate or what they do). This way you can work your way all through the code and mark WHERE EACH . Ifetch block begins The only problem is knowing where to start If you know where one ifetch block is then you can find all the subsequent ones, but you have to know where the first one begins Here are some guidelines..:
The first ifetch block after a jump, call, or return can begin either at the first instruction or at the nearest preceding 16-bytes boundary, according to the table above. If you align the first instruction to begin at a 16-byte boundary then you can be sure that the first ifetch block begins here. you may want to align important subroutine entries and loop entries by 16 for this purpose. If the combined length of two consecutive instructions is more than 16 bytes then you can be certain that the second one does not fit into the same ifetch block as the first one, and consequently you will always have an ifetch block beginning at the second instruction. you can use this as a starting point for finding where subsequent ifetch blocks begin. The first ifetch block after a branch misprediction begins at a 16-byte boundary. As explained in chapter 22.2, a loop that repeats more than 5 times will always have a misprediction when it exits. The first ifetch block after such a loop will therefor e begin at the nearest preceding 16-byte boundary. Other serializing events also cause the next ifetch block to start at a 16-byte boundary. Such events include interrupts, exceptions, self-modifying code, and serializing instructions such as CPUID, IN, And out.i am sure you want an esample now:
Address INSTRUCTION Length UOPS Expected Decoder
-------------------------------------------------- --------------------
1000H MOV ECX, 1000 5 1 D0
1005H ll: MOV [ESI], EAX 2 2 d0
1007H MOV [MEM], 0 10 2 D0
1011h Lea EBX, [EAX 200] 6 1 D1
1017H MOV BYTE PTR [ESI], 0 3 2 D0101AH BSR EDX, EAX 3 2 D0
101DH MOV BYTE PTR [ESI 1], 0 4 2 D0
1021H DEC ECX 1 1 D1
1022H JNZ LL 2 1 D2
Let '
s assume that the first ifetch block begins at 1000h and ends at 1010h. This is before the end of the MOV [MEM], 0 instruction so the next ifetch block will begin at 1007h and end at 1017h address. This is at an instruction boundary so the third ifetch block will begin at 1017h and cover the rest of the loop. The number of clock cycles it takes to decode this is the number of D0 instructions, which is 5 per iteration of the LL loop. The last ifetch block contained three decode blocks covering the last five instructions, and it has one 16-byte boundary (1020h). Looking at the table above we find that the first ifetch block after the jump will begin at the first instruction after the jump, that is the LL label at 1005h, and end at 1015h. This is before the end of the LEA instruction, so the next ifetch block will go from 1011h to 1021h, and the last one from 1021h covering the rest. Now the LEA instruction and the DEC instruction both fall At The Beginning of An iFETCH Block Which Forces them to go into D0. We now have 7 instructions in D0 and the loop takes 7 clocks to decode in the second iteration. The last ifetch block contains only one decode group (DEC ECX / JNZ LL) and has no 16-byte boundary. According to the table, the next ifetch block after the jump will begin at a 16-byte boundary, which is 1000h. This will give us the same situation as in the first iteration, and you will see that the loop takes alternatingly 5 and 7 clock cycles to decode. Since there are no other bottlenecks, the complete loop will take 6000 clocks to run 1000 iterations. If the starting address had been different so that you had a 16-byte boundary in the first or the last instruction of the loop The IT Would Take 8000 Clocks.
If you reorder the loop so that no D1 or D2 instructions fall at the beginning of an ifetch block then you can make it take only 5000 clocks.The example above was deliberately constructed so that fetch and decoding is the only bottleneck. The easiest way to avoid this problem is to structure your code to generate much more than 3 uops per clock cycle so that decoding will not be a bottleneck despite the penalties described here. In small loops this may not be possible and then you have to find out how to optimize The instruction fetch and decoding.
One thing you can do is to change the starting address of your procedure in order to avoid 16-byte boundaries where you do not want them. Remember to make your code segment paragraph aligned so that you know where the boundaries are.
If you insert an ALIGN 16 directive before the loop entry then the assembler will put in NOP's and other filler instructions up to the nearest 16 byte boundary. Most assemblers use the instruction XCHG EBX, EBX as a 2-byte filler (the so called 2 -byte NOP). Whoever got this idea, it's a bad one because this instruction takes more time than two NOP's on most processors! If the loop executes many times then whatever is outside the loop is unimportant in terms of speed and you do not have to care about the suboptimal filler instructions. But if the time taken by the fillers is important then you may select the filler instructions manually. you may as well use filler instructions that do something useful, such as refreshing a register in order to avoid register read stalls (see chapter 16.2) for example, if you are using register EBP for addressing but seldom write to it, then you may use MOV EBP, EBP or ADD EBP, 0 as filler in order to reduce the possibilities of register read stalls. IF you have nothing useful to do, you may use FXCH ST (0) as a good filler because it does not put any load on the execution ports, provided that ST (0) contains a valid floating point value.Another possible remedy is to reorder Your instructions in Order To Get The iFetch Boundaries Where The I ''
Yet another possibility is to manipulate instruction lengths. Sometimes you can substitute one instruction with another one with a different length. Many instructions can be coded in different versions with different lengths. The assembler always chooses the shortest possible version of an instruction, but it is FOR EXAMPLE, DEC ECX IS One Byte Long, Sub ECX, 1 IS 3 BYTES, AND You CAN CODE A 6 BYtes Version with a long immediate Operand Using this trick: Sub ECX, 9999
Org $ -4
DD 1
Instructions with a memory operand can be made one byte longer with a SIB byte, but the easiest way of making an instruction one byte longer is to add a DS: segment prefix (DB 3Eh) The microprocessors generally accept redundant and meaningless prefixes (except. Lock) Not Exceed 15 Bytes. Even INSTRUCTIONS WITHOUT A MEMORY OPERAND CAN HAVE A Segment Prefix. So if you want the dec ECX INSTRUCTION TO BE 2 bytes long, Write:
DB 3EH
Dec ECX
Remember that you get a penalty in the decoder if an instruction has more than one prefix It is possible that instructions with meaningless prefixes -. Especially repeat and lock prefixes - will be used in future processors for new instructions when there are no more vacant instruction codes But I Would Consider IT Safe To Use A Segment Prefix with anything.
With these methods it will usually be pasile to put the meansetch boundaries where you want, although it can be becom, although..
16. Register Renaming (PPRO, PII AND PIII)
16.1 Eliminating Dependencies
Register renaming is an advanced technique used by these Microprocessors to Remove Dependencies Between Different Parts of the code. Example:
Mov Eax, [MEM1] Imul Eax, 6
MOV [MEM2], EAX
Mov Eax, [MEM3]
INC EAX
MOV [MEM4], EAX
Here the last three instructions are independent of the first three in the sense that they do not need any result from the first three instructions. To optimize this on earlier processors you would have to use a different register instead of EAX in the last three instructions and reorder the instructions so that the last three instructions could execute in parallel with the first three instructions. The PPro, PII and PIII processors do this for you automatically. They assign a new temporary register for EAX every time you write to it. Thereby the MOV EAX, [MEM3] Instruction Becomes Independent of the Preceding Instructions. With out-of-order execution it is likely to finish the move to [mem4] before the slow imul instruction is finished.
Register renaming goes fully automatically. A new temporary register is assigned as an alias for the permanent register every time an instruction writes to this register. An instruction that both reads and writes a register also causes renaming. For example the INC EAX instruction above uses one .
All general purpose registers, stack pointer, flags, floating point registers, MMX registers, XMM registers and segment registers can be renamed. Control words, and the floating point status word can not be renamed and this is the reason why the use of these registers is .
A common way of setting a register to zero is XOR EAX, EAX or SUB EAX, EAX. These instructions are not recognized as independent of the previous value of the register. If you want to remove the dependency on slow preceding instructions then use MOV EAX , 0.Register renaming is controlled by the register alias table (RAT) and the reorder buffer (ROB). The uops from the decoders go to the RAT via a queue, and then to the ROB and the reservation station. The RAT can handle On the means.
................ ..
16.2 Register Read Stalls
But there is another limitation which may be quite serious, and that is that you can only read two different permanent register names per clock cycle This limitation applies to all registers used by an instruction except those registers that the instruction writes to only Example..:
MOV [EDI ESI], EAX
MOV EBX, [ESP EBP]
The first instruction generates two uops: one that reads EAX and one that reads EDI and ESI The second instruction generates one uop that reads ESP and EBP EBX does not count as a read because it is only written to by the instruction Let's assume... that these three uops go through the RAT together. I will use the word triplet for a group of three consecutive uops that go through the RAT together. Since the ROB can handle only two permanent register reads per clock cycle and we need five register reads, our triplet will be delayed for two extra clock cycles before it comes to the reservation station. With 3 or 4 register reads in the triplet it would be delayed by one clock cycle.The same register can be read more than once in the same triplet without Adding to the count. if the instructions above area change to:
MOV [EDI ESI], EDI
MOV EBX, [EDI EDI]
...................... ..
A Register That Is Going Uop Is Stored in The Rob So That Can Be Read for Free Until It Is Written Back, Which Takes At Least 3 Clock Cycles, And Usually More. Write-Back Is The end of the execution stage where the value becomes available. in other words, you can read any number of registers in the RAT without stall if their values are not yet available from the execution units. The reason for this is that when a value becomes available it is immediately written directly to any subsequent ROB entries that need it. But if the value has already been written back to a temporary or permanent register when a subsequent uop that needs it goes into the RAT, then the value has to be read from the register file, which has only two read ports. There are three pipeline stages from the RAT to the execution unit so you can be certain that a register written to in one uop-triplet can be read for free in at least the next three triplets. If The Writeback Is Delayed by Reordering, Slow Instructions, Dependency Chains, Cache Misses, or by Any Other Kind of Stall, The Register CAN Be Read for Free Further Down The Instruction Stream.example:
MOV EAX, EBX
SUB ECX, EAX
Inc EBX
Mov Edx, [EAX]
Add ESI, EBX
Add Edi, ECX
These 6 instructions generate 1 uop each. Let's assume that the first 3 uops go through the RAT together. These 3 uops read register EBX, ECX, and EAX. But since we are writing to EAX before reading it, the read is free and we get no stall. The next three uops read EAX, ESI, EBX, EDI, and ECX. Since both EAX, EBX and ECX have been modified in the preceding triplet and not yet back then they can be read for free, so that only written ESI and EDI count, and we get no stall in the second triplet either. If the SUB ECX, EAX instruction in the first triplet is changed to CMP ECX, EAX then ECX is not written to and we will get a stall in the second triplet for reading ESI, EDI and ECX. Similarly, if the INC EBX instruction in the first triplet is changed to NOP or something else then we will get a stall in the second triplet for reading ESI, EBX and EDI.No uop can read more than Therefore, All Instructions That Need To Read More Two Registers Are Split Up Into Two or More U OPS.
To count the number of register reads, you have to include all registers which are read by the instruction. This includes integer registers, the flags register, the stack pointer, floating point registers and MMX registers. An XMM register counts as two registers, except when only part of it is used, as eg in ADDSS and MOVHLPS. Segment registers and the instruction pointer do not count. For example, in SETZ AL you count the flags register but not AL. ADD EBX, ECX counts both EBX and ECX, ...................
The FXCH instruction is a special case. It works by renaming, but does not read any values so that it does not count in the rules for register read stalls. An FXCH instruction behaves like 1 uop that neither reads nor writes any registers with regard to the rules for register read stalls.Don't confuse uop triplets with decode groups. A decode group can generate from 1 to 6 uops, and even if the decode group has three instructions and generates three uops there is no guarantee that the three Uops Will Go Into the Rat Together.
The Queue Between The Decoders and the Rat Is So SHORT (10 uops) That You Cannot Assume That Register Read Stalls Do Not Stall The Decoders Or That Flu Now Stall The Rat.
It is very difficult to predict which uops go through the RAT together unless the queue is empty, and for optimized code the queue should be empty only after mispredicted branches Several uops generated by the same instruction do not necessarily go through the RAT together;. The uops are simply taken consecutively from the queue, three at at time The sequence is not broken by a predicted jump:. uops before and after the jump can go through the RAT together Only a mispredicted jump will discard the queue and start over again so. That the next three uops are sag.
If three consecutive uops read more than two different registers then you would of course prefer that they do not go through the RAT together. The probability that they do is one third. The penalty of reading three or four written-back registers in one triplet of uops is one clock cycle. You can think of the one clock delay as equivalent to the load of three more uops through the RAT. With the probability of 1/3 of the three uops going into the RAT together, the average penalty will be the equivalent of 3/3 = 1 uop. to calculate the average time it will take for a piece of code to go through the RAT, add the number of potential register read stalls to the number of uops and divide by three. You can see that It does not pay to remove the stall by putting in an extra instruction unless you know for sure which uops go into the RAT together or you can prevent more than one potential register read stall by one extra instruction.In situations where you aim at a Throughput of 3 uops per clock, THE LIMIT OF TWO Permanent Register Reads Per Clock Cycle May Be a problematic bottleneck to handle. Possible Ways to remove Register Read Stalls Are:
keep uops that read the same register close together so that they are likely to go into the same triplet keep uops that read different registers spaced so that they can not go into the same triplet place uops that read a register no more than 3 -.. 4 triplets after an instruction that writes to or modifies this register to make sure it has not been written back before it is read (it does not matter if you have a jump between as long as it is predicted). If you have reason to expect the register write to be delayed for whatever reason then you can safely read the register somewhat further down the instruction stream. use absolute addresses instead of pointers in order to reduce the number of register reads. you may rename a register in a triplet where it Doesn't Cause A Stall in Order To Prevent a Read Stall for this Register in One or More Later Triplets. EXAMPLE: MOV ESP, ESP / ... / MOV EX, [ESP 8]. This Method COSTS An Extra uop and Therefore doesn't pay unsses the expected avee number er of read stalls prevented is more than 1 / 3.For instructions that generate more than one uop you may want to know the order of the uops generated by the instruction in order to make a precise analysis of the possibility of register read stalls. I Have the theefore listed the MOST Common Case Below.
. Writes to memory A memory write generates two uops The first one (to port 4) is a store operation, reading the register to store The second uop (port 3) calculates the memory address, reading any pointer registers Examples:.. MOV [ EDI], EAX First Uop Reads Eax, Second Uop Reads EDI. FSTP Qword PTR [EBX 8 * ECX] First Uop Reads St (0), Second Uop Reads EBX AND ECX.
Read and modify An instruction that reads a memory operand and modifies a register by some arithmetic or logical operation generates two uops. The first one (port 2) is a memory load instruction reading any pointer registers, the second uop is an arithmetic instruction (port 0 or 1) reading and writing to the destination register and possibly writing to the flags Example:. ADD EAX, [ESI 20] First uop reads ESI, second uop reads EAX and writes EAX and flags.Read/modify/write A read / modify / write instruction generates four uops. The first uop (port 2) reads any pointer registers, the second uop (port 0 or 1) reads and writes to any source register and possibly writes to the flags, the third uop (port 4 ) reads only the temporary result which does not count here, the fourth uop (port 3) reads any pointer registers again. Since the first and the fourth uop can not go into the RAT together you can not take advantage of the fact that they read the Same Pointer Registers. EXAMPLE: OR [ESI EDI], EA X The first uop reads ESI and EDI, the second uop reads EAX and writes EAX and the flags, the third uop reads only the temporary result, the fourth uop reads ESI and EDI again. No matter how these uops go into the RAT you can be sure that the uop that reads EAX goes together with one of the uops that read ESI and EDI. A register read stall is therefore inevitable for this instruction unless one of the registers has been modified recently.
Push register A push register instruction generates 3 uops. The first one (port 4) is a store instruction, reading the register. The second uop (port 3) generates the address, reading the stack pointer. The third uop (port 0 or 1 ) subtracts the word size from the stack pointer, reading and modifying the stack pointer.Pop register A pop register instruction generates 2 uops. The first uop (port 2) loads the value, reading the stack pointer and writing to the register. The second UOP (port 0 or 1) Adjusts The Stack Pointer, Reading and Modifying The Stack Pointer.
Call A near call generates 4 uops (port 1, 4, 3, 01). The first two uops read only the instruction pointer which does not count because it can not be renamed. The third uop reads the stack pointer. The last uop reads And Modifies The Stack Pointer.
Return A Near Return GeneRates 4 UOPS (Port 2, 01, 01, 1). The first uop reads the stack pointer. The Third Uop Reads and Modifier The Stack Pointer.
An Example of How To Avoid A Register Read Stall is Given in Example 2.6.
17. Out of Order Execution (PPRO, PII and PIII)
The reorder buffer (ROB) can hold 40 uops. Each uop waits in the ROB until all its operands are ready and there is a vacant execution unit for it. This makes out-of-order execution possible. If one part of the code is DELAYED BECAUSE OF A Cache Miss The IT Won't delay later parts of the code ife...............
Writes to memory can not execute out of order relative to other writes. There are four write buffers, so if you expect many cache misses on writes or you are writing to uncached memory then it is recommended that you schedule four writes at at time and make sure the processor has something else to do before you give it the next four writes. Memory reads and other instructions can execute out of order, except IN, OUT and serializing instructions.If your code writes to a memory address and soon after reads from the same address, then the read may by mistake be executed before the write because the ROB does not know the memory addresses at the time of reordering. This error is detected when the write address is calculated, and then the read operation (which was executed speculatively ) HAS TO BE RE-DONE. The Penalty For this Is Approximately 3 Clocks. The Only Way To Avoid this Penalty Is To Make Sure The Execution Unit Has Other Things To Do Between A Write and A Subsequent Read from The SA ME MEMORY ADDRESS.
There are several execution units clustered around five ports. Port 0 and 1 are for arithmetic operations etc. Simple move, arithmetic and logic operations can go to either port 0 or 1, whichever is vacant first. Port 0 also handles multiplication, division, integer shifts and rotates, and floating point operations. Port 1 also handles jumps and some MMX and XMM operations. Port 2 handles all reads from memory and a few string and XMM operations, port 3 calculates addresses for memory write, and port 4 executes all memory write operations. In chapter 29 you'll find a complete list of the uops generated by code instructions with an indication of which ports they go to. Note that all memory write operations require two uops, one for port 3 and one for port 4, while memory read operations use only one uop (port 2) .In most cases each port can receive one new uop per clock cycle. This means that you can execute up to 5 uops in the same clock cycle if they go to five different ports, But sin CE THERE IS A LIMIT OF 3 UOPS Per Clock Earlier in The Pipeline You Will Never Execute More Than 3 Uops Per CLOCK ON AVERAGE.
You must make sure that no execution port receives more than one third of the uops if you want to maintain a throughput of 3 uops per clock. Use the table of uops in chapter 29 and count how many uops go to each port. If port 0 and 1 are saturated while port 2 is free then you can improve your code by replacing some MOV register, register or MOV register, immediate instructions with MOV register, memory in order to move some of the load from port 0 and 1 to port 2.
Most Uops Take Only ONE Clock Cycle To Execute, But Multiplications, Division, and Many Floating Point Operations Take More:
Floating point addition and subtraction takes 3 clocks, but the execution unit is fully pipelined so that it can receive a new FADD or FSUB in every clock cycle before the preceding ones are finished (provided, of course, that they are independent) .Integer multiplication takes 4 clocks, floating point multiplication 5, and MMX multiplication 3 clocks Integer and MMX multiplication is pipelined so that it can receive a new instruction every clock cycle Floating point multiplication is partially pipelined:.. The execution unit can receive a new FMUL instruction two clocks after the preceding one, so that the maximum throughput is one FMUL per two clock cycles. The holes between the FMUL's can not be filled by integer multiplications because they use the same circuitry. XMM additions and multiplications take 3 and 4 clocks respectively, and are Fully Pipelined. But Since Each Logical XMM Register Is Implement As Two Physical 64-Bit Registers, You NEED TWO UOPS for a Packed XMM Operation, And The Throughput Will The BE One Arithmetic XMM Instruction Every Two Clock Cycles. Xmm Add and Multiply Instructions CAN EXECUTE IN Parallel Because They Don't Use The Same Execution Port.
Integer and floating point division takes up to 39 clocks and is not pipelined. This means that the execution unit can not begin a new division until the previous division is finished. The same applies to squareroot and transcendental functions.
Also jump instructions, calls, and returns are not fully pipelined. You can not execute a new jump in the first clock cycle after a preceding jump. So the maximum throughput for jumps, calls, and returns is one for every two clocks.
. You should, of course, avoid instructions that generate many uops The LOOP XX instruction, for example, should be replaced by DEC ECX / JNZ XX.If you have consecutive POP instructions then you may break them up to reduce the number of uops:
POP ECX / POP EBX / POP EAX; Can Be Changed TO:
MOV ECX, [ESP] / MOV EBX, [ESP 4] / MOV EAX, [ESP] / Add ESP, 12 The former code generate 6 uops, the latter generates "doing the same
PUSH instructions is less advantageous because the split-up code is likely to generate register read stalls unless you have other instructions to put in between or the registers have been renamed recently. Doing it with
Call and
RET INSTRUCTIONS WILL Interfere with prediction in the return stack buffer. Note Also That the
Add ESP INSTRUCTION CAUSE AN AGI Stall in Earlier Processors.
18. Retirement (PPRO, PII and PIII)
Retirement is a process where the temporary registers use by the uops are copy.
The retirement station can handle three uops per clock cycle. This may not seem like a problem because the throughput is already limited to 3 uops per clock in the RAT. But retirement may still be a bottleneck for two reasons. Firstly, instructions must retire in order. If a uop is executed out of order then it can not retire before all preceding uops in the order have retired. And the second limitation is that taken jumps must retire in the first of the three slots in the retirement station. Just like decoder D1 and D2 can be idle if the next instruction only fits into D0, the last two slots in the retirement station can be idle if the next uop to retire is a taken jump. This is significant if you have a small loop where the number of uops in the loop is not divisible by three.All uops stay in the reorder buffer (ROB) until they retire. The ROB can hold 40 uops. This sets a limit to the number of instructions that can execute during the long delay of a division or Other slow operation. Before the division is finished the ROB will be filled up with executed uops waiting to retire. Only when the division is finished and retired can the subsequent uops begin to retire, because retirement takes place in order.
In case of speculative execution of predicted branches (see chapter 22) the speculatively executed uops can not retire until it is certain that the prediction was correct. If the prediction turns out to be wrong then the speculatively executed uops are discarded without retirement.
.
19. Partial Stalls (PPRO, PII and PIII)
19.1 Partial Register Stalls
Partial Register Stall Is A Problem That Occurs WHEN You Write To Part of A 32 Bit Register And Later Read from The Whole Register OR A Bigger Part of It. EXAMPLE: MOV Al, Byte Ptr [M8]
MOV EBX, EAX; Partial Register Stall
This gives a delay of 5-6 clocks. The reason is that a temporary register has been assigned to AL (to make it independent of AH). The execution unit has to wait until the write to AL has retired before it is possible to combine The value from al with the value of the rest of eax. The stall can be avoided by changing to code to:
Movzx EBX, Byte Ptr [Mem8]
And Eax, 0FFFFFFFFFFF00h
OR EBX, EAX
Of Course You Can Also Avoid The Partial Stalls by Putting In Other Instructions After the Write To The Partial Register So That It Has Time To Retire Before Read from The Full Register.
You Should Be Aware of Partial Stalls WHENEVER You Mix Different Data Sizes (8, 16, And 32 Bits):
MOV BH, 0
Add BX, Ax; Stall
Inc EBX; Stall
You don't get a stall at Writing to the full register, or a bigger part of it:
Mov Eax, [MEM32]
Add BL, Al; NO Stall
Add Bh, Ah; No Stall
MOV CX, AX; No Stall
MOV DX, BX; Stall
The easiest way to avoid partial register stalls is to always use full registers and use MOVZX or MOVSX when reading from smaller memory operands. These instructions are fast on the PPro, PII and PIII, but slow on earlier processors. Therefore, a compromise is offered When You Want Your Code to Perform Reasonably Well on All Processors. The Replacement for Movzx Eax, Byte Ptr [M8] Looks Like this:
XOR EAX, EAX
MOV Al, Byte Ptr [M8]
The PPro, PII and PIII processors make a special case out of this combination to avoid a partial register stall when later reading from EAX. The trick is that a register is tagged as empty when it is XOR'ed with itself. The processor remembers that THE ZERO, SO THAT $ Eax Area
MOV Al, 3
MOV EBX, EAX; no Stall
XOR AH, AH
MOV Al, 3
MOV BX, AX; No Stall
XOR EAX, EAX
Mov Ah, 3
MOV EBX, EAX; Stall
SUB EBX, EBX
MOV BL, DL
MOV ECX, EBX; No Stall
MOV EBX, 0
MOV BL, DL
MOV ECX, EBX; Stall
MOV BL, DL
XOR EBX, EBX; NO Stall
Setting a register to zero by subtracting it from itself Works The Same as the xor, but setting it to zero with the Mov Instruction Doesn't Prevent The Stall.
You can set the xor outside a loop:
XOR EAX, EAX
MOV ECX, 100
LL: MOV Al, [ESI]
MOV [EDI], EAX; No Stall
Inc ESI
Add Edi, 4
Dec ECX
JNZ LL
In the Upper 24 Bits of Eax Are The Upper 24 Bits of Eax Are The Upload, Misprediction, or OR Other Serializing Event.
You Should Remember To Neutralize Any Partial Register You Have Used Before Calling a Subroutine That Might Push The Full Register:
Add BL, Al
MOV [MEM8], BL
XOR EBX, EBX; Neutralize BL
Call _highlevelfunction
Most High Level Language Procedures Push Ebx At The Start of The Procedure Which Would Generate A Partial Register Stall In The Example Aboveness BL.
Setting a register to zero with the xor method Doesn't Break ITS Dependency On Earlier Instructions:
Div EBX
MOV [MEM], EAX
Mov Eax, 0; Break DependencyXor Eax, Eax; Prevent Partial Register Stall
MOV Al, Cl
Add Ebx, EAX
Setting Eax To Zero TWICE Here Seem Redundant, But Without the Mov Eax, 0 The Last Instructions Would Have To Wait For The Slow Div To Finish, And Without Xor Eax, Eax You Would Have A Partial Register Stall.
The FNSTSW AX instruction is special: in 32 bit mode it behaves as if writing to the entire EAX In fact, it does something like this in 32 bit mode:. AND EAX, 0FFFF0000h / FNSTSW TEMP / OR EAX, TEMP hence, you don 'T Get a Partial Register Stall When Reading Eax After this Instruction in 32 bit mode:
Fnstsw AX / MOV EBX, EAX; Stall ONLY IF 16 BIT MODE
MOV AX, 0 / FNSTSW AX; Stall ONLY IF 32 Bit Mode
19.2 Partial Flags Stalls
The Flags Register Can Also Cause Partial Register Stalls:
CMP EAX, EBX
Inc ECX
JBE XX; Partial Flags Stall
The JBE instruction reads both the carry flag and the zero flag. Since the INC instruction changes the zero flag, but not the carry flag, the JBE instruction has to wait for the two preceding instructions to retire before it can combine the carry flag from the CMP instruction and the zero flag from the INC instruction. This situation is likely to be a bug rather than an intended combination of flags. to correct it change INC ECX to ADD ECX, 1. A similar bug that causes a partial flags stall is SAHF / Jl xx. The Jl Instruction Tests The Sign Flag and the overflow flag, But Sahf Doesn't Change The overflow flag. To Correct IT, Change JL XX To JS XX.
Unexpectedly (and contrary to what intel manuals say) You Also Get a Partial Flags Stall An Instruction That Modifies Some of the Flag Bits When Reading Only Unmodified Flag Bits: CMP EAX, EBX
Inc ECX
JC XX; Partial Flags Stall
But not When Reading Only Modified Bits:
CMP EAX, EBX
Inc ECX
JE xx; no stall
Partial flags stalls are likely to occur on instructions that read many or all flags bits, ie LAHF, PUSHF, PUSHFD The following instructions cause partial flags stalls when followed by LAHF or PUSHF (D):. INC, DEC, TEST, bit tests, Bit Scan, CLC, STC, CMC, CLD, STD, CLI, STI, MUL, IMUL, AND All Shifts and Rotates. The Following Instructions: and, OR, XOR, Add, ADC, SUB, SBB , CMP, NEG. It is strange that TEST and aND behave differently while, by definition, they do exactly the same thing to the flags. You may use a SETcc instruction instead of LAHF or PUSHF (D) for storing the value of a flag In ORDER TO AVOID A Stall.
EXAMPLES:
Inc Eax / Pushfd; Stall
Add Eax, 1 / Pushfd; No Stall
SHR EAX, 1 / Pushfd; Stall
SHR EAX, 1 / OR EAX, EAX / PUSHFD; NO Stall
Test EBX, EBX / LAHF; Stall
And EBX, EBX / LAHF; NO Stall
Test EBX, EBX / Setz Al; No Stall
CLC / Setz Al; Stall
CLD / setz al; no stall
The Penalty for Partial Flags Stalls Is Approximately 4 Clocks.
19.3 Flags Stalls After Shifts and Rotates
You Can Get a stall reasoning the partial flags stall at a shift or rotate, Except for Shifts and Rotates by One (Short Form):
SHR EAX, 1 / JZ XX; No Stall
SHR EAX, 2 / JZ XX; Stall
SHR EAX, 2 / OR EAX, EAX / JZ XX; No Stall
SHR EAX, 5 / JC XX; StallShr Eax, 4 / SHR EAX, 1 / JC XX; No Stall
SHR EAX, CL / JZ XX; Stall, Even IF CL = 1
Shrd EAX, EBX, 1 / JZ XX; Stall
ROL EBX, 8 / JC XX; Stall
The Penalty For There Stalls Is ApproxImately 4 Clocks.
19.4 Partial Memory Stalls
A Partial Memory Stall Is Somewhat Analog to a Partial Register Stall. It Occurs When You Mix Data Sizes for the Same Memory Address:
MOV BYTE PTR [ESI], Al
MOV EBX, DWORD PTR [ESI]; Partial Memory Stall
Here you get a stall because the processor has to combine the byte written from AL with the next three bytes, which were in memory before, to get the four bytes needed for reading into EBX. The penalty is approximately 7-8 clocks.
Unlike The Partial Register Stalls, You Also Get A Partial Memory Stall When You Write a Bigger Operand To Memory and Then Read Part of It, IF The Smaller Part Doesn't Start At The Same Address:
Mov DWORD PTR [ESI], EAX
MOV BL, BYTE PTR [ESI]; No Stall
MOV BH, BYTE PTR [ESI 1]; Stall
You can avoid this stall by changing the last line to MOV BH, AH, But Such a Solution IS NOT POSSIBLE IN A SITION LIKE THIS:
Fistp Qword PTR [EDI]
MOV EAX, DWORD PTR [EDI]
MOV EDX, DWORD PTR [EDI 4]; Stall
Interestingly, You Can Also Get A Partial Memory Stall When Writing and Reading Completely Different Addresses If They Happen To Have The Same Set-Value In Different Cache Banks:
MOV BYTE PTR [ESI], Al
MOV EBX, DWORD PTR [ESI 4092]; No Stall
MOV ECX, DWORD PTR [ESI 4096]; Stall
20. Dependency Chains (PPRO, PII AND PIII)
A series of instructions where each instruction depends on the result of the preceding one is called a dependency chain Long dependency chains should be avoided, if possible, because they prevent out-of-order and parallel execution.Example.:
MOV EAX, [MEM1]
Add Eax, [MEM2]
Add Eax, [MEM3]
Add Eax, [MEM4]
MOV [MEM5], EAX
In this EaxMple, The Add Instructions Generate 2 Uops Each, One forread from Memory (Port 2), AND One for adding (port 0 or 1). The read uops can execute out or order, while the add uops virt wait for T previous uops to finish This dependency chain does not take very long to execute, because each addition adds only 1 clock to the execution time But if you have slow instructions like multiplications, or even worse:.. divisions, then you should definitely do something to Break the dependency chain. The Way to do this is to use multiple accumulators:
Mov Eax, [MEM1]; Start First Chain
MOV EBX, [MEM2]; Start Other Chain in Different Accumulator
Imul Eax, [MEM3]
Imul EBX, [MEM4]
Imul Eax, EBX; JOIN CHAINS IN THE END
MOV [MEM5], EAX
Here, The Second Imul Instruction Can Start Before The First One IS Finished. Since The Imul Instruction Has A Delay of 4 Clocks and is Fully Pipelined, You May Have Up To 4 Accumulators.
.
FLOATING POINT INTRUCTIONS HAVE A LONGER DELAY THAN INTEGER INSTRUCTIONS, SO you Should Definitely Break Up Long Dependency Chains with floating point instructions:
FLD [MEM1]; Start First Chain
FLD [MEM2]; Start Second Chain in Different Accumulator
Fadd [MEM3]
FXCH
Fadd [MEM4]
FXCH
Fadd [MEM5]
Fadd; Join Chains in the End
FSTP [MEM6]
You need a lot of FXCH instructions for this, but do not worry: they are cheap FXCH instructions are resolved in the RAT by register renaming so they do not put any load on the execution ports An FXCH does count as 1 uop.. In the Rat, Rob, And Retirement Station, Though.
IF The Dependency Chain Is Long You NEED Three Accumulators:
FLD [MEM1]; Start First Chain
FLD [MEM2]; Start Second Chain
FLD [MEM3]; Start Third Chain
Fadd [MEM4]; Third Chain
FXCH ST (1)
Fadd [Mem5]; SECOND CHAIN
FXCH ST (2)
Fadd [MEM6]; First Chain
FXCH ST (1)
Fadd [MEM7]; Third Chain
FXCH ST (2)
Fadd [MEM8]; Second Chain
FXCH ST (1)
Fadd; Join First and Third Chain
Fadd; Join with Second Chain
FSTP [MEM9]
Avoid Storing Intermediate Data in Memory and Read ThemmediatelyAfterwards:
MOV [Temp], EAX
MOV EBX, [TEMP]
There is a penalty for attempting to read from a memory address before a previous write to that address is finished. In the example above, change the last instruction to MOV EBX, EAX or put some other instructions in between.
There IS One Situation Where You Cannot Avoid Storing Intermediate Data In Memory, And That Is When Transferring Data from An Integer Register To A Floating Point Register, or Vice Versa. For Example:
MOV EAX, [MEM1]
Add Eax, [MEM2]
MOV [Temp], EAX
Fild [Temp]
IF you don't have anything to put in between the Write to Temp and the read from teit, the you may consider Using A Floating Point Register Instead of Eax:
Fild [MEM1]
FIADD [MEM2]
Consecutive jumps, calls, or returns may also be considered dependency chains. The throughput for these instructions is one jump per two clock cycles. It is therefore recommended that you give the microprocessor something else to do between the jumps.21. Searching for bottlenecks ( PPRO, PII and PIII)
When optimizing code for these processors, it is important to analyze where the bottlenecks are. Spending time on optimizing away one bottleneck does not make sense if there is another bottleneck which is narrower.
IF you expect code cache misses the you will..
If you expect many data cache misses then forget about everything else and concentrate on how to restructure your data to reduce the number of cache misses (chapter 7), and avoid long dependency chains after a data read cache miss (chapter 20).
IF you have managened the division.
Dependency chains tend to hamper out-of-order execution (chapter 20). Try to break long dependency chains, especially if they contain slow instructions such as multiplication, division, and floating point instructions.
If you have many jumps, calls, or returns, and especially if the jumps are poorly predictable, then try if some of them can be avoided. Replace conditional jumps with conditional moves if possible, and replace small procedures with macros (chapter 22.3).
If you are mixing different data sizes (8, 16, and 32 bit integers) then look out for partial stalls. If you use PUSHF or LAHF instructions then look out for partial flags stalls. Avoid testing flags after shifts or rotates by more than 1 (Chapter 19) .IF You AT A THROUGHPUT OF 3 uops per clock cycle the be aware of possible delays in instruction fetch and decoding (Chapter and 14 and 15), especially in small loops.
The limit of two permanent register reads per clock cycle may reduce your throughput to less than 3 uops per clock cycle (chapter 16.2). This is likely to happen if you often read registers more than 4 clock cycles after they last were modified. This may , for example, happen if you offten us ,,,,,,,,,,,,,,,,,,,,,,,
A Throughput of 3 UOps Per Clock Requires That No Execution Port Gets More Than One Third of THE UOPS (Chapter 17).
The Retirement Station CAN Handle 3 UOPS Per Clock, But May Be Slightly Less Effective For Taken Jumps (Chapter 18).
22. Jumps and branches (all processors)
The Pentium family of processors attempt to predict where a jump will go to, and whether a conditional jump will be taken or fall through. If the prediction is correct, then it can save a considerable amount of time by loading the subsequent instructions into the pipeline And Start Decoding Theme Before The Prediction Turns Out To Be Wrong, The Pipeline Has To BE Flushed, Which Will Cost A Penalty Depending on The length of the pipeline.
The predictions are based on a Branch Target Buffer (BTB) which stores the history for each branch or jump instruction and makes predictions based on the prior history of executions of each instruction. The BTB is organized like a set-associative cache where new entries are allocated according to a pseudo-random replacement method.When optimizing code, it is important to minimize the number of misprediction penalties. This requires a good understanding of how the jump prediction works.
The branch prediction mechanisms are not described adequately in Intel manuals or anywhere else. I am therefore giving a very detailed description here. This information is based on my own research (with the help of Karki Jitendra Bahadur for the PPlain).
In the following, I will use the term 'control transfer instruction' for any instruction which can change the instruction pointer, including conditional and unconditional, direct and indirect, near and far, jumps, calls, and returns. All these instructions use prediction.
22.1 Branch prediction in Pplain
The branch prediction mechanism for the PPlain is very different from the other three processors. Information found in Intel documents and elsewhere on this subject is directly misleading, and following the advises given is such documents is likely to lead to sub-optimal code.
The PPlain has a branch target buffer (BTB), which can hold information for up to 256 jump instructions. The BTB is organized like a 4-way set-associative cache with 64 entries per way. This means that the BTB can hold no more than 4 entries with the same set value. Unlike the data cache, the BTB uses a pseudo random replacement algorithm, which means that a new entry will not necessarily displace the least recently used entry of the same set-value. How the set-value is calculated will be explained later Each BTB entry stores the address of the jump target and a prediction state, which can have four different values:. state 0: "strongly not taken" state 1: "weakly not taken" state 2: "weakly Taken "State 3:" Strongly Taken "
A branch instruction is predicted to jump when in state 2 or 3, and to fall through when in state 0 or 1. The state transition works like a two-bit counter, so that the state is incremented when the branch is taken, and decremented when it falls through. The counter saturates, rather than wrap around, so that it does not decrement beyond 0 or increment beyond 3. Ideally, this would provide a reasonably good prediction, because a branch instruction would have to deviate twice from what it does Most of the time, before the prediction change.
However, this mechanism has been compromised by the fact that state 0 also means 'unused BTB entry'. So a BTB entry in state 0 is the same as no BTB entry. This makes sense, because a branch instruction is predicted to fall through if IT HAS NO BTB Entry. This Improves The Utilization of The BTB, Because A Branch Instruction Which IS Seldom Taken Will Most of The Time Not Take Up Any BTB Entry.
Now, if a jumping instruction has no BTB entry, then a new BTB entry will be generated, and this new entry will always be set to state 3. This means that it is impossible to go from state 0 to state 1 (except for a very special case discussed later). From state 0 you can only go to state 3, if the branch is taken. If the branch falls through, then it will stay out of the BTB.This is a serious design flaw. By throwing state 0 entries out of the BTB and always setting new entries to state 3, the designers apparently have given priority to minimizing the first time penalty for unconditional jumps and branches often taken, and ignored that this seriously compromises the basic idea behind the mechanism and reduces the performance in small innermost loops. The consequence of this flaw is, that a branch instruction which falls through most of the time will have up to three times as many mispredictions as a branch instruction which is taken most of the time. (Apparently, Intel engineers have B Een UnaWare of this flaw untric I public my findings.
You May Take this Asymmetry Into Account by Organizing Your Branches So That The isy. Consider for Example this if -hen-else Construction:
Test Eax, EAX
JZ A
JMP E
A:
E:
If branch 1 is executed more often than branch 2, and branch 2 is seldom executed twice in succession, then you can reduce the number of branch mispredictions by up to a factor 3 by swapping the two branches so that the branch instruction will jump more often Than Fall THROUGH:
Test Eax, EAX
JNZ A
JMP E
A:
E:
(This is contrary to the recommendations in intel's manuals and tutorials).
There may be reasons to put the most often executed branch first, however:. Putting seldom executed branches away in the bottom of your code can improve code cache utilization A branch instruction seldom taken will stay out of the BTB most of the time, possibly improving BRANCH INSTRUCTION. The Asymmetry In Branch Prediction Only The PPLICTION.
These considerations have little weight, however, for small critical loops, so I would still recommend organizing branches with a skewed distribution so that the branch instruction is taken more often than not, unless branch 2 is executed so seldom, that misprediction does not matter .
Likewise, you's ,,,,,,,,,,,,,,,,,,
MOV ECX, [N]
L: MOV [EDI], EAX
Add Edi, 4
Dec ECX
Jnz L
IF N IS High, THE JNZ INSTRUCTION Here Will Be Taken More Offen Than NOT, AND Never Fall Through TWICE IN SUCCESSION.
Consider the situation where a branch is taken every second time. The first time it jumps the BTB entry will go into state 3, and will then alternate between state 2 and 3. It is predicted to jump all the time, which gives 50% mispredictions Assume Now That It Deviates from this regular pattern and falls throughs.. The jump pattern is:
01010101010101010101010, WHERE 0 means nojump, AND 1 means jump.
^ The Extra Nojump is Idicated with a
^ Above. After this incident, the BTB entry will alternate between state 1 and 2, which gives 100% mispredictions. It will continue in this unfortunate mode until there is another deviation from the 0101 pattern. This is the worst case for this branch prediction mechanism.22.1.2 BTB is looking ahead (PPlain) The BTB mechanism is counting instruction pairs, rather than single instructions, so you have to know how instructions are pairing in order to analyze where a BTB entry is stored. The BTB entry for any AN UN Unpaired Instruction Counts as One Pair. EXAMPLE:
SHR EAX, 1
MOV EBX, [ESI]
CMP EAX, EBX
JB L
Here Shr Pairs with Mov, And Cmp Pairs with JB. The BTB Entry for JB L is Thr Eax, 1 Instruction. When this btb entry is met, and if it is in state 2 or 3, then the Pentium will read the target address from the BTB entry, and load the instructions following L into the pipeline. This happens before the branch instruction has been decoded, so the Pentium relies solely on the information in the BTB when doing this.
You may remember, that instructions are seldom pairing the first time they are executed (see chapter 8). If the instructions above are not pairing, then the BTB entry should be attached to the address of the CMP instruction, and this entry would be wrong on the next execution, when instructions are pairing. However, in most cases the PPlain is smart enough to not make a BTB entry when there is an unused pairing opportunity, so you do not get a BTB entry until the second execution, and hence you will not get a prediction until the third execution. (in the rare case, where every second instruction is a single-byte instruction, you may get a BTB entry on the first execution which becomes invalid in the second execution, but since the instruction it is attached to will then go to the V-pipe, it is ignored and gives no penalty. A BTB entry is only read if it is attached to the address of a U-pipe instruction) .A BTB entry is identified by its Set-Value Which Is Equal to Bits 0-5 of the Address I T is attached to. BITS 6-31 Are Tag. Addresses Which Are Spaced a Multiple of 64 Bytes Apart Will Have The Same Set-Value. You Can Have No More Than Four BTB Entries with the Same Set -value. If you want to check whether your jump instructions contend for the same BTB entries, then you have to compare bits 0-5 of the addresses of the U-pipe instructions in the preceding instruction pairs. This is very tedious, and I Have Never Heard of Anybody Doing So. There Are no Tools Available to do this job for you.
22.1.3 Consesecutive Branches (PPLAIN)
When a jump is mispredicted, then the pipeline gets flushed. If the next instruction pair executed also contains a control transfer instruction, then the PPlain will not load its target because it can not load a new target while the pipeline is being flushed. The result is that the second jump instruction is predicted to fall through regardless of the state of its BTB entry. Therefore, if the second jump is also taken, then you will get another penalty. The state of the BTB entry for the second jump instruction does get correctly updated, though. If you have a long chain of control transfer instructions, and the first jump in the chain is mispredicted, then the pipeline will get flushed all the time, and you will get nothing but mispredictions until you meet an instruction pair which Does Not Jump. The Most Extreme Case of this Is A Loop Which Jumps To Itself: It Will Get A Misprediction Penalty For Each Iteration.this is Not The Only Problem with Conncutive Control Transfer Instructions. Another problem is that you can have another branch instruction between a BTB entry and the control transfer instruction it belongs to If the first branch instruction jumps to somewhere else, then strange things may happen Consider this example..:
SHR EAX, 1
MOV EBX, [ESI]
CMP EAX, EBX
JB L1
JMP L2
L1: MOV EAX, EBX
Inc EBX
WHEN JB L1 Falls Through, He Will Get A BTB Entry For Jmp L2 Attached to The Address of Cmp Eax, EBX. But What Will Happen WHEN JB L1 LATER IS TAKEN? AT TIME WHEN TAKEN? AT TIME WHEN THE BTB Entry for JMP L2 Is Read, the processor does not know that the next instruction pair does not contain a jump instruction, so it will actually predict the instruction pair MOV EAX, EBX / INC EBX to jump to L2. The penalty for predicting non-jump instructions to jump is 3 clock cycles. The BTB entry for JMP L2 will get its state decremented, because it is applied to something which does not jump. If we keep going to L1, then the BTB entry for JMP L2 will be decremented to state 1 and 0, so that the problem will disappear until next time JMP L2 is executed.The penalty for predicting the non-jumping instructions to jump only occurs when the jump to L1 is predicted. In the case that JB L1 is mispredictedly jumping, then the pipeline gets flushed And we't get the false l2 target loaded, so in this case we will not SEE The Penalty of Predickning The Non-Jumping Instructions To Jump, But We do Get The BTB Entry for JMP L2 Decrement.
Suppose, now, that we replace the INC EBX instruction above with another jump instruction. This third jump instruction will then use the same BTB entry as JMP L2 with the possible penalty of predicting a wrong target, (unless it happens to also have L2 as Target).
To Summarize, Consecutive Jumps CAN Lead to the Following Problems:
failure to load a jump target when the pipeline is being flushed by a preceding mispredicted jump. a BTB entry being mis-applied to non-jumping instructions and predicting them to jump. a second consequence of the above is that a mis-applied BTB entry will get its state decremented, possibly leading to a later misprediction of the jump it belongs to. Even unconditional jumps can be predicted to fall through for this reason. two jump instructions may share the same BTB entry, leading to the prediction of a wrong target .All this message, SO You Should Definitely Avoid Having An Instruction Pair Containing a Jump Immediately After Another Poorly Predictable Control Transfer Instruction Or ITS Target.
IT IS Time for Another Illustrative Example:
Call P
Test Eax, EAX
JZ L2
L1: MOV [EDI], EBX
Add Edi, 4
Dec EAX
JNZ L1
L2: Call P
THIS LOOKS LIKE A QUITE NICE AND NORMAL PIECE OF CODE: A Function Call, a loop Which is bypasssed WHEN THE Count Is ZERO, AND ANOTHER FUNCTION CALL. How Many PROBLEMS CAN you spot in this program?
First, we may note that the function P is called alternatingly from two different locations. This means that the target for the return from P will be changing all the time. Consequently, the return from P will always be mispredicted.
Assume, now, that EAX is zero. The jump to L2 will not have its target loaded because the mispredicted return caused a pipeline flush. Next, the second CALL P will also fail to have its target loaded because JZ L2 caused a pipeline flush. Here we have the situation where a chain of consecutive jumps makes the pipeline flush repeatedly because the first jump was mispredicted. The BTB entry for JZ L2 is stored at the address of P's return instruction. This BTB entry will now be mis-applied to whatever comes after the second CALL P, but that does not give a penalty because the pipeline is flushed by the mispredicted second return.Now, let's see what happens if EAX has a nonzero value the next time: JZ L2 is always predicted to fall through because of the flush. The second CALL P has a BTB entry at the address of TEST EAX, EAX. This entry will be mis-applied to the MOV / ADD pair, predicting it to jump to P. This causes a flush which prevents JNZ L1 from loading its target. If we have been her e before, then the second CALL P will have another BTB entry at the address of DEC EAX. On the second and third iteration of the loop, this entry will also be mis-applied to the MOV / ADD pair, until it has had its state decremented to 1 or 0. This will not cause a penalty on the second iteration because the flush from JNZ L1 prevents it from loading its false target, but on the third iteration it will. The subsequent iterations of the loop have no penalties, but when it exits, JNZ L1 is mispredicted. The flush would now prevent CALL P from loading its target, were it not for the fact that the BTB entry for CALL P has already been destroyed by being mis-applied several times.
We can Improve this code by Putting in Some Nop's to Separate All Consecutive Jumps: Call P
Test Eax, EAX
NOP
JZ L2
L1: MOV [EDI], EBX
Add Edi, 4
Dec EAX
JNZ L1
L2: NOP
NOP
Call P
The extra NOP's cost 2 clock cycles, but they save much more. Furthermore, JZ L2 is now moved to the U-pipe which reduces its penalty from 4 to 3 when mispredicted. The only problem that remains is that the returns from P are always Mispredic THIS Problem CAN Only Be Solved by Replacing The Call To P by An Inline Macro (if You Have Enough Cache).
The lesson to learn from this example is that you should always look carefully for consecutive jumps and see if you can save time by inserting some NOP's. You should be particularly aware of those situations where misprediction is unavoidable, such as loop exits and returns from procedures Which Are Called from Varying Locations. If You Have Something Useful to Put in, Instead of The...
Multiway branches (case statements) may be implemented either as a tree of branch instructions or as a list of jump addresses. If you choose to use a tree of branch instructions, then you have to include some NOP's or other instructions to separate the consecutive branches ......................................... ..
22.1.4 Tight Loops (PPLAIN)
In a small loop you will often access the same BTB entry repeatedly with small intervals. This never causes a stall. Rather than waiting for a BTB entry to be updated, the PPlain somehow bypasses the pipeline and gets the resulting state from the last jump before . it has been written to the BTB This mechanism is almost transparent to the user, but it does in some cases have funny effects: You can see a branch prediction going from state 0 to state 1, rather than to state 3, if the zero has not yet been written to the BTB. This happens if the loop has no more than four instruction pairs. In loops with only two instruction pairs you may sometimes have state 0 for two consecutive iterations without going out of the BTB. In such small loops it also happens in rare cases that the prediction uses the state resulting from two iterations ago, rather than from the last iteration. These funny effects will usually not have any negative effects on performance.22.2 Branch prediction in PMMX, PPro, PII and PIII
22.2.1 BTB Organization (PMMX, PPRO, PII AND PIII)
The branch target buffer (BTB) of the PMMX has 256 entries organized as 16 ways * 16 sets. Each entry is identified by bits 2-31 of the address of the last byte of the control transfer instruction it belongs to. Bits 2-5 define the set, and bits 6-31 are stored in the BTB as a tag. Control transfer instructions which are spaced 64 bytes apart have the same set-value and may therefore occasionally push each other out of the BTB. Since there are 16 ways Per Set, this won't happen too offten.
The branch target buffer (BTB) of the PPro, PII and PIII has 512 entries organized as 16 ways * 32 sets. Each entry is identified by bits 4-31 of the address of the last byte of the control transfer instruction it belongs to. bits 4-8 define the set, and all bits are stored in the BTB as a tag. Control transfer instructions which are spaced 512 bytes apart have the same set-value and may therefore occasionally push each other out of the BTB. Since there are 16 ways per set, this will not happen too often.The PPro, PII and PIII allocate a BTB entry to any control transfer instruction the first time it is executed. The PMMX allocates it the first time it jumps. A branch instruction which never Jumps Will Stay Out of the btb on the pmmx. As soon as it has jumped, it will stay in the btb, eveniff it never jumps again.
.
22.2.2 Misprediction Penalty (PMMX, PPRO, PII AND PIII)
In the PMMX, The Penalty for Misprediction of a Conditional Jump IS 4 Clocks IN The U-PIPE, AND 5 Clocks IT IT IS Executed in The V-PIPE. For All Other Control Transfer Instructions IT IS 4 Clocks.
In the PPro, PII and PIII, the misprediction penalty is very high due to the long pipeline. A misprediction usually costs between 10 and 20 clock cycles. It is therefore very important to be aware of poorly predictable branches when running on PPro, PII and PIII.
22.2.3 Pattern Recognition for Conditional Jumps (PMMX, PPRO, PII AND PIII)
These processors have an advanced pattern recognition mechanism which will correctly predict a branch instruction which, for example, is taken every fourth time and falls through the other three times. In fact, they can predict any repetitive pattern of jumps and nojumps with a period of Up to FIVE, AND MANY PATTERNS WITH HIGHER Periods.The Mechanism Is A So-Called "Two-Level Adaptive Branch Prediction Scheme", Invented By T.-Y. Yeh and Yn Patt. it is based on the same kind of two- bit counters as described above for the PPlain (but without the assymmetry flaw). The counter is incremented when the jump is taken and decremented when not taken. There is no wrap-around when counting up from 3 or down from 0. A branch instruction is predicted to be taken when the corresponding counter is in state 2 or 3, and to fall through when in state 0 or 1. An impressive improvement is now obtained by having sixteen such counters for each BTB entry. It selects one of these sixteen counters Based on the history of the branch instruction for the last four executions. If, for example, the branch instruction jumps once and then falls through three times, then you have the history bits 1000 (1 = jump, 0 = nojump). This will make it Use counter Number 8 (1000 binary = 8) for predicing the next time and update counter 8 afterwards.
If the sequence 1000 is always followed by a 1, then counter number 8 will soon end up in its highest state (state 3) so that it will always predict a 1000 sequence to be followed by a 1. It will take two deviations from this pattern to change the prediction. The repetitive pattern 100010001000 will have counter 8 in state 3, and counter 1, 2 and 4 in state 0. The other twelve counters will be unused.22.2.4 Perfectly predicted patterns (PMMX, PPro, PII and PIII)
A Repetitive Branch Pattern Is Predicted Perfectly by this Mechanism if Every PERIOD IS UNIQUE. BELOW IS A List of Repetitive Branch Patterns Which Are PredicTED Perfect
period perfectly predicted patterns 1-5all6000011, 000101, 000111, 00101170000101, 0000111, 0001011800001011, 00001111, 00010011, 00010111, 001011019000010011, 000010111, 000100111, 000101101100000100111, 0000101101, 0000101111, 0000110111, 0001010011, 00010111011100001001111, 00001010011, 00001011101, 0001010011112000010100111, 000010111101, 000011010111, 000100110111, 000100111011130000100110111, 0000100111011, 00001010011111400001001101111, 00001001111011, 00010011010111, 00010011101011, 00010110011101, 0001011010011115000010011010111, 000010011101011, 000010100110111, 000010100111011, 000010110011101, 000010110100111, 000010111010011, 000011010010111160000100110101111, 0000100111101011, 0000101100111101, 0000101101001111
When reading this table, you should be aware that if a pattern is predicted correctly than the same pattern reversed (read backwards) is also predicted correctly, as well as the same pattern with all bits inverted Example:. In the table we find the pattern : 0001011. Reversing this pattern gives: 1101000. Inverting all bits gives: 1110100. Both reversing and inverting: 0010111. These four patterns are all recognizable Rotating the pattern one place to the left gives:. 0010110. This is of course not a new pattern, only a phase shifted version of the same pattern. All patterns which can be derived from one of the patterns in the table by reversing, inverting and rotating are also recognizable. For reasons of brevity, these are not listed.It takes two periods for the pattern recognition mechanism to learn a regular repetitive pattern after the BTB entry has been allocated. The pattern of mispredictions in the learning period is not reproducible. This is probably because the BTB entry conta Ined Something Prior To Allocated According to a Random Scheme, There is Little Chance of Predicting What Happens During The Initial Learning Period.
22.2.5 Handling Deviations from A Regular Pattern (PMMX, PPRO, PII AND PIII)
The branch prediction mechanism is also extremely good at handling 'almost regular' patterns, or deviations from the regular pattern. Not only does it learn what the regular pattern looks like. It also learns what deviations from the regular pattern look like. If deviations are Always of the Same Type, The IT Will Remember What Coms After The Irregular Event, and The Deviation Will Cost Only One Misprediction.
EXAMPLE:
000111001011110111000101110010111000111000101110000
^ ^ In this sequence, a 0 means nojump, a 1 means jump. The mechanism learns that the repeated sequence is 000111. The first irregularity is an unexpected 0, which I have marked with a ^. After this 0 the next three jumps may be mispredicted, because it has not learned what comes after 0010, 0101, and 1011. After one or two irregularities of the same kind it has learned that after 0010 comes a 1, after 0101 comes 1, and after 1011 comes 1. This Means That After at Most Two Irregularity of the Same Kind, It Has Learned to Handle This Kind of Irregularity With Only One Misprediction.
The prediction mechanism is also very effective when alternating between two different regular patterns. If, for example, we have the pattern 000111 (with period 6) repeated many times, then the pattern 01 (period 2) many times, and then return to the 000111 pattern, then the mechanism does not have to relearn the 000111 pattern, because the counters used in the 000111 sequence have been left un-touched during the 01 sequence. After a few alternations between the two patterns, it has also learned to handle The Changes of Pattern with Only One Misprediction for Each Time The Pattern is Switch.
22.2.6 Patterns Which Are Not PredicTED Perfectly (PMMX, PPRO, PII AND PIII)
The SimpleSt Branch Pattern Which Cannot Be Predicted Perfectly Is A Branch Which is Taken on Every Pattern IS:
000001000001000001
^^ ^^ ^^
AB AB AB
The sequence 0000 is alternatingly followed by a 0, in the positions marked a above, and by a 1, in the positions marked b. This affects counter number 0 which will count up and down all the time. If counter 0 happens to start in state 0 or 1, then it will alternate between state 0 and 1. This will lead to a misprediction in position b. If counter 0 happens to start in state 3, then it will alternate between state 2 and 3 which will cause a misprediction in position a. The worst case is when it starts in state 2. It will alternate between state 1 and 2 with the unfortunate consequence that we get a misprediction both in position a and b. (This is analogous to the worst case for the PPlain explained above). Which of these four situations we will get depends on the history of the BTB entry prior to allocation to this branch. This is beyond our control because of the random allocation method.In principle, it is possible to avoid the worst case situation WHERE WE HAVE TWO MISPREDICTIONS PE r cycle by giving it an initial branch sequence which is specially designed for putting the counter in the desired state. Such an approach can not be recommended, however, because of the considerable extra code complexity required, and because whatever information we have put into the counter Is Likey to Be Lost During The next Timer Interrupt or Task Switch.
22.2.7 Completely Random Patterns (PMMX, PPRO, PII AND PIII)
............
The Following Table Lists The Experimental Fraction of Mispredictions for a Completely Random Sequence of Jumps and nojumps:
fraction of jumps / nojumps fraction of mispredictions 0.001 / 0.9990.0010010.01 / 0.990.01010.05 / 0.950.05250.10 / 0.900.1100.15 / 0.850.1710.20 / 0.800.2350.25 / 0.750.3000.30 / 0.700.3620.35 / 0.650.4180.40 / 0.600.4620.45 / 0.550.4900.50/0.500.500The fraction of mispredictions is slightly higher than it would be without pattern recognition because the processor keeps trying to find repeated patterns in a sequence which has no regularities.
22.2.8 Tight Loops (PMMX)
The branch prediction is not reliable in tiny loops where the pattern recognition mechanism does not have time to update its data before the next branch is met. This means that simple patterns, which would normally be predicted perfectly, are not recognized. Incidentally, some patterns which normally would not be recognized, are predicted perfectly in tight loops. for example, a loop which always repeats 6 times would have the branch pattern 111110 for the branch instruction at the bottom of the loop. This pattern would normally have one or two mispredictions per iteration, but in a tight loop it has none. The same applies to a loop which repeats 7 times. Most other repeat counts are predicted poorer in tight loops than normally. This means that a loop which iterates 6 or 7 times should preferably .
To find out whether a loop will behave as 'tight' on the PMMX you may follow the following rule of thumb:. Count the number of instructions in the loop If the number is 6 or less, then the loop will behave as tight If. you have more than 7 instructions, then you can be reasonably sure that the pattern recognition functions normally. strangely enough, it does not matter how many clock cycles each instruction takes, whether it has stalls, or whether it is paired or not. Complex integer instructions do not count. A loop can have lots of complex integer instructions and still behave as a tight loop. A complex integer instruction is a non-pairable integer instruction which always takes more than one clock cycle. Complex floating point instructions and MMX instructions still count as one. Note, that this rule of thumb is heuristic and not completely reliable. In important cases you may want to do your own testing. you can use performance monitor counter number 35H for the PMMX to count branch mispredictions. Test results may not be completely deterministic, because branch predictions may depend on the history of the BTB entry prior to allocation.Tight loops on PPro, PII and PIII are predicted normally, and take minimum two clock cycles per iteration.
22.2.9 Indirect Jumps and Calls (PMMX, PPRO, PII AND PIII)
............... ..
22.2.10 Jecxz and Loop (PMMX)
There is no pattern recognition for these two instructions in the PMMX. They are simply predicted to go the same way as last time they were executed. These two instructions should be avoided in time-critical code for PMMX. (In PPro, PII and PIII THEY Are Predicted Using Pattern Recognition, But The Loop Instruction Is Still Inferior To Dec ECX / JNZ). 22.2.11 Returns (PMMX, PPRO, PII AND PIII)
The PMMX, PPro, PII and PIII processors have a Return Stack Buffer (RSB) which is used for predicting return instructions. The RSB works as a First-In-Last-Out buffer. Each time a call instruction is executed, the corresponding return address is pushed into the RSB. and each time a return instruction is executed, a return address is pulled out of the RSB and used for prediction of the return. This mechanism makes sure that return instructions are correctly predicted when the same subroutine is called from Several DiffERENT LOCATIONS.
In order to make sure this mechanism works correctly, you must make sure that all calls and returns are matched. Never jump out of a subroutine without a return and never use a return as an indirect jump if speed is critical.
The RSB can hold four entries in the PMMX, sixteen in the PPro, PII and PIII. In the case where the RSB is empty, the return instruction is predicted in the same way as an indirect jump, ie it is expected to go to the Same Target As It Did Last Time.
On the PMMX, when subroutines are nested deeper than four levels then the innermost four levels use the RSB, whereas all subsequent returns from the outer levels use the simpler prediction mechanism as long as there are no new calls. A return instruction which uses the RSB still occupies a BTB entry. Four entries in the RSB of the PMMX does not sound of much, but it is probably sufficient. Subroutine nesting deeper than four levels is certainly not unusual, but only the innermost levels matter in terms of speed, except possibly for recursive procedures.On the PPro, PII and PIII, when subroutines are nested deeper than sixteen levels then the innermost 16 levels use the RSB, whereas all subsequent returns from the outer levels are mispredicted. Recursive subroutines should therefore not go deeper than 16 Levels.
22.2.12 static prediction in pmmx
A Control Transfer Instruction Which Has Not Been Seen Before or Which Is Not in The BTB IS ALWAYS PREDICTED TO Fall Through On The Pmmx. It Doesn't Matter WHether It Goes Forward or Backwards.
A branch instruction will not get a BTB entry if it always falls through. As soon as it is taken once, it will get into the BTB and stay there no matter how many times it falls through. A control transfer instruction can only go out of .
Any Control Transfer Instruction Which Jumps To The Address Immediately Following Itself Will Not get a btb entry. EXAMPLE:
JMP Short LL
LL:
This Instruction Will Never Get A BTB Entry and Therefore Always Have A Misprediction Penalty.
22.2.13 Static Prediction In PPRO, PII AND PIII
On PPro, PII and PIII, a control transfer instruction which has not been seen before or which is not in the BTB is predicted to fall through if it goes forwards, and to be taken if it goes backwards (eg a loop). Static prediction takes longer time than dynamic prediction on these processors.If your code is unlikely to be cached then it is preferred to have the most frequently executed branch fall through in order to improve prefetching.
22.2.14 Close Jumps (PMMX)
On The Pmmx, There Is A Risk That Two Control Transfer Instructions Will Share Too Close To each other. The obvious result is what.
The BTB entry for a control transfer instruction is identified by bits 2-31 of the address of the last byte in the instruction. If two control transfer instructions are so close together that they differ only in bits 0-1 of the address, then we Have The Problem of a Shared BTB Entry. EXAMPLE:
Call P
JNC Short L
If the last byte of the CALL instruction and the last byte of the JNC instruction lie within the same dword of memory, then we have the penalty. You have to look at the output list file from the assembler to see whether the two addresses are separated By A DWORD Boundary or Not. (A DWORD Boundary is an address divisible by 4).
There are various ways to solve this problem: 1. Move the code sequence a little up or down in memory so that you get a dword boundary between the two addresses 2. Change the short jump to a near jump (with 4 bytes displacement). so that the end of the instruction is moved further down. There is no way you can force the assembler to use anything but the shortest form of an instruction so you have to hard-code the near branch if you choose this solution. 3. Put in some instruction between the CALL and the JNC instructions. This is the easiest method, and the only method if you do not know where DWORD boundaries are because your segment is not dword aligned or because the code keeps moving up and down as you make Changes in The Preceding Code: Call P
Mov Eax, Eax; Two Bytes Filler to Be Safe
JNC Short L
If You Want to Avoid Problems on The PPLAIN TOO, THEN PUT IN Two Nop's Instead to Prevent Pairing (See Section 22.1.3 Above).
THE RET INSTRUCTION IS PARTICLARLARLARLARLY THIS This Problem Because IT IS Only One Byte Long:
Jnz next
RET
Here You May NEED UP THREE BYTES OF FILLERS:
Jnz next
NOP
Mov Eax, EAX
RET
22.2.15 Consecutive Calls or Returns (PMMX)
THE IS a Penalty WHEN THE FIRE INSTRUCTION PAIR FOLLOWING The Target Label of a Call Contains Another Call instruction or if a return Follows Immediately After ANOTHER RETURN. EXAMPLE:
Func1 Proc Near
NOP; Avoid Call After Call
NOP
Call Func2
Call Func3
Nop; Avoid Return AfTer Return
RET
Func1 ENDP
Two NOP's are required before CALL FUNC2 because a single NOP would pair with the CALL. One NOP is enough before the RET because RET is unpairable. No NOP's are required between the two CALL instructions because there is no penalty for call after return. (On the PPlain you would need two NOP's here too) .The penalty for chained calls only occurs when the same subroutines are called from more than one location (probably because the RSB needs updating). chained returns always have a penalty. There is sometimes a small Stall for a Jump after a call, but no penalty for return at call; call at return; jump, call, or return atter jump; or jump after return.
22.2.16 Chained Jumps (PPRO, PII AND PIII)
A jump, call, or return can not be executed in the first clock cycle after a previous jump, call, or return. Therefore, chained jumps will take two clock cycles for each jump, and you may want to make sure that the processor has something Else to do in Parallel. for the Same Reason, a Loop Will Take At Least Two Clock Cycles Per Iteration On these Processors.
22.2.17 Designing for Branch Predictabiligy (PMMX, PPRO, PII AND PIII)
Multiway branches (switch / case statements) are implemented either as an indirect jump using a list of jump addresses, or as a tree of branch instructions. Since indirect jumps are poorly predicted, the latter method may be preferred if easily predicted patterns can be expected And you have enough to use the the former method, the it is recommended That You Put the list of jump address.
You may want to reorganize your code so that branch patterns which are not predicted perfectly can be replaced by other patterns which are. Consider, for example, a loop which always executes 20 times. The conditional jump at the bottom of the loop is taken 19 times and falls through every 20'th time. This pattern is regular, but not recognized by the pattern recognition mechanism, so the fall-through is always mispredicted. You may make two nested loops by four and five, or unroll the loop by four and let it execute 5 times, in order to have only recognizable patterns. This kind of complicated schemes are only worth the extra code on the PPro, PII and PIII processors where mispredictions are very expensive. For higher loop counts there is no reason to do Anything About The Single Misprediction.22.3. Avoiding Jumps (All Processors)
There Can Be Many Reasons Why You May Want Reduce The Number of Jumps, Calls and Returns:
jump mispredictions are very expensive, there are various penalties for consecutive or chained jumps, depending on the processor, jump instructions may push one another out of the branch target buffer because of the random replacement algorithm, a return takes 2 clocks on PPlain and PMMX, calls and returns generate 4 uops on PPro, PII and PIII. on PPro, PII and PIII, instruction fetch may be delayed after a jump (chapter 15), and retirement may be slightly less effective for taken jumps then for other uops (chapter 18 ).
Calls and returns can be avoided by replacing small procedures with inline macros. And in many cases it is possible to reduce the number of jumps by restructuring your code. For example, a jump to a jump should be replaced by a jump to the final target . In some cases this is even possible with conditional jumps if the condition is the same or is known. A jump to a return can be replaced by a return. If you want to eliminate a return to a return, then you should not manipulate the stack pointer because that would interfere with the prediction mechanism of the return stack buffer. Instead, you can replace the preceding call with a jump. For example CALL PRO1 / RET can be replaced by JMP PRO1 if PRO1 ends with the same kind of RET. You May Also Eliminate A Jump by Dublicating The Code Jumped to. This Can Be Useful if You Have A Two-Way Branch Inside a loop or Before A Return. EXAMPLE:
A: CMP [EAX 4 * EDX], ECX
Je B
Call x
JMP C
B: Call Y
C: Inc EDX
JNZ A
MOV ESP, EBP
POP EBP
RET
THE JUMP TO C May Be Eliminated by Dublicating The Loop Epilog:
A: CMP [EAX 4 * EDX], ECX
Je B
Call x
Inc EDX
JNZ A
JMP D
B: Call Y
C: Inc EDX
JNZ A
D: MOV ESP, EBP
POP EBP
RET
The most often executed branch should come first here. The jump to D is outside the loop and therefore less critical. If this jump is executed so often that it needs optimizing too, then replace it with the three instructions following D.
22.4. Avoiding Conditional Jumps by Using Flags (All Processors)
The most important jumps to eliminate are conditional jumps, especially if they are poorly predictable. Sometimes it is possible to obtain the same effect as a branch by ingenious manipulation of bits and flags. For example you may calculate the absolute value of a signed number without Branching: CDQ
XOR EAX, EDX
Sub Eax, EDX
(On PPLAIN AND PMMX, USE MOV EDX, EAX / SAR EDX, 31 INSTEAD OF CDQ).
The Carry Flag Is Particularly Useful for this Kind of Tricks: Setting Carry if a value is Zero: CMP [Value], 1 setting carry if a value is not zero: xor Eax, Eax / Cmp Eax, [value] incrementing a counter Carry: ADC EAX, 0 SETTING A BIT for Each Time The Carry Is Set: RCL EAX, 1 Generating A Bit Mask IF Carry IS Set: SBB Eax, Eax Setting A Bit On AN Arbitrary All Bits ON AN Arbitrary Condition: xor eax, eax / setncond Al / Dec Eax (Remember to Reverse The Condition In the Last Example)