1 ====================================
2 LLVM's Analysis and Transform Passes
3 ====================================
15 .. warning:: This document is not updated frequently, and the list of passes
16 is most likely incomplete. It is possible to list passes known by the opt
17 tool using ``opt -print-passes``.
19 This document serves as a high level summary of the optimization features that
20 LLVM provides. Optimizations are implemented as Passes that traverse some
21 portion of a program to either collect information or transform the program.
22 The table below divides the passes that LLVM provides into three categories.
23 Analysis passes compute information that other passes can use or for debugging
24 or program visualization purposes. Transform passes can use (or invalidate)
25 the analysis passes. Transform passes all mutate the program in some way.
26 Utility passes provides some utility but don't otherwise fit categorization.
27 For example passes to extract functions to bitcode or write a module to bitcode
28 are neither analysis nor transform passes. The table of contents above
29 provides a quick summary of each pass and links to the more complete pass
30 description later in the document.
35 This section describes the LLVM Analysis Passes.
37 ``aa-eval``: Exhaustive Alias Analysis Precision Evaluator
38 ----------------------------------------------------------
40 This is a simple N^2 alias analysis accuracy evaluator. Basically, for each
41 function in the program, it simply queries to see how the alias analysis
42 implementation answers alias queries between each pair of pointers in the
45 This is inspired and adapted from code by: Naveen Neelakantam, Francesco
46 Spadini, and Wojciech Stryjewski.
48 ``basic-aa``: Basic Alias Analysis (stateless AA impl)
49 ------------------------------------------------------
51 A basic alias analysis pass that implements identities (two different globals
52 cannot alias, etc), but does no stateful analysis.
54 ``basiccg``: Basic CallGraph Construction
55 -----------------------------------------
61 ``da``: Dependence Analysis
62 ---------------------------
64 Dependence analysis framework, which is used to detect dependences in memory
67 ``domfrontier``: Dominance Frontier Construction
68 ------------------------------------------------
70 This pass is a simple dominator construction algorithm for finding forward
73 ``domtree``: Dominator Tree Construction
74 ----------------------------------------
76 This pass is a simple dominator construction algorithm for finding forward
80 ``dot-callgraph``: Print Call Graph to "dot" file
81 -------------------------------------------------
83 This pass, only available in ``opt``, prints the call graph into a ``.dot``
84 graph. This graph can then be processed with the "dot" tool to convert it to
85 postscript or some other suitable format.
87 ``dot-cfg``: Print CFG of function to "dot" file
88 ------------------------------------------------
90 This pass, only available in ``opt``, prints the control flow graph into a
91 ``.dot`` graph. This graph can then be processed with the :program:`dot` tool
92 to convert it to postscript or some other suitable format.
93 Additionally the ``-cfg-func-name=<substring>`` option can be used to filter the
94 functions that are printed. All functions that contain the specified substring
97 ``dot-cfg-only``: Print CFG of function to "dot" file (with no function bodies)
98 -------------------------------------------------------------------------------
100 This pass, only available in ``opt``, prints the control flow graph into a
101 ``.dot`` graph, omitting the function bodies. This graph can then be processed
102 with the :program:`dot` tool to convert it to postscript or some other suitable
104 Additionally the ``-cfg-func-name=<substring>`` option can be used to filter the
105 functions that are printed. All functions that contain the specified substring
108 ``dot-dom``: Print dominance tree of function to "dot" file
109 -----------------------------------------------------------
111 This pass, only available in ``opt``, prints the dominator tree into a ``.dot``
112 graph. This graph can then be processed with the :program:`dot` tool to
113 convert it to postscript or some other suitable format.
115 ``dot-dom-only``: Print dominance tree of function to "dot" file (with no function bodies)
116 ------------------------------------------------------------------------------------------
118 This pass, only available in ``opt``, prints the dominator tree into a ``.dot``
119 graph, omitting the function bodies. This graph can then be processed with the
120 :program:`dot` tool to convert it to postscript or some other suitable format.
122 ``dot-post-dom``: Print postdominance tree of function to "dot" file
123 --------------------------------------------------------------------
125 This pass, only available in ``opt``, prints the post dominator tree into a
126 ``.dot`` graph. This graph can then be processed with the :program:`dot` tool
127 to convert it to postscript or some other suitable format.
129 ``dot-post-dom-only``: Print postdominance tree of function to "dot" file (with no function bodies)
130 ---------------------------------------------------------------------------------------------------
132 This pass, only available in ``opt``, prints the post dominator tree into a
133 ``.dot`` graph, omitting the function bodies. This graph can then be processed
134 with the :program:`dot` tool to convert it to postscript or some other suitable
137 ``globals-aa``: Simple mod/ref analysis for globals
138 ---------------------------------------------------
140 This simple pass provides alias and mod/ref information for global values that
141 do not have their address taken, and keeps track of whether functions read or
142 write memory (are "pure"). For this simple (but very common) case, we can
143 provide pretty accurate and useful information.
145 ``instcount``: Counts the various types of ``Instruction``\ s
146 -------------------------------------------------------------
148 This pass collects the count of all instructions and reports them.
150 ``iv-users``: Induction Variable Users
151 --------------------------------------
153 Bookkeeping for "interesting" users of expressions computed from induction
156 ``kernel-info``: GPU Kernel Info
157 --------------------------------
159 Reports various statistics for codes compiled for GPUs. This pass is
160 :doc:`documented separately<KernelInfo>`.
162 ``lazy-value-info``: Lazy Value Information Analysis
163 ----------------------------------------------------
165 Interface for lazy computation of value constraint information.
167 ``lint``: Statically lint-checks LLVM IR
168 ----------------------------------------
170 This pass statically checks for common and easily-identified constructs which
171 produce undefined or likely unintended behavior in LLVM IR.
173 It is not a guarantee of correctness, in two ways. First, it isn't
174 comprehensive. There are checks which could be done statically which are not
175 yet implemented. Some of these are indicated by TODO comments, but those
176 aren't comprehensive either. Second, many conditions cannot be checked
177 statically. This pass does no dynamic instrumentation, so it can't check for
178 all possible problems.
180 Another limitation is that it assumes all code will be executed. A store
181 through a null pointer in a basic block which is never reached is harmless, but
182 this pass will warn about it anyway.
184 Optimization passes may make conditions that this pass checks for more or less
185 obvious. If an optimization pass appears to be introducing a warning, it may
186 be that the optimization pass is merely exposing an existing condition in the
189 This code may be run before :ref:`instcombine <passes-instcombine>`. In many
190 cases, instcombine checks for the same kinds of things and turns instructions
191 with undefined behavior into unreachable (or equivalent). Because of this,
192 this pass makes some effort to look through bitcasts and so on.
194 ``loops``: Natural Loop Information
195 -----------------------------------
197 This analysis is used to identify natural loops and determine the loop depth of
198 various nodes of the CFG. Note that the loops identified may actually be
199 several natural loops that share the same header node... not just a single
202 ``memdep``: Memory Dependence Analysis
203 --------------------------------------
205 An analysis that determines, for a given memory operation, what preceding
206 memory operations it depends on. It builds on alias analysis information, and
207 tries to provide a lazy, caching interface to a common kind of alias
210 ``print<module-debuginfo>``: Decodes module-level debug info
211 ------------------------------------------------------------
213 This pass decodes the debug info metadata in a module and prints it to standard output in a
214 (sufficiently-prepared-) human-readable form.
216 ``postdomtree``: Post-Dominator Tree Construction
217 -------------------------------------------------
219 This pass is a simple post-dominator construction algorithm for finding
222 ``print-alias-sets``: Alias Set Printer
223 ---------------------------------------
227 ``print-callgraph``: Print a call graph
228 ---------------------------------------
230 This pass, only available in ``opt``, prints the call graph to standard error
231 in a human-readable form.
233 ``print-callgraph-sccs``: Print SCCs of the Call Graph
234 ------------------------------------------------------
236 This pass, only available in ``opt``, prints the SCCs of the call graph to
237 standard error in a human-readable form.
239 ``print-cfg-sccs``: Print SCCs of each function CFG
240 ---------------------------------------------------
242 This pass, only available in ``opt``, prints the SCCs of each function CFG to
243 standard error in a human-readable fom.
245 ``function(print)``: Print function to stderr
246 ---------------------------------------------
248 The ``PrintFunctionPass`` class is designed to be pipelined with other
249 ``FunctionPasses``, and prints out the functions of the module as they are
252 ``module(print)``: Print module to stderr
253 -----------------------------------------
255 This pass simply prints out the entire module when it is executed.
257 ``regions``: Detect single entry single exit regions
258 ----------------------------------------------------
260 The ``RegionInfo`` pass detects single entry single exit regions in a function,
261 where a region is defined as any subgraph that is connected to the remaining
262 graph at only two spots. Furthermore, a hierarchical region tree is built.
264 .. _passes-scalar-evolution:
266 ``scalar-evolution``: Scalar Evolution Analysis
267 -----------------------------------------------
269 The ``ScalarEvolution`` analysis can be used to analyze and categorize scalar
270 expressions in loops. It specializes in recognizing general induction
271 variables, representing them with the abstract and opaque ``SCEV`` class.
272 Given this analysis, trip counts of loops and other important properties can be
275 This analysis is primarily useful for induction variable substitution and
278 ``scev-aa``: ScalarEvolution-based Alias Analysis
279 -------------------------------------------------
281 Simple alias analysis implemented in terms of ``ScalarEvolution`` queries.
283 This differs from traditional loop dependence analysis in that it tests for
284 dependencies within a single iteration of a loop, rather than dependencies
285 between different iterations.
287 ``ScalarEvolution`` has a more complete understanding of pointer arithmetic
288 than ``BasicAliasAnalysis``' collection of ad-hoc analyses.
290 ``stack-safety``: Stack Safety Analysis
291 ---------------------------------------
293 The ``StackSafety`` analysis can be used to determine if stack allocated
294 variables can be considered safe from memory access bugs.
296 This analysis' primary purpose is to be used by sanitizers to avoid unnecessary
297 instrumentation of safe variables.
302 This section describes the LLVM Transform Passes.
304 ``adce``: Aggressive Dead Code Elimination
305 ------------------------------------------
307 ADCE aggressively tries to eliminate code. This pass is similar to :ref:`DCE
308 <passes-dce>` but it assumes that values are dead until proven otherwise. This
309 is similar to :ref:`SCCP <passes-sccp>`, except applied to the liveness of
312 ``always-inline``: Inliner for ``always_inline`` functions
313 ----------------------------------------------------------
315 A custom inliner that handles only functions that are marked as "always
318 ``argpromotion``: Promote 'by reference' arguments to scalars
319 -------------------------------------------------------------
321 This pass promotes "by reference" arguments to be "by value" arguments. In
322 practice, this means looking for internal functions that have pointer
323 arguments. If it can prove, through the use of alias analysis, that an
324 argument is *only* loaded, then it can pass the value into the function instead
325 of the address of the value. This can cause recursive simplification of code
326 and lead to the elimination of allocas (especially in C++ template code like
329 This pass also handles aggregate arguments that are passed into a function,
330 scalarizing them if the elements of the aggregate are only loaded. Note that
331 it refuses to scalarize aggregates which would require passing in more than
332 three operands to the function, because passing thousands of operands for a
333 large array or structure is unprofitable!
335 Note that this transformation could also be done for arguments that are only
336 stored to (returning the value instead), but does not currently. This case
337 would be best handled when and if LLVM starts supporting multiple return values
340 ``block-placement``: Profile Guided Basic Block Placement
341 ---------------------------------------------------------
343 This pass is a very simple profile guided basic block placement algorithm. The
344 idea is to put frequently executed blocks together at the start of the function
345 and hopefully increase the number of fall-through conditional branches. If
346 there is no profile information for a particular function, this pass basically
347 orders blocks in depth-first order.
349 ``break-crit-edges``: Break critical edges in CFG
350 -------------------------------------------------
352 Break all of the critical edges in the CFG by inserting a dummy basic block.
353 It may be "required" by passes that cannot deal with critical edges. This
354 transformation obviously invalidates the CFG, but can update forward dominator
355 (set, immediate dominators, tree, and frontier) information.
357 ``codegenprepare``: Optimize for code generation
358 ------------------------------------------------
360 This pass munges the code in the input function to better prepare it for
361 SelectionDAG-based code generation. This works around limitations in its
362 basic-block-at-a-time approach. It should eventually be removed.
364 ``constmerge``: Merge Duplicate Global Constants
365 ------------------------------------------------
367 Merges duplicate global constants together into a single constant that is
368 shared. This is useful because some passes (i.e., TraceValues) insert a lot of
369 string constants into the program, regardless of whether or not an existing
374 ``dce``: Dead Code Elimination
375 ------------------------------
377 Dead code elimination is similar to dead instruction elimination, but it
378 rechecks instructions that were used by removed instructions to see if they
381 ``deadargelim``: Dead Argument Elimination
382 ------------------------------------------
384 This pass deletes dead arguments from internal functions. Dead argument
385 elimination removes arguments which are directly dead, as well as arguments
386 only passed into function calls as dead arguments of other functions. This
387 pass also deletes dead arguments in a similar way.
389 This pass is often useful as a cleanup pass to run after aggressive
390 interprocedural passes, which add possibly-dead arguments.
392 ``dse``: Dead Store Elimination
393 -------------------------------
395 A trivial dead store elimination that only considers basic-block local
398 .. _passes-function-attrs:
400 ``function-attrs``: Deduce function attributes
401 ----------------------------------------------
403 A simple interprocedural pass which walks the call-graph, looking for functions
404 which do not access or only read non-local memory, and marking them
405 ``readnone``/``readonly``. In addition, it marks function arguments (of
406 pointer type) "``nocapture``" if a call to the function does not create any
407 copies of the pointer value that outlive the call. This more or less means
408 that the pointer is only dereferenced, and not returned from the function or
409 stored in a global. This pass is implemented as a bottom-up traversal of the
412 ``globaldce``: Dead Global Elimination
413 --------------------------------------
415 This transform is designed to eliminate unreachable internal globals from the
416 program. It uses an aggressive algorithm, searching out globals that are known
417 to be alive. After it finds all of the globals which are needed, it deletes
418 whatever is left over. This allows it to delete recursive chunks of the
419 program which are unreachable.
421 ``globalopt``: Global Variable Optimizer
422 ----------------------------------------
424 This pass transforms simple global variables that never have their address
425 taken. If obviously true, it marks read/write globals as constant, deletes
426 variables only stored to, etc.
428 ``gvn``: Global Value Numbering
429 -------------------------------
431 This pass performs global value numbering to eliminate fully and partially
432 redundant instructions. It also performs redundant load elimination.
436 ``indvars``: Canonicalize Induction Variables
437 ---------------------------------------------
439 This transformation analyzes and transforms the induction variables (and
440 computations derived from them) into simpler forms suitable for subsequent
441 analysis and transformation.
443 This transformation makes the following changes to each loop with an
444 identifiable induction variable:
446 * All loops are transformed to have a *single* canonical induction variable
447 which starts at zero and steps by one.
448 * The canonical induction variable is guaranteed to be the first PHI node in
449 the loop header block.
450 * Any pointer arithmetic recurrences are raised to use array subscripts.
452 If the trip count of a loop is computable, this pass also makes the following
455 * The exit condition for the loop is canonicalized to compare the induction
456 value against the exit value. This turns loops like:
460 for (i = 7; i*i < 1000; ++i)
466 for (i = 0; i != 25; ++i)
468 * Any use outside of the loop of an expression derived from the indvar is
469 changed to compute the derived value outside of the loop, eliminating the
470 dependence on the exit value of the induction variable. If the only purpose
471 of the loop is to compute the exit value of some derived expression, this
472 transformation will make the loop dead.
474 This transformation should be followed by strength reduction after all of the
475 desired loop transformations have been performed. Additionally, on targets
476 where it is profitable, the loop could be transformed to count down to zero
477 (the "do loop" optimization).
479 ``inline``: Function Integration/Inlining
480 -----------------------------------------
482 Bottom-up inlining of functions into callees.
484 .. _passes-instcombine:
486 ``instcombine``: Combine redundant instructions
487 -----------------------------------------------
489 Combine instructions to form fewer, simple instructions. This pass does not
490 modify the CFG. This pass is where algebraic simplification happens.
492 This pass combines things like:
505 This is a simple worklist driven algorithm.
507 This pass guarantees that the following canonicalizations are performed on the
510 #. If a binary operator has a constant operand, it is moved to the right-hand
512 #. Bitwise operators with constant operands are always grouped so that shifts
513 are performed first, then ``or``\ s, then ``and``\ s, then ``xor``\ s.
514 #. Compare instructions are converted from ``<``, ``>``, ``≤``, or ``≥`` to
515 ``=`` or ``≠`` if possible.
516 #. All ``cmp`` instructions on boolean values are replaced with logical
518 #. ``add X, X`` is represented as ``mul X, 2`` ⇒ ``shl X, 1``
519 #. Multiplies with a constant power-of-two argument are transformed into
523 This pass can also simplify calls to specific well-known function calls (e.g.
524 runtime library functions). For example, a call ``exit(3)`` that occurs within
525 the ``main()`` function can be transformed into simply ``return 3``. Whether or
526 not library calls are simplified is controlled by the
527 :ref:`-function-attrs <passes-function-attrs>` pass and LLVM's knowledge of
528 library calls on different targets.
530 .. _passes-aggressive-instcombine:
532 ``aggressive-instcombine``: Combine expression patterns
533 --------------------------------------------------------
535 Combine expression patterns to form expressions with fewer, simple instructions.
537 For example, this pass reduce width of expressions post-dominated by TruncInst
538 into smaller width when applicable.
540 It differs from instcombine pass in that it can modify CFG and contains pattern
541 optimization that requires higher complexity than the O(1), thus, it should run fewer
542 times than instcombine pass.
544 ``internalize``: Internalize Global Symbols
545 -------------------------------------------
547 This pass loops over all of the functions in the input module, looking for a
548 main function. If a main function is found, all other functions and all global
549 variables with initializers are marked as internal.
551 ``ipsccp``: Interprocedural Sparse Conditional Constant Propagation
552 -------------------------------------------------------------------
554 An interprocedural variant of :ref:`Sparse Conditional Constant Propagation
557 ``ir-normalizer``: Transforms IR into a normal form that's easier to diff
558 ----------------------------------------------------------------------------
560 This pass aims to transform LLVM Modules into a normal form by reordering and
561 renaming instructions while preserving the same semantics. The normalizer makes
562 it easier to spot semantic differences while diffing two modules which have
563 undergone two different passes.
565 ``jump-threading``: Jump Threading
566 ----------------------------------
568 Jump threading tries to find distinct threads of control flow running through a
569 basic block. This pass looks at blocks that have multiple predecessors and
570 multiple successors. If one or more of the predecessors of the block can be
571 proven to always cause a jump to one of the successors, we forward the edge
572 from the predecessor to the successor by duplicating the contents of this
575 An example of when this can occur is code like this:
584 In this case, the unconditional branch at the end of the first if can be
585 revectored to the false side of the second if.
589 ``lcssa``: Loop-Closed SSA Form Pass
590 ------------------------------------
592 This pass transforms loops by placing phi nodes at the end of the loops for all
593 values that are live across the loop boundary. For example, it turns the left
603 X3 = phi(X1, X2) X3 = phi(X1, X2)
604 ... = X3 + 4 X4 = phi(X3)
607 This is still valid LLVM; the extra phi nodes are purely redundant, and will be
608 trivially eliminated by ``InstCombine``. The major benefit of this
609 transformation is that it makes many other loop optimizations, such as
610 ``LoopUnswitch``\ ing, simpler. You can read more in the
611 :ref:`loop terminology section for the LCSSA form <loop-terminology-lcssa>`.
615 ``licm``: Loop Invariant Code Motion
616 ------------------------------------
618 This pass performs loop invariant code motion, attempting to remove as much
619 code from the body of a loop as possible. It does this by either hoisting code
620 into the preheader block, or by sinking code to the exit blocks if it is safe.
621 This pass also promotes must-aliased memory locations in the loop to live in
622 registers, thus hoisting and sinking "invariant" loads and stores.
624 Hoisting operations out of loops is a canonicalization transform. It enables
625 and simplifies subsequent optimizations in the middle-end. Rematerialization
626 of hoisted instructions to reduce register pressure is the responsibility of
627 the back-end, which has more accurate information about register pressure and
628 also handles other optimizations than LICM that increase live-ranges.
630 This pass uses alias analysis for two purposes:
632 #. Moving loop invariant loads and calls out of loops. If we can determine
633 that a load or call inside of a loop never aliases anything stored to, we
634 can hoist it or sink it like any other instruction.
636 #. Scalar Promotion of Memory. If there is a store instruction inside of the
637 loop, we try to move the store to happen AFTER the loop instead of inside of
638 the loop. This can only happen if a few conditions are true:
640 #. The pointer stored through is loop invariant.
641 #. There are no stores or loads in the loop which *may* alias the pointer.
642 There are no calls in the loop which mod/ref the pointer.
644 If these conditions are true, we can promote the loads and stores in the
645 loop of the pointer to use a temporary alloca'd variable. We then use the
646 :ref:`mem2reg <passes-mem2reg>` functionality to construct the appropriate
647 SSA form for the variable.
649 ``loop-deletion``: Delete dead loops
650 ------------------------------------
652 This file implements the Dead Loop Deletion Pass. This pass is responsible for
653 eliminating loops with non-infinite computable trip counts that have no side
654 effects or volatile instructions, and do not contribute to the computation of
655 the function's return value.
657 .. _passes-loop-extract:
659 ``loop-extract``: Extract loops into new functions
660 --------------------------------------------------
662 A pass wrapper around the ``ExtractLoop()`` scalar transformation to extract
663 each top-level loop into its own new function. If the loop is the *only* loop
664 in a given function, it is not touched. This is a pass most useful for
665 debugging via bugpoint.
667 ``loop-reduce``: Loop Strength Reduction
668 ----------------------------------------
670 This pass performs a strength reduction on array references inside loops that
671 have as one or more of their components the loop induction variable. This is
672 accomplished by creating a new value to hold the initial value of the array
673 access for the first iteration, and then creating a new GEP instruction in the
674 loop to increment the value by the appropriate amount.
676 .. _passes-loop-rotate:
678 ``loop-rotate``: Rotate Loops
679 -----------------------------
681 A simple loop rotation transformation. A summary of it can be found in
682 :ref:`Loop Terminology for Rotated Loops <loop-terminology-loop-rotate>`.
685 .. _passes-loop-simplify:
687 ``loop-simplify``: Canonicalize natural loops
688 ---------------------------------------------
690 This pass performs several transformations to transform natural loops into a
691 simpler form, which makes subsequent analyses and transformations simpler and
692 more effective. A summary of it can be found in
693 :ref:`Loop Terminology, Loop Simplify Form <loop-terminology-loop-simplify>`.
695 Loop pre-header insertion guarantees that there is a single, non-critical entry
696 edge from outside of the loop to the loop header. This simplifies a number of
697 analyses and transformations, such as :ref:`LICM <passes-licm>`.
699 Loop exit-block insertion guarantees that all exit blocks from the loop (blocks
700 which are outside of the loop that have predecessors inside of the loop) only
701 have predecessors from inside of the loop (and are thus dominated by the loop
702 header). This simplifies transformations such as store-sinking that are built
705 This pass also guarantees that loops will have exactly one backedge.
707 Note that the :ref:`simplifycfg <passes-simplifycfg>` pass will clean up blocks
708 which are split out but end up being unnecessary, so usage of this pass should
709 not pessimize generated code.
711 This pass obviously modifies the CFG, but updates loop information and
712 dominator information.
714 ``loop-unroll``: Unroll loops
715 -----------------------------
717 This pass implements a simple loop unroller. It works best when loops have
718 been canonicalized by the :ref:`indvars <passes-indvars>` pass, allowing it to
719 determine the trip counts of loops easily.
721 ``loop-unroll-and-jam``: Unroll and Jam loops
722 ---------------------------------------------
724 This pass implements a simple unroll and jam classical loop optimisation pass.
725 It transforms loop from:
729 for i.. i+= 1 for i.. i+= 4
731 code(i, j) code(i, j)
737 Which can be seen as unrolling the outer loop and "jamming" (fusing) the inner
738 loops into one. When variables or loads can be shared in the new inner loop, this
739 can lead to significant performance improvements. It uses
740 :ref:`Dependence Analysis <passes-da>` for proving the transformations are safe.
742 ``lower-global-dtors``: Lower global destructors
743 ------------------------------------------------
745 This pass lowers global module destructors (``llvm.global_dtors``) by creating
746 wrapper functions that are registered as global constructors in
747 ``llvm.global_ctors`` and which contain a call to ``__cxa_atexit`` to register
748 their destructor functions.
750 ``lower-atomic``: Lower atomic intrinsics to non-atomic form
751 ------------------------------------------------------------
753 This pass lowers atomic intrinsics to non-atomic form for use in a known
754 non-preemptible environment.
756 The pass does not verify that the environment is non-preemptible (in general
757 this would require knowledge of the entire call graph of the program including
758 any libraries which may not be available in bitcode form); it simply lowers
759 every atomic intrinsic.
761 ``lower-invoke``: Lower invokes to calls, for unwindless code generators
762 ------------------------------------------------------------------------
764 This transformation is designed for use by code generators which do not yet
765 support stack unwinding. This pass converts ``invoke`` instructions to
766 ``call`` instructions, so that any exception-handling ``landingpad`` blocks
767 become dead code (which can be removed by running the ``-simplifycfg`` pass
770 ``lower-switch``: Lower ``SwitchInst``\ s to branches
771 -----------------------------------------------------
773 Rewrites switch instructions with a sequence of branches, which allows targets
774 to get away with not implementing the switch instruction until it is
779 ``mem2reg``: Promote Memory to Register
780 ---------------------------------------
782 This file promotes memory references to be register references. It promotes
783 alloca instructions which only have loads and stores as uses. An ``alloca`` is
784 transformed by using dominator frontiers to place phi nodes, then traversing
785 the function in depth-first order to rewrite loads and stores as appropriate.
786 This is just the standard SSA construction algorithm to construct "pruned" SSA
789 ``memcpyopt``: MemCpy Optimization
790 ----------------------------------
792 This pass performs various transformations related to eliminating ``memcpy``
793 calls, or transforming sets of stores into ``memset``\ s.
795 ``mergefunc``: Merge Functions
796 ------------------------------
798 This pass looks for equivalent functions that are mergeable and folds them.
800 Total-ordering is introduced among the functions set: we define comparison
801 that answers for every two functions which of them is greater. It allows to
802 arrange functions into the binary tree.
804 For every new function we check for equivalent in tree.
806 If equivalent exists we fold such functions. If both functions are overridable,
807 we move the functionality into a new internal function and leave two
808 overridable thunks to it.
810 If there is no equivalent, then we add this function to tree.
812 Lookup routine has O(log(n)) complexity, while whole merging process has
813 complexity of O(n*log(n)).
816 :doc:`this <MergeFunctions>`
817 article for more details.
819 ``mergereturn``: Unify function exit nodes
820 ------------------------------------------
822 Ensure that functions have at most one ``ret`` instruction in them.
823 Additionally, it keeps track of which node is the new exit node of the CFG.
825 ``partial-inliner``: Partial Inliner
826 ------------------------------------
828 This pass performs partial inlining, typically by inlining an ``if`` statement
829 that surrounds the body of the function.
831 ``reassociate``: Reassociate expressions
832 ----------------------------------------
834 This pass reassociates commutative expressions in an order that is designed to
835 promote better constant propagation, GCSE, :ref:`LICM <passes-licm>`, PRE, etc.
837 For example: 4 + (x + 5) ⇒ x + (4 + 5)
839 In the implementation of this algorithm, constants are assigned rank = 0,
840 function arguments are rank = 1, and other values are assigned ranks
841 corresponding to the reverse post order traversal of current function (starting
842 at 2), which effectively gives values in deep loops higher rank than values not
845 ``rel-lookup-table-converter``: Relative lookup table converter
846 ---------------------------------------------------------------
848 This pass converts lookup tables to PIC-friendly relative lookup tables.
850 ``reg2mem``: Demote all values to stack slots
851 ---------------------------------------------
853 This file demotes all registers to memory references. It is intended to be the
854 inverse of :ref:`mem2reg <passes-mem2reg>`. By converting to ``load``
855 instructions, the only values live across basic blocks are ``alloca``
856 instructions and ``load`` instructions before ``phi`` nodes. It is intended
857 that this should make CFG hacking much easier. To make later hacking easier,
858 the entry block is split into two, such that all introduced ``alloca``
859 instructions (and nothing else) are in the entry block.
861 ``sroa``: Scalar Replacement of Aggregates
862 ------------------------------------------
864 The well-known scalar replacement of aggregates transformation. This transform
865 breaks up ``alloca`` instructions of aggregate type (structure or array) into
866 individual ``alloca`` instructions for each member if possible. Then, if
867 possible, it transforms the individual ``alloca`` instructions into nice clean
872 ``sccp``: Sparse Conditional Constant Propagation
873 -------------------------------------------------
875 Sparse conditional constant propagation and merging, which can be summarized
878 * Assumes values are constant unless proven otherwise
879 * Assumes BasicBlocks are dead unless proven otherwise
880 * Proves values to be constant, and replaces them with constants
881 * Proves conditional branches to be unconditional
883 Note that this pass has a habit of making definitions be dead. It is a good
884 idea to run a :ref:`DCE <passes-dce>` pass sometime after running this pass.
886 .. _passes-simplifycfg:
888 ``simplifycfg``: Simplify the CFG
889 ---------------------------------
891 Performs dead code elimination and basic block merging. Specifically:
893 * Removes basic blocks with no predecessors.
894 * Merges a basic block into its predecessor if there is only one and the
895 predecessor only has one successor.
896 * Eliminates PHI nodes for basic blocks with a single predecessor.
897 * Eliminates a basic block that only contains an unconditional branch.
899 ``sink``: Code sinking
900 ----------------------
902 This pass moves instructions into successor blocks, when possible, so that they
903 aren't executed on paths where their results aren't needed.
905 .. _passes-simple-loop-unswitch:
907 ``simple-loop-unswitch``: Unswitch loops
908 ----------------------------------------
910 This pass transforms loops that contain branches on loop-invariant conditions
911 to have multiple loops. For example, it turns the left into the right code:
922 This can increase the size of the code exponentially (doubling it every time a
923 loop is unswitched) so we only unswitch if the resultant code will be smaller
926 This pass expects :ref:`LICM <passes-licm>` to be run before it to hoist
927 invariant conditions out of the loop, to make the unswitching opportunity
930 ``strip``: Strip all symbols from a module
931 ------------------------------------------
933 Performs code stripping. This transformation can delete:
935 * names for virtual registers
936 * symbols for internal globals and functions
939 Note that this transformation makes code much less readable, so it should only
940 be used in situations where the strip utility would be used, such as reducing
941 code size or making it harder to reverse engineer code.
943 ``strip-dead-debug-info``: Strip debug info for unused symbols
944 --------------------------------------------------------------
946 Performs code stripping. Similar to strip, but only strips debug info for
949 ``strip-dead-prototypes``: Strip Unused Function Prototypes
950 -----------------------------------------------------------
952 This pass loops over all of the functions in the input module, looking for dead
953 declarations and removes them. Dead declarations are declarations of functions
954 for which no implementation is available (i.e., declarations for unused library
957 ``strip-debug-declare``: Strip all ``llvm.dbg.declare`` intrinsics and
958 ``#dbg_declare`` records.
959 -------------------------------------------------------------------
961 Performs code stripping. Similar to strip, but only strips
962 ``llvm.dbg.declare`` intrinsics.
964 ``strip-nondebug``: Strip all symbols, except dbg symbols, from a module
965 ------------------------------------------------------------------------
967 Performs code stripping. Similar to strip, but dbg info is preserved.
969 ``tailcallelim``: Tail Call Elimination
970 ---------------------------------------
972 This file transforms calls of the current function (self recursion) followed by
973 a return instruction with a branch to the entry of the function, creating a
974 loop. This pass also implements the following extensions to the basic
977 #. Trivial instructions between the call and return do not prevent the
978 transformation from taking place, though currently the analysis cannot
979 support moving any really useful instructions (only dead ones).
980 #. This pass transforms functions that are prevented from being tail recursive
981 by an associative expression to use an accumulator variable, thus compiling
982 the typical naive factorial or fib implementation into efficient code.
983 #. TRE is performed if the function returns void, if the return returns the
984 result returned by the call, or if the function returns a run-time constant
985 on all exits from the function. It is possible, though unlikely, that the
986 return returns something else (like constant 0), and can still be TRE'd. It
987 can be TRE'd if *all other* return instructions in the function return the
989 #. If it can prove that callees do not access their caller stack frame, they
990 are marked as eligible for tail call elimination (by the code generator).
995 This section describes the LLVM Utility Passes.
997 ``deadarghaX0r``: Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)
998 -----------------------------------------------------------------------
1000 Same as dead argument elimination, but deletes arguments to functions which are
1001 external. This is only for use by :doc:`bugpoint <Bugpoint>`.
1003 ``extract-blocks``: Extract Basic Blocks From Module (for bugpoint use)
1004 -----------------------------------------------------------------------
1006 This pass is used by bugpoint to extract all blocks from the module into their
1009 ``instnamer``: Assign names to anonymous instructions
1010 -----------------------------------------------------
1012 This is a little utility pass that gives instructions names, this is mostly
1013 useful when diffing the effect of an optimization because deleting an unnamed
1014 instruction can change all other instruction numbering, making the diff very
1019 ``verify``: Module Verifier
1020 ---------------------------
1022 Verifies an LLVM IR code. This is useful to run after an optimization which is
1023 undergoing testing. Note that llvm-as verifies its input before emitting
1024 bitcode, and also that malformed bitcode is likely to make LLVM crash. All
1025 language front-ends are therefore encouraged to verify their output before
1026 performing optimizing transformations.
1028 #. Both of a binary operator's parameters are of the same type.
1029 #. Verify that the indices of mem access instructions match other operands.
1030 #. Verify that arithmetic and other things are only performed on first-class
1031 types. Verify that shifts and logicals only happen on integrals f.e.
1032 #. All of the constants in a switch statement are of the correct type.
1033 #. The code is in valid SSA form.
1034 #. It is illegal to put a label into any other type (like a structure) or to
1036 #. Only phi nodes can be self referential: ``%x = add i32 %x``, ``%x`` is
1038 #. PHI nodes must have an entry for each predecessor, with no extras.
1039 #. PHI nodes must be the first thing in a basic block, all grouped together.
1040 #. PHI nodes must have at least one entry.
1041 #. All basic blocks should only end with terminator insts, not contain them.
1042 #. The entry node to a function must not have predecessors.
1043 #. All Instructions must be embedded into a basic block.
1044 #. Functions cannot take a void-typed parameter.
1045 #. Verify that a function's argument list agrees with its declared type.
1046 #. It is illegal to specify a name for a void value.
1047 #. It is illegal to have an internal global value with no initializer.
1048 #. It is illegal to have a ``ret`` instruction that returns a value that does
1049 not agree with the function return value type.
1050 #. Function call argument types match the function prototype.
1051 #. All other things that are tested by asserts spread about the code.
1053 Note that this does not provide full security verification (like Java), but
1054 instead just tries to ensure that code is well-formed.
1056 .. _passes-view-cfg:
1058 ``view-cfg``: View CFG of function
1059 ----------------------------------
1061 Displays the control flow graph using the GraphViz tool.
1062 Additionally the ``-cfg-func-name=<substring>`` option can be used to filter the
1063 functions that are displayed. All functions that contain the specified substring
1066 ``view-cfg-only``: View CFG of function (with no function bodies)
1067 -----------------------------------------------------------------
1069 Displays the control flow graph using the GraphViz tool, but omitting function
1071 Additionally the ``-cfg-func-name=<substring>`` option can be used to filter the
1072 functions that are displayed. All functions that contain the specified substring
1075 ``view-dom``: View dominance tree of function
1076 ---------------------------------------------
1078 Displays the dominator tree using the GraphViz tool.
1080 ``view-dom-only``: View dominance tree of function (with no function bodies)
1081 ----------------------------------------------------------------------------
1083 Displays the dominator tree using the GraphViz tool, but omitting function
1086 ``view-post-dom``: View postdominance tree of function
1087 ------------------------------------------------------
1089 Displays the post dominator tree using the GraphViz tool.
1091 ``view-post-dom-only``: View postdominance tree of function (with no function bodies)
1092 -------------------------------------------------------------------------------------
1094 Displays the post dominator tree using the GraphViz tool, but omitting function
1097 ``transform-warning``: Report missed forced transformations
1098 -----------------------------------------------------------
1100 Emits warnings about not yet applied forced transformations (e.g. from
1101 ``#pragma omp simd``).