<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body style="word-wrap: break-word; -webkit-nbsp-mode: space; line-break: after-white-space;" class=""><br class=""><div><blockquote type="cite" class=""><div class="">On Mar 1, 2018, at 9:22 AM, Andrea Di Biagio <<a href="mailto:andrea.dibiagio@gmail.com" class="">andrea.dibiagio@gmail.com</a>> wrote:</div><br class="Apple-interchange-newline"><div class=""><div dir="ltr" class="">Hi all,<br class=""><br class="">At Sony we developed an LLVM based performance analysis tool named llvm-mca. We<br class="">currently use it internally to statically measure the performance of code, and<br class="">to help triage potential problems with target scheduling models.  We decided to<br class="">post this RFC because we are interested in the feedback from the community, and<br class="">we also believe that other people might be interested in a tool like this.<br class=""></div></div></blockquote><div><br class=""></div>This is a dream come true!</div><div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">llvm-mca uses information which is already available in LLVM (e.g. scheduling<br class="">models) to statically measure the performance of machine code in a specific cpu.<br class="">Performance is measured in terms of throughput as well as processor resource<br class="">consumption.  The tool currently works for processors with an out-of-order<br class="">backend, for which there is a scheduling model available in LLVM.<br class=""><br class="">The main goal of this tool is not just to predict the performance of the code<br class="">when run on the target, but also help with diagnosing potential performance<br class="">issues.<br class=""></div></div></blockquote><div><br class=""></div>You can’t really have one without the other, which is why this is a dream come true.</div><div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">Given an assembly code sequence, llvm-mca estimates the IPC (instructions per<br class="">cycle), as well as hardware resources pressure. The analysis and reporting style<br class="">were inspired by the IACA tool from Intel.<br class=""><br class="">The presence of long data dependency chains, as well as poor usage of hardware<br class="">resources may lead to bottlenecks in the back-end.  The tool is able to generate<br class="">a detailed report which should help with identifying and analyzing sources of<br class="">bottlenecks.<br class=""><br class="">Scheduling models are mostly used to compute instruction latencies, to obtain<br class="">read-advance information, and understand how processor resources are used by<br class="">instructions.  By design, the quality of the performance analysis conducted by<br class="">the tool is inevitably affected by the quality of the target scheduling models. <br class=""><br class="">However, scheduling models intentionally do not describe all processors details,<br class="">since the goal is just to enable the scheduling of machine instructions during<br class="">compilation. That means, there are processor details which are not important for<br class="">the purpose of scheduling instructions (and therefore not described by the<br class="">scheduling model), but are very important for this tool.<br class=""></div></div></blockquote><div><br class=""></div><div>The LLVM machine model can have as much detail as we want, as long as it’s opt-in for targets.</div><div>We’ve always had more detail than the generic scheduler actually needed. e.g. the scheduler doesn’t currently care how big the per-resource buffer sizes are.</div><div>Targets have their own scheduling strategies that can pick and choose.</div><div><br class=""></div><div>At one point I wrote code that could be called by the scheduler to simulate OOO execution at much greater detail, but the benefit didn’t justify the complexity and compile time. I always felt that a static analysis tool was the right place for this kind of simulation.</div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">A few examples of details that are missing in scheduling models are:<br class=""> - Maximum number of instructions retired per cycle.<br class=""></div></div></blockquote><div><br class=""></div>MicroOpBufferSize is presumed to cover register renaming and retirement, assuming they are well-balanced. For your tool, you certainly want to be more precise.</div><div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class=""> - Actual dispatch width (it often differs from the issue width).<br class=""></div></div></blockquote><div><br class=""></div>This was always a hard one to generalize in a machine independent way, and half the world seems to swap the meaning of those terms. If you’re going to make this distinction please define the terms clearly in the machine model and explain how tools are expected to use the information.</div><div><br class=""></div><div>Currently IssueWidth is used to tell the scheduler that ’N' microops will definitely take ’N’ / ‘IssueWidth’ cycles regardless of which functional units or dispatch pipeline is involved.</div><div><br class=""></div><div>[Reading below, I saw that you define instruction “dispatch" as what the LLVM machine model calls “issue”. LLVM doesn’t model dispatch directly because, by its definition, it is redundant with the number of function units, modulo some dynamic behavior that can’t be statically predicted anyway]</div><div><br class=""></div><div>We also don’t model decoding, because, presumably you hit the micro-op limit first.</div><div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class=""> - Number of temporary registers available for renaming.<br class=""></div></div></blockquote><div><br class=""></div>See MicroOpBufferSize above.</div><div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class=""> - Number of read/write ports in the register file(s).<br class=""></div></div></blockquote><div><br class=""></div>The assumption is that we hit micro-op issue width first. I suppose it’s good to have though.</div><div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class=""> - Length of the load/store queue in the LSUnit.<br class=""></div></div></blockquote><div><br class=""></div>That was supposed to be covered by per-processor-resource buffer size. Maybe you want to simulate the load/store queue differently from other functional units? e.g. one shared queue across multiple load store units?</div><div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">It is also very difficult to find a "good" abstract model to describe the<br class="">behavior of out-of-order processors. So, we have to keep in mind that all of<br class="">these aspects are going to affect the quality of the static analysis performed<br class="">by the tool.<br class=""></div></div></blockquote><div><br class=""></div><div>Like the scheduler, the tool should be extensible so that different targets can simulate behavior that doesn’t fit some abstract model.</div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">An extensive list of known limitations is reported in one of the last sections<br class="">of this document. There is also a section related to design problems which must<br class="">be addressed (hopefully with the help of the community).  At the moment, the<br class="">tool has been mostly tested for x86 targets, but there are still several<br class="">limitations, some of which could be overcome by integrating extra information<br class="">into the scheduling models.<br class=""><br class="">As was mentioned before, this tool has been (and is still being) used internally<br class="">in Sony to debug/triage issues in the btver2 scheduling model. We have also<br class="">tested it on other targets to check how generic the tool is. In our experience,<br class="">the tool makes it easy to identify simple mistakes like "wrong number of micro<br class="">opcodes specified for an instruction", or "wrong set of hardware resources".<br class="">Some of these mistakes are quite common (sometimes on mature models too), and<br class="">often difficult to catch.  Reports generated by this tool are simple to analyze,<br class="">and contain enough details to help triage most performance problems.<br class=""><br class="">1. How the tool works<br class="">——————————</div></div></blockquote><div><br class=""></div>Nice documentation. Please find a good place for it to live and include it in your patch.</div><div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class=""><snip><br class=""></div></div></blockquote><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">Timeline View<br class="">-------------<br class=""><br class="">A detailed report of each instruction's state transitions over time can be<br class="">enabled using the command line flag '-timeline'.  This prints an extra section<br class="">in the report which contains the so-called "timeline view".  Below is the<br class="">timeline view for the dot-product example from the previous section.<br class=""><br class="">///////////////<br class="">Timeline view:<br class="">                   012345<br class="">Index    0123456789      <br class=""><br class="">[0,0]    DeeER.    .    .    vmulps    %xmm0, %xmm1, %xmm2<br class="">[0,1]    D==eeeER  .    .    vhaddps    %xmm2, %xmm2, %xmm3<br class="">[0,2]    .D====eeeER    .    vhaddps    %xmm3, %xmm3, %xmm4<br class=""><br class="">[1,0]    .DeeE-----R    .    vmulps    %xmm0, %xmm1, %xmm2<br class="">[1,1]    . D=eeeE---R   .    vhaddps    %xmm2, %xmm2, %xmm3<br class="">[1,2]    . D====eeeER   .    vhaddps    %xmm3, %xmm3, %xmm4<br class=""><br class="">[2,0]    .  DeeE-----R  .    vmulps    %xmm0, %xmm1, %xmm2<br class="">[2,1]    .  D====eeeER  .    vhaddps    %xmm2, %xmm2, %xmm3<br class="">[2,2]    .   D======eeeER    vhaddps    %xmm3, %xmm3, %xmm4<br class=""></div></div></blockquote><div><br class=""></div>Truly awesome.</div><div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class=""><br class=""><br class="">Extra statistics to further diagnose performance issues.<br class="">--------------------------------------------------------<br class=""><br class="">Flag '-verbose' enables extra statistics and performance counters for the<br class="">dispatch logic, the reorder buffer, the retire control unit and the register<br class="">file.<br class=""><br class="">Below is an example of verbose output generated by the tool for the dot-product<br class="">example discussed in the previous sections.<br class=""><br class="">///////////////////<br class="">Iterations:     300<br class="">Instructions:   900<br class="">Total Cycles:   610<br class="">Dispatch Width: 2<br class="">IPC:            1.48<br class=""><br class=""><br class="">Dynamic Dispatch Stall Cycles:<br class="">RAT     - Register unavailable:                      0<br class="">RCU     - Retire tokens unavailable:                 0<br class="">SCHEDQ  - Scheduler full:                            272<br class="">LQ      - Load queue full:                           0<br class="">SQ      - Store queue full:                          0<br class="">GROUP   - Static restrictions on the dispatch group: 0<br class=""><br class=""><br class="">Register Alias Table:<br class="">Total number of mappings created: 900<br class="">Max number of mappings used:      35<br class=""><br class=""><br class="">Dispatch Logic - number of cycles where we saw N instructions dispatched:<br class="">[# dispatched], [# cycles]<br class=""> 0,              24  (3.9%)<br class=""> 1,              272  (44.6%)<br class=""> 2,              314  (51.5%)<br class=""><br class=""><br class="">Schedulers - number of cycles where we saw N instructions issued:<br class="">[# issued], [# cycles]<br class=""> 0,          7  (1.1%)<br class=""> 1,          306  (50.2%)<br class=""> 2,          297  (48.7%)<br class=""><br class=""><br class="">Retire Control Unit - number of cycles where we saw N instructions retired:<br class="">[# retired], [# cycles]<br class=""> 0,           109  (17.9%)<br class=""> 1,           102  (16.7%)<br class=""> 2,           399  (65.4%)<br class=""><br class=""><br class="">Scheduler's queue usage:<br class="">JALU01,  0/20<br class="">JFPU01,  18/18<br class="">JLSAGU,  0/12<br class="">///////////////////<br class=""></div></div></blockquote><div><br class=""></div>So great!</div><div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">LLVM-MCA instruction flow<br class="">-------------------------<br class=""><br class="">This section describes the instruction flow through the out-of-order backend, as<br class="">well as the functional units involved in the process. <br class=""><br class="">An instruction goes through a default sequence of stages:<br class="">    - Dispatch (Instruction is dispatched to the schedulers).<br class="">    - Issue (Instruction is issued to the processor pipelines).<br class="">    - Write Back (Instruction is executed, and results are written back).<br class="">    - Retire (Instruction is retired; writes are architecturally committed).<br class=""><br class="">The tool only models the out-of-order portion of a processor. Therefore, the<br class="">instruction fetch and decode stages are not modeled. Performance bottlenecks in<br class="">the frontend are not diagnosed by this tool.  The tool assumes that instructions<br class="">have all been decoded and placed in a queue.  Also, the tool doesn't know<br class="">anything about branch prediction.<br class=""></div></div></blockquote><div><br class=""></div><div>The following sections are fantastic documentation for your tool and the machine model in general. I hope you check all this in somewhere.</div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">Instruction Dispatch<br class="">--------------------<br class=""><br class="">During the Dispatch stage, instructions are picked in program order from a queue<br class="">of already decoded instructions, and dispatched in groups to the hardware<br class="">schedulers.  The dispatch logic is implemented by class DispatchUnit in file<br class="">Dispatch.h.<br class=""><br class="">The size of a dispatch group depends on the availability of hardware resources,<br class="">and it cannot exceed the value of field 'DispatchWidth' in class DispatchUnit.<br class="">Note that field DispatchWidth defaults to the value of field 'IssueWidth' from<br class="">the scheduling model.<br class=""><br class="">Users can override the DispatchWidth value with flag "-dispatch=<N>" (where 'N'<br class="">is an unsigned quantity).<br class=""><br class="">An instruction can be dispatched if:<br class=""> - The size of the dispatch group is smaller than DispatchWidth<br class=""> - There are enough entries in the reorder buffer<br class=""> - There are enough temporary registers to do register renaming<br class=""> - Schedulers are not full.<br class=""></div></div></blockquote><div><br class=""></div><div>This is really what’s meant by LLVM’s IssueWidth. I think Intel always preferred to call it “dispatch”. Presumably, instructions are buffered before being dispatched/issued to functional units, so LLVM’s “IssueWidth” is meant to model a hardware restriction that is independent from the number of functional units (processor resources).</div><div><br class=""></div><div>It’s especially confusing because some µArchs have dispatch pipelines decoupled from the functional units.</div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">Scheduling models don't describe register files, and therefore the tool doesn't<br class="">know if there is more than one register file, and how many temporaries are<br class="">available for register renaming.<br class=""></div></div></blockquote><div><br class=""></div><div>The LLVM machine model can model the size of the register renaming pool if you like.</div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">By default, the tool (optimistically) assumes a single register file with an<br class="">unbounded number of temporary registers.  Users can limit the number of<br class="">temporary registers available for register renaming using flag<br class="">`-register-file-size=<N>`, where N is the number of temporaries.  A value of<br class="">zero for N means 'unbounded'.  Knowing how many temporaries are available for<br class="">register renaming, the tool can predict dispatch stalls caused by the lack of<br class="">temporaries.<br class=""><br class="">The number of reorder buffer entries consumed by an instruction depends on the<br class="">number of micro-opcodes it specifies in the target scheduling model (see field<br class="">'NumMicroOpcodes' of tablegen class ProcWriteResources and its derived classes;<br class="">TargetSchedule.td).<br class=""><br class="">The reorder buffer is implemented by class RetireControlUnit (see Dispatch.h).<br class="">Its goal is to track the progress of instructions that are "in-flight", and<br class="">retire instructions in program order.  The number of entries in the reorder<br class="">buffer defaults to the value of field 'MicroOpBufferSize' from the target<br class="">scheduling model.<br class=""><br class="">Instructions that are dispatched to the schedulers consume scheduler buffer<br class="">entries.  The tool queries the scheduling model to figure out the set of<br class="">buffered resources consumed by an instruction.  Buffered resources are treated<br class="">like "scheduler" resources, and the field 'BufferSize' (from the processor<br class="">resource tablegen definition) defines the size of the scheduler's queue.<br class=""><br class="">Zero latency instructions (for example NOP instructions) don't consume scheduler<br class="">resources.  However, those instructions still reserve a number of slots in the<br class="">reorder buffer.<br class=""></div></div></blockquote><div><br class=""></div><div>As currently modeled by dummy µOps:</div><div><br class=""></div><div>// A single nop micro-op (uX).</div><div>def WriteX : SchedWriteRes<[]> { let Latency = 0; }</div><div><br class=""></div><div>You’ll need MachineInstr’s though.</div></div><div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">Instruction Issue<br class="">-----------------<br class=""><br class="">As mentioned in the previous section, each scheduler resource implements a queue<br class="">of instructions.  An instruction has to wait in the scheduler's queue until<br class="">input register operands become available.  Only at that point, does the<br class="">instruction becomes eligible for execution and may be issued (potentially<br class="">out-of-order) to a pipeline for execution.<br class=""><br class="">Instruction latencies can be computed by the tool with the help of the<br class="">scheduling model; latency values are defined by the scheduling model through<br class="">ProcWriteResources objects.<br class=""><br class="">Class Scheduler (see file Scheduler.h) knows how to emulate multiple processor<br class="">schedulers.  A Scheduler is responsible for tracking data dependencies, and<br class="">dynamically select which processor resources are consumed/used by instructions.<br class=""><br class="">Internally, the Scheduler class delegates the management of processor resource<br class="">units and resource groups to the ResourceManager class.  ResourceManager is also<br class="">responsible for selecting resource units that are effectively consumed by<br class="">instructions.  For example, if an instruction consumes 1cy of a resource group,<br class="">the ResourceManager object selects one of the available units from the group; by<br class="">default, it uses a round-robin selector to guarantee that resource usage is<br class="">uniformly distributed between all units of a group.<br class=""></div></div></blockquote><div><br class=""></div><div>To be a cross-subtarget tool, this needs to be a customization point. It’s not always so simple.</div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class=""><snip><br class=""></div></div></blockquote><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">Load/Store Unit and Memory Consistency Model<br class="">--------------------------------------------<br class=""><br class="">The tool attempts to emulate out-of-order execution of memory operations.  Class<br class="">LSUnit (see file LSUnit.h) emulates a load/store unit implementing queues for<br class="">speculative execution of loads and stores.<br class=""> <br class="">Each load (or store) consumes an entry in the load (or store) queue.  The number<br class="">of slots in the load/store queues is unknown by the tool, since there is no<br class="">mention of it in the scheduling model.  In practice, users can specify flag<br class="">`-lqueue=N` (vic. `-squeue=N`) to limit the number of entries in the queue to be<br class="">equal to exactly N (an unsigned value). If N is zero, then the tool assumes an<br class="">unbounded queue (this is the default).<br class=""><br class="">LSUnit implements a relaxed consistency model for memory loads and stores. The<br class="">rules are:<br class="">1) A younger load is allowed to pass an older load only if there is no<br class="">   intervening store in between the two loads.<br class="">2) An younger store is not allowed to pass an older store.<br class="">3) A younger store is not allowed to pass an older load.<br class="">4) A younger load is allowed to pass an older store provided that the load does<br class="">   not alias with the store.<br class=""><br class="">By default, this class conservatively (i.e. pessimistically) assumes that loads<br class="">always may-alias store operations.  Essentially, this LSUnit doesn't perform any<br class="">sort of alias analysis to rule out cases where loads and stores don't overlap<br class="">with each other.  The downside of this approach however is that younger loads are<br class="">never allowed to pass older stores.  To make it possible for a younger load to<br class="">pass an older store, users can use the command line flag -noalias.  Under<br class="">'noalias', a younger load is always allowed to pass an older store.<br class=""></div></div></blockquote><div><br class=""></div><div>I’m surprised it isn’t optimistic by default. Being pessimistic hides other bottlenecks and seems less accurate. I guess consistency with other similar tools (IACA) should be the aim.</div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">Note that, in the case of write-combining memory, rule 2. could be relaxed a bit<br class="">to allow reordering of non-aliasing store operations.  That being said, at the<br class="">moment, there is no way to further relax the memory model (flag -noalias is the<br class="">only option).  Essentially, there is no option to specify a different memory<br class="">type (for example: write-back, write-combining, write-through; etc.) and<br class="">consequently to weaken or strengthen the memory model.<br class=""><br class="">Other limitations are:<br class=""> * LSUnit doesn't know when store-to-load forwarding may occur.<br class=""> * LSUnit doesn't know anything about the cache hierarchy and memory types.<br class=""> * LSUnit doesn't know how to identify serializing operations and memory fences.<br class=""></div></div></blockquote><div><br class=""></div><div>Combining the static model with a sampled dynamic hardware event profile would be amazing.</div><div><br class=""></div><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">No assumption is made on the store buffer size.  As mentioned before, LSUnit<br class="">conservatively assumes a may-alias relation between loads and stores, and it<br class="">doesn't attempt to identify cases where store-to-load forwarding would occur in<br class="">practice.<br class=""></div></div></blockquote><div><br class=""></div><div>The LSUnits have a buffer size of course. The question is whether you really need to separately model issuing the instructions to a separate memory pipeline via a shared queue.</div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">LSUnit doesn't attempt to predict whether a load or store hits or misses the L1<br class="">cache.  It only knows if an instruction "MayLoad" and/or "MayStore".  For loads,<br class="">the scheduling model provides an "optimistic" load-to-use latency (which usually<br class="">matches the load-to-use latency for when there is a hit in the L1D).<br class=""></div></div></blockquote><div><br class=""></div>You’re optimistic here, which is good, but pessimistic with aliasing.</div><div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">Class MCInstrDesc in LLVM doesn't know about serializing operations, nor<br class="">memory-barrier like instructions.  LSUnit conservatively assumes that an<br class="">instruction which has both 'MayLoad' and 'UnmodeledSideEffects' behaves like a<br class="">"soft" load-barrier.  That means, it serializes loads without forcing a flush of<br class="">the load queue.  Similarly, instructions flagged with both 'MayStore' and<br class="">'UnmodeledSideEffects' are treated like store barriers.  A full memory barrier<br class="">is a 'MayLoad' and 'MayStore' instruction with 'UnmodeledSideEffects'.  This is<br class="">inaccurate, but it is the best that we can do at the moment with the current<br class="">information available in LLVM.<br class=""></div></div></blockquote><div><br class=""></div><div>LLVM *should* have this information. It needs some design work though.</div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">A load/store barrier consumes one entry of the load/store queue.  A load/store<br class="">barrier enforces ordering of loads/stores.  A younger load cannot pass a load<br class="">barrier.  Also, a younger store cannot pass a store barrier.  A younger load has<br class="">to wait for the memory/load barrier to execute.  A load/store barrier is<br class="">"executed" when it becomes the oldest entry in the load/store queue(s). That<br class="">also means, by construction, all the older loads/stores have been executed.<br class=""><br class="">In conclusion the full set of rules is:<br class="">  1. A store may not pass a previous store.<br class="">  2. A load may not pass a previous store unless flag 'NoAlias' is set.<br class="">  3. A load may pass a previous load.<br class="">  4. A store may not pass a previous load (regardless of flag 'NoAlias').<br class="">  5. A load has to wait until an older load barrier is fully executed.<br class="">  6. A store has to wait until an older store barrier is fully executed.<br class=""><br class="">Known limitations<br class="">-----------------<br class="">Previous sections described cases where the tool is missing information to give<br class="">an accurate report.  For example, the first sections of this document explained<br class="">how the lack of knowledge about the processor negatively affects the performance<br class="">analysis.  The lack of knowledge is often a consequence of how scheduling models<br class="">are defined; as mentioned before, scheduling models intentionally don't describe<br class="">processors in fine details.<br class=""></div></div></blockquote><div><br class=""></div><div>LLVM’s machine model should be optionally extended to model whatever a static analysis tool needs. There’s some dynamic behavior that can’t be modeled statically—predictive structures, the state of the pipeline entering a  loop—but machine model precision shouldn’t be the limiting factor for your tool.</div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">The accuracy of the performance analysis is also affected by assumptions made by<br class="">the processor model used by the tool.<br class=""><br class="">Most recent Intel and AMD processors implement dedicated LoopBuffer/OpCache in<br class="">the hardware frontend to speedup the throughput in the presence of tight loops.<br class="">The presence of these buffers complicates the decoding logic, and requires<br class="">knowledge on the branch predictor too.  Class 'SchedMachineModel' in tablegen<br class="">provides a field named 'LoopMicroOpBufferSize' which is used to describe loop<br class="">buffers.  However, the purpose of that field is to enable loop unrolling of<br class="">tight loops; essentially, it affects the cost model used by pass loop-unroll.<br class=""><br class="">By design, the tool only cares about the out-of-order portion of a processor,<br class="">and consequently doesn't try to predict the frontend throughput.  Processors may<br class="">implement complex decoding schemes; statically predicting the frontend<br class="">throughput is in general beyond the scope of this tool.  For the same reasons,<br class="">this tool intentionally doesn't model branch prediction.  That being said, this<br class="">tool could be definitely extended in future to also account for the hardware<br class="">frontend when doing performance analysis.  This would inevitably require extra<br class="">(extensive) processor knowledge related to all the available decoding paths in<br class="">the hardware frontend.<br class=""></div></div></blockquote><div><br class=""></div>If loops are ever definitely limited by decoder or fetch throughput, it would be good to know that. You don’t need to model the predictive aspect of it, or “all the paths”.</div><div><br class=""></div><div>You might as well say you don’t need to model issue/dispatch width, or retirement logic, because it’s decoupled from OOO execution via instruction buffers. The point of this tool is to tell you that there is definitely a bottleneck in a particular area of the pipeline.</div><div><br class=""></div><div>Would it be more appropriate to say that a simple abstract model of decoding is too inaccurate for your particular subtarget so there was not enough benefit to implementing it?</div><div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">When computing the IPC, the tool assumes a zero-latency "perfect" fetch&decode<br class="">stage; the full sequence of decoded instructions is immediately visible to the<br class="">dispatch logic from the start.<br class=""><br class="">The tool doesn't know about simultaneous mutithreading.  According to the tool,<br class="">processor resources are not statically/dynamically partitioned.  Processor<br class="">resources are fully available to the hardware thread executing the<br class="">microbenchmark.<br class=""><br class="">The execution model implemented by this tool assumes that instructions are<br class="">firstly dispatched in groups to hardware schedulers, and then issued to<br class="">pipelines for execution.  The model assumes dynamic scheduling of instructions.<br class="">Instructions are placed in a queue and potentially executed out-of-order (based<br class="">on the operand availability). The dispatch stage is definitely distinct from the<br class="">issue stage.<br class=""></div></div></blockquote><div><br class=""></div><div>I wonder why in-order analysis doesn’t mostly fall out as a degenerate case in your tool. There’s some grey area where in-order processors hardware interlocks that cause stalls that aren’t explicit in the scheduling groups. Those processors would still benefit from your tool. Even if that target doesn’t benefit from the OOO simulation, it would be nice to compare the output of your tool with the observed performance to find bugs in the model.</div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">This model doesn't correctly describe processors where the dispatch/issue is a<br class="">single stage. This is what happens for example in VLIW processors, where<br class="">instructions are packaged and statically scheduled at compile time; it is up to<br class="">the compiler to predict the latency of instructions and package issue groups<br class="">accordingly. For such targets, there is no dynamic scheduling done by the<br class="">hardware.<br class=""><br class="">Existing classes (DispatchUnit, Scheduler, etc.) could be extended/adapted to<br class="">support processors with a single dispatch/issue stage. The execution flow would<br class="">require some changes in the way how existing components (i.e.  DispatchUnit,<br class="">Scheduler, etc.) interact. This can be a future development.<br class=""></div></div></blockquote><div><br class=""></div>Ah…. Extended with future development sounds better.</div><div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">The following sections describes other known limitations.  The goal is not to<br class="">provide an extensive list of limitations; we want to report what we believe are<br class="">the most important limitations, and suggest possible methods to overcome them.<br class=""><br class="">Load/Store barrier instructions and serializing operations<br class="">----------------------------------------------------------<br class="">Section "Load/Store Unit and Memory Consistency Model" already mentioned how<br class="">LLVM doesn't know about serializing operations and memory barriers.  Most of it<br class="">boils down to the fact that class MCInstrDesc (intentionally) doesn't expose<br class="">those properties.  Instead, both serializing operations and memory barriers<br class="">"have side-effects" according to MCInstrDesc.  That is because, at least for<br class="">scheduling purposes, knowing that an instruction has unmodeled side effects is<br class="">often enough to treat the instruction like a compiler scheduling barrier.<br class=""><br class="">A performance analysis tool could use the extra knowledge on barriers and<br class="">serializing operations to generate a more accurate performance report.  One way<br class="">to improve this is by reserving a couple of bits in field 'Flags' from class<br class="">MCInstrDesc: one bit for barrier operations, and another bit to mark<br class="">instructions as serializing operations.<br class=""><br class="">Lack of support for instruction itineraries<br class="">-------------------------------------------<br class="">The current version of the tool doesn't know how to process instruction<br class="">itineraries.  This is probably one of the most important limitations, since it<br class="">affects a few out-of-order processors in LLVM.<br class=""></div></div></blockquote><div><br class=""></div>I don’t think OOO LLVM targets should be using itineraries. If those targets are still actively maintained, they could migrate.</div><div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">As mentioned in section 'Instruction Issue', class Scheduler delegates to an<br class="">instance of class ResourceManager the handling of processor resources.<br class="">ResourceManager is where most of the scheduling logic is implemented.<br class=""><br class="">Adding support for instruction itineraries requires that we teach<br class="">ResourceManager how to handle functional units and instruction stages.  This<br class="">development can be a future extension, and it would probably require a few<br class="">changes to the ResourceManager interface.<br class=""><br class="">Instructions that affect control flow are not correctly modeled<br class="">---------------------------------------------------------------<br class="">Examples of instructions that affect the control flow are: return, indirect<br class="">branches, calls, etc.  The tool doesn't try to predict/evaluate branch targets.<br class="">In particular, the tool doesn't model any sort of branch prediction, nor does it<br class="">attempt to track changes to the program counter.  The tool always assumes that<br class="">the input assembly sequence is the body of a microbenchmark (a simple loop<br class="">executed for a number of iterations). The "next" instruction in sequence is<br class="">always the next instruction to dispatch.<br class=""><br class="">Call instructions default to an arbitrary high latency of 100cy. A warning is<br class="">generated if the tool encounters a call instruction in the sequence.  Return<br class="">instructions are not evaluated, and therefore control flow is not affected.<br class="">However, the tool still queries the processor scheduling model to obtain latency<br class="">information for instructions that affect the control flow.<br class=""></div></div></blockquote><div><br class=""></div><div>By decompiling to MachineInst’s it would be easy to build a mostly complete CFG and call graph.</div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">Possible extensions to the scheduling model<br class="">-------------------------------------------<br class="">Section "Instruction Dispatch" explained how the tool doesn't know about the<br class="">register files, and temporaries available in each register file for register<br class="">renaming purposes.<br class=""><br class="">The LLVM scheduling model could be extended to better describe register files.<br class="">Ideally, scheduling model should be able to define:<br class=""> - The size of each register file<br class=""> - How many temporary registers are available for register renaming<br class=""> - How register classes map to register files<br class=""><br class="">The scheduling model doesn't specify the retire throughput (i.e. how many<br class="">instructions can be retired every cycle).  Users can specify flag<br class="">`-max-retire-per-cycle=<uint>` to limit how many instructions the retire control<br class="">unit can retire every cycle.  Ideally, every processor should be able to specify<br class="">the retire throughput (for example, by adding an extra field to the scheduling<br class="">model tablegen class).<br class=""><br class="">Known limitations on X86 processors<br class="">-----------------------------------<br class=""><br class="">1) Partial register updates versus full register updates.<br class=""><snip><br class=""></div></div></blockquote><div><br class=""></div>MachineOperand handles this. You just need to create the machine instrs.</div><div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">2) Macro Op fusion.<br class=""><br class="">The tool doesn't know about macro-op fusion. On modern x86 processors, a<br class="">'cmp/test' followed by a 'jmp' is fused into a single macro operation.  The<br class="">advantage is that the fused pair only consumes a single slot in the dispatch<br class="">group. <br class=""><br class="">As a future development, the tool should be extended to address macro-fusion.<br class="">Ideally, we could have LLVM generate a table enumerating all the opcode pairs<br class="">that can be fused together. That table could be exposed to the tool via the<br class="">MCSubtargetInfo interface.  This is just an idea; there may be better ways to<br class="">implement this.<br class=""></div></div></blockquote><div><br class=""></div><div>This is already expressed by subtarget code. That code just needs to be exposed as a common subtarget interface. Typically the interfaces take MachineInst, but in this case the opcode is probably sufficient.</div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">4) Zero-latency register moves and Zero-idioms.<br class=""><br class="">Most modern AMD/Intel processors know how to optimize out register-register<br class="">moves and zero idioms at register renaming stage. The tool doesn't know<br class="">about these patterns, and this may negatively impact the performance analysis.<br class=""></div></div></blockquote><div><br class=""></div><div>The machine model has this, but requires proper MachineInstrs.</div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">Known design problems<br class="">---------------------<br class="">This section describes two design issues that are currently affecting the tool.<br class="">The long term plan is to "fix" these issues.<br class=""><br class="">1) Variant instructions not correctly modeled.<br class=""><br class="">The tool doesn't know how to analyze instructions with a "variant" scheduling<br class="">class descriptor. A variant scheduling class needs to be resolved dynamically.<br class="">The "actual" scheduling class often depends on the subtarget, as well as<br class="">properties of the specific MachineInstr object.<br class=""><br class="">Unfortunately, the tool manipulates MCInst, and it doesn't know anything about<br class="">MachineInstr. As a consequence, the tool cannot use the existing machine<br class="">subtarget hooks that are normally used to resolve the variant scheduling class.<br class="">This is a major design issue which mostly affects ARM/AArch64 targets.  It<br class="">mostly boils down to the fact that the existing scheduling framework was meant<br class="">to work for MachineInstr.<br class=""></div></div></blockquote><div><br class=""></div><div>There are good reasons for the scheduler to work with MachineInstrs, and any static analysis tool should work with MachineInstrs for the same reasons...</div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">2) MCInst and MCInstrDesc.<br class=""><br class="">Performance analysis tools require data dependency information to correctly<br class="">predict the runtime performance of the code. This tool must always be able to<br class="">obtain the set of implicit/explicit register defs/uses for every instruction of<br class="">the input assembly sequence.<br class=""><br class="">In the first section of this document, it was mentioned how the tool takes as<br class="">input an assembly sequence. That sequence is parsed into a MCInst sequence with<br class="">the help of assembly parsers available from the targets.<br class=""><br class="">A MCInst is a very low-level instruction representation. The tool can inspect<br class="">the MCOperand sequence of an MCInst to identify register operands. However,<br class="">there is no way to tell register operands that are definitions from register<br class="">operands that are uses.<br class=""><br class="">In LLVM, class MCInstrDesc is used to fully describe target instructions and<br class="">their operands. The opcode of a machine instruction (a MachineInstr object) can<br class="">be used to query the instruction set through method `MCInstrInfo::get' to obtain<br class="">the associated MCInstrDesc object.<br class=""><br class="">However class MCInstrDesc describes properties and operands of MachineInstr<br class="">objects. Essentially, MCInstrDesc is not meant to be used to describe MCInst<br class="">objects.  To be more specific, MCInstrDesc objects are automatically generated<br class="">via tablegen from the instruction set description in the target .td files.  For<br class="">example, field `MCInstrDesc::NumDefs' is always equal to the cardinality of the<br class="">`(outs)` set from the tablegen instruction definition.<br class=""><br class="">By construction, register definitions always appear at the beginning of the<br class="">MachineOperands list in MachineInstr. Basically, the (outs) are the first<br class="">operands of a MachineInstr, and the (ins) will come after in the machine operand<br class="">list. Knowing the number of register definitions is enough to identify<br class="">all the register operands that are definitions.<br class=""><br class="">In a normal compilation process, MCInst objects are generated from MachineInstr<br class="">objects through a lowering step. By default the lowering logic simply iterates<br class="">over the machine operands of a MachineInstr, and converts/expands them into<br class="">equivalent MCOperand objects.<br class=""><br class="">The default lowering strategy has the advantage of preserving all of the<br class="">above mentioned assumptions on the machine operand sequence. That means, register<br class="">definitions would still be at the beginning of the MCOperand sequence, and<br class="">register uses would come after.<br class=""><br class="">Targets may still define custom lowering routines for specific opcodes. Some of<br class="">these routines may lower operands in a way that potentially breaks (some of) the<br class="">assumptions on the machine operand sequence which were valid for MachineInstr.<br class="">Luckily, this is not the most common form of lowering done by the targets, and<br class="">the vast majority of the MachineInstr are lowered based on the default strategy<br class="">which preserves the original machine operand sequence.  This is especially true<br class="">for x86, where the custom lowering logic always preserves the original (i.e.<br class="">from the MachineInstr) operand sequence.<br class=""><br class="">This tool currently works under the strong (and potentially incorrect)<br class="">assumption that register def/uses in a MCInst can always be identified by<br class="">querying the machine instruction descriptor for the opcode. This assumption made<br class="">it possible to develop this tool and get good numbers at least for the<br class="">processors available in the x86 backend.<br class=""><br class="">That being said, the analysis is still potentially incorrect for other targets.<br class="">So we plan (with the help of the community) to find a proper mechanism to map<br class="">when possible MCOperand indices back to MachineOperand indices of the equivalent<br class="">MachineInstr.  This would be equivalent to describing changes made by the<br class="">lowering step which affected the operand sequence. For example, we could have an<br class="">index for every register MCOperand (or -1, if the operand didn't exist in the<br class="">original MachineInstr). The mapping could look like this <0,1,3,2>.  Here,<br class="">MCOperand #2 was obtained from the lowering of MachineOperand #3. etc.<br class=""><br class="">This information could be automatically generated via tablegen for all the<br class="">instructions whose custom lowering step breaks assumptions made by the tool on<br class="">the register operand sequence (In general, these instructions should be the<br class="">minority of a target's instruction set). Unfortunately, we don't have that<br class="">information now.  As a consequence, we assume that the number of explicit<br class="">register definitions is the same number specified in MCInstrDesc.  We also<br class="">assume that register definitions always come first in the operand sequence.<br class=""><br class="">In conclusion: these are for now the strong assumptions made by the tool:<br class="">  * The number of explicit and implicit register definitions in a MCInst<br class="">    matches the number of explicit and implicit definitions specified by the<br class="">    MCInstrDesc object.<br class="">  * Register uses always come after register definitions.<br class="">  * If an opcode specifies an optional definition, then the optional<br class="">    definition is always the last register operand in the sequence.<br class=""><br class="">Note that some of the information accessible from the MCInstrDesc is always<br class="">valid for MCInst. For example: implicit register defs, implicit register uses<br class="">and 'MayLoad/MayStore/HasUnmodeledSideEffects' opcode properties still apply to<br class="">MCInst. The tool knows about this, and uses that information during its<br class="">analysis.<br class=""></div></div></blockquote><div><br class=""></div><div>You just made a very strong argument for building the MachineInstrs before running mca. So I wonder why you didn’t do that.</div><br class=""><blockquote type="cite" class=""><div class=""><div dir="ltr" class="">What to do next<br class="">---------------<br class="">The source code has been uploaded for review on phabricator at this link: <a href="https://reviews.llvm.org/D43951" class="">https://reviews.llvm.org/D43951</a>.<br class=""><br class="">The review covers two patches:<br class="">A first (very small) patch that always enables the generation of processor<br class="">resource names in the SubtargetEmitter. Currently, the processor resource names<br class="">are only generated for debugging purposes, but are needed by the tool to<br class="">generate user friendly reports, so we would like to always generate them.<br class="">A second patch with the actual static analysis tool (in llvm/tools).<br class=""><br class="">Once these first two patches are committed, the plan is to keep working on the<br class="">tool with the help of the community to address all of the limitations described<br class="">by the previous sections, and find good solutions/fixes for the design issues<br class="">described by section "Known design problems".<br class=""><br class="">We hope the community will find this tool useful like we have.<br class=""><br class="">Special thanks to Simon Pilgrim, Filipe Cabecinhas and Greg Bedwell who really<br class="">helped me a lot by suggesting improvements and testing the tool.<br class=""><br class="">Thanks for your time.<br class="">-Andrea<br class=""></div>
</div></blockquote><br class=""></div><div>There are a number of people on llvm-dev who can explain better than I how to decompile into MachineInstrs. I’m not totally opposed to checking in something that works with MCInstr, but this does run strongly contrary to the design of LLVM’s subtarget support.</div><div><br class=""></div><div>-Andy</div></body></html>