2 If Passes.html is up to date, the following "one-liner" should print
5 egrep -e '^<tr><td><a href="#.*">-.*</a></td><td>.*</td></tr>$' \
6 -e '^ <a name=".*">.*</a>$' < Passes.html >html; \
7 perl >help <<'EOT' && diff -u help html; rm -f help html
8 open HTML, "<Passes.html" or die "open: Passes.html: $!\n";
10 m:^<tr><td><a href="#(.*)">-.*</a></td><td>.*</td></tr>$: or next;
11 $order{$1} = sprintf("%03d", 1 + int %order);
13 open HELP, "../Release/bin/opt -help|" or die "open: opt -help: $!\n";
15 m:^ -([^ ]+) +- (.*)$: or next;
17 $o = "000" unless defined $o;
18 push @x, "$o<tr><td><a href=\"#$1\">-$1</a></td><td>$2</td></tr>\n";
19 push @y, "$o <a name=\"$1\">-$1: $2</a>\n";
21 @x = map { s/^\d\d\d//; $_ } sort @x;
22 @y = map { s/^\d\d\d//; $_ } sort @y;
26 This (real) one-liner can also be helpful when converting comments to HTML:
28 perl -e '$/ = undef; for (split(/\n/, <>)) { s:^ *///? ?::; print " <p>\n" if !$on && $_ =~ /\S/; print " </p>\n" if $on && $_ =~ /^\s*$/; print " $_\n"; $on = ($_ =~ /\S/); } print " </p>\n" if $on'
30 ====================================
31 LLVM's Analysis and Transform Passes
32 ====================================
37 Written by `Reid Spencer <mailto:rspencer@x10sys.com>`_
43 This document serves as a high level summary of the optimization features that
44 LLVM provides. Optimizations are implemented as Passes that traverse some
45 portion of a program to either collect information or transform the program.
46 The table below divides the passes that LLVM provides into three categories.
47 Analysis passes compute information that other passes can use or for debugging
48 or program visualization purposes. Transform passes can use (or invalidate)
49 the analysis passes. Transform passes all mutate the program in some way.
50 Utility passes provides some utility but don't otherwise fit categorization.
51 For example passes to extract functions to bitcode or write a module to bitcode
52 are neither analysis nor transform passes. The table of contents above
53 provides a quick summary of each pass and links to the more complete pass
54 description later in the document.
59 This section describes the LLVM Analysis Passes.
61 ``-aa-eval``: Exhaustive Alias Analysis Precision Evaluator
62 -----------------------------------------------------------
64 This is a simple N^2 alias analysis accuracy evaluator. Basically, for each
65 function in the program, it simply queries to see how the alias analysis
66 implementation answers alias queries between each pair of pointers in the
69 This is inspired and adapted from code by: Naveen Neelakantam, Francesco
70 Spadini, and Wojciech Stryjewski.
72 ``-basicaa``: Basic Alias Analysis (stateless AA impl)
73 ------------------------------------------------------
75 A basic alias analysis pass that implements identities (two different globals
76 cannot alias, etc), but does no stateful analysis.
78 ``-basiccg``: Basic CallGraph Construction
79 ------------------------------------------
83 ``-count-aa``: Count Alias Analysis Query Responses
84 ---------------------------------------------------
86 A pass which can be used to count how many alias queries are being made and how
87 the alias analysis implementation being used responds.
89 ``-da``: Dependence Analysis
90 ----------------------------
92 Dependence analysis framework, which is used to detect dependences in memory
95 ``-debug-aa``: AA use debugger
96 ------------------------------
98 This simple pass checks alias analysis users to ensure that if they create a
99 new value, they do not query AA without informing it of the value. It acts as
100 a shim over any other AA pass you want.
102 Yes keeping track of every value in the program is expensive, but this is a
105 ``-domfrontier``: Dominance Frontier Construction
106 -------------------------------------------------
108 This pass is a simple dominator construction algorithm for finding forward
111 ``-domtree``: Dominator Tree Construction
112 -----------------------------------------
114 This pass is a simple dominator construction algorithm for finding forward
118 ``-dot-callgraph``: Print Call Graph to "dot" file
119 --------------------------------------------------
121 This pass, only available in ``opt``, prints the call graph into a ``.dot``
122 graph. This graph can then be processed with the "dot" tool to convert it to
123 postscript or some other suitable format.
125 ``-dot-cfg``: Print CFG of function to "dot" file
126 -------------------------------------------------
128 This pass, only available in ``opt``, prints the control flow graph into a
129 ``.dot`` graph. This graph can then be processed with the :program:`dot` tool
130 to convert it to postscript or some other suitable format.
132 ``-dot-cfg-only``: Print CFG of function to "dot" file (with no function bodies)
133 --------------------------------------------------------------------------------
135 This pass, only available in ``opt``, prints the control flow graph into a
136 ``.dot`` graph, omitting the function bodies. This graph can then be processed
137 with the :program:`dot` tool to convert it to postscript or some other suitable
140 ``-dot-dom``: Print dominance tree of function to "dot" file
141 ------------------------------------------------------------
143 This pass, only available in ``opt``, prints the dominator tree into a ``.dot``
144 graph. This graph can then be processed with the :program:`dot` tool to
145 convert it to postscript or some other suitable format.
147 ``-dot-dom-only``: Print dominance tree of function to "dot" file (with no function bodies)
148 -------------------------------------------------------------------------------------------
150 This pass, only available in ``opt``, prints the dominator tree into a ``.dot``
151 graph, omitting the function bodies. This graph can then be processed with the
152 :program:`dot` tool to convert it to postscript or some other suitable format.
154 ``-dot-postdom``: Print postdominance tree of function to "dot" file
155 --------------------------------------------------------------------
157 This pass, only available in ``opt``, prints the post dominator tree into a
158 ``.dot`` graph. This graph can then be processed with the :program:`dot` tool
159 to convert it to postscript or some other suitable format.
161 ``-dot-postdom-only``: Print postdominance tree of function to "dot" file (with no function bodies)
162 ---------------------------------------------------------------------------------------------------
164 This pass, only available in ``opt``, prints the post dominator tree into a
165 ``.dot`` graph, omitting the function bodies. This graph can then be processed
166 with the :program:`dot` tool to convert it to postscript or some other suitable
169 ``-globalsmodref-aa``: Simple mod/ref analysis for globals
170 ----------------------------------------------------------
172 This simple pass provides alias and mod/ref information for global values that
173 do not have their address taken, and keeps track of whether functions read or
174 write memory (are "pure"). For this simple (but very common) case, we can
175 provide pretty accurate and useful information.
177 ``-instcount``: Counts the various types of ``Instruction``\ s
178 --------------------------------------------------------------
180 This pass collects the count of all instructions and reports them.
182 ``-intervals``: Interval Partition Construction
183 -----------------------------------------------
185 This analysis calculates and represents the interval partition of a function,
186 or a preexisting interval partition.
188 In this way, the interval partition may be used to reduce a flow graph down to
189 its degenerate single node interval partition (unless it is irreducible).
191 ``-iv-users``: Induction Variable Users
192 ---------------------------------------
194 Bookkeeping for "interesting" users of expressions computed from induction
197 ``-lazy-value-info``: Lazy Value Information Analysis
198 -----------------------------------------------------
200 Interface for lazy computation of value constraint information.
202 ``-libcall-aa``: LibCall Alias Analysis
203 ---------------------------------------
205 LibCall Alias Analysis.
207 ``-lint``: Statically lint-checks LLVM IR
208 -----------------------------------------
210 This pass statically checks for common and easily-identified constructs which
211 produce undefined or likely unintended behavior in LLVM IR.
213 It is not a guarantee of correctness, in two ways. First, it isn't
214 comprehensive. There are checks which could be done statically which are not
215 yet implemented. Some of these are indicated by TODO comments, but those
216 aren't comprehensive either. Second, many conditions cannot be checked
217 statically. This pass does no dynamic instrumentation, so it can't check for
218 all possible problems.
220 Another limitation is that it assumes all code will be executed. A store
221 through a null pointer in a basic block which is never reached is harmless, but
222 this pass will warn about it anyway.
224 Optimization passes may make conditions that this pass checks for more or less
225 obvious. If an optimization pass appears to be introducing a warning, it may
226 be that the optimization pass is merely exposing an existing condition in the
229 This code may be run before :ref:`instcombine <passes-instcombine>`. In many
230 cases, instcombine checks for the same kinds of things and turns instructions
231 with undefined behavior into unreachable (or equivalent). Because of this,
232 this pass makes some effort to look through bitcasts and so on.
234 ``-loops``: Natural Loop Information
235 ------------------------------------
237 This analysis is used to identify natural loops and determine the loop depth of
238 various nodes of the CFG. Note that the loops identified may actually be
239 several natural loops that share the same header node... not just a single
242 ``-memdep``: Memory Dependence Analysis
243 ---------------------------------------
245 An analysis that determines, for a given memory operation, what preceding
246 memory operations it depends on. It builds on alias analysis information, and
247 tries to provide a lazy, caching interface to a common kind of alias
250 ``-module-debuginfo``: Decodes module-level debug info
251 ------------------------------------------------------
253 This pass decodes the debug info metadata in a module and prints in a
254 (sufficiently-prepared-) human-readable form.
256 For example, run this pass from ``opt`` along with the ``-analyze`` option, and
257 it'll print to standard output.
259 ``-no-aa``: No Alias Analysis (always returns 'may' alias)
260 ----------------------------------------------------------
262 This is the default implementation of the Alias Analysis interface. It always
263 returns "I don't know" for alias queries. NoAA is unlike other alias analysis
264 implementations, in that it does not chain to a previous analysis. As such it
265 doesn't follow many of the rules that other alias analyses must.
267 ``-no-profile``: No Profile Information
268 ---------------------------------------
270 The default "no profile" implementation of the abstract ``ProfileInfo``
273 ``-postdomfrontier``: Post-Dominance Frontier Construction
274 ----------------------------------------------------------
276 This pass is a simple post-dominator construction algorithm for finding
277 post-dominator frontiers.
279 ``-postdomtree``: Post-Dominator Tree Construction
280 --------------------------------------------------
282 This pass is a simple post-dominator construction algorithm for finding
285 ``-print-alias-sets``: Alias Set Printer
286 ----------------------------------------
290 ``-print-callgraph``: Print a call graph
291 ----------------------------------------
293 This pass, only available in ``opt``, prints the call graph to standard error
294 in a human-readable form.
296 ``-print-callgraph-sccs``: Print SCCs of the Call Graph
297 -------------------------------------------------------
299 This pass, only available in ``opt``, prints the SCCs of the call graph to
300 standard error in a human-readable form.
302 ``-print-cfg-sccs``: Print SCCs of each function CFG
303 ----------------------------------------------------
305 This pass, only available in ``opt``, printsthe SCCs of each function CFG to
306 standard error in a human-readable fom.
308 ``-print-dbginfo``: Print debug info in human readable form
309 -----------------------------------------------------------
311 Pass that prints instructions, and associated debug info:
313 #. source/line/col information
314 #. original variable name
315 #. original type name
317 ``-print-dom-info``: Dominator Info Printer
318 -------------------------------------------
320 Dominator Info Printer.
322 ``-print-externalfnconstants``: Print external fn callsites passed constants
323 ----------------------------------------------------------------------------
325 This pass, only available in ``opt``, prints out call sites to external
326 functions that are called with constant arguments. This can be useful when
327 looking for standard library functions we should constant fold or handle in
330 ``-print-function``: Print function to stderr
331 ---------------------------------------------
333 The ``PrintFunctionPass`` class is designed to be pipelined with other
334 ``FunctionPasses``, and prints out the functions of the module as they are
337 ``-print-module``: Print module to stderr
338 -----------------------------------------
340 This pass simply prints out the entire module when it is executed.
342 .. _passes-print-used-types:
344 ``-print-used-types``: Find Used Types
345 --------------------------------------
347 This pass is used to seek out all of the types in use by the program. Note
348 that this analysis explicitly does not include types only used by the symbol
351 ``-profile-estimator``: Estimate profiling information
352 ------------------------------------------------------
354 Profiling information that estimates the profiling information in a very crude
355 and unimaginative way.
357 ``-profile-loader``: Load profile information from ``llvmprof.out``
358 -------------------------------------------------------------------
360 A concrete implementation of profiling information that loads the information
361 from a profile dump file.
363 ``-profile-verifier``: Verify profiling information
364 ---------------------------------------------------
366 Pass that checks profiling information for plausibility.
368 ``-regions``: Detect single entry single exit regions
369 -----------------------------------------------------
371 The ``RegionInfo`` pass detects single entry single exit regions in a function,
372 where a region is defined as any subgraph that is connected to the remaining
373 graph at only two spots. Furthermore, an hierarchical region tree is built.
375 ``-scalar-evolution``: Scalar Evolution Analysis
376 ------------------------------------------------
378 The ``ScalarEvolution`` analysis can be used to analyze and catagorize scalar
379 expressions in loops. It specializes in recognizing general induction
380 variables, representing them with the abstract and opaque ``SCEV`` class.
381 Given this analysis, trip counts of loops and other important properties can be
384 This analysis is primarily useful for induction variable substitution and
387 ``-scev-aa``: ScalarEvolution-based Alias Analysis
388 --------------------------------------------------
390 Simple alias analysis implemented in terms of ``ScalarEvolution`` queries.
392 This differs from traditional loop dependence analysis in that it tests for
393 dependencies within a single iteration of a loop, rather than dependencies
394 between different iterations.
396 ``ScalarEvolution`` has a more complete understanding of pointer arithmetic
397 than ``BasicAliasAnalysis``' collection of ad-hoc analyses.
399 ``-targetdata``: Target Data Layout
400 -----------------------------------
402 Provides other passes access to information on how the size and alignment
403 required by the target ABI for various data types.
408 This section describes the LLVM Transform Passes.
410 ``-adce``: Aggressive Dead Code Elimination
411 -------------------------------------------
413 ADCE aggressively tries to eliminate code. This pass is similar to :ref:`DCE
414 <passes-dce>` but it assumes that values are dead until proven otherwise. This
415 is similar to :ref:`SCCP <passes-sccp>`, except applied to the liveness of
418 ``-always-inline``: Inliner for ``always_inline`` functions
419 -----------------------------------------------------------
421 A custom inliner that handles only functions that are marked as "always
424 ``-argpromotion``: Promote 'by reference' arguments to scalars
425 --------------------------------------------------------------
427 This pass promotes "by reference" arguments to be "by value" arguments. In
428 practice, this means looking for internal functions that have pointer
429 arguments. If it can prove, through the use of alias analysis, that an
430 argument is *only* loaded, then it can pass the value into the function instead
431 of the address of the value. This can cause recursive simplification of code
432 and lead to the elimination of allocas (especially in C++ template code like
435 This pass also handles aggregate arguments that are passed into a function,
436 scalarizing them if the elements of the aggregate are only loaded. Note that
437 it refuses to scalarize aggregates which would require passing in more than
438 three operands to the function, because passing thousands of operands for a
439 large array or structure is unprofitable!
441 Note that this transformation could also be done for arguments that are only
442 stored to (returning the value instead), but does not currently. This case
443 would be best handled when and if LLVM starts supporting multiple return values
446 ``-bb-vectorize``: Basic-Block Vectorization
447 --------------------------------------------
449 This pass combines instructions inside basic blocks to form vector
450 instructions. It iterates over each basic block, attempting to pair compatible
451 instructions, repeating this process until no additional pairs are selected for
452 vectorization. When the outputs of some pair of compatible instructions are
453 used as inputs by some other pair of compatible instructions, those pairs are
454 part of a potential vectorization chain. Instruction pairs are only fused into
455 vector instructions when they are part of a chain longer than some threshold
456 length. Moreover, the pass attempts to find the best possible chain for each
457 pair of compatible instructions. These heuristics are intended to prevent
458 vectorization in cases where it would not yield a performance increase of the
461 ``-block-placement``: Profile Guided Basic Block Placement
462 ----------------------------------------------------------
464 This pass is a very simple profile guided basic block placement algorithm. The
465 idea is to put frequently executed blocks together at the start of the function
466 and hopefully increase the number of fall-through conditional branches. If
467 there is no profile information for a particular function, this pass basically
468 orders blocks in depth-first order.
470 ``-break-crit-edges``: Break critical edges in CFG
471 --------------------------------------------------
473 Break all of the critical edges in the CFG by inserting a dummy basic block.
474 It may be "required" by passes that cannot deal with critical edges. This
475 transformation obviously invalidates the CFG, but can update forward dominator
476 (set, immediate dominators, tree, and frontier) information.
478 ``-codegenprepare``: Optimize for code generation
479 -------------------------------------------------
481 This pass munges the code in the input function to better prepare it for
482 SelectionDAG-based code generation. This works around limitations in it's
483 basic-block-at-a-time approach. It should eventually be removed.
485 ``-constmerge``: Merge Duplicate Global Constants
486 -------------------------------------------------
488 Merges duplicate global constants together into a single constant that is
489 shared. This is useful because some passes (i.e., TraceValues) insert a lot of
490 string constants into the program, regardless of whether or not an existing
493 ``-constprop``: Simple constant propagation
494 -------------------------------------------
496 This file implements constant propagation and merging. It looks for
497 instructions involving only constant operands and replaces them with a constant
498 value instead of an instruction. For example:
510 NOTE: this pass has a habit of making definitions be dead. It is a good idea
511 to to run a :ref:`Dead Instruction Elimination <passes-die>` pass sometime
512 after running this pass.
516 ``-dce``: Dead Code Elimination
517 -------------------------------
519 Dead code elimination is similar to :ref:`dead instruction elimination
520 <passes-die>`, but it rechecks instructions that were used by removed
521 instructions to see if they are newly dead.
523 ``-deadargelim``: Dead Argument Elimination
524 -------------------------------------------
526 This pass deletes dead arguments from internal functions. Dead argument
527 elimination removes arguments which are directly dead, as well as arguments
528 only passed into function calls as dead arguments of other functions. This
529 pass also deletes dead arguments in a similar way.
531 This pass is often useful as a cleanup pass to run after aggressive
532 interprocedural passes, which add possibly-dead arguments.
534 ``-deadtypeelim``: Dead Type Elimination
535 ----------------------------------------
537 This pass is used to cleanup the output of GCC. It eliminate names for types
538 that are unused in the entire translation unit, using the :ref:`find used types
539 <passes-print-used-types>` pass.
543 ``-die``: Dead Instruction Elimination
544 --------------------------------------
546 Dead instruction elimination performs a single pass over the function, removing
547 instructions that are obviously dead.
549 ``-dse``: Dead Store Elimination
550 --------------------------------
552 A trivial dead store elimination that only considers basic-block local
555 ``-functionattrs``: Deduce function attributes
556 ----------------------------------------------
558 A simple interprocedural pass which walks the call-graph, looking for functions
559 which do not access or only read non-local memory, and marking them
560 ``readnone``/``readonly``. In addition, it marks function arguments (of
561 pointer type) "``nocapture``" if a call to the function does not create any
562 copies of the pointer value that outlive the call. This more or less means
563 that the pointer is only dereferenced, and not returned from the function or
564 stored in a global. This pass is implemented as a bottom-up traversal of the
567 ``-globaldce``: Dead Global Elimination
568 ---------------------------------------
570 This transform is designed to eliminate unreachable internal globals from the
571 program. It uses an aggressive algorithm, searching out globals that are known
572 to be alive. After it finds all of the globals which are needed, it deletes
573 whatever is left over. This allows it to delete recursive chunks of the
574 program which are unreachable.
576 ``-globalopt``: Global Variable Optimizer
577 -----------------------------------------
579 This pass transforms simple global variables that never have their address
580 taken. If obviously true, it marks read/write globals as constant, deletes
581 variables only stored to, etc.
583 ``-gvn``: Global Value Numbering
584 --------------------------------
586 This pass performs global value numbering to eliminate fully and partially
587 redundant instructions. It also performs redundant load elimination.
591 ``-indvars``: Canonicalize Induction Variables
592 ----------------------------------------------
594 This transformation analyzes and transforms the induction variables (and
595 computations derived from them) into simpler forms suitable for subsequent
596 analysis and transformation.
598 This transformation makes the following changes to each loop with an
599 identifiable induction variable:
601 * All loops are transformed to have a *single* canonical induction variable
602 which starts at zero and steps by one.
603 * The canonical induction variable is guaranteed to be the first PHI node in
604 the loop header block.
605 * Any pointer arithmetic recurrences are raised to use array subscripts.
607 If the trip count of a loop is computable, this pass also makes the following
610 * The exit condition for the loop is canonicalized to compare the induction
611 value against the exit value. This turns loops like:
615 for (i = 7; i*i < 1000; ++i)
621 for (i = 0; i != 25; ++i)
623 * Any use outside of the loop of an expression derived from the indvar is
624 changed to compute the derived value outside of the loop, eliminating the
625 dependence on the exit value of the induction variable. If the only purpose
626 of the loop is to compute the exit value of some derived expression, this
627 transformation will make the loop dead.
629 This transformation should be followed by strength reduction after all of the
630 desired loop transformations have been performed. Additionally, on targets
631 where it is profitable, the loop could be transformed to count down to zero
632 (the "do loop" optimization).
634 ``-inline``: Function Integration/Inlining
635 ------------------------------------------
637 Bottom-up inlining of functions into callees.
639 ``-insert-edge-profiling``: Insert instrumentation for edge profiling
640 ---------------------------------------------------------------------
642 This pass instruments the specified program with counters for edge profiling.
643 Edge profiling can give a reasonable approximation of the hot paths through a
644 program, and is used for a wide variety of program transformations.
646 Note that this implementation is very naïve. It inserts a counter for *every*
647 edge in the program, instead of using control flow information to prune the
648 number of counters inserted.
650 ``-insert-optimal-edge-profiling``: Insert optimal instrumentation for edge profiling
651 -------------------------------------------------------------------------------------
653 This pass instruments the specified program with counters for edge profiling.
654 Edge profiling can give a reasonable approximation of the hot paths through a
655 program, and is used for a wide variety of program transformations.
657 .. _passes-instcombine:
659 ``-instcombine``: Combine redundant instructions
660 ------------------------------------------------
662 Combine instructions to form fewer, simple instructions. This pass does not
663 modify the CFG This pass is where algebraic simplification happens.
665 This pass combines things like:
678 This is a simple worklist driven algorithm.
680 This pass guarantees that the following canonicalizations are performed on the
683 #. If a binary operator has a constant operand, it is moved to the right-hand
685 #. Bitwise operators with constant operands are always grouped so that shifts
686 are performed first, then ``or``\ s, then ``and``\ s, then ``xor``\ s.
687 #. Compare instructions are converted from ``<``, ``>``, ``≤``, or ``≥`` to
688 ``=`` or ``≠`` if possible.
689 #. All ``cmp`` instructions on boolean values are replaced with logical
691 #. ``add X, X`` is represented as ``mul X, 2`` ⇒ ``shl X, 1``
692 #. Multiplies with a constant power-of-two argument are transformed into
696 ``-internalize``: Internalize Global Symbols
697 --------------------------------------------
699 This pass loops over all of the functions in the input module, looking for a
700 main function. If a main function is found, all other functions and all global
701 variables with initializers are marked as internal.
703 ``-ipconstprop``: Interprocedural constant propagation
704 ------------------------------------------------------
706 This pass implements an *extremely* simple interprocedural constant propagation
707 pass. It could certainly be improved in many different ways, like using a
708 worklist. This pass makes arguments dead, but does not remove them. The
709 existing dead argument elimination pass should be run after this to clean up
712 ``-ipsccp``: Interprocedural Sparse Conditional Constant Propagation
713 --------------------------------------------------------------------
715 An interprocedural variant of :ref:`Sparse Conditional Constant Propagation
718 ``-jump-threading``: Jump Threading
719 -----------------------------------
721 Jump threading tries to find distinct threads of control flow running through a
722 basic block. This pass looks at blocks that have multiple predecessors and
723 multiple successors. If one or more of the predecessors of the block can be
724 proven to always cause a jump to one of the successors, we forward the edge
725 from the predecessor to the successor by duplicating the contents of this
728 An example of when this can occur is code like this:
737 In this case, the unconditional branch at the end of the first if can be
738 revectored to the false side of the second if.
740 ``-lcssa``: Loop-Closed SSA Form Pass
741 -------------------------------------
743 This pass transforms loops by placing phi nodes at the end of the loops for all
744 values that are live across the loop boundary. For example, it turns the left
754 X3 = phi(X1, X2) X3 = phi(X1, X2)
755 ... = X3 + 4 X4 = phi(X3)
758 This is still valid LLVM; the extra phi nodes are purely redundant, and will be
759 trivially eliminated by ``InstCombine``. The major benefit of this
760 transformation is that it makes many other loop optimizations, such as
761 ``LoopUnswitch``\ ing, simpler.
765 ``-licm``: Loop Invariant Code Motion
766 -------------------------------------
768 This pass performs loop invariant code motion, attempting to remove as much
769 code from the body of a loop as possible. It does this by either hoisting code
770 into the preheader block, or by sinking code to the exit blocks if it is safe.
771 This pass also promotes must-aliased memory locations in the loop to live in
772 registers, thus hoisting and sinking "invariant" loads and stores.
774 This pass uses alias analysis for two purposes:
776 #. Moving loop invariant loads and calls out of loops. If we can determine
777 that a load or call inside of a loop never aliases anything stored to, we
778 can hoist it or sink it like any other instruction.
780 #. Scalar Promotion of Memory. If there is a store instruction inside of the
781 loop, we try to move the store to happen AFTER the loop instead of inside of
782 the loop. This can only happen if a few conditions are true:
784 #. The pointer stored through is loop invariant.
785 #. There are no stores or loads in the loop which *may* alias the pointer.
786 There are no calls in the loop which mod/ref the pointer.
788 If these conditions are true, we can promote the loads and stores in the
789 loop of the pointer to use a temporary alloca'd variable. We then use the
790 :ref:`mem2reg <passes-mem2reg>` functionality to construct the appropriate
791 SSA form for the variable.
793 ``-loop-deletion``: Delete dead loops
794 -------------------------------------
796 This file implements the Dead Loop Deletion Pass. This pass is responsible for
797 eliminating loops with non-infinite computable trip counts that have no side
798 effects or volatile instructions, and do not contribute to the computation of
799 the function's return value.
801 .. _passes-loop-extract:
803 ``-loop-extract``: Extract loops into new functions
804 ---------------------------------------------------
806 A pass wrapper around the ``ExtractLoop()`` scalar transformation to extract
807 each top-level loop into its own new function. If the loop is the *only* loop
808 in a given function, it is not touched. This is a pass most useful for
809 debugging via bugpoint.
811 ``-loop-extract-single``: Extract at most one loop into a new function
812 ----------------------------------------------------------------------
814 Similar to :ref:`Extract loops into new functions <passes-loop-extract>`, this
815 pass extracts one natural loop from the program into a function if it can.
816 This is used by :program:`bugpoint`.
818 ``-loop-reduce``: Loop Strength Reduction
819 -----------------------------------------
821 This pass performs a strength reduction on array references inside loops that
822 have as one or more of their components the loop induction variable. This is
823 accomplished by creating a new value to hold the initial value of the array
824 access for the first iteration, and then creating a new GEP instruction in the
825 loop to increment the value by the appropriate amount.
827 ``-loop-rotate``: Rotate Loops
828 ------------------------------
830 A simple loop rotation transformation.
832 ``-loop-simplify``: Canonicalize natural loops
833 ----------------------------------------------
835 This pass performs several transformations to transform natural loops into a
836 simpler form, which makes subsequent analyses and transformations simpler and
839 Loop pre-header insertion guarantees that there is a single, non-critical entry
840 edge from outside of the loop to the loop header. This simplifies a number of
841 analyses and transformations, such as :ref:`LICM <passes-licm>`.
843 Loop exit-block insertion guarantees that all exit blocks from the loop (blocks
844 which are outside of the loop that have predecessors inside of the loop) only
845 have predecessors from inside of the loop (and are thus dominated by the loop
846 header). This simplifies transformations such as store-sinking that are built
849 This pass also guarantees that loops will have exactly one backedge.
851 Note that the :ref:`simplifycfg <passes-simplifycfg>` pass will clean up blocks
852 which are split out but end up being unnecessary, so usage of this pass should
853 not pessimize generated code.
855 This pass obviously modifies the CFG, but updates loop information and
856 dominator information.
858 ``-loop-unroll``: Unroll loops
859 ------------------------------
861 This pass implements a simple loop unroller. It works best when loops have
862 been canonicalized by the :ref:`indvars <passes-indvars>` pass, allowing it to
863 determine the trip counts of loops easily.
865 ``-loop-unswitch``: Unswitch loops
866 ----------------------------------
868 This pass transforms loops that contain branches on loop-invariant conditions
869 to have multiple loops. For example, it turns the left into the right code:
880 This can increase the size of the code exponentially (doubling it every time a
881 loop is unswitched) so we only unswitch if the resultant code will be smaller
884 This pass expects :ref:`LICM <passes-licm>` to be run before it to hoist
885 invariant conditions out of the loop, to make the unswitching opportunity
888 ``-loweratomic``: Lower atomic intrinsics to non-atomic form
889 ------------------------------------------------------------
891 This pass lowers atomic intrinsics to non-atomic form for use in a known
892 non-preemptible environment.
894 The pass does not verify that the environment is non-preemptible (in general
895 this would require knowledge of the entire call graph of the program including
896 any libraries which may not be available in bitcode form); it simply lowers
897 every atomic intrinsic.
899 ``-lowerinvoke``: Lower invoke and unwind, for unwindless code generators
900 -------------------------------------------------------------------------
902 This transformation is designed for use by code generators which do not yet
903 support stack unwinding. This pass supports two models of exception handling
904 lowering, the "cheap" support and the "expensive" support.
906 "Cheap" exception handling support gives the program the ability to execute any
907 program which does not "throw an exception", by turning "``invoke``"
908 instructions into calls and by turning "``unwind``" instructions into calls to
909 ``abort()``. If the program does dynamically use the "``unwind``" instruction,
910 the program will print a message then abort.
912 "Expensive" exception handling support gives the full exception handling
913 support to the program at the cost of making the "``invoke``" instruction
914 really expensive. It basically inserts ``setjmp``/``longjmp`` calls to emulate
915 the exception handling as necessary.
917 Because the "expensive" support slows down programs a lot, and EH is only used
918 for a subset of the programs, it must be specifically enabled by the
919 ``-enable-correct-eh-support`` option.
921 Note that after this pass runs the CFG is not entirely accurate (exceptional
922 control flow edges are not correct anymore) so only very simple things should
923 be done after the ``lowerinvoke`` pass has run (like generation of native
924 code). This should not be used as a general purpose "my LLVM-to-LLVM pass
925 doesn't support the ``invoke`` instruction yet" lowering pass.
927 ``-lowerswitch``: Lower ``SwitchInst``\ s to branches
928 -----------------------------------------------------
930 Rewrites switch instructions with a sequence of branches, which allows targets
931 to get away with not implementing the switch instruction until it is
936 ``-mem2reg``: Promote Memory to Register
937 ----------------------------------------
939 This file promotes memory references to be register references. It promotes
940 alloca instructions which only have loads and stores as uses. An ``alloca`` is
941 transformed by using dominator frontiers to place phi nodes, then traversing
942 the function in depth-first order to rewrite loads and stores as appropriate.
943 This is just the standard SSA construction algorithm to construct "pruned" SSA
946 ``-memcpyopt``: MemCpy Optimization
947 -----------------------------------
949 This pass performs various transformations related to eliminating ``memcpy``
950 calls, or transforming sets of stores into ``memset``\ s.
952 ``-mergefunc``: Merge Functions
953 -------------------------------
955 This pass looks for equivalent functions that are mergable and folds them.
957 A hash is computed from the function, based on its type and number of basic
960 Once all hashes are computed, we perform an expensive equality comparison on
961 each function pair. This takes n^2/2 comparisons per bucket, so it's important
962 that the hash function be high quality. The equality comparison iterates
963 through each instruction in each basic block.
965 When a match is found the functions are folded. If both functions are
966 overridable, we move the functionality into a new internal function and leave
967 two overridable thunks to it.
969 ``-mergereturn``: Unify function exit nodes
970 -------------------------------------------
972 Ensure that functions have at most one ``ret`` instruction in them.
973 Additionally, it keeps track of which node is the new exit node of the CFG.
975 ``-partial-inliner``: Partial Inliner
976 -------------------------------------
978 This pass performs partial inlining, typically by inlining an ``if`` statement
979 that surrounds the body of the function.
981 ``-prune-eh``: Remove unused exception handling info
982 ----------------------------------------------------
984 This file implements a simple interprocedural pass which walks the call-graph,
985 turning invoke instructions into call instructions if and only if the callee
986 cannot throw an exception. It implements this as a bottom-up traversal of the
989 ``-reassociate``: Reassociate expressions
990 -----------------------------------------
992 This pass reassociates commutative expressions in an order that is designed to
993 promote better constant propagation, GCSE, :ref:`LICM <passes-licm>`, PRE, etc.
995 For example: 4 + (x + 5) ⇒ x + (4 + 5)
997 In the implementation of this algorithm, constants are assigned rank = 0,
998 function arguments are rank = 1, and other values are assigned ranks
999 corresponding to the reverse post order traversal of current function (starting
1000 at 2), which effectively gives values in deep loops higher rank than values not
1003 ``-reg2mem``: Demote all values to stack slots
1004 ----------------------------------------------
1006 This file demotes all registers to memory references. It is intended to be the
1007 inverse of :ref:`mem2reg <passes-mem2reg>`. By converting to ``load``
1008 instructions, the only values live across basic blocks are ``alloca``
1009 instructions and ``load`` instructions before ``phi`` nodes. It is intended
1010 that this should make CFG hacking much easier. To make later hacking easier,
1011 the entry block is split into two, such that all introduced ``alloca``
1012 instructions (and nothing else) are in the entry block.
1014 ``-scalarrepl``: Scalar Replacement of Aggregates (DT)
1015 ------------------------------------------------------
1017 The well-known scalar replacement of aggregates transformation. This transform
1018 breaks up ``alloca`` instructions of aggregate type (structure or array) into
1019 individual ``alloca`` instructions for each member if possible. Then, if
1020 possible, it transforms the individual ``alloca`` instructions into nice clean
1023 This combines a simple scalar replacement of aggregates algorithm with the
1024 :ref:`mem2reg <passes-mem2reg>` algorithm because often interact, especially
1025 for C++ programs. As such, iterating between ``scalarrepl``, then
1026 :ref:`mem2reg <passes-mem2reg>` until we run out of things to promote works
1031 ``-sccp``: Sparse Conditional Constant Propagation
1032 --------------------------------------------------
1034 Sparse conditional constant propagation and merging, which can be summarized
1037 * Assumes values are constant unless proven otherwise
1038 * Assumes BasicBlocks are dead unless proven otherwise
1039 * Proves values to be constant, and replaces them with constants
1040 * Proves conditional branches to be unconditional
1042 Note that this pass has a habit of making definitions be dead. It is a good
1043 idea to to run a :ref:`DCE <passes-dce>` pass sometime after running this pass.
1045 ``-simplify-libcalls``: Simplify well-known library calls
1046 ---------------------------------------------------------
1048 Applies a variety of small optimizations for calls to specific well-known
1049 function calls (e.g. runtime library functions). For example, a call
1050 ``exit(3)`` that occurs within the ``main()`` function can be transformed into
1051 simply ``return 3``.
1053 .. _passes-simplifycfg:
1055 ``-simplifycfg``: Simplify the CFG
1056 ----------------------------------
1058 Performs dead code elimination and basic block merging. Specifically:
1060 * Removes basic blocks with no predecessors.
1061 * Merges a basic block into its predecessor if there is only one and the
1062 predecessor only has one successor.
1063 * Eliminates PHI nodes for basic blocks with a single predecessor.
1064 * Eliminates a basic block that only contains an unconditional branch.
1066 ``-sink``: Code sinking
1067 -----------------------
1069 This pass moves instructions into successor blocks, when possible, so that they
1070 aren't executed on paths where their results aren't needed.
1072 ``-strip``: Strip all symbols from a module
1073 -------------------------------------------
1075 Performs code stripping. This transformation can delete:
1077 * names for virtual registers
1078 * symbols for internal globals and functions
1081 Note that this transformation makes code much less readable, so it should only
1082 be used in situations where the strip utility would be used, such as reducing
1083 code size or making it harder to reverse engineer code.
1085 ``-strip-dead-debug-info``: Strip debug info for unused symbols
1086 ---------------------------------------------------------------
1088 .. FIXME: this description is the same as for -strip
1090 performs code stripping. this transformation can delete:
1092 * names for virtual registers
1093 * symbols for internal globals and functions
1096 note that this transformation makes code much less readable, so it should only
1097 be used in situations where the strip utility would be used, such as reducing
1098 code size or making it harder to reverse engineer code.
1100 ``-strip-dead-prototypes``: Strip Unused Function Prototypes
1101 ------------------------------------------------------------
1103 This pass loops over all of the functions in the input module, looking for dead
1104 declarations and removes them. Dead declarations are declarations of functions
1105 for which no implementation is available (i.e., declarations for unused library
1108 ``-strip-debug-declare``: Strip all ``llvm.dbg.declare`` intrinsics
1109 -------------------------------------------------------------------
1111 .. FIXME: this description is the same as for -strip
1113 This pass implements code stripping. Specifically, it can delete:
1115 #. names for virtual registers
1116 #. symbols for internal globals and functions
1117 #. debug information
1119 Note that this transformation makes code much less readable, so it should only
1120 be used in situations where the 'strip' utility would be used, such as reducing
1121 code size or making it harder to reverse engineer code.
1123 ``-strip-nondebug``: Strip all symbols, except dbg symbols, from a module
1124 -------------------------------------------------------------------------
1126 .. FIXME: this description is the same as for -strip
1128 This pass implements code stripping. Specifically, it can delete:
1130 #. names for virtual registers
1131 #. symbols for internal globals and functions
1132 #. debug information
1134 Note that this transformation makes code much less readable, so it should only
1135 be used in situations where the 'strip' utility would be used, such as reducing
1136 code size or making it harder to reverse engineer code.
1138 ``-tailcallelim``: Tail Call Elimination
1139 ----------------------------------------
1141 This file transforms calls of the current function (self recursion) followed by
1142 a return instruction with a branch to the entry of the function, creating a
1143 loop. This pass also implements the following extensions to the basic
1146 #. Trivial instructions between the call and return do not prevent the
1147 transformation from taking place, though currently the analysis cannot
1148 support moving any really useful instructions (only dead ones).
1149 #. This pass transforms functions that are prevented from being tail recursive
1150 by an associative expression to use an accumulator variable, thus compiling
1151 the typical naive factorial or fib implementation into efficient code.
1152 #. TRE is performed if the function returns void, if the return returns the
1153 result returned by the call, or if the function returns a run-time constant
1154 on all exits from the function. It is possible, though unlikely, that the
1155 return returns something else (like constant 0), and can still be TRE'd. It
1156 can be TRE'd if *all other* return instructions in the function return the
1158 #. If it can prove that callees do not access theier caller stack frame, they
1159 are marked as eligible for tail call elimination (by the code generator).
1164 This section describes the LLVM Utility Passes.
1166 ``-deadarghaX0r``: Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)
1167 ------------------------------------------------------------------------
1169 Same as dead argument elimination, but deletes arguments to functions which are
1170 external. This is only for use by :doc:`bugpoint <Bugpoint>`.
1172 ``-extract-blocks``: Extract Basic Blocks From Module (for bugpoint use)
1173 ------------------------------------------------------------------------
1175 This pass is used by bugpoint to extract all blocks from the module into their
1178 ``-instnamer``: Assign names to anonymous instructions
1179 ------------------------------------------------------
1181 This is a little utility pass that gives instructions names, this is mostly
1182 useful when diffing the effect of an optimization because deleting an unnamed
1183 instruction can change all other instruction numbering, making the diff very
1186 ``-preverify``: Preliminary module verification
1187 -----------------------------------------------
1189 Ensures that the module is in the form required by the :ref:`Module Verifier
1190 <passes-verify>` pass. Running the verifier runs this pass automatically, so
1191 there should be no need to use it directly.
1195 ``-verify``: Module Verifier
1196 ----------------------------
1198 Verifies an LLVM IR code. This is useful to run after an optimization which is
1199 undergoing testing. Note that llvm-as verifies its input before emitting
1200 bitcode, and also that malformed bitcode is likely to make LLVM crash. All
1201 language front-ends are therefore encouraged to verify their output before
1202 performing optimizing transformations.
1204 #. Both of a binary operator's parameters are of the same type.
1205 #. Verify that the indices of mem access instructions match other operands.
1206 #. Verify that arithmetic and other things are only performed on first-class
1207 types. Verify that shifts and logicals only happen on integrals f.e.
1208 #. All of the constants in a switch statement are of the correct type.
1209 #. The code is in valid SSA form.
1210 #. It is illegal to put a label into any other type (like a structure) or to
1212 #. Only phi nodes can be self referential: ``%x = add i32 %x``, ``%x`` is
1214 #. PHI nodes must have an entry for each predecessor, with no extras.
1215 #. PHI nodes must be the first thing in a basic block, all grouped together.
1216 #. PHI nodes must have at least one entry.
1217 #. All basic blocks should only end with terminator insts, not contain them.
1218 #. The entry node to a function must not have predecessors.
1219 #. All Instructions must be embedded into a basic block.
1220 #. Functions cannot take a void-typed parameter.
1221 #. Verify that a function's argument list agrees with its declared type.
1222 #. It is illegal to specify a name for a void value.
1223 #. It is illegal to have an internal global value with no initializer.
1224 #. It is illegal to have a ``ret`` instruction that returns a value that does
1225 not agree with the function return value type.
1226 #. Function call argument types match the function prototype.
1227 #. All other things that are tested by asserts spread about the code.
1229 Note that this does not provide full security verification (like Java), but
1230 instead just tries to ensure that code is well-formed.
1232 ``-view-cfg``: View CFG of function
1233 -----------------------------------
1235 Displays the control flow graph using the GraphViz tool.
1237 ``-view-cfg-only``: View CFG of function (with no function bodies)
1238 ------------------------------------------------------------------
1240 Displays the control flow graph using the GraphViz tool, but omitting function
1243 ``-view-dom``: View dominance tree of function
1244 ----------------------------------------------
1246 Displays the dominator tree using the GraphViz tool.
1248 ``-view-dom-only``: View dominance tree of function (with no function bodies)
1249 -----------------------------------------------------------------------------
1251 Displays the dominator tree using the GraphViz tool, but omitting function
1254 ``-view-postdom``: View postdominance tree of function
1255 ------------------------------------------------------
1257 Displays the post dominator tree using the GraphViz tool.
1259 ``-view-postdom-only``: View postdominance tree of function (with no function bodies)
1260 -------------------------------------------------------------------------------------
1262 Displays the post dominator tree using the GraphViz tool, but omitting function