CFLAliasAnalysis.cpp revision 277718
118334Speter//===- CFLAliasAnalysis.cpp - CFL-Based Alias Analysis Implementation ------==// 290075Sobrien// 390075Sobrien// The LLVM Compiler Infrastructure 418334Speter// 590075Sobrien// This file is distributed under the University of Illinois Open Source 618334Speter// License. See LICENSE.TXT for details. 790075Sobrien// 890075Sobrien//===----------------------------------------------------------------------===// 990075Sobrien// 1090075Sobrien// This file implements a CFL-based context-insensitive alias analysis 1118334Speter// algorithm. It does not depend on types. The algorithm is a mixture of the one 1290075Sobrien// described in "Demand-driven alias analysis for C" by Xin Zheng and Radu 1390075Sobrien// Rugina, and "Fast algorithms for Dyck-CFL-reachability with applications to 1490075Sobrien// Alias Analysis" by Zhang Q, Lyu M R, Yuan H, and Su Z. -- to summarize the 1590075Sobrien// papers, we build a graph of the uses of a variable, where each node is a 1618334Speter// memory location, and each edge is an action that happened on that memory 1718334Speter// location. The "actions" can be one of Dereference, Reference, Assign, or 1890075Sobrien// Assign. 1990075Sobrien// 2090075Sobrien// Two variables are considered as aliasing iff you can reach one value's node 2118334Speter// from the other value's node and the language formed by concatenating all of 2218334Speter// the edge labels (actions) conforms to a context-free grammar. 2318334Speter// 2418334Speter// Because this algorithm requires a graph search on each query, we execute the 2518334Speter// algorithm outlined in "Fast algorithms..." (mentioned above) 2618334Speter// in order to transform the graph into sets of variables that may alias in 2718334Speter// ~nlogn time (n = number of variables.), which makes queries take constant 2818334Speter// time. 2918334Speter//===----------------------------------------------------------------------===// 3018334Speter 3118334Speter#include "StratifiedSets.h" 3218334Speter#include "llvm/ADT/BitVector.h" 3318334Speter#include "llvm/ADT/DenseMap.h" 3418334Speter#include "llvm/ADT/None.h" 3518334Speter#include "llvm/ADT/Optional.h" 3618334Speter#include "llvm/Analysis/AliasAnalysis.h" 3718334Speter#include "llvm/Analysis/Passes.h" 3850397Sobrien#include "llvm/IR/Constants.h" 3950397Sobrien#include "llvm/IR/Function.h" 4050397Sobrien#include "llvm/IR/InstVisitor.h" 4150397Sobrien#include "llvm/IR/Instructions.h" 4250397Sobrien#include "llvm/IR/ValueHandle.h" 4350397Sobrien#include "llvm/Pass.h" 4450397Sobrien#include "llvm/Support/Allocator.h" 4550397Sobrien#include "llvm/Support/Compiler.h" 4650397Sobrien#include "llvm/Support/ErrorHandling.h" 4790075Sobrien#include <algorithm> 4850397Sobrien#include <cassert> 4918334Speter#include <forward_list> 5018334Speter#include <tuple> 5118334Speter 5218334Speterusing namespace llvm; 5318334Speter 5418334Speter// Try to go from a Value* to a Function*. Never returns nullptr. 5518334Speterstatic Optional<Function *> parentFunctionOfValue(Value *); 5618334Speter 5718334Speter// Returns possible functions called by the Inst* into the given 5818334Speter// SmallVectorImpl. Returns true if targets found, false otherwise. 5918334Speter// This is templated because InvokeInst/CallInst give us the same 6018334Speter// set of functions that we care about, and I don't like repeating 6150397Sobrien// myself. 6250397Sobrientemplate <typename Inst> 6350397Sobrienstatic bool getPossibleTargets(Inst *, SmallVectorImpl<Function *> &); 6418334Speter 6518334Speter// Some instructions need to have their users tracked. Instructions like 6618334Speter// `add` require you to get the users of the Instruction* itself, other 6718334Speter// instructions like `store` require you to get the users of the first 6818334Speter// operand. This function gets the "proper" value to track for each 6918334Speter// type of instruction we support. 7018334Speterstatic Optional<Value *> getTargetValue(Instruction *); 7118334Speter 7218334Speter// There are certain instructions (i.e. FenceInst, etc.) that we ignore. 7318334Speter// This notes that we should ignore those. 7418334Speterstatic bool hasUsefulEdges(Instruction *); 7518334Speter 7618334Speterconst StratifiedIndex StratifiedLink::SetSentinel = 7718334Speter std::numeric_limits<StratifiedIndex>::max(); 7818334Speter 7950397Sobriennamespace { 8050397Sobrien// StratifiedInfo Attribute things. 8118334Spetertypedef unsigned StratifiedAttr; 8218334SpeterLLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs; 8318334SpeterLLVM_CONSTEXPR unsigned AttrAllIndex = 0; 8418334SpeterLLVM_CONSTEXPR unsigned AttrGlobalIndex = 1; 8590075SobrienLLVM_CONSTEXPR unsigned AttrFirstArgIndex = 2; 8690075SobrienLLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex; 8790075SobrienLLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex; 8890075Sobrien 8990075SobrienLLVM_CONSTEXPR StratifiedAttr AttrNone = 0; 9090075SobrienLLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone; 9190075Sobrien 9290075Sobrien// \brief StratifiedSets call for knowledge of "direction", so this is how we 9390075Sobrien// represent that locally. 9418334Speterenum class Level { Same, Above, Below }; 9590075Sobrien 9690075Sobrien// \brief Edges can be one of four "weights" -- each weight must have an inverse 9790075Sobrien// weight (Assign has Assign; Reference has Dereference). 9890075Sobrienenum class EdgeType { 9990075Sobrien // The weight assigned when assigning from or to a value. For example, in: 10090075Sobrien // %b = getelementptr %a, 0 10190075Sobrien // ...The relationships are %b assign %a, and %a assign %b. This used to be 10290075Sobrien // two edges, but having a distinction bought us nothing. 10390075Sobrien Assign, 10490075Sobrien 10590075Sobrien // The edge used when we have an edge going from some handle to a Value. 10690075Sobrien // Examples of this include: 10790075Sobrien // %b = load %a (%b Dereference %a) 10890075Sobrien // %b = extractelement %a, 0 (%a Dereference %b) 10990075Sobrien Dereference, 11090075Sobrien 11190075Sobrien // The edge used when our edge goes from a value to a handle that may have 11290075Sobrien // contained it at some point. Examples: 11390075Sobrien // %b = load %a (%a Reference %b) 11490075Sobrien // %b = extractelement %a, 0 (%b Reference %a) 11590075Sobrien Reference 11690075Sobrien}; 11790075Sobrien 11890075Sobrien// \brief Encodes the notion of a "use" 11990075Sobrienstruct Edge { 12090075Sobrien // \brief Which value the edge is coming from 12190075Sobrien Value *From; 12290075Sobrien 12390075Sobrien // \brief Which value the edge is pointing to 12490075Sobrien Value *To; 12590075Sobrien 12690075Sobrien // \brief Edge weight 12790075Sobrien EdgeType Weight; 12890075Sobrien 12990075Sobrien // \brief Whether we aliased any external values along the way that may be 13090075Sobrien // invisible to the analysis (i.e. landingpad for exceptions, calls for 13190075Sobrien // interprocedural analysis, etc.) 13290075Sobrien StratifiedAttrs AdditionalAttrs; 13390075Sobrien 13490075Sobrien Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A) 13590075Sobrien : From(From), To(To), Weight(W), AdditionalAttrs(A) {} 13690075Sobrien}; 13790075Sobrien 13890075Sobrien// \brief Information we have about a function and would like to keep around 13990075Sobrienstruct FunctionInfo { 14090075Sobrien StratifiedSets<Value *> Sets; 14190075Sobrien // Lots of functions have < 4 returns. Adjust as necessary. 14290075Sobrien SmallVector<Value *, 4> ReturnedValues; 14390075Sobrien 14490075Sobrien FunctionInfo(StratifiedSets<Value *> &&S, 14590075Sobrien SmallVector<Value *, 4> &&RV) 14690075Sobrien : Sets(std::move(S)), ReturnedValues(std::move(RV)) {} 14790075Sobrien}; 14890075Sobrien 14990075Sobrienstruct CFLAliasAnalysis; 15090075Sobrien 15190075Sobrienstruct FunctionHandle : public CallbackVH { 15290075Sobrien FunctionHandle(Function *Fn, CFLAliasAnalysis *CFLAA) 15390075Sobrien : CallbackVH(Fn), CFLAA(CFLAA) { 15490075Sobrien assert(Fn != nullptr); 15590075Sobrien assert(CFLAA != nullptr); 15690075Sobrien } 15790075Sobrien 15890075Sobrien virtual ~FunctionHandle() {} 15990075Sobrien 16090075Sobrien void deleted() override { removeSelfFromCache(); } 16190075Sobrien void allUsesReplacedWith(Value *) override { removeSelfFromCache(); } 16290075Sobrien 16390075Sobrienprivate: 16490075Sobrien CFLAliasAnalysis *CFLAA; 16590075Sobrien 16690075Sobrien void removeSelfFromCache(); 16718334Speter}; 16818334Speter 16918334Speterstruct CFLAliasAnalysis : public ImmutablePass, public AliasAnalysis { 17018334Speterprivate: 17118334Speter /// \brief Cached mapping of Functions to their StratifiedSets. 17218334Speter /// If a function's sets are currently being built, it is marked 17318334Speter /// in the cache as an Optional without a value. This way, if we 17418334Speter /// have any kind of recursion, it is discernable from a function 17518334Speter /// that simply has empty sets. 17618334Speter DenseMap<Function *, Optional<FunctionInfo>> Cache; 17718334Speter std::forward_list<FunctionHandle> Handles; 17818334Speter 17918334Speterpublic: 18018334Speter static char ID; 18118334Speter 18218334Speter CFLAliasAnalysis() : ImmutablePass(ID) { 18318334Speter initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry()); 18418334Speter } 18518334Speter 18690075Sobrien virtual ~CFLAliasAnalysis() {} 18718334Speter 18818334Speter void getAnalysisUsage(AnalysisUsage &AU) const override { 18918334Speter AliasAnalysis::getAnalysisUsage(AU); 19018334Speter } 19118334Speter 19218334Speter void *getAdjustedAnalysisPointer(const void *ID) override { 19352284Sobrien if (ID == &AliasAnalysis::ID) 19452284Sobrien return (AliasAnalysis *)this; 19552284Sobrien return this; 19652284Sobrien } 19752284Sobrien 19852284Sobrien /// \brief Inserts the given Function into the cache. 19952284Sobrien void scan(Function *Fn); 20052284Sobrien 20152284Sobrien void evict(Function *Fn) { Cache.erase(Fn); } 20252284Sobrien 20352284Sobrien /// \brief Ensures that the given function is available in the cache. 20452284Sobrien /// Returns the appropriate entry from the cache. 20552284Sobrien const Optional<FunctionInfo> &ensureCached(Function *Fn) { 20652284Sobrien auto Iter = Cache.find(Fn); 20752284Sobrien if (Iter == Cache.end()) { 20852284Sobrien scan(Fn); 20952284Sobrien Iter = Cache.find(Fn); 21052284Sobrien assert(Iter != Cache.end()); 21152284Sobrien assert(Iter->second.hasValue()); 21252284Sobrien } 21352284Sobrien return Iter->second; 21452284Sobrien } 21552284Sobrien 21652284Sobrien AliasResult query(const Location &LocA, const Location &LocB); 21752284Sobrien 21852284Sobrien AliasResult alias(const Location &LocA, const Location &LocB) override { 21952284Sobrien if (LocA.Ptr == LocB.Ptr) { 22090075Sobrien if (LocA.Size == LocB.Size) { 22190075Sobrien return MustAlias; 22290075Sobrien } else { 22352284Sobrien return PartialAlias; 22490075Sobrien } 22590075Sobrien } 22690075Sobrien 22752284Sobrien // Comparisons between global variables and other constants should be 22852284Sobrien // handled by BasicAA. 22952284Sobrien if (isa<Constant>(LocA.Ptr) && isa<Constant>(LocB.Ptr)) { 23052284Sobrien return MayAlias; 23152284Sobrien } 23252284Sobrien 23352284Sobrien return query(LocA, LocB); 23452284Sobrien } 23552284Sobrien 23652284Sobrien void initializePass() override { InitializeAliasAnalysis(this); } 23752284Sobrien}; 23852284Sobrien 23952284Sobrienvoid FunctionHandle::removeSelfFromCache() { 24052284Sobrien assert(CFLAA != nullptr); 24152284Sobrien auto *Val = getValPtr(); 24252284Sobrien CFLAA->evict(cast<Function>(Val)); 24352284Sobrien setValPtr(nullptr); 24452284Sobrien} 24552284Sobrien 24652284Sobrien// \brief Gets the edges our graph should have, based on an Instruction* 24752284Sobrienclass GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> { 24852284Sobrien CFLAliasAnalysis &AA; 24952284Sobrien SmallVectorImpl<Edge> &Output; 25090075Sobrien 25152284Sobrienpublic: 25290075Sobrien GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output) 25352284Sobrien : AA(AA), Output(Output) {} 25452284Sobrien 25518334Speter void visitInstruction(Instruction &) { 25618334Speter llvm_unreachable("Unsupported instruction encountered"); 25718334Speter } 25818334Speter 25918334Speter void visitCastInst(CastInst &Inst) { 26090075Sobrien Output.push_back(Edge(&Inst, Inst.getOperand(0), EdgeType::Assign, 26118334Speter AttrNone)); 26218334Speter } 26318334Speter 26490075Sobrien void visitBinaryOperator(BinaryOperator &Inst) { 26518334Speter auto *Op1 = Inst.getOperand(0); 26618334Speter auto *Op2 = Inst.getOperand(1); 26718334Speter Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone)); 26890075Sobrien Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone)); 26918334Speter } 27052284Sobrien 27152284Sobrien void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) { 27252284Sobrien auto *Ptr = Inst.getPointerOperand(); 27352284Sobrien auto *Val = Inst.getNewValOperand(); 27490075Sobrien Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone)); 27518334Speter } 27618334Speter 27718334Speter void visitAtomicRMWInst(AtomicRMWInst &Inst) { 27818334Speter auto *Ptr = Inst.getPointerOperand(); 27990075Sobrien auto *Val = Inst.getValOperand(); 28018334Speter Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone)); 28190075Sobrien } 28290075Sobrien 28318334Speter void visitPHINode(PHINode &Inst) { 28418334Speter for (unsigned I = 0, E = Inst.getNumIncomingValues(); I != E; ++I) { 28518334Speter Value *Val = Inst.getIncomingValue(I); 28618334Speter Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone)); 28790075Sobrien } 28818334Speter } 28918334Speter 29018334Speter void visitGetElementPtrInst(GetElementPtrInst &Inst) { 29118334Speter auto *Op = Inst.getPointerOperand(); 29218334Speter Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone)); 29390075Sobrien for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I) 29418334Speter Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone)); 29518334Speter } 29618334Speter 29790075Sobrien void visitSelectInst(SelectInst &Inst) { 29818334Speter auto *Condition = Inst.getCondition(); 29918334Speter Output.push_back(Edge(&Inst, Condition, EdgeType::Assign, AttrNone)); 30018334Speter auto *TrueVal = Inst.getTrueValue(); 30118334Speter Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone)); 30290075Sobrien auto *FalseVal = Inst.getFalseValue(); 30318334Speter Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone)); 30450397Sobrien } 30590075Sobrien 30650397Sobrien void visitAllocaInst(AllocaInst &) {} 30718334Speter 30818334Speter void visitLoadInst(LoadInst &Inst) { 30990075Sobrien auto *Ptr = Inst.getPointerOperand(); 31018334Speter auto *Val = &Inst; 31118334Speter Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone)); 31218334Speter } 31318334Speter 31490075Sobrien void visitStoreInst(StoreInst &Inst) { 31590075Sobrien auto *Ptr = Inst.getPointerOperand(); 31618334Speter auto *Val = Inst.getValueOperand(); 31718334Speter Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone)); 31890075Sobrien } 31918334Speter 32018334Speter void visitVAArgInst(VAArgInst &Inst) { 32118334Speter // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does 32290075Sobrien // two things: 32318334Speter // 1. Loads a value from *((T*)*Ptr). 32418334Speter // 2. Increments (stores to) *Ptr by some target-specific amount. 32518334Speter // For now, we'll handle this like a landingpad instruction (by placing the 32690075Sobrien // result in its own group, and having that group alias externals). 32718334Speter auto *Val = &Inst; 32818334Speter Output.push_back(Edge(Val, Val, EdgeType::Assign, AttrAll)); 32918334Speter } 33090075Sobrien 33190075Sobrien static bool isFunctionExternal(Function *Fn) { 33218334Speter return Fn->isDeclaration() || !Fn->hasLocalLinkage(); 33390075Sobrien } 33490075Sobrien 33590075Sobrien // Gets whether the sets at Index1 above, below, or equal to the sets at 33690075Sobrien // Index2. Returns None if they are not in the same set chain. 33790075Sobrien static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets, 33890075Sobrien StratifiedIndex Index1, 33990075Sobrien StratifiedIndex Index2) { 34090075Sobrien if (Index1 == Index2) 34118334Speter return Level::Same; 34218334Speter 34390075Sobrien const auto *Current = &Sets.getLink(Index1); 34490075Sobrien while (Current->hasBelow()) { 34550397Sobrien if (Current->Below == Index2) 34618334Speter return Level::Below; 34790075Sobrien Current = &Sets.getLink(Current->Below); 34818334Speter } 34918334Speter 35090075Sobrien Current = &Sets.getLink(Index1); 35118334Speter while (Current->hasAbove()) { 35218334Speter if (Current->Above == Index2) 35318334Speter return Level::Above; 35490075Sobrien Current = &Sets.getLink(Current->Above); 35518334Speter } 35618334Speter 35718334Speter return NoneType(); 35890075Sobrien } 35918334Speter 36018334Speter bool 36118334Speter tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns, 36218334Speter Value *FuncValue, 36390075Sobrien const iterator_range<User::op_iterator> &Args) { 36418334Speter const unsigned ExpectedMaxArgs = 8; 36552284Sobrien const unsigned MaxSupportedArgs = 50; 36690075Sobrien assert(Fns.size() > 0); 36752284Sobrien 36818334Speter // I put this here to give us an upper bound on time taken by IPA. Is it 36918334Speter // really (realistically) needed? Keep in mind that we do have an n^2 algo. 37018334Speter if (std::distance(Args.begin(), Args.end()) > (int) MaxSupportedArgs) 37190075Sobrien return false; 37218334Speter 37318334Speter // Exit early if we'll fail anyway 37490075Sobrien for (auto *Fn : Fns) { 37518334Speter if (isFunctionExternal(Fn) || Fn->isVarArg()) 37618334Speter return false; 37790075Sobrien auto &MaybeInfo = AA.ensureCached(Fn); 37818334Speter if (!MaybeInfo.hasValue()) 37918334Speter return false; 38090075Sobrien } 38152284Sobrien 38252284Sobrien SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end()); 38390075Sobrien SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters; 38470635Sobrien for (auto *Fn : Fns) { 38590075Sobrien auto &Info = *AA.ensureCached(Fn); 38690075Sobrien auto &Sets = Info.Sets; 38790075Sobrien auto &RetVals = Info.ReturnedValues; 388 389 Parameters.clear(); 390 for (auto &Param : Fn->args()) { 391 auto MaybeInfo = Sets.find(&Param); 392 // Did a new parameter somehow get added to the function/slip by? 393 if (!MaybeInfo.hasValue()) 394 return false; 395 Parameters.push_back(*MaybeInfo); 396 } 397 398 // Adding an edge from argument -> return value for each parameter that 399 // may alias the return value 400 for (unsigned I = 0, E = Parameters.size(); I != E; ++I) { 401 auto &ParamInfo = Parameters[I]; 402 auto &ArgVal = Arguments[I]; 403 bool AddEdge = false; 404 StratifiedAttrs Externals; 405 for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) { 406 auto MaybeInfo = Sets.find(RetVals[X]); 407 if (!MaybeInfo.hasValue()) 408 return false; 409 410 auto &RetInfo = *MaybeInfo; 411 auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs; 412 auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs; 413 auto MaybeRelation = 414 getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index); 415 if (MaybeRelation.hasValue()) { 416 AddEdge = true; 417 Externals |= RetAttrs | ParamAttrs; 418 } 419 } 420 if (AddEdge) 421 Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign, 422 StratifiedAttrs().flip())); 423 } 424 425 if (Parameters.size() != Arguments.size()) 426 return false; 427 428 // Adding edges between arguments for arguments that may end up aliasing 429 // each other. This is necessary for functions such as 430 // void foo(int** a, int** b) { *a = *b; } 431 // (Technically, the proper sets for this would be those below 432 // Arguments[I] and Arguments[X], but our algorithm will produce 433 // extremely similar, and equally correct, results either way) 434 for (unsigned I = 0, E = Arguments.size(); I != E; ++I) { 435 auto &MainVal = Arguments[I]; 436 auto &MainInfo = Parameters[I]; 437 auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs; 438 for (unsigned X = I + 1; X != E; ++X) { 439 auto &SubInfo = Parameters[X]; 440 auto &SubVal = Arguments[X]; 441 auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs; 442 auto MaybeRelation = 443 getIndexRelation(Sets, MainInfo.Index, SubInfo.Index); 444 445 if (!MaybeRelation.hasValue()) 446 continue; 447 448 auto NewAttrs = SubAttrs | MainAttrs; 449 Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs)); 450 } 451 } 452 } 453 return true; 454 } 455 456 template <typename InstT> void visitCallLikeInst(InstT &Inst) { 457 SmallVector<Function *, 4> Targets; 458 if (getPossibleTargets(&Inst, Targets)) { 459 if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands())) 460 return; 461 // Cleanup from interprocedural analysis 462 Output.clear(); 463 } 464 465 for (Value *V : Inst.arg_operands()) 466 Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll)); 467 } 468 469 void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); } 470 471 void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); } 472 473 // Because vectors/aggregates are immutable and unaddressable, 474 // there's nothing we can do to coax a value out of them, other 475 // than calling Extract{Element,Value}. We can effectively treat 476 // them as pointers to arbitrary memory locations we can store in 477 // and load from. 478 void visitExtractElementInst(ExtractElementInst &Inst) { 479 auto *Ptr = Inst.getVectorOperand(); 480 auto *Val = &Inst; 481 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone)); 482 } 483 484 void visitInsertElementInst(InsertElementInst &Inst) { 485 auto *Vec = Inst.getOperand(0); 486 auto *Val = Inst.getOperand(1); 487 Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone)); 488 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone)); 489 } 490 491 void visitLandingPadInst(LandingPadInst &Inst) { 492 // Exceptions come from "nowhere", from our analysis' perspective. 493 // So we place the instruction its own group, noting that said group may 494 // alias externals 495 Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll)); 496 } 497 498 void visitInsertValueInst(InsertValueInst &Inst) { 499 auto *Agg = Inst.getOperand(0); 500 auto *Val = Inst.getOperand(1); 501 Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone)); 502 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone)); 503 } 504 505 void visitExtractValueInst(ExtractValueInst &Inst) { 506 auto *Ptr = Inst.getAggregateOperand(); 507 Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone)); 508 } 509 510 void visitShuffleVectorInst(ShuffleVectorInst &Inst) { 511 auto *From1 = Inst.getOperand(0); 512 auto *From2 = Inst.getOperand(1); 513 Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone)); 514 Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone)); 515 } 516}; 517 518// For a given instruction, we need to know which Value* to get the 519// users of in order to build our graph. In some cases (i.e. add), 520// we simply need the Instruction*. In other cases (i.e. store), 521// finding the users of the Instruction* is useless; we need to find 522// the users of the first operand. This handles determining which 523// value to follow for us. 524// 525// Note: we *need* to keep this in sync with GetEdgesVisitor. Add 526// something to GetEdgesVisitor, add it here -- remove something from 527// GetEdgesVisitor, remove it here. 528class GetTargetValueVisitor 529 : public InstVisitor<GetTargetValueVisitor, Value *> { 530public: 531 Value *visitInstruction(Instruction &Inst) { return &Inst; } 532 533 Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); } 534 535 Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) { 536 return Inst.getPointerOperand(); 537 } 538 539 Value *visitAtomicRMWInst(AtomicRMWInst &Inst) { 540 return Inst.getPointerOperand(); 541 } 542 543 Value *visitInsertElementInst(InsertElementInst &Inst) { 544 return Inst.getOperand(0); 545 } 546 547 Value *visitInsertValueInst(InsertValueInst &Inst) { 548 return Inst.getAggregateOperand(); 549 } 550}; 551 552// Set building requires a weighted bidirectional graph. 553template <typename EdgeTypeT> class WeightedBidirectionalGraph { 554public: 555 typedef std::size_t Node; 556 557private: 558 const static Node StartNode = Node(0); 559 560 struct Edge { 561 EdgeTypeT Weight; 562 Node Other; 563 564 Edge(const EdgeTypeT &W, const Node &N) 565 : Weight(W), Other(N) {} 566 567 bool operator==(const Edge &E) const { 568 return Weight == E.Weight && Other == E.Other; 569 } 570 571 bool operator!=(const Edge &E) const { return !operator==(E); } 572 }; 573 574 struct NodeImpl { 575 std::vector<Edge> Edges; 576 }; 577 578 std::vector<NodeImpl> NodeImpls; 579 580 bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); } 581 582 const NodeImpl &getNode(Node N) const { return NodeImpls[N]; } 583 NodeImpl &getNode(Node N) { return NodeImpls[N]; } 584 585public: 586 // ----- Various Edge iterators for the graph ----- // 587 588 // \brief Iterator for edges. Because this graph is bidirected, we don't 589 // allow modificaiton of the edges using this iterator. Additionally, the 590 // iterator becomes invalid if you add edges to or from the node you're 591 // getting the edges of. 592 struct EdgeIterator : public std::iterator<std::forward_iterator_tag, 593 std::tuple<EdgeTypeT, Node *>> { 594 EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter) 595 : Current(Iter) {} 596 597 EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {} 598 599 EdgeIterator &operator++() { 600 ++Current; 601 return *this; 602 } 603 604 EdgeIterator operator++(int) { 605 EdgeIterator Copy(Current); 606 operator++(); 607 return Copy; 608 } 609 610 std::tuple<EdgeTypeT, Node> &operator*() { 611 Store = std::make_tuple(Current->Weight, Current->Other); 612 return Store; 613 } 614 615 bool operator==(const EdgeIterator &Other) const { 616 return Current == Other.Current; 617 } 618 619 bool operator!=(const EdgeIterator &Other) const { 620 return !operator==(Other); 621 } 622 623 private: 624 typename std::vector<Edge>::const_iterator Current; 625 std::tuple<EdgeTypeT, Node> Store; 626 }; 627 628 // Wrapper for EdgeIterator with begin()/end() calls. 629 struct EdgeIterable { 630 EdgeIterable(const std::vector<Edge> &Edges) 631 : BeginIter(Edges.begin()), EndIter(Edges.end()) {} 632 633 EdgeIterator begin() { return EdgeIterator(BeginIter); } 634 635 EdgeIterator end() { return EdgeIterator(EndIter); } 636 637 private: 638 typename std::vector<Edge>::const_iterator BeginIter; 639 typename std::vector<Edge>::const_iterator EndIter; 640 }; 641 642 // ----- Actual graph-related things ----- // 643 644 WeightedBidirectionalGraph() {} 645 646 WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other) 647 : NodeImpls(std::move(Other.NodeImpls)) {} 648 649 WeightedBidirectionalGraph<EdgeTypeT> & 650 operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) { 651 NodeImpls = std::move(Other.NodeImpls); 652 return *this; 653 } 654 655 Node addNode() { 656 auto Index = NodeImpls.size(); 657 auto NewNode = Node(Index); 658 NodeImpls.push_back(NodeImpl()); 659 return NewNode; 660 } 661 662 void addEdge(Node From, Node To, const EdgeTypeT &Weight, 663 const EdgeTypeT &ReverseWeight) { 664 assert(inbounds(From)); 665 assert(inbounds(To)); 666 auto &FromNode = getNode(From); 667 auto &ToNode = getNode(To); 668 FromNode.Edges.push_back(Edge(Weight, To)); 669 ToNode.Edges.push_back(Edge(ReverseWeight, From)); 670 } 671 672 EdgeIterable edgesFor(const Node &N) const { 673 const auto &Node = getNode(N); 674 return EdgeIterable(Node.Edges); 675 } 676 677 bool empty() const { return NodeImpls.empty(); } 678 std::size_t size() const { return NodeImpls.size(); } 679 680 // \brief Gets an arbitrary node in the graph as a starting point for 681 // traversal. 682 Node getEntryNode() { 683 assert(inbounds(StartNode)); 684 return StartNode; 685 } 686}; 687 688typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT; 689typedef DenseMap<Value *, GraphT::Node> NodeMapT; 690} 691 692// -- Setting up/registering CFLAA pass -- // 693char CFLAliasAnalysis::ID = 0; 694 695INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa", 696 "CFL-Based AA implementation", false, true, false) 697 698ImmutablePass *llvm::createCFLAliasAnalysisPass() { 699 return new CFLAliasAnalysis(); 700} 701 702//===----------------------------------------------------------------------===// 703// Function declarations that require types defined in the namespace above 704//===----------------------------------------------------------------------===// 705 706// Given an argument number, returns the appropriate Attr index to set. 707static StratifiedAttr argNumberToAttrIndex(StratifiedAttr); 708 709// Given a Value, potentially return which AttrIndex it maps to. 710static Optional<StratifiedAttr> valueToAttrIndex(Value *Val); 711 712// Gets the inverse of a given EdgeType. 713static EdgeType flipWeight(EdgeType); 714 715// Gets edges of the given Instruction*, writing them to the SmallVector*. 716static void argsToEdges(CFLAliasAnalysis &, Instruction *, 717 SmallVectorImpl<Edge> &); 718 719// Gets the "Level" that one should travel in StratifiedSets 720// given an EdgeType. 721static Level directionOfEdgeType(EdgeType); 722 723// Builds the graph needed for constructing the StratifiedSets for the 724// given function 725static void buildGraphFrom(CFLAliasAnalysis &, Function *, 726 SmallVectorImpl<Value *> &, NodeMapT &, GraphT &); 727 728// Builds the graph + StratifiedSets for a function. 729static FunctionInfo buildSetsFrom(CFLAliasAnalysis &, Function *); 730 731static Optional<Function *> parentFunctionOfValue(Value *Val) { 732 if (auto *Inst = dyn_cast<Instruction>(Val)) { 733 auto *Bb = Inst->getParent(); 734 return Bb->getParent(); 735 } 736 737 if (auto *Arg = dyn_cast<Argument>(Val)) 738 return Arg->getParent(); 739 return NoneType(); 740} 741 742template <typename Inst> 743static bool getPossibleTargets(Inst *Call, 744 SmallVectorImpl<Function *> &Output) { 745 if (auto *Fn = Call->getCalledFunction()) { 746 Output.push_back(Fn); 747 return true; 748 } 749 750 // TODO: If the call is indirect, we might be able to enumerate all potential 751 // targets of the call and return them, rather than just failing. 752 return false; 753} 754 755static Optional<Value *> getTargetValue(Instruction *Inst) { 756 GetTargetValueVisitor V; 757 return V.visit(Inst); 758} 759 760static bool hasUsefulEdges(Instruction *Inst) { 761 bool IsNonInvokeTerminator = 762 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst); 763 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator; 764} 765 766static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) { 767 if (isa<GlobalValue>(Val)) 768 return AttrGlobalIndex; 769 770 if (auto *Arg = dyn_cast<Argument>(Val)) 771 if (!Arg->hasNoAliasAttr()) 772 return argNumberToAttrIndex(Arg->getArgNo()); 773 return NoneType(); 774} 775 776static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) { 777 if (ArgNum > AttrMaxNumArgs) 778 return AttrAllIndex; 779 return ArgNum + AttrFirstArgIndex; 780} 781 782static EdgeType flipWeight(EdgeType Initial) { 783 switch (Initial) { 784 case EdgeType::Assign: 785 return EdgeType::Assign; 786 case EdgeType::Dereference: 787 return EdgeType::Reference; 788 case EdgeType::Reference: 789 return EdgeType::Dereference; 790 } 791 llvm_unreachable("Incomplete coverage of EdgeType enum"); 792} 793 794static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst, 795 SmallVectorImpl<Edge> &Output) { 796 GetEdgesVisitor v(Analysis, Output); 797 v.visit(Inst); 798} 799 800static Level directionOfEdgeType(EdgeType Weight) { 801 switch (Weight) { 802 case EdgeType::Reference: 803 return Level::Above; 804 case EdgeType::Dereference: 805 return Level::Below; 806 case EdgeType::Assign: 807 return Level::Same; 808 } 809 llvm_unreachable("Incomplete switch coverage"); 810} 811 812// Aside: We may remove graph construction entirely, because it doesn't really 813// buy us much that we don't already have. I'd like to add interprocedural 814// analysis prior to this however, in case that somehow requires the graph 815// produced by this for efficient execution 816static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn, 817 SmallVectorImpl<Value *> &ReturnedValues, 818 NodeMapT &Map, GraphT &Graph) { 819 const auto findOrInsertNode = [&Map, &Graph](Value *Val) { 820 auto Pair = Map.insert(std::make_pair(Val, GraphT::Node())); 821 auto &Iter = Pair.first; 822 if (Pair.second) { 823 auto NewNode = Graph.addNode(); 824 Iter->second = NewNode; 825 } 826 return Iter->second; 827 }; 828 829 SmallVector<Edge, 8> Edges; 830 for (auto &Bb : Fn->getBasicBlockList()) { 831 for (auto &Inst : Bb.getInstList()) { 832 // We don't want the edges of most "return" instructions, but we *do* want 833 // to know what can be returned. 834 if (auto *Ret = dyn_cast<ReturnInst>(&Inst)) 835 ReturnedValues.push_back(Ret); 836 837 if (!hasUsefulEdges(&Inst)) 838 continue; 839 840 Edges.clear(); 841 argsToEdges(Analysis, &Inst, Edges); 842 843 // In the case of an unused alloca (or similar), edges may be empty. Note 844 // that it exists so we can potentially answer NoAlias. 845 if (Edges.empty()) { 846 auto MaybeVal = getTargetValue(&Inst); 847 assert(MaybeVal.hasValue()); 848 auto *Target = *MaybeVal; 849 findOrInsertNode(Target); 850 continue; 851 } 852 853 for (const Edge &E : Edges) { 854 auto To = findOrInsertNode(E.To); 855 auto From = findOrInsertNode(E.From); 856 auto FlippedWeight = flipWeight(E.Weight); 857 auto Attrs = E.AdditionalAttrs; 858 Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs), 859 std::make_pair(FlippedWeight, Attrs)); 860 } 861 } 862 } 863} 864 865static FunctionInfo buildSetsFrom(CFLAliasAnalysis &Analysis, Function *Fn) { 866 NodeMapT Map; 867 GraphT Graph; 868 SmallVector<Value *, 4> ReturnedValues; 869 870 buildGraphFrom(Analysis, Fn, ReturnedValues, Map, Graph); 871 872 DenseMap<GraphT::Node, Value *> NodeValueMap; 873 NodeValueMap.resize(Map.size()); 874 for (const auto &Pair : Map) 875 NodeValueMap.insert(std::make_pair(Pair.second, Pair.first)); 876 877 const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) { 878 auto ValIter = NodeValueMap.find(Node); 879 assert(ValIter != NodeValueMap.end()); 880 return ValIter->second; 881 }; 882 883 StratifiedSetsBuilder<Value *> Builder; 884 885 SmallVector<GraphT::Node, 16> Worklist; 886 for (auto &Pair : Map) { 887 Worklist.clear(); 888 889 auto *Value = Pair.first; 890 Builder.add(Value); 891 auto InitialNode = Pair.second; 892 Worklist.push_back(InitialNode); 893 while (!Worklist.empty()) { 894 auto Node = Worklist.pop_back_val(); 895 auto *CurValue = findValueOrDie(Node); 896 if (isa<Constant>(CurValue) && !isa<GlobalValue>(CurValue)) 897 continue; 898 899 for (const auto &EdgeTuple : Graph.edgesFor(Node)) { 900 auto Weight = std::get<0>(EdgeTuple); 901 auto Label = Weight.first; 902 auto &OtherNode = std::get<1>(EdgeTuple); 903 auto *OtherValue = findValueOrDie(OtherNode); 904 905 if (isa<Constant>(OtherValue) && !isa<GlobalValue>(OtherValue)) 906 continue; 907 908 bool Added; 909 switch (directionOfEdgeType(Label)) { 910 case Level::Above: 911 Added = Builder.addAbove(CurValue, OtherValue); 912 break; 913 case Level::Below: 914 Added = Builder.addBelow(CurValue, OtherValue); 915 break; 916 case Level::Same: 917 Added = Builder.addWith(CurValue, OtherValue); 918 break; 919 } 920 921 if (Added) { 922 auto Aliasing = Weight.second; 923 if (auto MaybeCurIndex = valueToAttrIndex(CurValue)) 924 Aliasing.set(*MaybeCurIndex); 925 if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue)) 926 Aliasing.set(*MaybeOtherIndex); 927 Builder.noteAttributes(CurValue, Aliasing); 928 Builder.noteAttributes(OtherValue, Aliasing); 929 Worklist.push_back(OtherNode); 930 } 931 } 932 } 933 } 934 935 // There are times when we end up with parameters not in our graph (i.e. if 936 // it's only used as the condition of a branch). Other bits of code depend on 937 // things that were present during construction being present in the graph. 938 // So, we add all present arguments here. 939 for (auto &Arg : Fn->args()) { 940 Builder.add(&Arg); 941 } 942 943 return FunctionInfo(Builder.build(), std::move(ReturnedValues)); 944} 945 946void CFLAliasAnalysis::scan(Function *Fn) { 947 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>())); 948 (void)InsertPair; 949 assert(InsertPair.second && 950 "Trying to scan a function that has already been cached"); 951 952 FunctionInfo Info(buildSetsFrom(*this, Fn)); 953 Cache[Fn] = std::move(Info); 954 Handles.push_front(FunctionHandle(Fn, this)); 955} 956 957AliasAnalysis::AliasResult 958CFLAliasAnalysis::query(const AliasAnalysis::Location &LocA, 959 const AliasAnalysis::Location &LocB) { 960 auto *ValA = const_cast<Value *>(LocA.Ptr); 961 auto *ValB = const_cast<Value *>(LocB.Ptr); 962 963 Function *Fn = nullptr; 964 auto MaybeFnA = parentFunctionOfValue(ValA); 965 auto MaybeFnB = parentFunctionOfValue(ValB); 966 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) { 967 llvm_unreachable("Don't know how to extract the parent function " 968 "from values A or B"); 969 } 970 971 if (MaybeFnA.hasValue()) { 972 Fn = *MaybeFnA; 973 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) && 974 "Interprocedural queries not supported"); 975 } else { 976 Fn = *MaybeFnB; 977 } 978 979 assert(Fn != nullptr); 980 auto &MaybeInfo = ensureCached(Fn); 981 assert(MaybeInfo.hasValue()); 982 983 auto &Sets = MaybeInfo->Sets; 984 auto MaybeA = Sets.find(ValA); 985 if (!MaybeA.hasValue()) 986 return AliasAnalysis::MayAlias; 987 988 auto MaybeB = Sets.find(ValB); 989 if (!MaybeB.hasValue()) 990 return AliasAnalysis::MayAlias; 991 992 auto SetA = *MaybeA; 993 auto SetB = *MaybeB; 994 995 if (SetA.Index == SetB.Index) 996 return AliasAnalysis::PartialAlias; 997 998 auto AttrsA = Sets.getLink(SetA.Index).Attrs; 999 auto AttrsB = Sets.getLink(SetB.Index).Attrs; 1000 // Stratified set attributes are used as markets to signify whether a member 1001 // of a StratifiedSet (or a member of a set above the current set) has 1002 // interacted with either arguments or globals. "Interacted with" meaning 1003 // its value may be different depending on the value of an argument or 1004 // global. The thought behind this is that, because arguments and globals 1005 // may alias each other, if AttrsA and AttrsB have touched args/globals, 1006 // we must conservatively say that they alias. However, if at least one of 1007 // the sets has no values that could legally be altered by changing the value 1008 // of an argument or global, then we don't have to be as conservative. 1009 if (AttrsA.any() && AttrsB.any()) 1010 return AliasAnalysis::MayAlias; 1011 1012 return AliasAnalysis::NoAlias; 1013} 1014