Passes.rst 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193
  1. ..
  2. If Passes.html is up to date, the following "one-liner" should print
  3. an empty diff.
  4. egrep -e '^<tr><td><a href="#.*">-.*</a></td><td>.*</td></tr>$' \
  5. -e '^ <a name=".*">.*</a>$' < Passes.html >html; \
  6. perl >help <<'EOT' && diff -u help html; rm -f help html
  7. open HTML, "<Passes.html" or die "open: Passes.html: $!\n";
  8. while (<HTML>) {
  9. m:^<tr><td><a href="#(.*)">-.*</a></td><td>.*</td></tr>$: or next;
  10. $order{$1} = sprintf("%03d", 1 + int %order);
  11. }
  12. open HELP, "../Release/bin/opt -help|" or die "open: opt -help: $!\n";
  13. while (<HELP>) {
  14. m:^ -([^ ]+) +- (.*)$: or next;
  15. my $o = $order{$1};
  16. $o = "000" unless defined $o;
  17. push @x, "$o<tr><td><a href=\"#$1\">-$1</a></td><td>$2</td></tr>\n";
  18. push @y, "$o <a name=\"$1\">-$1: $2</a>\n";
  19. }
  20. @x = map { s/^\d\d\d//; $_ } sort @x;
  21. @y = map { s/^\d\d\d//; $_ } sort @y;
  22. print @x, @y;
  23. EOT
  24. This (real) one-liner can also be helpful when converting comments to HTML:
  25. 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'
  26. ====================================
  27. LLVM's Analysis and Transform Passes
  28. ====================================
  29. .. contents::
  30. :local:
  31. Introduction
  32. ============
  33. This document serves as a high level summary of the optimization features that
  34. LLVM provides. Optimizations are implemented as Passes that traverse some
  35. portion of a program to either collect information or transform the program.
  36. The table below divides the passes that LLVM provides into three categories.
  37. Analysis passes compute information that other passes can use or for debugging
  38. or program visualization purposes. Transform passes can use (or invalidate)
  39. the analysis passes. Transform passes all mutate the program in some way.
  40. Utility passes provides some utility but don't otherwise fit categorization.
  41. For example passes to extract functions to bitcode or write a module to bitcode
  42. are neither analysis nor transform passes. The table of contents above
  43. provides a quick summary of each pass and links to the more complete pass
  44. description later in the document.
  45. Analysis Passes
  46. ===============
  47. This section describes the LLVM Analysis Passes.
  48. ``-aa-eval``: Exhaustive Alias Analysis Precision Evaluator
  49. -----------------------------------------------------------
  50. This is a simple N^2 alias analysis accuracy evaluator. Basically, for each
  51. function in the program, it simply queries to see how the alias analysis
  52. implementation answers alias queries between each pair of pointers in the
  53. function.
  54. This is inspired and adapted from code by: Naveen Neelakantam, Francesco
  55. Spadini, and Wojciech Stryjewski.
  56. ``-basicaa``: Basic Alias Analysis (stateless AA impl)
  57. ------------------------------------------------------
  58. A basic alias analysis pass that implements identities (two different globals
  59. cannot alias, etc), but does no stateful analysis.
  60. ``-basiccg``: Basic CallGraph Construction
  61. ------------------------------------------
  62. Yet to be written.
  63. ``-count-aa``: Count Alias Analysis Query Responses
  64. ---------------------------------------------------
  65. A pass which can be used to count how many alias queries are being made and how
  66. the alias analysis implementation being used responds.
  67. ``-da``: Dependence Analysis
  68. ----------------------------
  69. Dependence analysis framework, which is used to detect dependences in memory
  70. accesses.
  71. ``-debug-aa``: AA use debugger
  72. ------------------------------
  73. This simple pass checks alias analysis users to ensure that if they create a
  74. new value, they do not query AA without informing it of the value. It acts as
  75. a shim over any other AA pass you want.
  76. Yes keeping track of every value in the program is expensive, but this is a
  77. debugging pass.
  78. ``-domfrontier``: Dominance Frontier Construction
  79. -------------------------------------------------
  80. This pass is a simple dominator construction algorithm for finding forward
  81. dominator frontiers.
  82. ``-domtree``: Dominator Tree Construction
  83. -----------------------------------------
  84. This pass is a simple dominator construction algorithm for finding forward
  85. dominators.
  86. ``-dot-callgraph``: Print Call Graph to "dot" file
  87. --------------------------------------------------
  88. This pass, only available in ``opt``, prints the call graph into a ``.dot``
  89. graph. This graph can then be processed with the "dot" tool to convert it to
  90. postscript or some other suitable format.
  91. ``-dot-cfg``: Print CFG of function to "dot" file
  92. -------------------------------------------------
  93. This pass, only available in ``opt``, prints the control flow graph into a
  94. ``.dot`` graph. This graph can then be processed with the :program:`dot` tool
  95. to convert it to postscript or some other suitable format.
  96. ``-dot-cfg-only``: Print CFG of function to "dot" file (with no function bodies)
  97. --------------------------------------------------------------------------------
  98. This pass, only available in ``opt``, prints the control flow graph into a
  99. ``.dot`` graph, omitting the function bodies. This graph can then be processed
  100. with the :program:`dot` tool to convert it to postscript or some other suitable
  101. format.
  102. ``-dot-dom``: Print dominance tree of function to "dot" file
  103. ------------------------------------------------------------
  104. This pass, only available in ``opt``, prints the dominator tree into a ``.dot``
  105. graph. This graph can then be processed with the :program:`dot` tool to
  106. convert it to postscript or some other suitable format.
  107. ``-dot-dom-only``: Print dominance tree of function to "dot" file (with no function bodies)
  108. -------------------------------------------------------------------------------------------
  109. This pass, only available in ``opt``, prints the dominator tree into a ``.dot``
  110. graph, omitting the function bodies. This graph can then be processed with the
  111. :program:`dot` tool to convert it to postscript or some other suitable format.
  112. ``-dot-postdom``: Print postdominance tree of function to "dot" file
  113. --------------------------------------------------------------------
  114. This pass, only available in ``opt``, prints the post dominator tree into a
  115. ``.dot`` graph. This graph can then be processed with the :program:`dot` tool
  116. to convert it to postscript or some other suitable format.
  117. ``-dot-postdom-only``: Print postdominance tree of function to "dot" file (with no function bodies)
  118. ---------------------------------------------------------------------------------------------------
  119. This pass, only available in ``opt``, prints the post dominator tree into a
  120. ``.dot`` graph, omitting the function bodies. This graph can then be processed
  121. with the :program:`dot` tool to convert it to postscript or some other suitable
  122. format.
  123. ``-globalsmodref-aa``: Simple mod/ref analysis for globals
  124. ----------------------------------------------------------
  125. This simple pass provides alias and mod/ref information for global values that
  126. do not have their address taken, and keeps track of whether functions read or
  127. write memory (are "pure"). For this simple (but very common) case, we can
  128. provide pretty accurate and useful information.
  129. ``-instcount``: Counts the various types of ``Instruction``\ s
  130. --------------------------------------------------------------
  131. This pass collects the count of all instructions and reports them.
  132. ``-intervals``: Interval Partition Construction
  133. -----------------------------------------------
  134. This analysis calculates and represents the interval partition of a function,
  135. or a preexisting interval partition.
  136. In this way, the interval partition may be used to reduce a flow graph down to
  137. its degenerate single node interval partition (unless it is irreducible).
  138. ``-iv-users``: Induction Variable Users
  139. ---------------------------------------
  140. Bookkeeping for "interesting" users of expressions computed from induction
  141. variables.
  142. ``-lazy-value-info``: Lazy Value Information Analysis
  143. -----------------------------------------------------
  144. Interface for lazy computation of value constraint information.
  145. ``-libcall-aa``: LibCall Alias Analysis
  146. ---------------------------------------
  147. LibCall Alias Analysis.
  148. ``-lint``: Statically lint-checks LLVM IR
  149. -----------------------------------------
  150. This pass statically checks for common and easily-identified constructs which
  151. produce undefined or likely unintended behavior in LLVM IR.
  152. It is not a guarantee of correctness, in two ways. First, it isn't
  153. comprehensive. There are checks which could be done statically which are not
  154. yet implemented. Some of these are indicated by TODO comments, but those
  155. aren't comprehensive either. Second, many conditions cannot be checked
  156. statically. This pass does no dynamic instrumentation, so it can't check for
  157. all possible problems.
  158. Another limitation is that it assumes all code will be executed. A store
  159. through a null pointer in a basic block which is never reached is harmless, but
  160. this pass will warn about it anyway.
  161. Optimization passes may make conditions that this pass checks for more or less
  162. obvious. If an optimization pass appears to be introducing a warning, it may
  163. be that the optimization pass is merely exposing an existing condition in the
  164. code.
  165. This code may be run before :ref:`instcombine <passes-instcombine>`. In many
  166. cases, instcombine checks for the same kinds of things and turns instructions
  167. with undefined behavior into unreachable (or equivalent). Because of this,
  168. this pass makes some effort to look through bitcasts and so on.
  169. ``-loops``: Natural Loop Information
  170. ------------------------------------
  171. This analysis is used to identify natural loops and determine the loop depth of
  172. various nodes of the CFG. Note that the loops identified may actually be
  173. several natural loops that share the same header node... not just a single
  174. natural loop.
  175. ``-memdep``: Memory Dependence Analysis
  176. ---------------------------------------
  177. An analysis that determines, for a given memory operation, what preceding
  178. memory operations it depends on. It builds on alias analysis information, and
  179. tries to provide a lazy, caching interface to a common kind of alias
  180. information query.
  181. ``-module-debuginfo``: Decodes module-level debug info
  182. ------------------------------------------------------
  183. This pass decodes the debug info metadata in a module and prints in a
  184. (sufficiently-prepared-) human-readable form.
  185. For example, run this pass from ``opt`` along with the ``-analyze`` option, and
  186. it'll print to standard output.
  187. ``-no-aa``: No Alias Analysis (always returns 'may' alias)
  188. ----------------------------------------------------------
  189. This is the default implementation of the Alias Analysis interface. It always
  190. returns "I don't know" for alias queries. NoAA is unlike other alias analysis
  191. implementations, in that it does not chain to a previous analysis. As such it
  192. doesn't follow many of the rules that other alias analyses must.
  193. ``-postdomfrontier``: Post-Dominance Frontier Construction
  194. ----------------------------------------------------------
  195. This pass is a simple post-dominator construction algorithm for finding
  196. post-dominator frontiers.
  197. ``-postdomtree``: Post-Dominator Tree Construction
  198. --------------------------------------------------
  199. This pass is a simple post-dominator construction algorithm for finding
  200. post-dominators.
  201. ``-print-alias-sets``: Alias Set Printer
  202. ----------------------------------------
  203. Yet to be written.
  204. ``-print-callgraph``: Print a call graph
  205. ----------------------------------------
  206. This pass, only available in ``opt``, prints the call graph to standard error
  207. in a human-readable form.
  208. ``-print-callgraph-sccs``: Print SCCs of the Call Graph
  209. -------------------------------------------------------
  210. This pass, only available in ``opt``, prints the SCCs of the call graph to
  211. standard error in a human-readable form.
  212. ``-print-cfg-sccs``: Print SCCs of each function CFG
  213. ----------------------------------------------------
  214. This pass, only available in ``opt``, printsthe SCCs of each function CFG to
  215. standard error in a human-readable fom.
  216. ``-print-dom-info``: Dominator Info Printer
  217. -------------------------------------------
  218. Dominator Info Printer.
  219. ``-print-externalfnconstants``: Print external fn callsites passed constants
  220. ----------------------------------------------------------------------------
  221. This pass, only available in ``opt``, prints out call sites to external
  222. functions that are called with constant arguments. This can be useful when
  223. looking for standard library functions we should constant fold or handle in
  224. alias analyses.
  225. ``-print-function``: Print function to stderr
  226. ---------------------------------------------
  227. The ``PrintFunctionPass`` class is designed to be pipelined with other
  228. ``FunctionPasses``, and prints out the functions of the module as they are
  229. processed.
  230. ``-print-module``: Print module to stderr
  231. -----------------------------------------
  232. This pass simply prints out the entire module when it is executed.
  233. .. _passes-print-used-types:
  234. ``-print-used-types``: Find Used Types
  235. --------------------------------------
  236. This pass is used to seek out all of the types in use by the program. Note
  237. that this analysis explicitly does not include types only used by the symbol
  238. table.
  239. ``-regions``: Detect single entry single exit regions
  240. -----------------------------------------------------
  241. The ``RegionInfo`` pass detects single entry single exit regions in a function,
  242. where a region is defined as any subgraph that is connected to the remaining
  243. graph at only two spots. Furthermore, an hierarchical region tree is built.
  244. ``-scalar-evolution``: Scalar Evolution Analysis
  245. ------------------------------------------------
  246. The ``ScalarEvolution`` analysis can be used to analyze and catagorize scalar
  247. expressions in loops. It specializes in recognizing general induction
  248. variables, representing them with the abstract and opaque ``SCEV`` class.
  249. Given this analysis, trip counts of loops and other important properties can be
  250. obtained.
  251. This analysis is primarily useful for induction variable substitution and
  252. strength reduction.
  253. ``-scev-aa``: ScalarEvolution-based Alias Analysis
  254. --------------------------------------------------
  255. Simple alias analysis implemented in terms of ``ScalarEvolution`` queries.
  256. This differs from traditional loop dependence analysis in that it tests for
  257. dependencies within a single iteration of a loop, rather than dependencies
  258. between different iterations.
  259. ``ScalarEvolution`` has a more complete understanding of pointer arithmetic
  260. than ``BasicAliasAnalysis``' collection of ad-hoc analyses.
  261. ``-targetdata``: Target Data Layout
  262. -----------------------------------
  263. Provides other passes access to information on how the size and alignment
  264. required by the target ABI for various data types.
  265. Transform Passes
  266. ================
  267. This section describes the LLVM Transform Passes.
  268. ``-adce``: Aggressive Dead Code Elimination
  269. -------------------------------------------
  270. ADCE aggressively tries to eliminate code. This pass is similar to :ref:`DCE
  271. <passes-dce>` but it assumes that values are dead until proven otherwise. This
  272. is similar to :ref:`SCCP <passes-sccp>`, except applied to the liveness of
  273. values.
  274. ``-always-inline``: Inliner for ``always_inline`` functions
  275. -----------------------------------------------------------
  276. A custom inliner that handles only functions that are marked as "always
  277. inline".
  278. ``-argpromotion``: Promote 'by reference' arguments to scalars
  279. --------------------------------------------------------------
  280. This pass promotes "by reference" arguments to be "by value" arguments. In
  281. practice, this means looking for internal functions that have pointer
  282. arguments. If it can prove, through the use of alias analysis, that an
  283. argument is *only* loaded, then it can pass the value into the function instead
  284. of the address of the value. This can cause recursive simplification of code
  285. and lead to the elimination of allocas (especially in C++ template code like
  286. the STL).
  287. This pass also handles aggregate arguments that are passed into a function,
  288. scalarizing them if the elements of the aggregate are only loaded. Note that
  289. it refuses to scalarize aggregates which would require passing in more than
  290. three operands to the function, because passing thousands of operands for a
  291. large array or structure is unprofitable!
  292. Note that this transformation could also be done for arguments that are only
  293. stored to (returning the value instead), but does not currently. This case
  294. would be best handled when and if LLVM starts supporting multiple return values
  295. from functions.
  296. ``-bb-vectorize``: Basic-Block Vectorization
  297. --------------------------------------------
  298. This pass combines instructions inside basic blocks to form vector
  299. instructions. It iterates over each basic block, attempting to pair compatible
  300. instructions, repeating this process until no additional pairs are selected for
  301. vectorization. When the outputs of some pair of compatible instructions are
  302. used as inputs by some other pair of compatible instructions, those pairs are
  303. part of a potential vectorization chain. Instruction pairs are only fused into
  304. vector instructions when they are part of a chain longer than some threshold
  305. length. Moreover, the pass attempts to find the best possible chain for each
  306. pair of compatible instructions. These heuristics are intended to prevent
  307. vectorization in cases where it would not yield a performance increase of the
  308. resulting code.
  309. ``-block-placement``: Profile Guided Basic Block Placement
  310. ----------------------------------------------------------
  311. This pass is a very simple profile guided basic block placement algorithm. The
  312. idea is to put frequently executed blocks together at the start of the function
  313. and hopefully increase the number of fall-through conditional branches. If
  314. there is no profile information for a particular function, this pass basically
  315. orders blocks in depth-first order.
  316. ``-break-crit-edges``: Break critical edges in CFG
  317. --------------------------------------------------
  318. Break all of the critical edges in the CFG by inserting a dummy basic block.
  319. It may be "required" by passes that cannot deal with critical edges. This
  320. transformation obviously invalidates the CFG, but can update forward dominator
  321. (set, immediate dominators, tree, and frontier) information.
  322. ``-codegenprepare``: Optimize for code generation
  323. -------------------------------------------------
  324. This pass munges the code in the input function to better prepare it for
  325. SelectionDAG-based code generation. This works around limitations in its
  326. basic-block-at-a-time approach. It should eventually be removed.
  327. ``-constmerge``: Merge Duplicate Global Constants
  328. -------------------------------------------------
  329. Merges duplicate global constants together into a single constant that is
  330. shared. This is useful because some passes (i.e., TraceValues) insert a lot of
  331. string constants into the program, regardless of whether or not an existing
  332. string is available.
  333. ``-constprop``: Simple constant propagation
  334. -------------------------------------------
  335. This pass implements constant propagation and merging. It looks for
  336. instructions involving only constant operands and replaces them with a constant
  337. value instead of an instruction. For example:
  338. .. code-block:: llvm
  339. add i32 1, 2
  340. becomes
  341. .. code-block:: llvm
  342. i32 3
  343. NOTE: this pass has a habit of making definitions be dead. It is a good idea
  344. to run a :ref:`Dead Instruction Elimination <passes-die>` pass sometime after
  345. running this pass.
  346. .. _passes-dce:
  347. ``-dce``: Dead Code Elimination
  348. -------------------------------
  349. Dead code elimination is similar to :ref:`dead instruction elimination
  350. <passes-die>`, but it rechecks instructions that were used by removed
  351. instructions to see if they are newly dead.
  352. ``-deadargelim``: Dead Argument Elimination
  353. -------------------------------------------
  354. This pass deletes dead arguments from internal functions. Dead argument
  355. elimination removes arguments which are directly dead, as well as arguments
  356. only passed into function calls as dead arguments of other functions. This
  357. pass also deletes dead arguments in a similar way.
  358. This pass is often useful as a cleanup pass to run after aggressive
  359. interprocedural passes, which add possibly-dead arguments.
  360. ``-deadtypeelim``: Dead Type Elimination
  361. ----------------------------------------
  362. This pass is used to cleanup the output of GCC. It eliminate names for types
  363. that are unused in the entire translation unit, using the :ref:`find used types
  364. <passes-print-used-types>` pass.
  365. .. _passes-die:
  366. ``-die``: Dead Instruction Elimination
  367. --------------------------------------
  368. Dead instruction elimination performs a single pass over the function, removing
  369. instructions that are obviously dead.
  370. ``-dse``: Dead Store Elimination
  371. --------------------------------
  372. A trivial dead store elimination that only considers basic-block local
  373. redundant stores.
  374. .. _passes-functionattrs:
  375. ``-functionattrs``: Deduce function attributes
  376. ----------------------------------------------
  377. A simple interprocedural pass which walks the call-graph, looking for functions
  378. which do not access or only read non-local memory, and marking them
  379. ``readnone``/``readonly``. In addition, it marks function arguments (of
  380. pointer type) "``nocapture``" if a call to the function does not create any
  381. copies of the pointer value that outlive the call. This more or less means
  382. that the pointer is only dereferenced, and not returned from the function or
  383. stored in a global. This pass is implemented as a bottom-up traversal of the
  384. call-graph.
  385. ``-globaldce``: Dead Global Elimination
  386. ---------------------------------------
  387. This transform is designed to eliminate unreachable internal globals from the
  388. program. It uses an aggressive algorithm, searching out globals that are known
  389. to be alive. After it finds all of the globals which are needed, it deletes
  390. whatever is left over. This allows it to delete recursive chunks of the
  391. program which are unreachable.
  392. ``-globalopt``: Global Variable Optimizer
  393. -----------------------------------------
  394. This pass transforms simple global variables that never have their address
  395. taken. If obviously true, it marks read/write globals as constant, deletes
  396. variables only stored to, etc.
  397. ``-gvn``: Global Value Numbering
  398. --------------------------------
  399. This pass performs global value numbering to eliminate fully and partially
  400. redundant instructions. It also performs redundant load elimination.
  401. .. _passes-indvars:
  402. ``-indvars``: Canonicalize Induction Variables
  403. ----------------------------------------------
  404. This transformation analyzes and transforms the induction variables (and
  405. computations derived from them) into simpler forms suitable for subsequent
  406. analysis and transformation.
  407. This transformation makes the following changes to each loop with an
  408. identifiable induction variable:
  409. * All loops are transformed to have a *single* canonical induction variable
  410. which starts at zero and steps by one.
  411. * The canonical induction variable is guaranteed to be the first PHI node in
  412. the loop header block.
  413. * Any pointer arithmetic recurrences are raised to use array subscripts.
  414. If the trip count of a loop is computable, this pass also makes the following
  415. changes:
  416. * The exit condition for the loop is canonicalized to compare the induction
  417. value against the exit value. This turns loops like:
  418. .. code-block:: c++
  419. for (i = 7; i*i < 1000; ++i)
  420. into
  421. .. code-block:: c++
  422. for (i = 0; i != 25; ++i)
  423. * Any use outside of the loop of an expression derived from the indvar is
  424. changed to compute the derived value outside of the loop, eliminating the
  425. dependence on the exit value of the induction variable. If the only purpose
  426. of the loop is to compute the exit value of some derived expression, this
  427. transformation will make the loop dead.
  428. This transformation should be followed by strength reduction after all of the
  429. desired loop transformations have been performed. Additionally, on targets
  430. where it is profitable, the loop could be transformed to count down to zero
  431. (the "do loop" optimization).
  432. ``-inline``: Function Integration/Inlining
  433. ------------------------------------------
  434. Bottom-up inlining of functions into callees.
  435. .. _passes-instcombine:
  436. ``-instcombine``: Combine redundant instructions
  437. ------------------------------------------------
  438. Combine instructions to form fewer, simple instructions. This pass does not
  439. modify the CFG. This pass is where algebraic simplification happens.
  440. This pass combines things like:
  441. .. code-block:: llvm
  442. %Y = add i32 %X, 1
  443. %Z = add i32 %Y, 1
  444. into:
  445. .. code-block:: llvm
  446. %Z = add i32 %X, 2
  447. This is a simple worklist driven algorithm.
  448. This pass guarantees that the following canonicalizations are performed on the
  449. program:
  450. #. If a binary operator has a constant operand, it is moved to the right-hand
  451. side.
  452. #. Bitwise operators with constant operands are always grouped so that shifts
  453. are performed first, then ``or``\ s, then ``and``\ s, then ``xor``\ s.
  454. #. Compare instructions are converted from ``<``, ``>``, ``≤``, or ``≥`` to
  455. ``=`` or ``≠`` if possible.
  456. #. All ``cmp`` instructions on boolean values are replaced with logical
  457. operations.
  458. #. ``add X, X`` is represented as ``mul X, 2`` ⇒ ``shl X, 1``
  459. #. Multiplies with a constant power-of-two argument are transformed into
  460. shifts.
  461. #. … etc.
  462. This pass can also simplify calls to specific well-known function calls (e.g.
  463. runtime library functions). For example, a call ``exit(3)`` that occurs within
  464. the ``main()`` function can be transformed into simply ``return 3``. Whether or
  465. not library calls are simplified is controlled by the
  466. :ref:`-functionattrs <passes-functionattrs>` pass and LLVM's knowledge of
  467. library calls on different targets.
  468. ``-internalize``: Internalize Global Symbols
  469. --------------------------------------------
  470. This pass loops over all of the functions in the input module, looking for a
  471. main function. If a main function is found, all other functions and all global
  472. variables with initializers are marked as internal.
  473. ``-ipconstprop``: Interprocedural constant propagation
  474. ------------------------------------------------------
  475. This pass implements an *extremely* simple interprocedural constant propagation
  476. pass. It could certainly be improved in many different ways, like using a
  477. worklist. This pass makes arguments dead, but does not remove them. The
  478. existing dead argument elimination pass should be run after this to clean up
  479. the mess.
  480. ``-ipsccp``: Interprocedural Sparse Conditional Constant Propagation
  481. --------------------------------------------------------------------
  482. An interprocedural variant of :ref:`Sparse Conditional Constant Propagation
  483. <passes-sccp>`.
  484. ``-jump-threading``: Jump Threading
  485. -----------------------------------
  486. Jump threading tries to find distinct threads of control flow running through a
  487. basic block. This pass looks at blocks that have multiple predecessors and
  488. multiple successors. If one or more of the predecessors of the block can be
  489. proven to always cause a jump to one of the successors, we forward the edge
  490. from the predecessor to the successor by duplicating the contents of this
  491. block.
  492. An example of when this can occur is code like this:
  493. .. code-block:: c++
  494. if () { ...
  495. X = 4;
  496. }
  497. if (X < 3) {
  498. In this case, the unconditional branch at the end of the first if can be
  499. revectored to the false side of the second if.
  500. ``-lcssa``: Loop-Closed SSA Form Pass
  501. -------------------------------------
  502. This pass transforms loops by placing phi nodes at the end of the loops for all
  503. values that are live across the loop boundary. For example, it turns the left
  504. into the right code:
  505. .. code-block:: c++
  506. for (...) for (...)
  507. if (c) if (c)
  508. X1 = ... X1 = ...
  509. else else
  510. X2 = ... X2 = ...
  511. X3 = phi(X1, X2) X3 = phi(X1, X2)
  512. ... = X3 + 4 X4 = phi(X3)
  513. ... = X4 + 4
  514. This is still valid LLVM; the extra phi nodes are purely redundant, and will be
  515. trivially eliminated by ``InstCombine``. The major benefit of this
  516. transformation is that it makes many other loop optimizations, such as
  517. ``LoopUnswitch``\ ing, simpler.
  518. .. _passes-licm:
  519. ``-licm``: Loop Invariant Code Motion
  520. -------------------------------------
  521. This pass performs loop invariant code motion, attempting to remove as much
  522. code from the body of a loop as possible. It does this by either hoisting code
  523. into the preheader block, or by sinking code to the exit blocks if it is safe.
  524. This pass also promotes must-aliased memory locations in the loop to live in
  525. registers, thus hoisting and sinking "invariant" loads and stores.
  526. This pass uses alias analysis for two purposes:
  527. #. Moving loop invariant loads and calls out of loops. If we can determine
  528. that a load or call inside of a loop never aliases anything stored to, we
  529. can hoist it or sink it like any other instruction.
  530. #. Scalar Promotion of Memory. If there is a store instruction inside of the
  531. loop, we try to move the store to happen AFTER the loop instead of inside of
  532. the loop. This can only happen if a few conditions are true:
  533. #. The pointer stored through is loop invariant.
  534. #. There are no stores or loads in the loop which *may* alias the pointer.
  535. There are no calls in the loop which mod/ref the pointer.
  536. If these conditions are true, we can promote the loads and stores in the
  537. loop of the pointer to use a temporary alloca'd variable. We then use the
  538. :ref:`mem2reg <passes-mem2reg>` functionality to construct the appropriate
  539. SSA form for the variable.
  540. ``-loop-deletion``: Delete dead loops
  541. -------------------------------------
  542. This file implements the Dead Loop Deletion Pass. This pass is responsible for
  543. eliminating loops with non-infinite computable trip counts that have no side
  544. effects or volatile instructions, and do not contribute to the computation of
  545. the function's return value.
  546. .. _passes-loop-extract:
  547. ``-loop-extract``: Extract loops into new functions
  548. ---------------------------------------------------
  549. A pass wrapper around the ``ExtractLoop()`` scalar transformation to extract
  550. each top-level loop into its own new function. If the loop is the *only* loop
  551. in a given function, it is not touched. This is a pass most useful for
  552. debugging via bugpoint.
  553. ``-loop-extract-single``: Extract at most one loop into a new function
  554. ----------------------------------------------------------------------
  555. Similar to :ref:`Extract loops into new functions <passes-loop-extract>`, this
  556. pass extracts one natural loop from the program into a function if it can.
  557. This is used by :program:`bugpoint`.
  558. ``-loop-reduce``: Loop Strength Reduction
  559. -----------------------------------------
  560. This pass performs a strength reduction on array references inside loops that
  561. have as one or more of their components the loop induction variable. This is
  562. accomplished by creating a new value to hold the initial value of the array
  563. access for the first iteration, and then creating a new GEP instruction in the
  564. loop to increment the value by the appropriate amount.
  565. ``-loop-rotate``: Rotate Loops
  566. ------------------------------
  567. A simple loop rotation transformation.
  568. ``-loop-simplify``: Canonicalize natural loops
  569. ----------------------------------------------
  570. This pass performs several transformations to transform natural loops into a
  571. simpler form, which makes subsequent analyses and transformations simpler and
  572. more effective.
  573. Loop pre-header insertion guarantees that there is a single, non-critical entry
  574. edge from outside of the loop to the loop header. This simplifies a number of
  575. analyses and transformations, such as :ref:`LICM <passes-licm>`.
  576. Loop exit-block insertion guarantees that all exit blocks from the loop (blocks
  577. which are outside of the loop that have predecessors inside of the loop) only
  578. have predecessors from inside of the loop (and are thus dominated by the loop
  579. header). This simplifies transformations such as store-sinking that are built
  580. into LICM.
  581. This pass also guarantees that loops will have exactly one backedge.
  582. Note that the :ref:`simplifycfg <passes-simplifycfg>` pass will clean up blocks
  583. which are split out but end up being unnecessary, so usage of this pass should
  584. not pessimize generated code.
  585. This pass obviously modifies the CFG, but updates loop information and
  586. dominator information.
  587. ``-loop-unroll``: Unroll loops
  588. ------------------------------
  589. This pass implements a simple loop unroller. It works best when loops have
  590. been canonicalized by the :ref:`indvars <passes-indvars>` pass, allowing it to
  591. determine the trip counts of loops easily.
  592. ``-loop-unswitch``: Unswitch loops
  593. ----------------------------------
  594. This pass transforms loops that contain branches on loop-invariant conditions
  595. to have multiple loops. For example, it turns the left into the right code:
  596. .. code-block:: c++
  597. for (...) if (lic)
  598. A for (...)
  599. if (lic) A; B; C
  600. B else
  601. C for (...)
  602. A; C
  603. This can increase the size of the code exponentially (doubling it every time a
  604. loop is unswitched) so we only unswitch if the resultant code will be smaller
  605. than a threshold.
  606. This pass expects :ref:`LICM <passes-licm>` to be run before it to hoist
  607. invariant conditions out of the loop, to make the unswitching opportunity
  608. obvious.
  609. ``-loweratomic``: Lower atomic intrinsics to non-atomic form
  610. ------------------------------------------------------------
  611. This pass lowers atomic intrinsics to non-atomic form for use in a known
  612. non-preemptible environment.
  613. The pass does not verify that the environment is non-preemptible (in general
  614. this would require knowledge of the entire call graph of the program including
  615. any libraries which may not be available in bitcode form); it simply lowers
  616. every atomic intrinsic.
  617. ``-lowerinvoke``: Lower invokes to calls, for unwindless code generators
  618. ------------------------------------------------------------------------
  619. This transformation is designed for use by code generators which do not yet
  620. support stack unwinding. This pass converts ``invoke`` instructions to
  621. ``call`` instructions, so that any exception-handling ``landingpad`` blocks
  622. become dead code (which can be removed by running the ``-simplifycfg`` pass
  623. afterwards).
  624. ``-lowerswitch``: Lower ``SwitchInst``\ s to branches
  625. -----------------------------------------------------
  626. Rewrites switch instructions with a sequence of branches, which allows targets
  627. to get away with not implementing the switch instruction until it is
  628. convenient.
  629. .. _passes-mem2reg:
  630. ``-mem2reg``: Promote Memory to Register
  631. ----------------------------------------
  632. This file promotes memory references to be register references. It promotes
  633. alloca instructions which only have loads and stores as uses. An ``alloca`` is
  634. transformed by using dominator frontiers to place phi nodes, then traversing
  635. the function in depth-first order to rewrite loads and stores as appropriate.
  636. This is just the standard SSA construction algorithm to construct "pruned" SSA
  637. form.
  638. ``-memcpyopt``: MemCpy Optimization
  639. -----------------------------------
  640. This pass performs various transformations related to eliminating ``memcpy``
  641. calls, or transforming sets of stores into ``memset``\ s.
  642. ``-mergefunc``: Merge Functions
  643. -------------------------------
  644. This pass looks for equivalent functions that are mergable and folds them.
  645. Total-ordering is introduced among the functions set: we define comparison
  646. that answers for every two functions which of them is greater. It allows to
  647. arrange functions into the binary tree.
  648. For every new function we check for equivalent in tree.
  649. If equivalent exists we fold such functions. If both functions are overridable,
  650. we move the functionality into a new internal function and leave two
  651. overridable thunks to it.
  652. If there is no equivalent, then we add this function to tree.
  653. Lookup routine has O(log(n)) complexity, while whole merging process has
  654. complexity of O(n*log(n)).
  655. Read
  656. :doc:`this <MergeFunctions>`
  657. article for more details.
  658. ``-mergereturn``: Unify function exit nodes
  659. -------------------------------------------
  660. Ensure that functions have at most one ``ret`` instruction in them.
  661. Additionally, it keeps track of which node is the new exit node of the CFG.
  662. ``-partial-inliner``: Partial Inliner
  663. -------------------------------------
  664. This pass performs partial inlining, typically by inlining an ``if`` statement
  665. that surrounds the body of the function.
  666. ``-prune-eh``: Remove unused exception handling info
  667. ----------------------------------------------------
  668. This file implements a simple interprocedural pass which walks the call-graph,
  669. turning invoke instructions into call instructions if and only if the callee
  670. cannot throw an exception. It implements this as a bottom-up traversal of the
  671. call-graph.
  672. ``-reassociate``: Reassociate expressions
  673. -----------------------------------------
  674. This pass reassociates commutative expressions in an order that is designed to
  675. promote better constant propagation, GCSE, :ref:`LICM <passes-licm>`, PRE, etc.
  676. For example: 4 + (x + 5) ⇒ x + (4 + 5)
  677. In the implementation of this algorithm, constants are assigned rank = 0,
  678. function arguments are rank = 1, and other values are assigned ranks
  679. corresponding to the reverse post order traversal of current function (starting
  680. at 2), which effectively gives values in deep loops higher rank than values not
  681. in loops.
  682. ``-reg2mem``: Demote all values to stack slots
  683. ----------------------------------------------
  684. This file demotes all registers to memory references. It is intended to be the
  685. inverse of :ref:`mem2reg <passes-mem2reg>`. By converting to ``load``
  686. instructions, the only values live across basic blocks are ``alloca``
  687. instructions and ``load`` instructions before ``phi`` nodes. It is intended
  688. that this should make CFG hacking much easier. To make later hacking easier,
  689. the entry block is split into two, such that all introduced ``alloca``
  690. instructions (and nothing else) are in the entry block.
  691. ``-scalarrepl``: Scalar Replacement of Aggregates (DT)
  692. ------------------------------------------------------
  693. The well-known scalar replacement of aggregates transformation. This transform
  694. breaks up ``alloca`` instructions of aggregate type (structure or array) into
  695. individual ``alloca`` instructions for each member if possible. Then, if
  696. possible, it transforms the individual ``alloca`` instructions into nice clean
  697. scalar SSA form.
  698. This combines a simple scalar replacement of aggregates algorithm with the
  699. :ref:`mem2reg <passes-mem2reg>` algorithm because they often interact,
  700. especially for C++ programs. As such, iterating between ``scalarrepl``, then
  701. :ref:`mem2reg <passes-mem2reg>` until we run out of things to promote works
  702. well.
  703. .. _passes-sccp:
  704. ``-sccp``: Sparse Conditional Constant Propagation
  705. --------------------------------------------------
  706. Sparse conditional constant propagation and merging, which can be summarized
  707. as:
  708. * Assumes values are constant unless proven otherwise
  709. * Assumes BasicBlocks are dead unless proven otherwise
  710. * Proves values to be constant, and replaces them with constants
  711. * Proves conditional branches to be unconditional
  712. Note that this pass has a habit of making definitions be dead. It is a good
  713. idea to run a :ref:`DCE <passes-dce>` pass sometime after running this pass.
  714. .. _passes-simplifycfg:
  715. ``-simplifycfg``: Simplify the CFG
  716. ----------------------------------
  717. Performs dead code elimination and basic block merging. Specifically:
  718. * Removes basic blocks with no predecessors.
  719. * Merges a basic block into its predecessor if there is only one and the
  720. predecessor only has one successor.
  721. * Eliminates PHI nodes for basic blocks with a single predecessor.
  722. * Eliminates a basic block that only contains an unconditional branch.
  723. ``-sink``: Code sinking
  724. -----------------------
  725. This pass moves instructions into successor blocks, when possible, so that they
  726. aren't executed on paths where their results aren't needed.
  727. ``-strip``: Strip all symbols from a module
  728. -------------------------------------------
  729. Performs code stripping. This transformation can delete:
  730. * names for virtual registers
  731. * symbols for internal globals and functions
  732. * debug information
  733. Note that this transformation makes code much less readable, so it should only
  734. be used in situations where the strip utility would be used, such as reducing
  735. code size or making it harder to reverse engineer code.
  736. ``-strip-dead-debug-info``: Strip debug info for unused symbols
  737. ---------------------------------------------------------------
  738. .. FIXME: this description is the same as for -strip
  739. performs code stripping. this transformation can delete:
  740. * names for virtual registers
  741. * symbols for internal globals and functions
  742. * debug information
  743. note that this transformation makes code much less readable, so it should only
  744. be used in situations where the strip utility would be used, such as reducing
  745. code size or making it harder to reverse engineer code.
  746. ``-strip-dead-prototypes``: Strip Unused Function Prototypes
  747. ------------------------------------------------------------
  748. This pass loops over all of the functions in the input module, looking for dead
  749. declarations and removes them. Dead declarations are declarations of functions
  750. for which no implementation is available (i.e., declarations for unused library
  751. functions).
  752. ``-strip-debug-declare``: Strip all ``llvm.dbg.declare`` intrinsics
  753. -------------------------------------------------------------------
  754. .. FIXME: this description is the same as for -strip
  755. This pass implements code stripping. Specifically, it can delete:
  756. #. names for virtual registers
  757. #. symbols for internal globals and functions
  758. #. debug information
  759. Note that this transformation makes code much less readable, so it should only
  760. be used in situations where the 'strip' utility would be used, such as reducing
  761. code size or making it harder to reverse engineer code.
  762. ``-strip-nondebug``: Strip all symbols, except dbg symbols, from a module
  763. -------------------------------------------------------------------------
  764. .. FIXME: this description is the same as for -strip
  765. This pass implements code stripping. Specifically, it can delete:
  766. #. names for virtual registers
  767. #. symbols for internal globals and functions
  768. #. debug information
  769. Note that this transformation makes code much less readable, so it should only
  770. be used in situations where the 'strip' utility would be used, such as reducing
  771. code size or making it harder to reverse engineer code.
  772. ``-tailcallelim``: Tail Call Elimination
  773. ----------------------------------------
  774. This file transforms calls of the current function (self recursion) followed by
  775. a return instruction with a branch to the entry of the function, creating a
  776. loop. This pass also implements the following extensions to the basic
  777. algorithm:
  778. #. Trivial instructions between the call and return do not prevent the
  779. transformation from taking place, though currently the analysis cannot
  780. support moving any really useful instructions (only dead ones).
  781. #. This pass transforms functions that are prevented from being tail recursive
  782. by an associative expression to use an accumulator variable, thus compiling
  783. the typical naive factorial or fib implementation into efficient code.
  784. #. TRE is performed if the function returns void, if the return returns the
  785. result returned by the call, or if the function returns a run-time constant
  786. on all exits from the function. It is possible, though unlikely, that the
  787. return returns something else (like constant 0), and can still be TRE'd. It
  788. can be TRE'd if *all other* return instructions in the function return the
  789. exact same value.
  790. #. If it can prove that callees do not access theier caller stack frame, they
  791. are marked as eligible for tail call elimination (by the code generator).
  792. Utility Passes
  793. ==============
  794. This section describes the LLVM Utility Passes.
  795. ``-deadarghaX0r``: Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)
  796. ------------------------------------------------------------------------
  797. Same as dead argument elimination, but deletes arguments to functions which are
  798. external. This is only for use by :doc:`bugpoint <Bugpoint>`.
  799. ``-extract-blocks``: Extract Basic Blocks From Module (for bugpoint use)
  800. ------------------------------------------------------------------------
  801. This pass is used by bugpoint to extract all blocks from the module into their
  802. own functions.
  803. ``-instnamer``: Assign names to anonymous instructions
  804. ------------------------------------------------------
  805. This is a little utility pass that gives instructions names, this is mostly
  806. useful when diffing the effect of an optimization because deleting an unnamed
  807. instruction can change all other instruction numbering, making the diff very
  808. noisy.
  809. .. _passes-verify:
  810. ``-verify``: Module Verifier
  811. ----------------------------
  812. Verifies an LLVM IR code. This is useful to run after an optimization which is
  813. undergoing testing. Note that llvm-as verifies its input before emitting
  814. bitcode, and also that malformed bitcode is likely to make LLVM crash. All
  815. language front-ends are therefore encouraged to verify their output before
  816. performing optimizing transformations.
  817. #. Both of a binary operator's parameters are of the same type.
  818. #. Verify that the indices of mem access instructions match other operands.
  819. #. Verify that arithmetic and other things are only performed on first-class
  820. types. Verify that shifts and logicals only happen on integrals f.e.
  821. #. All of the constants in a switch statement are of the correct type.
  822. #. The code is in valid SSA form.
  823. #. It is illegal to put a label into any other type (like a structure) or to
  824. return one.
  825. #. Only phi nodes can be self referential: ``%x = add i32 %x``, ``%x`` is
  826. invalid.
  827. #. PHI nodes must have an entry for each predecessor, with no extras.
  828. #. PHI nodes must be the first thing in a basic block, all grouped together.
  829. #. PHI nodes must have at least one entry.
  830. #. All basic blocks should only end with terminator insts, not contain them.
  831. #. The entry node to a function must not have predecessors.
  832. #. All Instructions must be embedded into a basic block.
  833. #. Functions cannot take a void-typed parameter.
  834. #. Verify that a function's argument list agrees with its declared type.
  835. #. It is illegal to specify a name for a void value.
  836. #. It is illegal to have an internal global value with no initializer.
  837. #. It is illegal to have a ``ret`` instruction that returns a value that does
  838. not agree with the function return value type.
  839. #. Function call argument types match the function prototype.
  840. #. All other things that are tested by asserts spread about the code.
  841. Note that this does not provide full security verification (like Java), but
  842. instead just tries to ensure that code is well-formed.
  843. ``-view-cfg``: View CFG of function
  844. -----------------------------------
  845. Displays the control flow graph using the GraphViz tool.
  846. ``-view-cfg-only``: View CFG of function (with no function bodies)
  847. ------------------------------------------------------------------
  848. Displays the control flow graph using the GraphViz tool, but omitting function
  849. bodies.
  850. ``-view-dom``: View dominance tree of function
  851. ----------------------------------------------
  852. Displays the dominator tree using the GraphViz tool.
  853. ``-view-dom-only``: View dominance tree of function (with no function bodies)
  854. -----------------------------------------------------------------------------
  855. Displays the dominator tree using the GraphViz tool, but omitting function
  856. bodies.
  857. ``-view-postdom``: View postdominance tree of function
  858. ------------------------------------------------------
  859. Displays the post dominator tree using the GraphViz tool.
  860. ``-view-postdom-only``: View postdominance tree of function (with no function bodies)
  861. -------------------------------------------------------------------------------------
  862. Displays the post dominator tree using the GraphViz tool, but omitting function
  863. bodies.