AliasAnalysis.rst 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. ==================================
  2. LLVM Alias Analysis Infrastructure
  3. ==================================
  4. .. contents::
  5. :local:
  6. Introduction
  7. ============
  8. Alias Analysis (aka Pointer Analysis) is a class of techniques which attempt to
  9. determine whether or not two pointers ever can point to the same object in
  10. memory. There are many different algorithms for alias analysis and many
  11. different ways of classifying them: flow-sensitive vs. flow-insensitive,
  12. context-sensitive vs. context-insensitive, field-sensitive
  13. vs. field-insensitive, unification-based vs. subset-based, etc. Traditionally,
  14. alias analyses respond to a query with a `Must, May, or No`_ alias response,
  15. indicating that two pointers always point to the same object, might point to the
  16. same object, or are known to never point to the same object.
  17. The LLVM `AliasAnalysis
  18. <http://llvm.org/doxygen/classllvm_1_1AliasAnalysis.html>`__ class is the
  19. primary interface used by clients and implementations of alias analyses in the
  20. LLVM system. This class is the common interface between clients of alias
  21. analysis information and the implementations providing it, and is designed to
  22. support a wide range of implementations and clients (but currently all clients
  23. are assumed to be flow-insensitive). In addition to simple alias analysis
  24. information, this class exposes Mod/Ref information from those implementations
  25. which can provide it, allowing for powerful analyses and transformations to work
  26. well together.
  27. This document contains information necessary to successfully implement this
  28. interface, use it, and to test both sides. It also explains some of the finer
  29. points about what exactly results mean. If you feel that something is unclear
  30. or should be added, please `let me know <mailto:[email protected]>`_.
  31. ``AliasAnalysis`` Class Overview
  32. ================================
  33. The `AliasAnalysis <http://llvm.org/doxygen/classllvm_1_1AliasAnalysis.html>`__
  34. class defines the interface that the various alias analysis implementations
  35. should support. This class exports two important enums: ``AliasResult`` and
  36. ``ModRefResult`` which represent the result of an alias query or a mod/ref
  37. query, respectively.
  38. The ``AliasAnalysis`` interface exposes information about memory, represented in
  39. several different ways. In particular, memory objects are represented as a
  40. starting address and size, and function calls are represented as the actual
  41. ``call`` or ``invoke`` instructions that performs the call. The
  42. ``AliasAnalysis`` interface also exposes some helper methods which allow you to
  43. get mod/ref information for arbitrary instructions.
  44. All ``AliasAnalysis`` interfaces require that in queries involving multiple
  45. values, values which are not :ref:`constants <constants>` are all
  46. defined within the same function.
  47. Representation of Pointers
  48. --------------------------
  49. Most importantly, the ``AliasAnalysis`` class provides several methods which are
  50. used to query whether or not two memory objects alias, whether function calls
  51. can modify or read a memory object, etc. For all of these queries, memory
  52. objects are represented as a pair of their starting address (a symbolic LLVM
  53. ``Value*``) and a static size.
  54. Representing memory objects as a starting address and a size is critically
  55. important for correct Alias Analyses. For example, consider this (silly, but
  56. possible) C code:
  57. .. code-block:: c++
  58. int i;
  59. char C[2];
  60. char A[10];
  61. /* ... */
  62. for (i = 0; i != 10; ++i) {
  63. C[0] = A[i]; /* One byte store */
  64. C[1] = A[9-i]; /* One byte store */
  65. }
  66. In this case, the ``basicaa`` pass will disambiguate the stores to ``C[0]`` and
  67. ``C[1]`` because they are accesses to two distinct locations one byte apart, and
  68. the accesses are each one byte. In this case, the Loop Invariant Code Motion
  69. (LICM) pass can use store motion to remove the stores from the loop. In
  70. constrast, the following code:
  71. .. code-block:: c++
  72. int i;
  73. char C[2];
  74. char A[10];
  75. /* ... */
  76. for (i = 0; i != 10; ++i) {
  77. ((short*)C)[0] = A[i]; /* Two byte store! */
  78. C[1] = A[9-i]; /* One byte store */
  79. }
  80. In this case, the two stores to C do alias each other, because the access to the
  81. ``&C[0]`` element is a two byte access. If size information wasn't available in
  82. the query, even the first case would have to conservatively assume that the
  83. accesses alias.
  84. .. _alias:
  85. The ``alias`` method
  86. --------------------
  87. The ``alias`` method is the primary interface used to determine whether or not
  88. two memory objects alias each other. It takes two memory objects as input and
  89. returns MustAlias, PartialAlias, MayAlias, or NoAlias as appropriate.
  90. Like all ``AliasAnalysis`` interfaces, the ``alias`` method requires that either
  91. the two pointer values be defined within the same function, or at least one of
  92. the values is a :ref:`constant <constants>`.
  93. .. _Must, May, or No:
  94. Must, May, and No Alias Responses
  95. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  96. The ``NoAlias`` response may be used when there is never an immediate dependence
  97. between any memory reference *based* on one pointer and any memory reference
  98. *based* the other. The most obvious example is when the two pointers point to
  99. non-overlapping memory ranges. Another is when the two pointers are only ever
  100. used for reading memory. Another is when the memory is freed and reallocated
  101. between accesses through one pointer and accesses through the other --- in this
  102. case, there is a dependence, but it's mediated by the free and reallocation.
  103. As an exception to this is with the :ref:`noalias <noalias>` keyword;
  104. the "irrelevant" dependencies are ignored.
  105. The ``MayAlias`` response is used whenever the two pointers might refer to the
  106. same object.
  107. The ``PartialAlias`` response is used when the two memory objects are known to
  108. be overlapping in some way, but do not start at the same address.
  109. The ``MustAlias`` response may only be returned if the two memory objects are
  110. guaranteed to always start at exactly the same location. A ``MustAlias``
  111. response implies that the pointers compare equal.
  112. The ``getModRefInfo`` methods
  113. -----------------------------
  114. The ``getModRefInfo`` methods return information about whether the execution of
  115. an instruction can read or modify a memory location. Mod/Ref information is
  116. always conservative: if an instruction **might** read or write a location,
  117. ``ModRef`` is returned.
  118. The ``AliasAnalysis`` class also provides a ``getModRefInfo`` method for testing
  119. dependencies between function calls. This method takes two call sites (``CS1``
  120. & ``CS2``), returns ``NoModRef`` if neither call writes to memory read or
  121. written by the other, ``Ref`` if ``CS1`` reads memory written by ``CS2``,
  122. ``Mod`` if ``CS1`` writes to memory read or written by ``CS2``, or ``ModRef`` if
  123. ``CS1`` might read or write memory written to by ``CS2``. Note that this
  124. relation is not commutative.
  125. Other useful ``AliasAnalysis`` methods
  126. --------------------------------------
  127. Several other tidbits of information are often collected by various alias
  128. analysis implementations and can be put to good use by various clients.
  129. The ``pointsToConstantMemory`` method
  130. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  131. The ``pointsToConstantMemory`` method returns true if and only if the analysis
  132. can prove that the pointer only points to unchanging memory locations
  133. (functions, constant global variables, and the null pointer). This information
  134. can be used to refine mod/ref information: it is impossible for an unchanging
  135. memory location to be modified.
  136. .. _never access memory or only read memory:
  137. The ``doesNotAccessMemory`` and ``onlyReadsMemory`` methods
  138. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  139. These methods are used to provide very simple mod/ref information for function
  140. calls. The ``doesNotAccessMemory`` method returns true for a function if the
  141. analysis can prove that the function never reads or writes to memory, or if the
  142. function only reads from constant memory. Functions with this property are
  143. side-effect free and only depend on their input arguments, allowing them to be
  144. eliminated if they form common subexpressions or be hoisted out of loops. Many
  145. common functions behave this way (e.g., ``sin`` and ``cos``) but many others do
  146. not (e.g., ``acos``, which modifies the ``errno`` variable).
  147. The ``onlyReadsMemory`` method returns true for a function if analysis can prove
  148. that (at most) the function only reads from non-volatile memory. Functions with
  149. this property are side-effect free, only depending on their input arguments and
  150. the state of memory when they are called. This property allows calls to these
  151. functions to be eliminated and moved around, as long as there is no store
  152. instruction that changes the contents of memory. Note that all functions that
  153. satisfy the ``doesNotAccessMemory`` method also satisfies ``onlyReadsMemory``.
  154. Writing a new ``AliasAnalysis`` Implementation
  155. ==============================================
  156. Writing a new alias analysis implementation for LLVM is quite straight-forward.
  157. There are already several implementations that you can use for examples, and the
  158. following information should help fill in any details. For a examples, take a
  159. look at the `various alias analysis implementations`_ included with LLVM.
  160. Different Pass styles
  161. ---------------------
  162. The first step to determining what type of :doc:`LLVM pass <WritingAnLLVMPass>`
  163. you need to use for your Alias Analysis. As is the case with most other
  164. analyses and transformations, the answer should be fairly obvious from what type
  165. of problem you are trying to solve:
  166. #. If you require interprocedural analysis, it should be a ``Pass``.
  167. #. If you are a function-local analysis, subclass ``FunctionPass``.
  168. #. If you don't need to look at the program at all, subclass ``ImmutablePass``.
  169. In addition to the pass that you subclass, you should also inherit from the
  170. ``AliasAnalysis`` interface, of course, and use the ``RegisterAnalysisGroup``
  171. template to register as an implementation of ``AliasAnalysis``.
  172. Required initialization calls
  173. -----------------------------
  174. Your subclass of ``AliasAnalysis`` is required to invoke two methods on the
  175. ``AliasAnalysis`` base class: ``getAnalysisUsage`` and
  176. ``InitializeAliasAnalysis``. In particular, your implementation of
  177. ``getAnalysisUsage`` should explicitly call into the
  178. ``AliasAnalysis::getAnalysisUsage`` method in addition to doing any declaring
  179. any pass dependencies your pass has. Thus you should have something like this:
  180. .. code-block:: c++
  181. void getAnalysisUsage(AnalysisUsage &AU) const {
  182. AliasAnalysis::getAnalysisUsage(AU);
  183. // declare your dependencies here.
  184. }
  185. Additionally, your must invoke the ``InitializeAliasAnalysis`` method from your
  186. analysis run method (``run`` for a ``Pass``, ``runOnFunction`` for a
  187. ``FunctionPass``, or ``InitializePass`` for an ``ImmutablePass``). For example
  188. (as part of a ``Pass``):
  189. .. code-block:: c++
  190. bool run(Module &M) {
  191. InitializeAliasAnalysis(this);
  192. // Perform analysis here...
  193. return false;
  194. }
  195. Required methods to override
  196. ----------------------------
  197. You must override the ``getAdjustedAnalysisPointer`` method on all subclasses
  198. of ``AliasAnalysis``. An example implementation of this method would look like:
  199. .. code-block:: c++
  200. void *getAdjustedAnalysisPointer(const void* ID) override {
  201. if (ID == &AliasAnalysis::ID)
  202. return (AliasAnalysis*)this;
  203. return this;
  204. }
  205. Interfaces which may be specified
  206. ---------------------------------
  207. All of the `AliasAnalysis
  208. <http://llvm.org/doxygen/classllvm_1_1AliasAnalysis.html>`__ virtual methods
  209. default to providing :ref:`chaining <aliasanalysis-chaining>` to another alias
  210. analysis implementation, which ends up returning conservatively correct
  211. information (returning "May" Alias and "Mod/Ref" for alias and mod/ref queries
  212. respectively). Depending on the capabilities of the analysis you are
  213. implementing, you just override the interfaces you can improve.
  214. .. _aliasanalysis-chaining:
  215. ``AliasAnalysis`` chaining behavior
  216. -----------------------------------
  217. With only one special exception (the :ref:`-no-aa <aliasanalysis-no-aa>` pass)
  218. every alias analysis pass chains to another alias analysis implementation (for
  219. example, the user can specify "``-basicaa -ds-aa -licm``" to get the maximum
  220. benefit from both alias analyses). The alias analysis class automatically
  221. takes care of most of this for methods that you don't override. For methods
  222. that you do override, in code paths that return a conservative MayAlias or
  223. Mod/Ref result, simply return whatever the superclass computes. For example:
  224. .. code-block:: c++
  225. AliasResult alias(const Value *V1, unsigned V1Size,
  226. const Value *V2, unsigned V2Size) {
  227. if (...)
  228. return NoAlias;
  229. ...
  230. // Couldn't determine a must or no-alias result.
  231. return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
  232. }
  233. In addition to analysis queries, you must make sure to unconditionally pass LLVM
  234. `update notification`_ methods to the superclass as well if you override them,
  235. which allows all alias analyses in a change to be updated.
  236. .. _update notification:
  237. Updating analysis results for transformations
  238. ---------------------------------------------
  239. Alias analysis information is initially computed for a static snapshot of the
  240. program, but clients will use this information to make transformations to the
  241. code. All but the most trivial forms of alias analysis will need to have their
  242. analysis results updated to reflect the changes made by these transformations.
  243. The ``AliasAnalysis`` interface exposes four methods which are used to
  244. communicate program changes from the clients to the analysis implementations.
  245. Various alias analysis implementations should use these methods to ensure that
  246. their internal data structures are kept up-to-date as the program changes (for
  247. example, when an instruction is deleted), and clients of alias analysis must be
  248. sure to call these interfaces appropriately.
  249. The ``deleteValue`` method
  250. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  251. The ``deleteValue`` method is called by transformations when they remove an
  252. instruction or any other value from the program (including values that do not
  253. use pointers). Typically alias analyses keep data structures that have entries
  254. for each value in the program. When this method is called, they should remove
  255. any entries for the specified value, if they exist.
  256. The ``copyValue`` method
  257. ^^^^^^^^^^^^^^^^^^^^^^^^
  258. The ``copyValue`` method is used when a new value is introduced into the
  259. program. There is no way to introduce a value into the program that did not
  260. exist before (this doesn't make sense for a safe compiler transformation), so
  261. this is the only way to introduce a new value. This method indicates that the
  262. new value has exactly the same properties as the value being copied.
  263. The ``replaceWithNewValue`` method
  264. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  265. This method is a simple helper method that is provided to make clients easier to
  266. use. It is implemented by copying the old analysis information to the new
  267. value, then deleting the old value. This method cannot be overridden by alias
  268. analysis implementations.
  269. The ``addEscapingUse`` method
  270. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  271. The ``addEscapingUse`` method is used when the uses of a pointer value have
  272. changed in ways that may invalidate precomputed analysis information.
  273. Implementations may either use this callback to provide conservative responses
  274. for points whose uses have change since analysis time, or may recompute some or
  275. all of their internal state to continue providing accurate responses.
  276. In general, any new use of a pointer value is considered an escaping use, and
  277. must be reported through this callback, *except* for the uses below:
  278. * A ``bitcast`` or ``getelementptr`` of the pointer
  279. * A ``store`` through the pointer (but not a ``store`` *of* the pointer)
  280. * A ``load`` through the pointer
  281. Efficiency Issues
  282. -----------------
  283. From the LLVM perspective, the only thing you need to do to provide an efficient
  284. alias analysis is to make sure that alias analysis **queries** are serviced
  285. quickly. The actual calculation of the alias analysis results (the "run"
  286. method) is only performed once, but many (perhaps duplicate) queries may be
  287. performed. Because of this, try to move as much computation to the run method
  288. as possible (within reason).
  289. Limitations
  290. -----------
  291. The AliasAnalysis infrastructure has several limitations which make writing a
  292. new ``AliasAnalysis`` implementation difficult.
  293. There is no way to override the default alias analysis. It would be very useful
  294. to be able to do something like "``opt -my-aa -O2``" and have it use ``-my-aa``
  295. for all passes which need AliasAnalysis, but there is currently no support for
  296. that, short of changing the source code and recompiling. Similarly, there is
  297. also no way of setting a chain of analyses as the default.
  298. There is no way for transform passes to declare that they preserve
  299. ``AliasAnalysis`` implementations. The ``AliasAnalysis`` interface includes
  300. ``deleteValue`` and ``copyValue`` methods which are intended to allow a pass to
  301. keep an AliasAnalysis consistent, however there's no way for a pass to declare
  302. in its ``getAnalysisUsage`` that it does so. Some passes attempt to use
  303. ``AU.addPreserved<AliasAnalysis>``, however this doesn't actually have any
  304. effect.
  305. ``AliasAnalysisCounter`` (``-count-aa``) and ``AliasDebugger`` (``-debug-aa``)
  306. are implemented as ``ModulePass`` classes, so if your alias analysis uses
  307. ``FunctionPass``, it won't be able to use these utilities. If you try to use
  308. them, the pass manager will silently route alias analysis queries directly to
  309. ``BasicAliasAnalysis`` instead.
  310. Similarly, the ``opt -p`` option introduces ``ModulePass`` passes between each
  311. pass, which prevents the use of ``FunctionPass`` alias analysis passes.
  312. The ``AliasAnalysis`` API does have functions for notifying implementations when
  313. values are deleted or copied, however these aren't sufficient. There are many
  314. other ways that LLVM IR can be modified which could be relevant to
  315. ``AliasAnalysis`` implementations which can not be expressed.
  316. The ``AliasAnalysisDebugger`` utility seems to suggest that ``AliasAnalysis``
  317. implementations can expect that they will be informed of any relevant ``Value``
  318. before it appears in an alias query. However, popular clients such as ``GVN``
  319. don't support this, and are known to trigger errors when run with the
  320. ``AliasAnalysisDebugger``.
  321. Due to several of the above limitations, the most obvious use for the
  322. ``AliasAnalysisCounter`` utility, collecting stats on all alias queries in a
  323. compilation, doesn't work, even if the ``AliasAnalysis`` implementations don't
  324. use ``FunctionPass``. There's no way to set a default, much less a default
  325. sequence, and there's no way to preserve it.
  326. The ``AliasSetTracker`` class (which is used by ``LICM``) makes a
  327. non-deterministic number of alias queries. This can cause stats collected by
  328. ``AliasAnalysisCounter`` to have fluctuations among identical runs, for
  329. example. Another consequence is that debugging techniques involving pausing
  330. execution after a predetermined number of queries can be unreliable.
  331. Many alias queries can be reformulated in terms of other alias queries. When
  332. multiple ``AliasAnalysis`` queries are chained together, it would make sense to
  333. start those queries from the beginning of the chain, with care taken to avoid
  334. infinite looping, however currently an implementation which wants to do this can
  335. only start such queries from itself.
  336. Using alias analysis results
  337. ============================
  338. There are several different ways to use alias analysis results. In order of
  339. preference, these are:
  340. Using the ``MemoryDependenceAnalysis`` Pass
  341. -------------------------------------------
  342. The ``memdep`` pass uses alias analysis to provide high-level dependence
  343. information about memory-using instructions. This will tell you which store
  344. feeds into a load, for example. It uses caching and other techniques to be
  345. efficient, and is used by Dead Store Elimination, GVN, and memcpy optimizations.
  346. .. _AliasSetTracker:
  347. Using the ``AliasSetTracker`` class
  348. -----------------------------------
  349. Many transformations need information about alias **sets** that are active in
  350. some scope, rather than information about pairwise aliasing. The
  351. `AliasSetTracker <http://llvm.org/doxygen/classllvm_1_1AliasSetTracker.html>`__
  352. class is used to efficiently build these Alias Sets from the pairwise alias
  353. analysis information provided by the ``AliasAnalysis`` interface.
  354. First you initialize the AliasSetTracker by using the "``add``" methods to add
  355. information about various potentially aliasing instructions in the scope you are
  356. interested in. Once all of the alias sets are completed, your pass should
  357. simply iterate through the constructed alias sets, using the ``AliasSetTracker``
  358. ``begin()``/``end()`` methods.
  359. The ``AliasSet``\s formed by the ``AliasSetTracker`` are guaranteed to be
  360. disjoint, calculate mod/ref information and volatility for the set, and keep
  361. track of whether or not all of the pointers in the set are Must aliases. The
  362. AliasSetTracker also makes sure that sets are properly folded due to call
  363. instructions, and can provide a list of pointers in each set.
  364. As an example user of this, the `Loop Invariant Code Motion
  365. <doxygen/structLICM.html>`_ pass uses ``AliasSetTracker``\s to calculate alias
  366. sets for each loop nest. If an ``AliasSet`` in a loop is not modified, then all
  367. load instructions from that set may be hoisted out of the loop. If any alias
  368. sets are stored to **and** are must alias sets, then the stores may be sunk
  369. to outside of the loop, promoting the memory location to a register for the
  370. duration of the loop nest. Both of these transformations only apply if the
  371. pointer argument is loop-invariant.
  372. The AliasSetTracker implementation
  373. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  374. The AliasSetTracker class is implemented to be as efficient as possible. It
  375. uses the union-find algorithm to efficiently merge AliasSets when a pointer is
  376. inserted into the AliasSetTracker that aliases multiple sets. The primary data
  377. structure is a hash table mapping pointers to the AliasSet they are in.
  378. The AliasSetTracker class must maintain a list of all of the LLVM ``Value*``\s
  379. that are in each AliasSet. Since the hash table already has entries for each
  380. LLVM ``Value*`` of interest, the AliasesSets thread the linked list through
  381. these hash-table nodes to avoid having to allocate memory unnecessarily, and to
  382. make merging alias sets extremely efficient (the linked list merge is constant
  383. time).
  384. You shouldn't need to understand these details if you are just a client of the
  385. AliasSetTracker, but if you look at the code, hopefully this brief description
  386. will help make sense of why things are designed the way they are.
  387. Using the ``AliasAnalysis`` interface directly
  388. ----------------------------------------------
  389. If neither of these utility class are what your pass needs, you should use the
  390. interfaces exposed by the ``AliasAnalysis`` class directly. Try to use the
  391. higher-level methods when possible (e.g., use mod/ref information instead of the
  392. `alias`_ method directly if possible) to get the best precision and efficiency.
  393. Existing alias analysis implementations and clients
  394. ===================================================
  395. If you're going to be working with the LLVM alias analysis infrastructure, you
  396. should know what clients and implementations of alias analysis are available.
  397. In particular, if you are implementing an alias analysis, you should be aware of
  398. the `the clients`_ that are useful for monitoring and evaluating different
  399. implementations.
  400. .. _various alias analysis implementations:
  401. Available ``AliasAnalysis`` implementations
  402. -------------------------------------------
  403. This section lists the various implementations of the ``AliasAnalysis``
  404. interface. With the exception of the :ref:`-no-aa <aliasanalysis-no-aa>`
  405. implementation, all of these :ref:`chain <aliasanalysis-chaining>` to other
  406. alias analysis implementations.
  407. .. _aliasanalysis-no-aa:
  408. The ``-no-aa`` pass
  409. ^^^^^^^^^^^^^^^^^^^
  410. The ``-no-aa`` pass is just like what it sounds: an alias analysis that never
  411. returns any useful information. This pass can be useful if you think that alias
  412. analysis is doing something wrong and are trying to narrow down a problem.
  413. The ``-basicaa`` pass
  414. ^^^^^^^^^^^^^^^^^^^^^
  415. The ``-basicaa`` pass is an aggressive local analysis that *knows* many
  416. important facts:
  417. * Distinct globals, stack allocations, and heap allocations can never alias.
  418. * Globals, stack allocations, and heap allocations never alias the null pointer.
  419. * Different fields of a structure do not alias.
  420. * Indexes into arrays with statically differing subscripts cannot alias.
  421. * Many common standard C library functions `never access memory or only read
  422. memory`_.
  423. * Pointers that obviously point to constant globals "``pointToConstantMemory``".
  424. * Function calls can not modify or references stack allocations if they never
  425. escape from the function that allocates them (a common case for automatic
  426. arrays).
  427. The ``-globalsmodref-aa`` pass
  428. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  429. This pass implements a simple context-sensitive mod/ref and alias analysis for
  430. internal global variables that don't "have their address taken". If a global
  431. does not have its address taken, the pass knows that no pointers alias the
  432. global. This pass also keeps track of functions that it knows never access
  433. memory or never read memory. This allows certain optimizations (e.g. GVN) to
  434. eliminate call instructions entirely.
  435. The real power of this pass is that it provides context-sensitive mod/ref
  436. information for call instructions. This allows the optimizer to know that calls
  437. to a function do not clobber or read the value of the global, allowing loads and
  438. stores to be eliminated.
  439. .. note::
  440. This pass is somewhat limited in its scope (only support non-address taken
  441. globals), but is very quick analysis.
  442. The ``-steens-aa`` pass
  443. ^^^^^^^^^^^^^^^^^^^^^^^
  444. The ``-steens-aa`` pass implements a variation on the well-known "Steensgaard's
  445. algorithm" for interprocedural alias analysis. Steensgaard's algorithm is a
  446. unification-based, flow-insensitive, context-insensitive, and field-insensitive
  447. alias analysis that is also very scalable (effectively linear time).
  448. The LLVM ``-steens-aa`` pass implements a "speculatively field-**sensitive**"
  449. version of Steensgaard's algorithm using the Data Structure Analysis framework.
  450. This gives it substantially more precision than the standard algorithm while
  451. maintaining excellent analysis scalability.
  452. .. note::
  453. ``-steens-aa`` is available in the optional "poolalloc" module. It is not part
  454. of the LLVM core.
  455. The ``-ds-aa`` pass
  456. ^^^^^^^^^^^^^^^^^^^
  457. The ``-ds-aa`` pass implements the full Data Structure Analysis algorithm. Data
  458. Structure Analysis is a modular unification-based, flow-insensitive,
  459. context-**sensitive**, and speculatively field-**sensitive** alias
  460. analysis that is also quite scalable, usually at ``O(n * log(n))``.
  461. This algorithm is capable of responding to a full variety of alias analysis
  462. queries, and can provide context-sensitive mod/ref information as well. The
  463. only major facility not implemented so far is support for must-alias
  464. information.
  465. .. note::
  466. ``-ds-aa`` is available in the optional "poolalloc" module. It is not part of
  467. the LLVM core.
  468. The ``-scev-aa`` pass
  469. ^^^^^^^^^^^^^^^^^^^^^
  470. The ``-scev-aa`` pass implements AliasAnalysis queries by translating them into
  471. ScalarEvolution queries. This gives it a more complete understanding of
  472. ``getelementptr`` instructions and loop induction variables than other alias
  473. analyses have.
  474. Alias analysis driven transformations
  475. -------------------------------------
  476. LLVM includes several alias-analysis driven transformations which can be used
  477. with any of the implementations above.
  478. The ``-adce`` pass
  479. ^^^^^^^^^^^^^^^^^^
  480. The ``-adce`` pass, which implements Aggressive Dead Code Elimination uses the
  481. ``AliasAnalysis`` interface to delete calls to functions that do not have
  482. side-effects and are not used.
  483. The ``-licm`` pass
  484. ^^^^^^^^^^^^^^^^^^
  485. The ``-licm`` pass implements various Loop Invariant Code Motion related
  486. transformations. It uses the ``AliasAnalysis`` interface for several different
  487. transformations:
  488. * It uses mod/ref information to hoist or sink load instructions out of loops if
  489. there are no instructions in the loop that modifies the memory loaded.
  490. * It uses mod/ref information to hoist function calls out of loops that do not
  491. write to memory and are loop-invariant.
  492. * If uses alias information to promote memory objects that are loaded and stored
  493. to in loops to live in a register instead. It can do this if there are no may
  494. aliases to the loaded/stored memory location.
  495. The ``-argpromotion`` pass
  496. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  497. The ``-argpromotion`` pass promotes by-reference arguments to be passed in
  498. by-value instead. In particular, if pointer arguments are only loaded from it
  499. passes in the value loaded instead of the address to the function. This pass
  500. uses alias information to make sure that the value loaded from the argument
  501. pointer is not modified between the entry of the function and any load of the
  502. pointer.
  503. The ``-gvn``, ``-memcpyopt``, and ``-dse`` passes
  504. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  505. These passes use AliasAnalysis information to reason about loads and stores.
  506. .. _the clients:
  507. Clients for debugging and evaluation of implementations
  508. -------------------------------------------------------
  509. These passes are useful for evaluating the various alias analysis
  510. implementations. You can use them with commands like:
  511. .. code-block:: bash
  512. % opt -ds-aa -aa-eval foo.bc -disable-output -stats
  513. The ``-print-alias-sets`` pass
  514. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  515. The ``-print-alias-sets`` pass is exposed as part of the ``opt`` tool to print
  516. out the Alias Sets formed by the `AliasSetTracker`_ class. This is useful if
  517. you're using the ``AliasSetTracker`` class. To use it, use something like:
  518. .. code-block:: bash
  519. % opt -ds-aa -print-alias-sets -disable-output
  520. The ``-count-aa`` pass
  521. ^^^^^^^^^^^^^^^^^^^^^^
  522. The ``-count-aa`` pass is useful to see how many queries a particular pass is
  523. making and what responses are returned by the alias analysis. As an example:
  524. .. code-block:: bash
  525. % opt -basicaa -count-aa -ds-aa -count-aa -licm
  526. will print out how many queries (and what responses are returned) by the
  527. ``-licm`` pass (of the ``-ds-aa`` pass) and how many queries are made of the
  528. ``-basicaa`` pass by the ``-ds-aa`` pass. This can be useful when debugging a
  529. transformation or an alias analysis implementation.
  530. The ``-aa-eval`` pass
  531. ^^^^^^^^^^^^^^^^^^^^^
  532. The ``-aa-eval`` pass simply iterates through all pairs of pointers in a
  533. function and asks an alias analysis whether or not the pointers alias. This
  534. gives an indication of the precision of the alias analysis. Statistics are
  535. printed indicating the percent of no/may/must aliases found (a more precise
  536. algorithm will have a lower number of may aliases).
  537. Memory Dependence Analysis
  538. ==========================
  539. If you're just looking to be a client of alias analysis information, consider
  540. using the Memory Dependence Analysis interface instead. MemDep is a lazy,
  541. caching layer on top of alias analysis that is able to answer the question of
  542. what preceding memory operations a given instruction depends on, either at an
  543. intra- or inter-block level. Because of its laziness and caching policy, using
  544. MemDep can be a significant performance win over accessing alias analysis
  545. directly.