LLVM Alias Analysis Infrastructure

Introduction

Alias Analysis (aka Pointer Analysis) is a class of techniques which attempt todetermine whether or not two pointers ever can point to the same object inmemory. There are many different algorithms for alias analysis and manydifferent ways of classifying them: flow-sensitive vs. flow-insensitive,context-sensitive vs. context-insensitive, field-sensitivevs. field-insensitive, unification-based vs. subset-based, etc. Traditionally,alias analyses respond to a query with a Must, May, or No alias response,indicating that two pointers always point to the same object, might point to thesame object, or are known to never point to the same object.

The LLVM AliasAnalysis class is theprimary interface used by clients and implementations of alias analyses in theLLVM system. This class is the common interface between clients of aliasanalysis information and the implementations providing it, and is designed tosupport a wide range of implementations and clients (but currently all clientsare assumed to be flow-insensitive). In addition to simple alias analysisinformation, this class exposes Mod/Ref information from those implementationswhich can provide it, allowing for powerful analyses and transformations to workwell together.

This document contains information necessary to successfully implement thisinterface, use it, and to test both sides. It also explains some of the finerpoints about what exactly results mean.

AliasAnalysis Class Overview

The AliasAnalysisclass defines the interface that the various alias analysis implementationsshould support. This class exports two important enums: AliasResult andModRefResult which represent the result of an alias query or a mod/refquery, respectively.

The AliasAnalysis interface exposes information about memory, represented inseveral different ways. In particular, memory objects are represented as astarting address and size, and function calls are represented as the actualcall or invoke instructions that performs the call. TheAliasAnalysis interface also exposes some helper methods which allow you toget mod/ref information for arbitrary instructions.

All AliasAnalysis interfaces require that in queries involving multiplevalues, values which are not constants are alldefined within the same function.

Representation of Pointers

Most importantly, the AliasAnalysis class provides several methods which areused to query whether or not two memory objects alias, whether function callscan modify or read a memory object, etc. For all of these queries, memoryobjects are represented as a pair of their starting address (a symbolic LLVMValue*) and a static size.

Representing memory objects as a starting address and a size is criticallyimportant for correct Alias Analyses. For example, consider this (silly, butpossible) C code:

  1. int i;
  2. char C[2];
  3. char A[10];
  4. /* ... */
  5. for (i = 0; i != 10; ++i) {
  6. C[0] = A[i]; /* One byte store */
  7. C[1] = A[9-i]; /* One byte store */
  8. }

In this case, the basicaa pass will disambiguate the stores to C[0] andC[1] because they are accesses to two distinct locations one byte apart, andthe accesses are each one byte. In this case, the Loop Invariant Code Motion(LICM) pass can use store motion to remove the stores from the loop. Inconstrast, the following code:

  1. int i;
  2. char C[2];
  3. char A[10];
  4. /* ... */
  5. for (i = 0; i != 10; ++i) {
  6. ((short*)C)[0] = A[i]; /* Two byte store! */
  7. C[1] = A[9-i]; /* One byte store */
  8. }

In this case, the two stores to C do alias each other, because the access to the&C[0] element is a two byte access. If size information wasn’t available inthe query, even the first case would have to conservatively assume that theaccesses alias.

The alias method

The alias method is the primary interface used to determine whether or nottwo memory objects alias each other. It takes two memory objects as input andreturns MustAlias, PartialAlias, MayAlias, or NoAlias as appropriate.

Like all AliasAnalysis interfaces, the alias method requires that eitherthe two pointer values be defined within the same function, or at least one ofthe values is a constant.

Must, May, and No Alias Responses

The NoAlias response may be used when there is never an immediate dependencebetween any memory reference based on one pointer and any memory referencebased the other. The most obvious example is when the two pointers point tonon-overlapping memory ranges. Another is when the two pointers are only everused for reading memory. Another is when the memory is freed and reallocatedbetween accesses through one pointer and accesses through the other — in thiscase, there is a dependence, but it’s mediated by the free and reallocation.

As an exception to this is with the noalias keyword;the “irrelevant” dependencies are ignored.

The MayAlias response is used whenever the two pointers might refer to thesame object.

The PartialAlias response is used when the two memory objects are known tobe overlapping in some way, regardless whether they start at the same addressor not.

The MustAlias response may only be returned if the two memory objects areguaranteed to always start at exactly the same location. A MustAliasresponse does not imply that the pointers compare equal.

The getModRefInfo methods

The getModRefInfo methods return information about whether the execution ofan instruction can read or modify a memory location. Mod/Ref information isalways conservative: if an instruction might read or write a location,ModRef is returned.

The AliasAnalysis class also provides a getModRefInfo method for testingdependencies between function calls. This method takes two call sites (CS1& CS2), returns NoModRef if neither call writes to memory read orwritten by the other, Ref if CS1 reads memory written by CS2,Mod if CS1 writes to memory read or written by CS2, or ModRef ifCS1 might read or write memory written to by CS2. Note that thisrelation is not commutative.

Other useful AliasAnalysis methods

Several other tidbits of information are often collected by various aliasanalysis implementations and can be put to good use by various clients.

The pointsToConstantMemory method

The pointsToConstantMemory method returns true if and only if the analysiscan prove that the pointer only points to unchanging memory locations(functions, constant global variables, and the null pointer). This informationcan be used to refine mod/ref information: it is impossible for an unchangingmemory location to be modified.

The doesNotAccessMemory and onlyReadsMemory methods

These methods are used to provide very simple mod/ref information for functioncalls. The doesNotAccessMemory method returns true for a function if theanalysis can prove that the function never reads or writes to memory, or if thefunction only reads from constant memory. Functions with this property areside-effect free and only depend on their input arguments, allowing them to beeliminated if they form common subexpressions or be hoisted out of loops. Manycommon functions behave this way (e.g., sin and cos) but many others donot (e.g., acos, which modifies the errno variable).

The onlyReadsMemory method returns true for a function if analysis can provethat (at most) the function only reads from non-volatile memory. Functions withthis property are side-effect free, only depending on their input arguments andthe state of memory when they are called. This property allows calls to thesefunctions to be eliminated and moved around, as long as there is no storeinstruction that changes the contents of memory. Note that all functions thatsatisfy the doesNotAccessMemory method also satisfy onlyReadsMemory.

Writing a new AliasAnalysis Implementation

Writing a new alias analysis implementation for LLVM is quite straight-forward.There are already several implementations that you can use for examples, and thefollowing information should help fill in any details. For a examples, take alook at the various alias analysis implementations included with LLVM.

Different Pass styles

The first step to determining what type of LLVM passyou need to use for your Alias Analysis. As is the case with most otheranalyses and transformations, the answer should be fairly obvious from what typeof problem you are trying to solve:

  • If you require interprocedural analysis, it should be a Pass.
  • If you are a function-local analysis, subclass FunctionPass.
  • If you don’t need to look at the program at all, subclass ImmutablePass.In addition to the pass that you subclass, you should also inherit from theAliasAnalysis interface, of course, and use the RegisterAnalysisGrouptemplate to register as an implementation of AliasAnalysis.

Required initialization calls

Your subclass of AliasAnalysis is required to invoke two methods on theAliasAnalysis base class: getAnalysisUsage andInitializeAliasAnalysis. In particular, your implementation ofgetAnalysisUsage should explicitly call into theAliasAnalysis::getAnalysisUsage method in addition to doing any declaringany pass dependencies your pass has. Thus you should have something like this:

  1. void getAnalysisUsage(AnalysisUsage &AU) const {
  2. AliasAnalysis::getAnalysisUsage(AU);
  3. // declare your dependencies here.
  4. }

Additionally, your must invoke the InitializeAliasAnalysis method from youranalysis run method (run for a Pass, runOnFunction for aFunctionPass, or InitializePass for an ImmutablePass). For example(as part of a Pass):

  1. bool run(Module &M) {
  2. InitializeAliasAnalysis(this);
  3. // Perform analysis here...
  4. return false;
  5. }

Required methods to override

You must override the getAdjustedAnalysisPointer method on all subclassesof AliasAnalysis. An example implementation of this method would look like:

  1. void *getAdjustedAnalysisPointer(const void* ID) override {
  2. if (ID == &AliasAnalysis::ID)
  3. return (AliasAnalysis*)this;
  4. return this;
  5. }

Interfaces which may be specified

All of the AliasAnalysis virtual methodsdefault to providing chaining to another aliasanalysis implementation, which ends up returning conservatively correctinformation (returning “May” Alias and “Mod/Ref” for alias and mod/ref queriesrespectively). Depending on the capabilities of the analysis you areimplementing, you just override the interfaces you can improve.

AliasAnalysis chaining behavior

With only one special exception (the -no-aa pass)every alias analysis pass chains to another alias analysis implementation (forexample, the user can specify “-basicaa -ds-aa -licm” to get the maximumbenefit from both alias analyses). The alias analysis class automaticallytakes care of most of this for methods that you don’t override. For methodsthat you do override, in code paths that return a conservative MayAlias orMod/Ref result, simply return whatever the superclass computes. For example:

  1. AliasResult alias(const Value *V1, unsigned V1Size,
  2. const Value *V2, unsigned V2Size) {
  3. if (...)
  4. return NoAlias;
  5. ...
  6.  
  7. // Couldn't determine a must or no-alias result.
  8. return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
  9. }

In addition to analysis queries, you must make sure to unconditionally pass LLVMupdate notification methods to the superclass as well if you override them,which allows all alias analyses in a change to be updated.

Updating analysis results for transformations

Alias analysis information is initially computed for a static snapshot of theprogram, but clients will use this information to make transformations to thecode. All but the most trivial forms of alias analysis will need to have theiranalysis results updated to reflect the changes made by these transformations.

The AliasAnalysis interface exposes four methods which are used tocommunicate program changes from the clients to the analysis implementations.Various alias analysis implementations should use these methods to ensure thattheir internal data structures are kept up-to-date as the program changes (forexample, when an instruction is deleted), and clients of alias analysis must besure to call these interfaces appropriately.

The deleteValue method

The deleteValue method is called by transformations when they remove aninstruction or any other value from the program (including values that do notuse pointers). Typically alias analyses keep data structures that have entriesfor each value in the program. When this method is called, they should removeany entries for the specified value, if they exist.

The copyValue method

The copyValue method is used when a new value is introduced into theprogram. There is no way to introduce a value into the program that did notexist before (this doesn’t make sense for a safe compiler transformation), sothis is the only way to introduce a new value. This method indicates that thenew value has exactly the same properties as the value being copied.

The replaceWithNewValue method

This method is a simple helper method that is provided to make clients easier touse. It is implemented by copying the old analysis information to the newvalue, then deleting the old value. This method cannot be overridden by aliasanalysis implementations.

The addEscapingUse method

The addEscapingUse method is used when the uses of a pointer value havechanged in ways that may invalidate precomputed analysis information.Implementations may either use this callback to provide conservative responsesfor points whose uses have change since analysis time, or may recompute some orall of their internal state to continue providing accurate responses.

In general, any new use of a pointer value is considered an escaping use, andmust be reported through this callback, except for the uses below:

  • A bitcast or getelementptr of the pointer
  • A store through the pointer (but not a store of the pointer)
  • A load through the pointer

Efficiency Issues

From the LLVM perspective, the only thing you need to do to provide an efficientalias analysis is to make sure that alias analysis queries are servicedquickly. The actual calculation of the alias analysis results (the “run”method) is only performed once, but many (perhaps duplicate) queries may beperformed. Because of this, try to move as much computation to the run methodas possible (within reason).

Limitations

The AliasAnalysis infrastructure has several limitations which make writing anew AliasAnalysis implementation difficult.

There is no way to override the default alias analysis. It would be very usefulto be able to do something like “opt -my-aa -O2” and have it use -my-aafor all passes which need AliasAnalysis, but there is currently no support forthat, short of changing the source code and recompiling. Similarly, there isalso no way of setting a chain of analyses as the default.

There is no way for transform passes to declare that they preserveAliasAnalysis implementations. The AliasAnalysis interface includesdeleteValue and copyValue methods which are intended to allow a pass tokeep an AliasAnalysis consistent, however there’s no way for a pass to declarein its getAnalysisUsage that it does so. Some passes attempt to useAU.addPreserved<AliasAnalysis>, however this doesn’t actually have anyeffect.

Similarly, the opt -p option introduces ModulePass passes between eachpass, which prevents the use of FunctionPass alias analysis passes.

The AliasAnalysis API does have functions for notifying implementations whenvalues are deleted or copied, however these aren’t sufficient. There are manyother ways that LLVM IR can be modified which could be relevant toAliasAnalysis implementations which can not be expressed.

The AliasAnalysisDebugger utility seems to suggest that AliasAnalysisimplementations can expect that they will be informed of any relevant Valuebefore it appears in an alias query. However, popular clients such as GVNdon’t support this, and are known to trigger errors when run with theAliasAnalysisDebugger.

The AliasSetTracker class (which is used by LICM) makes anon-deterministic number of alias queries. This can cause debugging techniquesinvolving pausing execution after a predetermined number of queries to beunreliable.

Many alias queries can be reformulated in terms of other alias queries. Whenmultiple AliasAnalysis queries are chained together, it would make sense tostart those queries from the beginning of the chain, with care taken to avoidinfinite looping, however currently an implementation which wants to do this canonly start such queries from itself.

Using alias analysis results

There are several different ways to use alias analysis results. In order ofpreference, these are:

Using the MemoryDependenceAnalysis Pass

The memdep pass uses alias analysis to provide high-level dependenceinformation about memory-using instructions. This will tell you which storefeeds into a load, for example. It uses caching and other techniques to beefficient, and is used by Dead Store Elimination, GVN, and memcpy optimizations.

Using the AliasSetTracker class

Many transformations need information about alias sets that are active insome scope, rather than information about pairwise aliasing. TheAliasSetTrackerclass is used to efficiently build these Alias Sets from the pairwise aliasanalysis information provided by the AliasAnalysis interface.

First you initialize the AliasSetTracker by using the “add” methods to addinformation about various potentially aliasing instructions in the scope you areinterested in. Once all of the alias sets are completed, your pass shouldsimply iterate through the constructed alias sets, using the AliasSetTrackerbegin()/end() methods.

The AliasSets formed by the AliasSetTracker are guaranteed to bedisjoint, calculate mod/ref information and volatility for the set, and keeptrack of whether or not all of the pointers in the set are Must aliases. TheAliasSetTracker also makes sure that sets are properly folded due to callinstructions, and can provide a list of pointers in each set.

As an example user of this, the Loop Invariant Code Motion pass uses AliasSetTrackers to calculate aliassets for each loop nest. If an AliasSet in a loop is not modified, then allload instructions from that set may be hoisted out of the loop. If any aliassets are stored to and are must alias sets, then the stores may be sunkto outside of the loop, promoting the memory location to a register for theduration of the loop nest. Both of these transformations only apply if thepointer argument is loop-invariant.

The AliasSetTracker implementation

The AliasSetTracker class is implemented to be as efficient as possible. Ituses the union-find algorithm to efficiently merge AliasSets when a pointer isinserted into the AliasSetTracker that aliases multiple sets. The primary datastructure is a hash table mapping pointers to the AliasSet they are in.

The AliasSetTracker class must maintain a list of all of the LLVM Valuesthat are in each AliasSet. Since the hash table already has entries for eachLLVM Value of interest, the AliasesSets thread the linked list throughthese hash-table nodes to avoid having to allocate memory unnecessarily, and tomake merging alias sets extremely efficient (the linked list merge is constanttime).

You shouldn’t need to understand these details if you are just a client of theAliasSetTracker, but if you look at the code, hopefully this brief descriptionwill help make sense of why things are designed the way they are.

Using the AliasAnalysis interface directly

If neither of these utility class are what your pass needs, you should use theinterfaces exposed by the AliasAnalysis class directly. Try to use thehigher-level methods when possible (e.g., use mod/ref information instead of thealias method directly if possible) to get the best precision and efficiency.

Existing alias analysis implementations and clients

If you’re going to be working with the LLVM alias analysis infrastructure, youshould know what clients and implementations of alias analysis are available.In particular, if you are implementing an alias analysis, you should be aware ofthe the clients that are useful for monitoring and evaluating differentimplementations.

Available AliasAnalysis implementations

This section lists the various implementations of the AliasAnalysisinterface. With the exception of the -no-aaimplementation, all of these chain to otheralias analysis implementations.

The -no-aa pass

The -no-aa pass is just like what it sounds: an alias analysis that neverreturns any useful information. This pass can be useful if you think that aliasanalysis is doing something wrong and are trying to narrow down a problem.

The -basicaa pass

The -basicaa pass is an aggressive local analysis that knows manyimportant facts:

  • Distinct globals, stack allocations, and heap allocations can never alias.
  • Globals, stack allocations, and heap allocations never alias the null pointer.
  • Different fields of a structure do not alias.
  • Indexes into arrays with statically differing subscripts cannot alias.
  • Many common standard C library functions never access memory or only readmemory.
  • Pointers that obviously point to constant globals “pointToConstantMemory”.
  • Function calls can not modify or references stack allocations if they neverescape from the function that allocates them (a common case for automaticarrays).

The -globalsmodref-aa pass

This pass implements a simple context-sensitive mod/ref and alias analysis forinternal global variables that don’t “have their address taken”. If a globaldoes not have its address taken, the pass knows that no pointers alias theglobal. This pass also keeps track of functions that it knows never accessmemory or never read memory. This allows certain optimizations (e.g. GVN) toeliminate call instructions entirely.

The real power of this pass is that it provides context-sensitive mod/refinformation for call instructions. This allows the optimizer to know that callsto a function do not clobber or read the value of the global, allowing loads andstores to be eliminated.

Note

This pass is somewhat limited in its scope (only support non-address takenglobals), but is very quick analysis.

The -steens-aa pass

The -steens-aa pass implements a variation on the well-known “Steensgaard’salgorithm” for interprocedural alias analysis. Steensgaard’s algorithm is aunification-based, flow-insensitive, context-insensitive, and field-insensitivealias analysis that is also very scalable (effectively linear time).

The LLVM -steens-aa pass implements a “speculatively field-sensitive”version of Steensgaard’s algorithm using the Data Structure Analysis framework.This gives it substantially more precision than the standard algorithm whilemaintaining excellent analysis scalability.

Note

-steens-aa is available in the optional “poolalloc” module. It is not partof the LLVM core.

The -ds-aa pass

The -ds-aa pass implements the full Data Structure Analysis algorithm. DataStructure Analysis is a modular unification-based, flow-insensitive,context-sensitive, and speculatively field-sensitive aliasanalysis that is also quite scalable, usually at O(n * log(n)).

This algorithm is capable of responding to a full variety of alias analysisqueries, and can provide context-sensitive mod/ref information as well. Theonly major facility not implemented so far is support for must-aliasinformation.

Note

-ds-aa is available in the optional “poolalloc” module. It is not part ofthe LLVM core.

The -scev-aa pass

The -scev-aa pass implements AliasAnalysis queries by translating them intoScalarEvolution queries. This gives it a more complete understanding ofgetelementptr instructions and loop induction variables than other aliasanalyses have.

Alias analysis driven transformations

LLVM includes several alias-analysis driven transformations which can be usedwith any of the implementations above.

The -adce pass

The -adce pass, which implements Aggressive Dead Code Elimination uses theAliasAnalysis interface to delete calls to functions that do not haveside-effects and are not used.

The -licm pass

The -licm pass implements various Loop Invariant Code Motion relatedtransformations. It uses the AliasAnalysis interface for several differenttransformations:

  • It uses mod/ref information to hoist or sink load instructions out of loops ifthere are no instructions in the loop that modifies the memory loaded.
  • It uses mod/ref information to hoist function calls out of loops that do notwrite to memory and are loop-invariant.
  • It uses alias information to promote memory objects that are loaded and storedto in loops to live in a register instead. It can do this if there are no mayaliases to the loaded/stored memory location.

The -argpromotion pass

The -argpromotion pass promotes by-reference arguments to be passed inby-value instead. In particular, if pointer arguments are only loaded from itpasses in the value loaded instead of the address to the function. This passuses alias information to make sure that the value loaded from the argumentpointer is not modified between the entry of the function and any load of thepointer.

The -gvn, -memcpyopt, and -dse passes

These passes use AliasAnalysis information to reason about loads and stores.

Clients for debugging and evaluation of implementations

These passes are useful for evaluating the various alias analysisimplementations. You can use them with commands like:

  1. % opt -ds-aa -aa-eval foo.bc -disable-output -stats

The -print-alias-sets pass

The -print-alias-sets pass is exposed as part of the opt tool to printout the Alias Sets formed by the AliasSetTracker class. This is useful ifyou’re using the AliasSetTracker class. To use it, use something like:

  1. % opt -ds-aa -print-alias-sets -disable-output

The -aa-eval pass

The -aa-eval pass simply iterates through all pairs of pointers in afunction and asks an alias analysis whether or not the pointers alias. Thisgives an indication of the precision of the alias analysis. Statistics areprinted indicating the percent of no/may/must aliases found (a more precisealgorithm will have a lower number of may aliases).

Memory Dependence Analysis

Note

We are currently in the process of migrating things fromMemoryDependenceAnalysis to MemorySSA. Please try to usethat instead.

If you’re just looking to be a client of alias analysis information, considerusing the Memory Dependence Analysis interface instead. MemDep is a lazy,caching layer on top of alias analysis that is able to answer the question ofwhat preceding memory operations a given instruction depends on, either at anintra- or inter-block level. Because of its laziness and caching policy, usingMemDep can be a significant performance win over accessing alias analysisdirectly.