CFLAliasAnalysis.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  1. //===- CFLAliasAnalysis.cpp - CFL-Based Alias Analysis Implementation ------==//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements a CFL-based context-insensitive alias analysis
  11. // algorithm. It does not depend on types. The algorithm is a mixture of the one
  12. // described in "Demand-driven alias analysis for C" by Xin Zheng and Radu
  13. // Rugina, and "Fast algorithms for Dyck-CFL-reachability with applications to
  14. // Alias Analysis" by Zhang Q, Lyu M R, Yuan H, and Su Z. -- to summarize the
  15. // papers, we build a graph of the uses of a variable, where each node is a
  16. // memory location, and each edge is an action that happened on that memory
  17. // location. The "actions" can be one of Dereference, Reference, or Assign.
  18. //
  19. // Two variables are considered as aliasing iff you can reach one value's node
  20. // from the other value's node and the language formed by concatenating all of
  21. // the edge labels (actions) conforms to a context-free grammar.
  22. //
  23. // Because this algorithm requires a graph search on each query, we execute the
  24. // algorithm outlined in "Fast algorithms..." (mentioned above)
  25. // in order to transform the graph into sets of variables that may alias in
  26. // ~nlogn time (n = number of variables.), which makes queries take constant
  27. // time.
  28. //===----------------------------------------------------------------------===//
  29. #include "StratifiedSets.h"
  30. #include "llvm/ADT/BitVector.h"
  31. #include "llvm/ADT/DenseMap.h"
  32. #include "llvm/ADT/None.h"
  33. #include "llvm/ADT/Optional.h"
  34. #include "llvm/Analysis/AliasAnalysis.h"
  35. #include "llvm/Analysis/Passes.h"
  36. #include "llvm/IR/Constants.h"
  37. #include "llvm/IR/Function.h"
  38. #include "llvm/IR/InstVisitor.h"
  39. #include "llvm/IR/Instructions.h"
  40. #include "llvm/IR/ValueHandle.h"
  41. #include "llvm/Pass.h"
  42. #include "llvm/Support/Allocator.h"
  43. #include "llvm/Support/Compiler.h"
  44. #include "llvm/Support/Debug.h"
  45. #include "llvm/Support/ErrorHandling.h"
  46. #include "llvm/Support/raw_ostream.h"
  47. #include <algorithm>
  48. #include <cassert>
  49. #include <forward_list>
  50. #include <memory>
  51. #include <tuple>
  52. using namespace llvm;
  53. #define DEBUG_TYPE "cfl-aa"
  54. // Try to go from a Value* to a Function*. Never returns nullptr.
  55. static Optional<Function *> parentFunctionOfValue(Value *);
  56. // Returns possible functions called by the Inst* into the given
  57. // SmallVectorImpl. Returns true if targets found, false otherwise.
  58. // This is templated because InvokeInst/CallInst give us the same
  59. // set of functions that we care about, and I don't like repeating
  60. // myself.
  61. template <typename Inst>
  62. static bool getPossibleTargets(Inst *, SmallVectorImpl<Function *> &);
  63. // Some instructions need to have their users tracked. Instructions like
  64. // `add` require you to get the users of the Instruction* itself, other
  65. // instructions like `store` require you to get the users of the first
  66. // operand. This function gets the "proper" value to track for each
  67. // type of instruction we support.
  68. static Optional<Value *> getTargetValue(Instruction *);
  69. // There are certain instructions (i.e. FenceInst, etc.) that we ignore.
  70. // This notes that we should ignore those.
  71. static bool hasUsefulEdges(Instruction *);
  72. const StratifiedIndex StratifiedLink::SetSentinel =
  73. std::numeric_limits<StratifiedIndex>::max();
  74. namespace {
  75. // StratifiedInfo Attribute things.
  76. typedef unsigned StratifiedAttr;
  77. LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
  78. LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
  79. LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
  80. LLVM_CONSTEXPR unsigned AttrUnknownIndex = 2;
  81. LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 3;
  82. LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
  83. LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
  84. LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
  85. LLVM_CONSTEXPR StratifiedAttr AttrUnknown = 1 << AttrUnknownIndex;
  86. LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
  87. // \brief StratifiedSets call for knowledge of "direction", so this is how we
  88. // represent that locally.
  89. enum class Level { Same, Above, Below };
  90. // \brief Edges can be one of four "weights" -- each weight must have an inverse
  91. // weight (Assign has Assign; Reference has Dereference).
  92. enum class EdgeType {
  93. // The weight assigned when assigning from or to a value. For example, in:
  94. // %b = getelementptr %a, 0
  95. // ...The relationships are %b assign %a, and %a assign %b. This used to be
  96. // two edges, but having a distinction bought us nothing.
  97. Assign,
  98. // The edge used when we have an edge going from some handle to a Value.
  99. // Examples of this include:
  100. // %b = load %a (%b Dereference %a)
  101. // %b = extractelement %a, 0 (%a Dereference %b)
  102. Dereference,
  103. // The edge used when our edge goes from a value to a handle that may have
  104. // contained it at some point. Examples:
  105. // %b = load %a (%a Reference %b)
  106. // %b = extractelement %a, 0 (%b Reference %a)
  107. Reference
  108. };
  109. // \brief Encodes the notion of a "use"
  110. struct Edge {
  111. // \brief Which value the edge is coming from
  112. Value *From;
  113. // \brief Which value the edge is pointing to
  114. Value *To;
  115. // \brief Edge weight
  116. EdgeType Weight;
  117. // \brief Whether we aliased any external values along the way that may be
  118. // invisible to the analysis (i.e. landingpad for exceptions, calls for
  119. // interprocedural analysis, etc.)
  120. StratifiedAttrs AdditionalAttrs;
  121. Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
  122. : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
  123. };
  124. // \brief Information we have about a function and would like to keep around
  125. struct FunctionInfo {
  126. StratifiedSets<Value *> Sets;
  127. // Lots of functions have < 4 returns. Adjust as necessary.
  128. SmallVector<Value *, 4> ReturnedValues;
  129. FunctionInfo(StratifiedSets<Value *> &&S, SmallVector<Value *, 4> &&RV)
  130. : Sets(std::move(S)), ReturnedValues(std::move(RV)) {}
  131. };
  132. struct CFLAliasAnalysis;
  133. struct FunctionHandle : public CallbackVH {
  134. FunctionHandle(Function *Fn, CFLAliasAnalysis *CFLAA)
  135. : CallbackVH(Fn), CFLAA(CFLAA) {
  136. assert(Fn != nullptr);
  137. assert(CFLAA != nullptr);
  138. }
  139. ~FunctionHandle() override {}
  140. void deleted() override { removeSelfFromCache(); }
  141. void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }
  142. private:
  143. CFLAliasAnalysis *CFLAA;
  144. void removeSelfFromCache();
  145. };
  146. struct CFLAliasAnalysis : public ImmutablePass, public AliasAnalysis {
  147. private:
  148. /// \brief Cached mapping of Functions to their StratifiedSets.
  149. /// If a function's sets are currently being built, it is marked
  150. /// in the cache as an Optional without a value. This way, if we
  151. /// have any kind of recursion, it is discernable from a function
  152. /// that simply has empty sets.
  153. DenseMap<Function *, Optional<FunctionInfo>> Cache;
  154. std::forward_list<FunctionHandle> Handles;
  155. public:
  156. static char ID;
  157. CFLAliasAnalysis() : ImmutablePass(ID) {
  158. initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
  159. }
  160. ~CFLAliasAnalysis() override {}
  161. void getAnalysisUsage(AnalysisUsage &AU) const override {
  162. AliasAnalysis::getAnalysisUsage(AU);
  163. }
  164. void *getAdjustedAnalysisPointer(const void *ID) override {
  165. if (ID == &AliasAnalysis::ID)
  166. return (AliasAnalysis *)this;
  167. return this;
  168. }
  169. /// \brief Inserts the given Function into the cache.
  170. void scan(Function *Fn);
  171. void evict(Function *Fn) { Cache.erase(Fn); }
  172. /// \brief Ensures that the given function is available in the cache.
  173. /// Returns the appropriate entry from the cache.
  174. const Optional<FunctionInfo> &ensureCached(Function *Fn) {
  175. auto Iter = Cache.find(Fn);
  176. if (Iter == Cache.end()) {
  177. scan(Fn);
  178. Iter = Cache.find(Fn);
  179. assert(Iter != Cache.end());
  180. assert(Iter->second.hasValue());
  181. }
  182. return Iter->second;
  183. }
  184. AliasResult query(const MemoryLocation &LocA, const MemoryLocation &LocB);
  185. AliasResult alias(const MemoryLocation &LocA,
  186. const MemoryLocation &LocB) override {
  187. if (LocA.Ptr == LocB.Ptr) {
  188. if (LocA.Size == LocB.Size) {
  189. return MustAlias;
  190. } else {
  191. return PartialAlias;
  192. }
  193. }
  194. // Comparisons between global variables and other constants should be
  195. // handled by BasicAA.
  196. // TODO: ConstantExpr handling -- CFLAA may report NoAlias when comparing
  197. // a GlobalValue and ConstantExpr, but every query needs to have at least
  198. // one Value tied to a Function, and neither GlobalValues nor ConstantExprs
  199. // are.
  200. if (isa<Constant>(LocA.Ptr) && isa<Constant>(LocB.Ptr)) {
  201. return AliasAnalysis::alias(LocA, LocB);
  202. }
  203. AliasResult QueryResult = query(LocA, LocB);
  204. if (QueryResult == MayAlias)
  205. return AliasAnalysis::alias(LocA, LocB);
  206. return QueryResult;
  207. }
  208. bool doInitialization(Module &M) override;
  209. };
  210. void FunctionHandle::removeSelfFromCache() {
  211. assert(CFLAA != nullptr);
  212. auto *Val = getValPtr();
  213. CFLAA->evict(cast<Function>(Val));
  214. setValPtr(nullptr);
  215. }
  216. // \brief Gets the edges our graph should have, based on an Instruction*
  217. class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
  218. CFLAliasAnalysis &AA;
  219. SmallVectorImpl<Edge> &Output;
  220. public:
  221. GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
  222. : AA(AA), Output(Output) {}
  223. void visitInstruction(Instruction &) {
  224. llvm_unreachable("Unsupported instruction encountered");
  225. }
  226. void visitPtrToIntInst(PtrToIntInst &Inst) {
  227. auto *Ptr = Inst.getOperand(0);
  228. Output.push_back(Edge(Ptr, Ptr, EdgeType::Assign, AttrUnknown));
  229. }
  230. void visitIntToPtrInst(IntToPtrInst &Inst) {
  231. auto *Ptr = &Inst;
  232. Output.push_back(Edge(Ptr, Ptr, EdgeType::Assign, AttrUnknown));
  233. }
  234. void visitCastInst(CastInst &Inst) {
  235. Output.push_back(
  236. Edge(&Inst, Inst.getOperand(0), EdgeType::Assign, AttrNone));
  237. }
  238. void visitBinaryOperator(BinaryOperator &Inst) {
  239. auto *Op1 = Inst.getOperand(0);
  240. auto *Op2 = Inst.getOperand(1);
  241. Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
  242. Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
  243. }
  244. void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
  245. auto *Ptr = Inst.getPointerOperand();
  246. auto *Val = Inst.getNewValOperand();
  247. Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
  248. }
  249. void visitAtomicRMWInst(AtomicRMWInst &Inst) {
  250. auto *Ptr = Inst.getPointerOperand();
  251. auto *Val = Inst.getValOperand();
  252. Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
  253. }
  254. void visitPHINode(PHINode &Inst) {
  255. for (Value *Val : Inst.incoming_values()) {
  256. Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
  257. }
  258. }
  259. void visitGetElementPtrInst(GetElementPtrInst &Inst) {
  260. auto *Op = Inst.getPointerOperand();
  261. Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
  262. for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
  263. Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
  264. }
  265. void visitSelectInst(SelectInst &Inst) {
  266. // Condition is not processed here (The actual statement producing
  267. // the condition result is processed elsewhere). For select, the
  268. // condition is evaluated, but not loaded, stored, or assigned
  269. // simply as a result of being the condition of a select.
  270. auto *TrueVal = Inst.getTrueValue();
  271. Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
  272. auto *FalseVal = Inst.getFalseValue();
  273. Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
  274. }
  275. void visitAllocaInst(AllocaInst &) {}
  276. void visitLoadInst(LoadInst &Inst) {
  277. auto *Ptr = Inst.getPointerOperand();
  278. auto *Val = &Inst;
  279. Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
  280. }
  281. void visitStoreInst(StoreInst &Inst) {
  282. auto *Ptr = Inst.getPointerOperand();
  283. auto *Val = Inst.getValueOperand();
  284. Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
  285. }
  286. void visitVAArgInst(VAArgInst &Inst) {
  287. // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
  288. // two things:
  289. // 1. Loads a value from *((T*)*Ptr).
  290. // 2. Increments (stores to) *Ptr by some target-specific amount.
  291. // For now, we'll handle this like a landingpad instruction (by placing the
  292. // result in its own group, and having that group alias externals).
  293. auto *Val = &Inst;
  294. Output.push_back(Edge(Val, Val, EdgeType::Assign, AttrAll));
  295. }
  296. static bool isFunctionExternal(Function *Fn) {
  297. return Fn->isDeclaration() || !Fn->hasLocalLinkage();
  298. }
  299. // Gets whether the sets at Index1 above, below, or equal to the sets at
  300. // Index2. Returns None if they are not in the same set chain.
  301. static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
  302. StratifiedIndex Index1,
  303. StratifiedIndex Index2) {
  304. if (Index1 == Index2)
  305. return Level::Same;
  306. const auto *Current = &Sets.getLink(Index1);
  307. while (Current->hasBelow()) {
  308. if (Current->Below == Index2)
  309. return Level::Below;
  310. Current = &Sets.getLink(Current->Below);
  311. }
  312. Current = &Sets.getLink(Index1);
  313. while (Current->hasAbove()) {
  314. if (Current->Above == Index2)
  315. return Level::Above;
  316. Current = &Sets.getLink(Current->Above);
  317. }
  318. return NoneType();
  319. }
  320. bool
  321. tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
  322. Value *FuncValue,
  323. const iterator_range<User::op_iterator> &Args) {
  324. const unsigned ExpectedMaxArgs = 8;
  325. const unsigned MaxSupportedArgs = 50;
  326. assert(Fns.size() > 0);
  327. // I put this here to give us an upper bound on time taken by IPA. Is it
  328. // really (realistically) needed? Keep in mind that we do have an n^2 algo.
  329. if (std::distance(Args.begin(), Args.end()) > (int)MaxSupportedArgs)
  330. return false;
  331. // Exit early if we'll fail anyway
  332. for (auto *Fn : Fns) {
  333. if (isFunctionExternal(Fn) || Fn->isVarArg())
  334. return false;
  335. auto &MaybeInfo = AA.ensureCached(Fn);
  336. if (!MaybeInfo.hasValue())
  337. return false;
  338. }
  339. SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
  340. SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
  341. for (auto *Fn : Fns) {
  342. auto &Info = *AA.ensureCached(Fn);
  343. auto &Sets = Info.Sets;
  344. auto &RetVals = Info.ReturnedValues;
  345. Parameters.clear();
  346. for (auto &Param : Fn->args()) {
  347. auto MaybeInfo = Sets.find(&Param);
  348. // Did a new parameter somehow get added to the function/slip by?
  349. if (!MaybeInfo.hasValue())
  350. return false;
  351. Parameters.push_back(*MaybeInfo);
  352. }
  353. // Adding an edge from argument -> return value for each parameter that
  354. // may alias the return value
  355. for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
  356. auto &ParamInfo = Parameters[I];
  357. auto &ArgVal = Arguments[I];
  358. bool AddEdge = false;
  359. StratifiedAttrs Externals;
  360. for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
  361. auto MaybeInfo = Sets.find(RetVals[X]);
  362. if (!MaybeInfo.hasValue())
  363. return false;
  364. auto &RetInfo = *MaybeInfo;
  365. auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
  366. auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
  367. auto MaybeRelation =
  368. getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
  369. if (MaybeRelation.hasValue()) {
  370. AddEdge = true;
  371. Externals |= RetAttrs | ParamAttrs;
  372. }
  373. }
  374. if (AddEdge)
  375. Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
  376. StratifiedAttrs().flip()));
  377. }
  378. if (Parameters.size() != Arguments.size())
  379. return false;
  380. // Adding edges between arguments for arguments that may end up aliasing
  381. // each other. This is necessary for functions such as
  382. // void foo(int** a, int** b) { *a = *b; }
  383. // (Technically, the proper sets for this would be those below
  384. // Arguments[I] and Arguments[X], but our algorithm will produce
  385. // extremely similar, and equally correct, results either way)
  386. for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
  387. auto &MainVal = Arguments[I];
  388. auto &MainInfo = Parameters[I];
  389. auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
  390. for (unsigned X = I + 1; X != E; ++X) {
  391. auto &SubInfo = Parameters[X];
  392. auto &SubVal = Arguments[X];
  393. auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
  394. auto MaybeRelation =
  395. getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
  396. if (!MaybeRelation.hasValue())
  397. continue;
  398. auto NewAttrs = SubAttrs | MainAttrs;
  399. Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
  400. }
  401. }
  402. }
  403. return true;
  404. }
  405. template <typename InstT> void visitCallLikeInst(InstT &Inst) {
  406. SmallVector<Function *, 4> Targets;
  407. if (getPossibleTargets(&Inst, Targets)) {
  408. if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
  409. return;
  410. // Cleanup from interprocedural analysis
  411. Output.clear();
  412. }
  413. for (Value *V : Inst.arg_operands())
  414. Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
  415. }
  416. void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
  417. void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
  418. // Because vectors/aggregates are immutable and unaddressable,
  419. // there's nothing we can do to coax a value out of them, other
  420. // than calling Extract{Element,Value}. We can effectively treat
  421. // them as pointers to arbitrary memory locations we can store in
  422. // and load from.
  423. void visitExtractElementInst(ExtractElementInst &Inst) {
  424. auto *Ptr = Inst.getVectorOperand();
  425. auto *Val = &Inst;
  426. Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
  427. }
  428. void visitInsertElementInst(InsertElementInst &Inst) {
  429. auto *Vec = Inst.getOperand(0);
  430. auto *Val = Inst.getOperand(1);
  431. Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
  432. Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
  433. }
  434. void visitLandingPadInst(LandingPadInst &Inst) {
  435. // Exceptions come from "nowhere", from our analysis' perspective.
  436. // So we place the instruction its own group, noting that said group may
  437. // alias externals
  438. Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
  439. }
  440. void visitInsertValueInst(InsertValueInst &Inst) {
  441. auto *Agg = Inst.getOperand(0);
  442. auto *Val = Inst.getOperand(1);
  443. Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
  444. Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
  445. }
  446. void visitExtractValueInst(ExtractValueInst &Inst) {
  447. auto *Ptr = Inst.getAggregateOperand();
  448. Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
  449. }
  450. void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
  451. auto *From1 = Inst.getOperand(0);
  452. auto *From2 = Inst.getOperand(1);
  453. Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
  454. Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
  455. }
  456. void visitConstantExpr(ConstantExpr *CE) {
  457. switch (CE->getOpcode()) {
  458. default:
  459. llvm_unreachable("Unknown instruction type encountered!");
  460. // Build the switch statement using the Instruction.def file.
  461. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  462. case Instruction::OPCODE: \
  463. visit##OPCODE(*(CLASS *)CE); \
  464. break;
  465. #include "llvm/IR/Instruction.def"
  466. }
  467. }
  468. };
  469. // For a given instruction, we need to know which Value* to get the
  470. // users of in order to build our graph. In some cases (i.e. add),
  471. // we simply need the Instruction*. In other cases (i.e. store),
  472. // finding the users of the Instruction* is useless; we need to find
  473. // the users of the first operand. This handles determining which
  474. // value to follow for us.
  475. //
  476. // Note: we *need* to keep this in sync with GetEdgesVisitor. Add
  477. // something to GetEdgesVisitor, add it here -- remove something from
  478. // GetEdgesVisitor, remove it here.
  479. class GetTargetValueVisitor
  480. : public InstVisitor<GetTargetValueVisitor, Value *> {
  481. public:
  482. Value *visitInstruction(Instruction &Inst) { return &Inst; }
  483. Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
  484. Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
  485. return Inst.getPointerOperand();
  486. }
  487. Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
  488. return Inst.getPointerOperand();
  489. }
  490. Value *visitInsertElementInst(InsertElementInst &Inst) {
  491. return Inst.getOperand(0);
  492. }
  493. Value *visitInsertValueInst(InsertValueInst &Inst) {
  494. return Inst.getAggregateOperand();
  495. }
  496. };
  497. // Set building requires a weighted bidirectional graph.
  498. template <typename EdgeTypeT> class WeightedBidirectionalGraph {
  499. public:
  500. typedef std::size_t Node;
  501. private:
  502. const static Node StartNode = Node(0);
  503. struct Edge {
  504. EdgeTypeT Weight;
  505. Node Other;
  506. Edge(const EdgeTypeT &W, const Node &N) : Weight(W), Other(N) {}
  507. bool operator==(const Edge &E) const {
  508. return Weight == E.Weight && Other == E.Other;
  509. }
  510. bool operator!=(const Edge &E) const { return !operator==(E); }
  511. };
  512. struct NodeImpl {
  513. std::vector<Edge> Edges;
  514. };
  515. std::vector<NodeImpl> NodeImpls;
  516. bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
  517. const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
  518. NodeImpl &getNode(Node N) { return NodeImpls[N]; }
  519. public:
  520. // ----- Various Edge iterators for the graph ----- //
  521. // \brief Iterator for edges. Because this graph is bidirected, we don't
  522. // allow modificaiton of the edges using this iterator. Additionally, the
  523. // iterator becomes invalid if you add edges to or from the node you're
  524. // getting the edges of.
  525. struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
  526. std::tuple<EdgeTypeT, Node *>> {
  527. EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
  528. : Current(Iter) {}
  529. EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
  530. EdgeIterator &operator++() {
  531. ++Current;
  532. return *this;
  533. }
  534. EdgeIterator operator++(int) {
  535. EdgeIterator Copy(Current);
  536. operator++();
  537. return Copy;
  538. }
  539. std::tuple<EdgeTypeT, Node> &operator*() {
  540. Store = std::make_tuple(Current->Weight, Current->Other);
  541. return Store;
  542. }
  543. bool operator==(const EdgeIterator &Other) const {
  544. return Current == Other.Current;
  545. }
  546. bool operator!=(const EdgeIterator &Other) const {
  547. return !operator==(Other);
  548. }
  549. private:
  550. typename std::vector<Edge>::const_iterator Current;
  551. std::tuple<EdgeTypeT, Node> Store;
  552. };
  553. // Wrapper for EdgeIterator with begin()/end() calls.
  554. struct EdgeIterable {
  555. EdgeIterable(const std::vector<Edge> &Edges)
  556. : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
  557. EdgeIterator begin() { return EdgeIterator(BeginIter); }
  558. EdgeIterator end() { return EdgeIterator(EndIter); }
  559. private:
  560. typename std::vector<Edge>::const_iterator BeginIter;
  561. typename std::vector<Edge>::const_iterator EndIter;
  562. };
  563. // ----- Actual graph-related things ----- //
  564. WeightedBidirectionalGraph() {}
  565. WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
  566. : NodeImpls(std::move(Other.NodeImpls)) {}
  567. WeightedBidirectionalGraph<EdgeTypeT> &
  568. operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
  569. NodeImpls = std::move(Other.NodeImpls);
  570. return *this;
  571. }
  572. Node addNode() {
  573. auto Index = NodeImpls.size();
  574. auto NewNode = Node(Index);
  575. NodeImpls.push_back(NodeImpl());
  576. return NewNode;
  577. }
  578. void addEdge(Node From, Node To, const EdgeTypeT &Weight,
  579. const EdgeTypeT &ReverseWeight) {
  580. assert(inbounds(From));
  581. assert(inbounds(To));
  582. auto &FromNode = getNode(From);
  583. auto &ToNode = getNode(To);
  584. FromNode.Edges.push_back(Edge(Weight, To));
  585. ToNode.Edges.push_back(Edge(ReverseWeight, From));
  586. }
  587. EdgeIterable edgesFor(const Node &N) const {
  588. const auto &Node = getNode(N);
  589. return EdgeIterable(Node.Edges);
  590. }
  591. bool empty() const { return NodeImpls.empty(); }
  592. std::size_t size() const { return NodeImpls.size(); }
  593. // \brief Gets an arbitrary node in the graph as a starting point for
  594. // traversal.
  595. Node getEntryNode() {
  596. assert(inbounds(StartNode));
  597. return StartNode;
  598. }
  599. };
  600. typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
  601. typedef DenseMap<Value *, GraphT::Node> NodeMapT;
  602. }
  603. // -- Setting up/registering CFLAA pass -- //
  604. char CFLAliasAnalysis::ID = 0;
  605. INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
  606. "CFL-Based AA implementation", false, true, false)
  607. ImmutablePass *llvm::createCFLAliasAnalysisPass() {
  608. return new CFLAliasAnalysis();
  609. }
  610. //===----------------------------------------------------------------------===//
  611. // Function declarations that require types defined in the namespace above
  612. //===----------------------------------------------------------------------===//
  613. // Given an argument number, returns the appropriate Attr index to set.
  614. static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
  615. // Given a Value, potentially return which AttrIndex it maps to.
  616. static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
  617. // Gets the inverse of a given EdgeType.
  618. static EdgeType flipWeight(EdgeType);
  619. // Gets edges of the given Instruction*, writing them to the SmallVector*.
  620. static void argsToEdges(CFLAliasAnalysis &, Instruction *,
  621. SmallVectorImpl<Edge> &);
  622. // Gets edges of the given ConstantExpr*, writing them to the SmallVector*.
  623. static void argsToEdges(CFLAliasAnalysis &, ConstantExpr *,
  624. SmallVectorImpl<Edge> &);
  625. // Gets the "Level" that one should travel in StratifiedSets
  626. // given an EdgeType.
  627. static Level directionOfEdgeType(EdgeType);
  628. // Builds the graph needed for constructing the StratifiedSets for the
  629. // given function
  630. static void buildGraphFrom(CFLAliasAnalysis &, Function *,
  631. SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
  632. // Gets the edges of a ConstantExpr as if it was an Instruction. This
  633. // function also acts on any nested ConstantExprs, adding the edges
  634. // of those to the given SmallVector as well.
  635. static void constexprToEdges(CFLAliasAnalysis &, ConstantExpr &,
  636. SmallVectorImpl<Edge> &);
  637. // Given an Instruction, this will add it to the graph, along with any
  638. // Instructions that are potentially only available from said Instruction
  639. // For example, given the following line:
  640. // %0 = load i16* getelementptr ([1 x i16]* @a, 0, 0), align 2
  641. // addInstructionToGraph would add both the `load` and `getelementptr`
  642. // instructions to the graph appropriately.
  643. static void addInstructionToGraph(CFLAliasAnalysis &, Instruction &,
  644. SmallVectorImpl<Value *> &, NodeMapT &,
  645. GraphT &);
  646. // Notes whether it would be pointless to add the given Value to our sets.
  647. static bool canSkipAddingToSets(Value *Val);
  648. // Builds the graph + StratifiedSets for a function.
  649. static FunctionInfo buildSetsFrom(CFLAliasAnalysis &, Function *);
  650. static Optional<Function *> parentFunctionOfValue(Value *Val) {
  651. if (auto *Inst = dyn_cast<Instruction>(Val)) {
  652. auto *Bb = Inst->getParent();
  653. return Bb->getParent();
  654. }
  655. if (auto *Arg = dyn_cast<Argument>(Val))
  656. return Arg->getParent();
  657. return NoneType();
  658. }
  659. template <typename Inst>
  660. static bool getPossibleTargets(Inst *Call,
  661. SmallVectorImpl<Function *> &Output) {
  662. if (auto *Fn = Call->getCalledFunction()) {
  663. Output.push_back(Fn);
  664. return true;
  665. }
  666. // TODO: If the call is indirect, we might be able to enumerate all potential
  667. // targets of the call and return them, rather than just failing.
  668. return false;
  669. }
  670. static Optional<Value *> getTargetValue(Instruction *Inst) {
  671. GetTargetValueVisitor V;
  672. return V.visit(Inst);
  673. }
  674. static bool hasUsefulEdges(Instruction *Inst) {
  675. bool IsNonInvokeTerminator =
  676. isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
  677. return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
  678. }
  679. static bool hasUsefulEdges(ConstantExpr *CE) {
  680. // ConstantExpr doens't have terminators, invokes, or fences, so only needs
  681. // to check for compares.
  682. return CE->getOpcode() != Instruction::ICmp &&
  683. CE->getOpcode() != Instruction::FCmp;
  684. }
  685. static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
  686. if (isa<GlobalValue>(Val))
  687. return AttrGlobalIndex;
  688. if (auto *Arg = dyn_cast<Argument>(Val))
  689. // Only pointer arguments should have the argument attribute,
  690. // because things can't escape through scalars without us seeing a
  691. // cast, and thus, interaction with them doesn't matter.
  692. if (!Arg->hasNoAliasAttr() && Arg->getType()->isPointerTy())
  693. return argNumberToAttrIndex(Arg->getArgNo());
  694. return NoneType();
  695. }
  696. static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
  697. if (ArgNum >= AttrMaxNumArgs)
  698. return AttrAllIndex;
  699. return ArgNum + AttrFirstArgIndex;
  700. }
  701. static EdgeType flipWeight(EdgeType Initial) {
  702. switch (Initial) {
  703. case EdgeType::Assign:
  704. return EdgeType::Assign;
  705. case EdgeType::Dereference:
  706. return EdgeType::Reference;
  707. case EdgeType::Reference:
  708. return EdgeType::Dereference;
  709. }
  710. llvm_unreachable("Incomplete coverage of EdgeType enum");
  711. }
  712. static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
  713. SmallVectorImpl<Edge> &Output) {
  714. assert(hasUsefulEdges(Inst) &&
  715. "Expected instructions to have 'useful' edges");
  716. GetEdgesVisitor v(Analysis, Output);
  717. v.visit(Inst);
  718. }
  719. static void argsToEdges(CFLAliasAnalysis &Analysis, ConstantExpr *CE,
  720. SmallVectorImpl<Edge> &Output) {
  721. assert(hasUsefulEdges(CE) && "Expected constant expr to have 'useful' edges");
  722. GetEdgesVisitor v(Analysis, Output);
  723. v.visitConstantExpr(CE);
  724. }
  725. static Level directionOfEdgeType(EdgeType Weight) {
  726. switch (Weight) {
  727. case EdgeType::Reference:
  728. return Level::Above;
  729. case EdgeType::Dereference:
  730. return Level::Below;
  731. case EdgeType::Assign:
  732. return Level::Same;
  733. }
  734. llvm_unreachable("Incomplete switch coverage");
  735. }
  736. static void constexprToEdges(CFLAliasAnalysis &Analysis,
  737. ConstantExpr &CExprToCollapse,
  738. SmallVectorImpl<Edge> &Results) {
  739. SmallVector<ConstantExpr *, 4> Worklist;
  740. Worklist.push_back(&CExprToCollapse);
  741. SmallVector<Edge, 8> ConstexprEdges;
  742. SmallPtrSet<ConstantExpr *, 4> Visited;
  743. while (!Worklist.empty()) {
  744. auto *CExpr = Worklist.pop_back_val();
  745. if (!hasUsefulEdges(CExpr))
  746. continue;
  747. ConstexprEdges.clear();
  748. argsToEdges(Analysis, CExpr, ConstexprEdges);
  749. for (auto &Edge : ConstexprEdges) {
  750. if (auto *Nested = dyn_cast<ConstantExpr>(Edge.From))
  751. if (Visited.insert(Nested).second)
  752. Worklist.push_back(Nested);
  753. if (auto *Nested = dyn_cast<ConstantExpr>(Edge.To))
  754. if (Visited.insert(Nested).second)
  755. Worklist.push_back(Nested);
  756. }
  757. Results.append(ConstexprEdges.begin(), ConstexprEdges.end());
  758. }
  759. }
  760. static void addInstructionToGraph(CFLAliasAnalysis &Analysis, Instruction &Inst,
  761. SmallVectorImpl<Value *> &ReturnedValues,
  762. NodeMapT &Map, GraphT &Graph) {
  763. const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
  764. auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
  765. auto &Iter = Pair.first;
  766. if (Pair.second) {
  767. auto NewNode = Graph.addNode();
  768. Iter->second = NewNode;
  769. }
  770. return Iter->second;
  771. };
  772. // We don't want the edges of most "return" instructions, but we *do* want
  773. // to know what can be returned.
  774. if (isa<ReturnInst>(&Inst))
  775. ReturnedValues.push_back(&Inst);
  776. if (!hasUsefulEdges(&Inst))
  777. return;
  778. SmallVector<Edge, 8> Edges;
  779. argsToEdges(Analysis, &Inst, Edges);
  780. // In the case of an unused alloca (or similar), edges may be empty. Note
  781. // that it exists so we can potentially answer NoAlias.
  782. if (Edges.empty()) {
  783. auto MaybeVal = getTargetValue(&Inst);
  784. assert(MaybeVal.hasValue());
  785. auto *Target = *MaybeVal;
  786. findOrInsertNode(Target);
  787. return;
  788. }
  789. const auto addEdgeToGraph = [&Graph, &findOrInsertNode](const Edge &E) {
  790. auto To = findOrInsertNode(E.To);
  791. auto From = findOrInsertNode(E.From);
  792. auto FlippedWeight = flipWeight(E.Weight);
  793. auto Attrs = E.AdditionalAttrs;
  794. Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
  795. std::make_pair(FlippedWeight, Attrs));
  796. };
  797. SmallVector<ConstantExpr *, 4> ConstantExprs;
  798. for (const Edge &E : Edges) {
  799. addEdgeToGraph(E);
  800. if (auto *Constexpr = dyn_cast<ConstantExpr>(E.To))
  801. ConstantExprs.push_back(Constexpr);
  802. if (auto *Constexpr = dyn_cast<ConstantExpr>(E.From))
  803. ConstantExprs.push_back(Constexpr);
  804. }
  805. for (ConstantExpr *CE : ConstantExprs) {
  806. Edges.clear();
  807. constexprToEdges(Analysis, *CE, Edges);
  808. std::for_each(Edges.begin(), Edges.end(), addEdgeToGraph);
  809. }
  810. }
  811. // Aside: We may remove graph construction entirely, because it doesn't really
  812. // buy us much that we don't already have. I'd like to add interprocedural
  813. // analysis prior to this however, in case that somehow requires the graph
  814. // produced by this for efficient execution
  815. static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
  816. SmallVectorImpl<Value *> &ReturnedValues,
  817. NodeMapT &Map, GraphT &Graph) {
  818. for (auto &Bb : Fn->getBasicBlockList())
  819. for (auto &Inst : Bb.getInstList())
  820. addInstructionToGraph(Analysis, Inst, ReturnedValues, Map, Graph);
  821. }
  822. static bool canSkipAddingToSets(Value *Val) {
  823. // Constants can share instances, which may falsely unify multiple
  824. // sets, e.g. in
  825. // store i32* null, i32** %ptr1
  826. // store i32* null, i32** %ptr2
  827. // clearly ptr1 and ptr2 should not be unified into the same set, so
  828. // we should filter out the (potentially shared) instance to
  829. // i32* null.
  830. if (isa<Constant>(Val)) {
  831. bool Container = isa<ConstantVector>(Val) || isa<ConstantArray>(Val) ||
  832. isa<ConstantStruct>(Val);
  833. // TODO: Because all of these things are constant, we can determine whether
  834. // the data is *actually* mutable at graph building time. This will probably
  835. // come for free/cheap with offset awareness.
  836. bool CanStoreMutableData =
  837. isa<GlobalValue>(Val) || isa<ConstantExpr>(Val) || Container;
  838. return !CanStoreMutableData;
  839. }
  840. return false;
  841. }
  842. static FunctionInfo buildSetsFrom(CFLAliasAnalysis &Analysis, Function *Fn) {
  843. NodeMapT Map;
  844. GraphT Graph;
  845. SmallVector<Value *, 4> ReturnedValues;
  846. buildGraphFrom(Analysis, Fn, ReturnedValues, Map, Graph);
  847. DenseMap<GraphT::Node, Value *> NodeValueMap;
  848. NodeValueMap.resize(Map.size());
  849. for (const auto &Pair : Map)
  850. NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
  851. const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
  852. auto ValIter = NodeValueMap.find(Node);
  853. assert(ValIter != NodeValueMap.end());
  854. return ValIter->second;
  855. };
  856. StratifiedSetsBuilder<Value *> Builder;
  857. SmallVector<GraphT::Node, 16> Worklist;
  858. for (auto &Pair : Map) {
  859. Worklist.clear();
  860. auto *Value = Pair.first;
  861. Builder.add(Value);
  862. auto InitialNode = Pair.second;
  863. Worklist.push_back(InitialNode);
  864. while (!Worklist.empty()) {
  865. auto Node = Worklist.pop_back_val();
  866. auto *CurValue = findValueOrDie(Node);
  867. if (canSkipAddingToSets(CurValue))
  868. continue;
  869. for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
  870. auto Weight = std::get<0>(EdgeTuple);
  871. auto Label = Weight.first;
  872. auto &OtherNode = std::get<1>(EdgeTuple);
  873. auto *OtherValue = findValueOrDie(OtherNode);
  874. if (canSkipAddingToSets(OtherValue))
  875. continue;
  876. bool Added;
  877. switch (directionOfEdgeType(Label)) {
  878. case Level::Above:
  879. Added = Builder.addAbove(CurValue, OtherValue);
  880. break;
  881. case Level::Below:
  882. Added = Builder.addBelow(CurValue, OtherValue);
  883. break;
  884. case Level::Same:
  885. Added = Builder.addWith(CurValue, OtherValue);
  886. break;
  887. }
  888. auto Aliasing = Weight.second;
  889. if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
  890. Aliasing.set(*MaybeCurIndex);
  891. if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
  892. Aliasing.set(*MaybeOtherIndex);
  893. Builder.noteAttributes(CurValue, Aliasing);
  894. Builder.noteAttributes(OtherValue, Aliasing);
  895. if (Added)
  896. Worklist.push_back(OtherNode);
  897. }
  898. }
  899. }
  900. // There are times when we end up with parameters not in our graph (i.e. if
  901. // it's only used as the condition of a branch). Other bits of code depend on
  902. // things that were present during construction being present in the graph.
  903. // So, we add all present arguments here.
  904. for (auto &Arg : Fn->args()) {
  905. if (!Builder.add(&Arg))
  906. continue;
  907. auto Attrs = valueToAttrIndex(&Arg);
  908. if (Attrs.hasValue())
  909. Builder.noteAttributes(&Arg, *Attrs);
  910. }
  911. return FunctionInfo(Builder.build(), std::move(ReturnedValues));
  912. }
  913. void CFLAliasAnalysis::scan(Function *Fn) {
  914. auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
  915. (void)InsertPair;
  916. assert(InsertPair.second &&
  917. "Trying to scan a function that has already been cached");
  918. FunctionInfo Info(buildSetsFrom(*this, Fn));
  919. Cache[Fn] = std::move(Info);
  920. Handles.push_front(FunctionHandle(Fn, this));
  921. }
  922. AliasResult CFLAliasAnalysis::query(const MemoryLocation &LocA,
  923. const MemoryLocation &LocB) {
  924. auto *ValA = const_cast<Value *>(LocA.Ptr);
  925. auto *ValB = const_cast<Value *>(LocB.Ptr);
  926. Function *Fn = nullptr;
  927. auto MaybeFnA = parentFunctionOfValue(ValA);
  928. auto MaybeFnB = parentFunctionOfValue(ValB);
  929. if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
  930. // The only times this is known to happen are when globals + InlineAsm
  931. // are involved
  932. DEBUG(dbgs() << "CFLAA: could not extract parent function information.\n");
  933. return MayAlias;
  934. }
  935. if (MaybeFnA.hasValue()) {
  936. Fn = *MaybeFnA;
  937. assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
  938. "Interprocedural queries not supported");
  939. } else {
  940. Fn = *MaybeFnB;
  941. }
  942. assert(Fn != nullptr);
  943. auto &MaybeInfo = ensureCached(Fn);
  944. assert(MaybeInfo.hasValue());
  945. auto &Sets = MaybeInfo->Sets;
  946. auto MaybeA = Sets.find(ValA);
  947. if (!MaybeA.hasValue())
  948. return MayAlias;
  949. auto MaybeB = Sets.find(ValB);
  950. if (!MaybeB.hasValue())
  951. return MayAlias;
  952. auto SetA = *MaybeA;
  953. auto SetB = *MaybeB;
  954. auto AttrsA = Sets.getLink(SetA.Index).Attrs;
  955. auto AttrsB = Sets.getLink(SetB.Index).Attrs;
  956. // Stratified set attributes are used as markets to signify whether a member
  957. // of a StratifiedSet (or a member of a set above the current set) has
  958. // interacted with either arguments or globals. "Interacted with" meaning
  959. // its value may be different depending on the value of an argument or
  960. // global. The thought behind this is that, because arguments and globals
  961. // may alias each other, if AttrsA and AttrsB have touched args/globals,
  962. // we must conservatively say that they alias. However, if at least one of
  963. // the sets has no values that could legally be altered by changing the value
  964. // of an argument or global, then we don't have to be as conservative.
  965. if (AttrsA.any() && AttrsB.any())
  966. return MayAlias;
  967. // We currently unify things even if the accesses to them may not be in
  968. // bounds, so we can't return partial alias here because we don't
  969. // know whether the pointer is really within the object or not.
  970. // IE Given an out of bounds GEP and an alloca'd pointer, we may
  971. // unify the two. We can't return partial alias for this case.
  972. // Since we do not currently track enough information to
  973. // differentiate
  974. if (SetA.Index == SetB.Index)
  975. return MayAlias;
  976. return NoAlias;
  977. }
  978. bool CFLAliasAnalysis::doInitialization(Module &M) {
  979. InitializeAliasAnalysis(this, &M.getDataLayout());
  980. return true;
  981. }