BasicAliasAnalysis.cpp 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100
  1. //===- BasicAliasAnalysis.cpp - Stateless Alias Analysis Impl -------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the primary stateless implementation of the
  10. // Alias Analysis interface that implements identities (two different
  11. // globals cannot alias, etc), but does no stateful analysis.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Analysis/BasicAliasAnalysis.h"
  15. #include "llvm/ADT/APInt.h"
  16. #include "llvm/ADT/SmallPtrSet.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/ADT/Statistic.h"
  19. #include "llvm/Analysis/AliasAnalysis.h"
  20. #include "llvm/Analysis/AssumptionCache.h"
  21. #include "llvm/Analysis/CFG.h"
  22. #include "llvm/Analysis/CaptureTracking.h"
  23. #include "llvm/Analysis/InstructionSimplify.h"
  24. #include "llvm/Analysis/LoopInfo.h"
  25. #include "llvm/Analysis/MemoryBuiltins.h"
  26. #include "llvm/Analysis/MemoryLocation.h"
  27. #include "llvm/Analysis/TargetLibraryInfo.h"
  28. #include "llvm/Analysis/ValueTracking.h"
  29. #include "llvm/Analysis/PhiValues.h"
  30. #include "llvm/IR/Argument.h"
  31. #include "llvm/IR/Attributes.h"
  32. #include "llvm/IR/Constant.h"
  33. #include "llvm/IR/Constants.h"
  34. #include "llvm/IR/DataLayout.h"
  35. #include "llvm/IR/DerivedTypes.h"
  36. #include "llvm/IR/Dominators.h"
  37. #include "llvm/IR/Function.h"
  38. #include "llvm/IR/GetElementPtrTypeIterator.h"
  39. #include "llvm/IR/GlobalAlias.h"
  40. #include "llvm/IR/GlobalVariable.h"
  41. #include "llvm/IR/InstrTypes.h"
  42. #include "llvm/IR/Instruction.h"
  43. #include "llvm/IR/Instructions.h"
  44. #include "llvm/IR/IntrinsicInst.h"
  45. #include "llvm/IR/Intrinsics.h"
  46. #include "llvm/IR/Metadata.h"
  47. #include "llvm/IR/Operator.h"
  48. #include "llvm/IR/Type.h"
  49. #include "llvm/IR/User.h"
  50. #include "llvm/IR/Value.h"
  51. #include "llvm/Pass.h"
  52. #include "llvm/Support/Casting.h"
  53. #include "llvm/Support/CommandLine.h"
  54. #include "llvm/Support/Compiler.h"
  55. #include "llvm/Support/KnownBits.h"
  56. #include <cassert>
  57. #include <cstdint>
  58. #include <cstdlib>
  59. #include <utility>
  60. #define DEBUG_TYPE "basicaa"
  61. using namespace llvm;
  62. /// Enable analysis of recursive PHI nodes.
  63. static cl::opt<bool> EnableRecPhiAnalysis("basicaa-recphi", cl::Hidden,
  64. cl::init(false));
  65. /// By default, even on 32-bit architectures we use 64-bit integers for
  66. /// calculations. This will allow us to more-aggressively decompose indexing
  67. /// expressions calculated using i64 values (e.g., long long in C) which is
  68. /// common enough to worry about.
  69. static cl::opt<bool> ForceAtLeast64Bits("basicaa-force-at-least-64b",
  70. cl::Hidden, cl::init(true));
  71. static cl::opt<bool> DoubleCalcBits("basicaa-double-calc-bits",
  72. cl::Hidden, cl::init(false));
  73. /// SearchLimitReached / SearchTimes shows how often the limit of
  74. /// to decompose GEPs is reached. It will affect the precision
  75. /// of basic alias analysis.
  76. STATISTIC(SearchLimitReached, "Number of times the limit to "
  77. "decompose GEPs is reached");
  78. STATISTIC(SearchTimes, "Number of times a GEP is decomposed");
  79. /// Cutoff after which to stop analysing a set of phi nodes potentially involved
  80. /// in a cycle. Because we are analysing 'through' phi nodes, we need to be
  81. /// careful with value equivalence. We use reachability to make sure a value
  82. /// cannot be involved in a cycle.
  83. const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
  84. // The max limit of the search depth in DecomposeGEPExpression() and
  85. // GetUnderlyingObject(), both functions need to use the same search
  86. // depth otherwise the algorithm in aliasGEP will assert.
  87. static const unsigned MaxLookupSearchDepth = 6;
  88. bool BasicAAResult::invalidate(Function &Fn, const PreservedAnalyses &PA,
  89. FunctionAnalysisManager::Invalidator &Inv) {
  90. // We don't care if this analysis itself is preserved, it has no state. But
  91. // we need to check that the analyses it depends on have been. Note that we
  92. // may be created without handles to some analyses and in that case don't
  93. // depend on them.
  94. if (Inv.invalidate<AssumptionAnalysis>(Fn, PA) ||
  95. (DT && Inv.invalidate<DominatorTreeAnalysis>(Fn, PA)) ||
  96. (LI && Inv.invalidate<LoopAnalysis>(Fn, PA)) ||
  97. (PV && Inv.invalidate<PhiValuesAnalysis>(Fn, PA)))
  98. return true;
  99. // Otherwise this analysis result remains valid.
  100. return false;
  101. }
  102. //===----------------------------------------------------------------------===//
  103. // Useful predicates
  104. //===----------------------------------------------------------------------===//
  105. /// Returns true if the pointer is to a function-local object that never
  106. /// escapes from the function.
  107. static bool isNonEscapingLocalObject(
  108. const Value *V,
  109. SmallDenseMap<const Value *, bool, 8> *IsCapturedCache = nullptr) {
  110. SmallDenseMap<const Value *, bool, 8>::iterator CacheIt;
  111. if (IsCapturedCache) {
  112. bool Inserted;
  113. std::tie(CacheIt, Inserted) = IsCapturedCache->insert({V, false});
  114. if (!Inserted)
  115. // Found cached result, return it!
  116. return CacheIt->second;
  117. }
  118. // If this is a local allocation, check to see if it escapes.
  119. if (isa<AllocaInst>(V) || isNoAliasCall(V)) {
  120. // Set StoreCaptures to True so that we can assume in our callers that the
  121. // pointer is not the result of a load instruction. Currently
  122. // PointerMayBeCaptured doesn't have any special analysis for the
  123. // StoreCaptures=false case; if it did, our callers could be refined to be
  124. // more precise.
  125. auto Ret = !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
  126. if (IsCapturedCache)
  127. CacheIt->second = Ret;
  128. return Ret;
  129. }
  130. // If this is an argument that corresponds to a byval or noalias argument,
  131. // then it has not escaped before entering the function. Check if it escapes
  132. // inside the function.
  133. if (const Argument *A = dyn_cast<Argument>(V))
  134. if (A->hasByValAttr() || A->hasNoAliasAttr()) {
  135. // Note even if the argument is marked nocapture, we still need to check
  136. // for copies made inside the function. The nocapture attribute only
  137. // specifies that there are no copies made that outlive the function.
  138. auto Ret = !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
  139. if (IsCapturedCache)
  140. CacheIt->second = Ret;
  141. return Ret;
  142. }
  143. return false;
  144. }
  145. /// Returns true if the pointer is one which would have been considered an
  146. /// escape by isNonEscapingLocalObject.
  147. static bool isEscapeSource(const Value *V) {
  148. if (isa<CallBase>(V))
  149. return true;
  150. if (isa<Argument>(V))
  151. return true;
  152. // The load case works because isNonEscapingLocalObject considers all
  153. // stores to be escapes (it passes true for the StoreCaptures argument
  154. // to PointerMayBeCaptured).
  155. if (isa<LoadInst>(V))
  156. return true;
  157. return false;
  158. }
  159. /// Returns the size of the object specified by V or UnknownSize if unknown.
  160. static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
  161. const TargetLibraryInfo &TLI,
  162. bool NullIsValidLoc,
  163. bool RoundToAlign = false) {
  164. uint64_t Size;
  165. ObjectSizeOpts Opts;
  166. Opts.RoundToAlign = RoundToAlign;
  167. Opts.NullIsUnknownSize = NullIsValidLoc;
  168. if (getObjectSize(V, Size, DL, &TLI, Opts))
  169. return Size;
  170. return MemoryLocation::UnknownSize;
  171. }
  172. /// Returns true if we can prove that the object specified by V is smaller than
  173. /// Size.
  174. static bool isObjectSmallerThan(const Value *V, uint64_t Size,
  175. const DataLayout &DL,
  176. const TargetLibraryInfo &TLI,
  177. bool NullIsValidLoc) {
  178. // Note that the meanings of the "object" are slightly different in the
  179. // following contexts:
  180. // c1: llvm::getObjectSize()
  181. // c2: llvm.objectsize() intrinsic
  182. // c3: isObjectSmallerThan()
  183. // c1 and c2 share the same meaning; however, the meaning of "object" in c3
  184. // refers to the "entire object".
  185. //
  186. // Consider this example:
  187. // char *p = (char*)malloc(100)
  188. // char *q = p+80;
  189. //
  190. // In the context of c1 and c2, the "object" pointed by q refers to the
  191. // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
  192. //
  193. // However, in the context of c3, the "object" refers to the chunk of memory
  194. // being allocated. So, the "object" has 100 bytes, and q points to the middle
  195. // the "object". In case q is passed to isObjectSmallerThan() as the 1st
  196. // parameter, before the llvm::getObjectSize() is called to get the size of
  197. // entire object, we should:
  198. // - either rewind the pointer q to the base-address of the object in
  199. // question (in this case rewind to p), or
  200. // - just give up. It is up to caller to make sure the pointer is pointing
  201. // to the base address the object.
  202. //
  203. // We go for 2nd option for simplicity.
  204. if (!isIdentifiedObject(V))
  205. return false;
  206. // This function needs to use the aligned object size because we allow
  207. // reads a bit past the end given sufficient alignment.
  208. uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc,
  209. /*RoundToAlign*/ true);
  210. return ObjectSize != MemoryLocation::UnknownSize && ObjectSize < Size;
  211. }
  212. /// Return the minimal extent from \p V to the end of the underlying object,
  213. /// assuming the result is used in an aliasing query. E.g., we do use the query
  214. /// location size and the fact that null pointers cannot alias here.
  215. static uint64_t getMinimalExtentFrom(const Value &V,
  216. const LocationSize &LocSize,
  217. const DataLayout &DL,
  218. bool NullIsValidLoc) {
  219. // If we have dereferenceability information we know a lower bound for the
  220. // extent as accesses for a lower offset would be valid. We need to exclude
  221. // the "or null" part if null is a valid pointer.
  222. bool CanBeNull;
  223. uint64_t DerefBytes = V.getPointerDereferenceableBytes(DL, CanBeNull);
  224. DerefBytes = (CanBeNull && NullIsValidLoc) ? 0 : DerefBytes;
  225. // If queried with a precise location size, we assume that location size to be
  226. // accessed, thus valid.
  227. if (LocSize.isPrecise())
  228. DerefBytes = std::max(DerefBytes, LocSize.getValue());
  229. return DerefBytes;
  230. }
  231. /// Returns true if we can prove that the object specified by V has size Size.
  232. static bool isObjectSize(const Value *V, uint64_t Size, const DataLayout &DL,
  233. const TargetLibraryInfo &TLI, bool NullIsValidLoc) {
  234. uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc);
  235. return ObjectSize != MemoryLocation::UnknownSize && ObjectSize == Size;
  236. }
  237. //===----------------------------------------------------------------------===//
  238. // GetElementPtr Instruction Decomposition and Analysis
  239. //===----------------------------------------------------------------------===//
  240. /// Analyzes the specified value as a linear expression: "A*V + B", where A and
  241. /// B are constant integers.
  242. ///
  243. /// Returns the scale and offset values as APInts and return V as a Value*, and
  244. /// return whether we looked through any sign or zero extends. The incoming
  245. /// Value is known to have IntegerType, and it may already be sign or zero
  246. /// extended.
  247. ///
  248. /// Note that this looks through extends, so the high bits may not be
  249. /// represented in the result.
  250. /*static*/ const Value *BasicAAResult::GetLinearExpression(
  251. const Value *V, APInt &Scale, APInt &Offset, unsigned &ZExtBits,
  252. unsigned &SExtBits, const DataLayout &DL, unsigned Depth,
  253. AssumptionCache *AC, DominatorTree *DT, bool &NSW, bool &NUW) {
  254. assert(V->getType()->isIntegerTy() && "Not an integer value");
  255. // Limit our recursion depth.
  256. if (Depth == 6) {
  257. Scale = 1;
  258. Offset = 0;
  259. return V;
  260. }
  261. if (const ConstantInt *Const = dyn_cast<ConstantInt>(V)) {
  262. // If it's a constant, just convert it to an offset and remove the variable.
  263. // If we've been called recursively, the Offset bit width will be greater
  264. // than the constant's (the Offset's always as wide as the outermost call),
  265. // so we'll zext here and process any extension in the isa<SExtInst> &
  266. // isa<ZExtInst> cases below.
  267. Offset += Const->getValue().zextOrSelf(Offset.getBitWidth());
  268. assert(Scale == 0 && "Constant values don't have a scale");
  269. return V;
  270. }
  271. if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
  272. if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
  273. // If we've been called recursively, then Offset and Scale will be wider
  274. // than the BOp operands. We'll always zext it here as we'll process sign
  275. // extensions below (see the isa<SExtInst> / isa<ZExtInst> cases).
  276. APInt RHS = RHSC->getValue().zextOrSelf(Offset.getBitWidth());
  277. switch (BOp->getOpcode()) {
  278. default:
  279. // We don't understand this instruction, so we can't decompose it any
  280. // further.
  281. Scale = 1;
  282. Offset = 0;
  283. return V;
  284. case Instruction::Or:
  285. // X|C == X+C if all the bits in C are unset in X. Otherwise we can't
  286. // analyze it.
  287. if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), DL, 0, AC,
  288. BOp, DT)) {
  289. Scale = 1;
  290. Offset = 0;
  291. return V;
  292. }
  293. LLVM_FALLTHROUGH;
  294. case Instruction::Add:
  295. V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
  296. SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
  297. Offset += RHS;
  298. break;
  299. case Instruction::Sub:
  300. V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
  301. SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
  302. Offset -= RHS;
  303. break;
  304. case Instruction::Mul:
  305. V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
  306. SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
  307. Offset *= RHS;
  308. Scale *= RHS;
  309. break;
  310. case Instruction::Shl:
  311. V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
  312. SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
  313. // We're trying to linearize an expression of the kind:
  314. // shl i8 -128, 36
  315. // where the shift count exceeds the bitwidth of the type.
  316. // We can't decompose this further (the expression would return
  317. // a poison value).
  318. if (Offset.getBitWidth() < RHS.getLimitedValue() ||
  319. Scale.getBitWidth() < RHS.getLimitedValue()) {
  320. Scale = 1;
  321. Offset = 0;
  322. return V;
  323. }
  324. Offset <<= RHS.getLimitedValue();
  325. Scale <<= RHS.getLimitedValue();
  326. // the semantics of nsw and nuw for left shifts don't match those of
  327. // multiplications, so we won't propagate them.
  328. NSW = NUW = false;
  329. return V;
  330. }
  331. if (isa<OverflowingBinaryOperator>(BOp)) {
  332. NUW &= BOp->hasNoUnsignedWrap();
  333. NSW &= BOp->hasNoSignedWrap();
  334. }
  335. return V;
  336. }
  337. }
  338. // Since GEP indices are sign extended anyway, we don't care about the high
  339. // bits of a sign or zero extended value - just scales and offsets. The
  340. // extensions have to be consistent though.
  341. if (isa<SExtInst>(V) || isa<ZExtInst>(V)) {
  342. Value *CastOp = cast<CastInst>(V)->getOperand(0);
  343. unsigned NewWidth = V->getType()->getPrimitiveSizeInBits();
  344. unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
  345. unsigned OldZExtBits = ZExtBits, OldSExtBits = SExtBits;
  346. const Value *Result =
  347. GetLinearExpression(CastOp, Scale, Offset, ZExtBits, SExtBits, DL,
  348. Depth + 1, AC, DT, NSW, NUW);
  349. // zext(zext(%x)) == zext(%x), and similarly for sext; we'll handle this
  350. // by just incrementing the number of bits we've extended by.
  351. unsigned ExtendedBy = NewWidth - SmallWidth;
  352. if (isa<SExtInst>(V) && ZExtBits == 0) {
  353. // sext(sext(%x, a), b) == sext(%x, a + b)
  354. if (NSW) {
  355. // We haven't sign-wrapped, so it's valid to decompose sext(%x + c)
  356. // into sext(%x) + sext(c). We'll sext the Offset ourselves:
  357. unsigned OldWidth = Offset.getBitWidth();
  358. Offset = Offset.trunc(SmallWidth).sext(NewWidth).zextOrSelf(OldWidth);
  359. } else {
  360. // We may have signed-wrapped, so don't decompose sext(%x + c) into
  361. // sext(%x) + sext(c)
  362. Scale = 1;
  363. Offset = 0;
  364. Result = CastOp;
  365. ZExtBits = OldZExtBits;
  366. SExtBits = OldSExtBits;
  367. }
  368. SExtBits += ExtendedBy;
  369. } else {
  370. // sext(zext(%x, a), b) = zext(zext(%x, a), b) = zext(%x, a + b)
  371. if (!NUW) {
  372. // We may have unsigned-wrapped, so don't decompose zext(%x + c) into
  373. // zext(%x) + zext(c)
  374. Scale = 1;
  375. Offset = 0;
  376. Result = CastOp;
  377. ZExtBits = OldZExtBits;
  378. SExtBits = OldSExtBits;
  379. }
  380. ZExtBits += ExtendedBy;
  381. }
  382. return Result;
  383. }
  384. Scale = 1;
  385. Offset = 0;
  386. return V;
  387. }
  388. /// To ensure a pointer offset fits in an integer of size PointerSize
  389. /// (in bits) when that size is smaller than the maximum pointer size. This is
  390. /// an issue, for example, in particular for 32b pointers with negative indices
  391. /// that rely on two's complement wrap-arounds for precise alias information
  392. /// where the maximum pointer size is 64b.
  393. static APInt adjustToPointerSize(APInt Offset, unsigned PointerSize) {
  394. assert(PointerSize <= Offset.getBitWidth() && "Invalid PointerSize!");
  395. unsigned ShiftBits = Offset.getBitWidth() - PointerSize;
  396. return (Offset << ShiftBits).ashr(ShiftBits);
  397. }
  398. static unsigned getMaxPointerSize(const DataLayout &DL) {
  399. unsigned MaxPointerSize = DL.getMaxPointerSizeInBits();
  400. if (MaxPointerSize < 64 && ForceAtLeast64Bits) MaxPointerSize = 64;
  401. if (DoubleCalcBits) MaxPointerSize *= 2;
  402. return MaxPointerSize;
  403. }
  404. /// If V is a symbolic pointer expression, decompose it into a base pointer
  405. /// with a constant offset and a number of scaled symbolic offsets.
  406. ///
  407. /// The scaled symbolic offsets (represented by pairs of a Value* and a scale
  408. /// in the VarIndices vector) are Value*'s that are known to be scaled by the
  409. /// specified amount, but which may have other unrepresented high bits. As
  410. /// such, the gep cannot necessarily be reconstructed from its decomposed form.
  411. ///
  412. /// When DataLayout is around, this function is capable of analyzing everything
  413. /// that GetUnderlyingObject can look through. To be able to do that
  414. /// GetUnderlyingObject and DecomposeGEPExpression must use the same search
  415. /// depth (MaxLookupSearchDepth). When DataLayout not is around, it just looks
  416. /// through pointer casts.
  417. bool BasicAAResult::DecomposeGEPExpression(const Value *V,
  418. DecomposedGEP &Decomposed, const DataLayout &DL, AssumptionCache *AC,
  419. DominatorTree *DT) {
  420. // Limit recursion depth to limit compile time in crazy cases.
  421. unsigned MaxLookup = MaxLookupSearchDepth;
  422. SearchTimes++;
  423. unsigned MaxPointerSize = getMaxPointerSize(DL);
  424. Decomposed.VarIndices.clear();
  425. do {
  426. // See if this is a bitcast or GEP.
  427. const Operator *Op = dyn_cast<Operator>(V);
  428. if (!Op) {
  429. // The only non-operator case we can handle are GlobalAliases.
  430. if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
  431. if (!GA->isInterposable()) {
  432. V = GA->getAliasee();
  433. continue;
  434. }
  435. }
  436. Decomposed.Base = V;
  437. return false;
  438. }
  439. if (Op->getOpcode() == Instruction::BitCast ||
  440. Op->getOpcode() == Instruction::AddrSpaceCast) {
  441. V = Op->getOperand(0);
  442. continue;
  443. }
  444. const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
  445. if (!GEPOp) {
  446. if (const auto *Call = dyn_cast<CallBase>(V)) {
  447. // CaptureTracking can know about special capturing properties of some
  448. // intrinsics like launder.invariant.group, that can't be expressed with
  449. // the attributes, but have properties like returning aliasing pointer.
  450. // Because some analysis may assume that nocaptured pointer is not
  451. // returned from some special intrinsic (because function would have to
  452. // be marked with returns attribute), it is crucial to use this function
  453. // because it should be in sync with CaptureTracking. Not using it may
  454. // cause weird miscompilations where 2 aliasing pointers are assumed to
  455. // noalias.
  456. if (auto *RP = getArgumentAliasingToReturnedPointer(Call, false)) {
  457. V = RP;
  458. continue;
  459. }
  460. }
  461. // If it's not a GEP, hand it off to SimplifyInstruction to see if it
  462. // can come up with something. This matches what GetUnderlyingObject does.
  463. if (const Instruction *I = dyn_cast<Instruction>(V))
  464. // TODO: Get a DominatorTree and AssumptionCache and use them here
  465. // (these are both now available in this function, but this should be
  466. // updated when GetUnderlyingObject is updated). TLI should be
  467. // provided also.
  468. if (const Value *Simplified =
  469. SimplifyInstruction(const_cast<Instruction *>(I), DL)) {
  470. V = Simplified;
  471. continue;
  472. }
  473. Decomposed.Base = V;
  474. return false;
  475. }
  476. // Don't attempt to analyze GEPs over unsized objects.
  477. if (!GEPOp->getSourceElementType()->isSized()) {
  478. Decomposed.Base = V;
  479. return false;
  480. }
  481. unsigned AS = GEPOp->getPointerAddressSpace();
  482. // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
  483. gep_type_iterator GTI = gep_type_begin(GEPOp);
  484. unsigned PointerSize = DL.getPointerSizeInBits(AS);
  485. // Assume all GEP operands are constants until proven otherwise.
  486. bool GepHasConstantOffset = true;
  487. for (User::const_op_iterator I = GEPOp->op_begin() + 1, E = GEPOp->op_end();
  488. I != E; ++I, ++GTI) {
  489. const Value *Index = *I;
  490. // Compute the (potentially symbolic) offset in bytes for this index.
  491. if (StructType *STy = GTI.getStructTypeOrNull()) {
  492. // For a struct, add the member offset.
  493. unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
  494. if (FieldNo == 0)
  495. continue;
  496. Decomposed.StructOffset +=
  497. DL.getStructLayout(STy)->getElementOffset(FieldNo);
  498. continue;
  499. }
  500. // For an array/pointer, add the element offset, explicitly scaled.
  501. if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
  502. if (CIdx->isZero())
  503. continue;
  504. Decomposed.OtherOffset +=
  505. (DL.getTypeAllocSize(GTI.getIndexedType()) *
  506. CIdx->getValue().sextOrSelf(MaxPointerSize))
  507. .sextOrTrunc(MaxPointerSize);
  508. continue;
  509. }
  510. GepHasConstantOffset = false;
  511. APInt Scale(MaxPointerSize, DL.getTypeAllocSize(GTI.getIndexedType()));
  512. unsigned ZExtBits = 0, SExtBits = 0;
  513. // If the integer type is smaller than the pointer size, it is implicitly
  514. // sign extended to pointer size.
  515. unsigned Width = Index->getType()->getIntegerBitWidth();
  516. if (PointerSize > Width)
  517. SExtBits += PointerSize - Width;
  518. // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
  519. APInt IndexScale(Width, 0), IndexOffset(Width, 0);
  520. bool NSW = true, NUW = true;
  521. const Value *OrigIndex = Index;
  522. Index = GetLinearExpression(Index, IndexScale, IndexOffset, ZExtBits,
  523. SExtBits, DL, 0, AC, DT, NSW, NUW);
  524. // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
  525. // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
  526. // It can be the case that, even through C1*V+C2 does not overflow for
  527. // relevant values of V, (C2*Scale) can overflow. In that case, we cannot
  528. // decompose the expression in this way.
  529. //
  530. // FIXME: C1*Scale and the other operations in the decomposed
  531. // (C1*Scale)*V+C2*Scale can also overflow. We should check for this
  532. // possibility.
  533. APInt WideScaledOffset = IndexOffset.sextOrTrunc(MaxPointerSize*2) *
  534. Scale.sext(MaxPointerSize*2);
  535. if (WideScaledOffset.getMinSignedBits() > MaxPointerSize) {
  536. Index = OrigIndex;
  537. IndexScale = 1;
  538. IndexOffset = 0;
  539. ZExtBits = SExtBits = 0;
  540. if (PointerSize > Width)
  541. SExtBits += PointerSize - Width;
  542. } else {
  543. Decomposed.OtherOffset += IndexOffset.sextOrTrunc(MaxPointerSize) * Scale;
  544. Scale *= IndexScale.sextOrTrunc(MaxPointerSize);
  545. }
  546. // If we already had an occurrence of this index variable, merge this
  547. // scale into it. For example, we want to handle:
  548. // A[x][x] -> x*16 + x*4 -> x*20
  549. // This also ensures that 'x' only appears in the index list once.
  550. for (unsigned i = 0, e = Decomposed.VarIndices.size(); i != e; ++i) {
  551. if (Decomposed.VarIndices[i].V == Index &&
  552. Decomposed.VarIndices[i].ZExtBits == ZExtBits &&
  553. Decomposed.VarIndices[i].SExtBits == SExtBits) {
  554. Scale += Decomposed.VarIndices[i].Scale;
  555. Decomposed.VarIndices.erase(Decomposed.VarIndices.begin() + i);
  556. break;
  557. }
  558. }
  559. // Make sure that we have a scale that makes sense for this target's
  560. // pointer size.
  561. Scale = adjustToPointerSize(Scale, PointerSize);
  562. if (!!Scale) {
  563. VariableGEPIndex Entry = {Index, ZExtBits, SExtBits, Scale};
  564. Decomposed.VarIndices.push_back(Entry);
  565. }
  566. }
  567. // Take care of wrap-arounds
  568. if (GepHasConstantOffset) {
  569. Decomposed.StructOffset =
  570. adjustToPointerSize(Decomposed.StructOffset, PointerSize);
  571. Decomposed.OtherOffset =
  572. adjustToPointerSize(Decomposed.OtherOffset, PointerSize);
  573. }
  574. // Analyze the base pointer next.
  575. V = GEPOp->getOperand(0);
  576. } while (--MaxLookup);
  577. // If the chain of expressions is too deep, just return early.
  578. Decomposed.Base = V;
  579. SearchLimitReached++;
  580. return true;
  581. }
  582. /// Returns whether the given pointer value points to memory that is local to
  583. /// the function, with global constants being considered local to all
  584. /// functions.
  585. bool BasicAAResult::pointsToConstantMemory(const MemoryLocation &Loc,
  586. AAQueryInfo &AAQI, bool OrLocal) {
  587. assert(Visited.empty() && "Visited must be cleared after use!");
  588. unsigned MaxLookup = 8;
  589. SmallVector<const Value *, 16> Worklist;
  590. Worklist.push_back(Loc.Ptr);
  591. do {
  592. const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), DL);
  593. if (!Visited.insert(V).second) {
  594. Visited.clear();
  595. return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
  596. }
  597. // An alloca instruction defines local memory.
  598. if (OrLocal && isa<AllocaInst>(V))
  599. continue;
  600. // A global constant counts as local memory for our purposes.
  601. if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
  602. // Note: this doesn't require GV to be "ODR" because it isn't legal for a
  603. // global to be marked constant in some modules and non-constant in
  604. // others. GV may even be a declaration, not a definition.
  605. if (!GV->isConstant()) {
  606. Visited.clear();
  607. return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
  608. }
  609. continue;
  610. }
  611. // If both select values point to local memory, then so does the select.
  612. if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
  613. Worklist.push_back(SI->getTrueValue());
  614. Worklist.push_back(SI->getFalseValue());
  615. continue;
  616. }
  617. // If all values incoming to a phi node point to local memory, then so does
  618. // the phi.
  619. if (const PHINode *PN = dyn_cast<PHINode>(V)) {
  620. // Don't bother inspecting phi nodes with many operands.
  621. if (PN->getNumIncomingValues() > MaxLookup) {
  622. Visited.clear();
  623. return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
  624. }
  625. for (Value *IncValue : PN->incoming_values())
  626. Worklist.push_back(IncValue);
  627. continue;
  628. }
  629. // Otherwise be conservative.
  630. Visited.clear();
  631. return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
  632. } while (!Worklist.empty() && --MaxLookup);
  633. Visited.clear();
  634. return Worklist.empty();
  635. }
  636. /// Returns the behavior when calling the given call site.
  637. FunctionModRefBehavior BasicAAResult::getModRefBehavior(const CallBase *Call) {
  638. if (Call->doesNotAccessMemory())
  639. // Can't do better than this.
  640. return FMRB_DoesNotAccessMemory;
  641. FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
  642. // If the callsite knows it only reads memory, don't return worse
  643. // than that.
  644. if (Call->onlyReadsMemory())
  645. Min = FMRB_OnlyReadsMemory;
  646. else if (Call->doesNotReadMemory())
  647. Min = FMRB_DoesNotReadMemory;
  648. if (Call->onlyAccessesArgMemory())
  649. Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
  650. else if (Call->onlyAccessesInaccessibleMemory())
  651. Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem);
  652. else if (Call->onlyAccessesInaccessibleMemOrArgMem())
  653. Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem);
  654. // If the call has operand bundles then aliasing attributes from the function
  655. // it calls do not directly apply to the call. This can be made more precise
  656. // in the future.
  657. if (!Call->hasOperandBundles())
  658. if (const Function *F = Call->getCalledFunction())
  659. Min =
  660. FunctionModRefBehavior(Min & getBestAAResults().getModRefBehavior(F));
  661. return Min;
  662. }
  663. /// Returns the behavior when calling the given function. For use when the call
  664. /// site is not known.
  665. FunctionModRefBehavior BasicAAResult::getModRefBehavior(const Function *F) {
  666. // If the function declares it doesn't access memory, we can't do better.
  667. if (F->doesNotAccessMemory())
  668. return FMRB_DoesNotAccessMemory;
  669. FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
  670. // If the function declares it only reads memory, go with that.
  671. if (F->onlyReadsMemory())
  672. Min = FMRB_OnlyReadsMemory;
  673. else if (F->doesNotReadMemory())
  674. Min = FMRB_DoesNotReadMemory;
  675. if (F->onlyAccessesArgMemory())
  676. Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
  677. else if (F->onlyAccessesInaccessibleMemory())
  678. Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem);
  679. else if (F->onlyAccessesInaccessibleMemOrArgMem())
  680. Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem);
  681. return Min;
  682. }
  683. /// Returns true if this is a writeonly (i.e Mod only) parameter.
  684. static bool isWriteOnlyParam(const CallBase *Call, unsigned ArgIdx,
  685. const TargetLibraryInfo &TLI) {
  686. if (Call->paramHasAttr(ArgIdx, Attribute::WriteOnly))
  687. return true;
  688. // We can bound the aliasing properties of memset_pattern16 just as we can
  689. // for memcpy/memset. This is particularly important because the
  690. // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
  691. // whenever possible.
  692. // FIXME Consider handling this in InferFunctionAttr.cpp together with other
  693. // attributes.
  694. LibFunc F;
  695. if (Call->getCalledFunction() &&
  696. TLI.getLibFunc(*Call->getCalledFunction(), F) &&
  697. F == LibFunc_memset_pattern16 && TLI.has(F))
  698. if (ArgIdx == 0)
  699. return true;
  700. // TODO: memset_pattern4, memset_pattern8
  701. // TODO: _chk variants
  702. // TODO: strcmp, strcpy
  703. return false;
  704. }
  705. ModRefInfo BasicAAResult::getArgModRefInfo(const CallBase *Call,
  706. unsigned ArgIdx) {
  707. // Checking for known builtin intrinsics and target library functions.
  708. if (isWriteOnlyParam(Call, ArgIdx, TLI))
  709. return ModRefInfo::Mod;
  710. if (Call->paramHasAttr(ArgIdx, Attribute::ReadOnly))
  711. return ModRefInfo::Ref;
  712. if (Call->paramHasAttr(ArgIdx, Attribute::ReadNone))
  713. return ModRefInfo::NoModRef;
  714. return AAResultBase::getArgModRefInfo(Call, ArgIdx);
  715. }
  716. static bool isIntrinsicCall(const CallBase *Call, Intrinsic::ID IID) {
  717. const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Call);
  718. return II && II->getIntrinsicID() == IID;
  719. }
  720. #ifndef NDEBUG
  721. static const Function *getParent(const Value *V) {
  722. if (const Instruction *inst = dyn_cast<Instruction>(V)) {
  723. if (!inst->getParent())
  724. return nullptr;
  725. return inst->getParent()->getParent();
  726. }
  727. if (const Argument *arg = dyn_cast<Argument>(V))
  728. return arg->getParent();
  729. return nullptr;
  730. }
  731. static bool notDifferentParent(const Value *O1, const Value *O2) {
  732. const Function *F1 = getParent(O1);
  733. const Function *F2 = getParent(O2);
  734. return !F1 || !F2 || F1 == F2;
  735. }
  736. #endif
  737. AliasResult BasicAAResult::alias(const MemoryLocation &LocA,
  738. const MemoryLocation &LocB,
  739. AAQueryInfo &AAQI) {
  740. assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
  741. "BasicAliasAnalysis doesn't support interprocedural queries.");
  742. // If we have a directly cached entry for these locations, we have recursed
  743. // through this once, so just return the cached results. Notably, when this
  744. // happens, we don't clear the cache.
  745. auto CacheIt = AAQI.AliasCache.find(AAQueryInfo::LocPair(LocA, LocB));
  746. if (CacheIt != AAQI.AliasCache.end())
  747. return CacheIt->second;
  748. CacheIt = AAQI.AliasCache.find(AAQueryInfo::LocPair(LocB, LocA));
  749. if (CacheIt != AAQI.AliasCache.end())
  750. return CacheIt->second;
  751. AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.AATags, LocB.Ptr,
  752. LocB.Size, LocB.AATags, AAQI);
  753. VisitedPhiBBs.clear();
  754. return Alias;
  755. }
  756. /// Checks to see if the specified callsite can clobber the specified memory
  757. /// object.
  758. ///
  759. /// Since we only look at local properties of this function, we really can't
  760. /// say much about this query. We do, however, use simple "address taken"
  761. /// analysis on local objects.
  762. ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call,
  763. const MemoryLocation &Loc,
  764. AAQueryInfo &AAQI) {
  765. assert(notDifferentParent(Call, Loc.Ptr) &&
  766. "AliasAnalysis query involving multiple functions!");
  767. const Value *Object = GetUnderlyingObject(Loc.Ptr, DL);
  768. // Calls marked 'tail' cannot read or write allocas from the current frame
  769. // because the current frame might be destroyed by the time they run. However,
  770. // a tail call may use an alloca with byval. Calling with byval copies the
  771. // contents of the alloca into argument registers or stack slots, so there is
  772. // no lifetime issue.
  773. if (isa<AllocaInst>(Object))
  774. if (const CallInst *CI = dyn_cast<CallInst>(Call))
  775. if (CI->isTailCall() &&
  776. !CI->getAttributes().hasAttrSomewhere(Attribute::ByVal))
  777. return ModRefInfo::NoModRef;
  778. // Stack restore is able to modify unescaped dynamic allocas. Assume it may
  779. // modify them even though the alloca is not escaped.
  780. if (auto *AI = dyn_cast<AllocaInst>(Object))
  781. if (!AI->isStaticAlloca() && isIntrinsicCall(Call, Intrinsic::stackrestore))
  782. return ModRefInfo::Mod;
  783. // If the pointer is to a locally allocated object that does not escape,
  784. // then the call can not mod/ref the pointer unless the call takes the pointer
  785. // as an argument, and itself doesn't capture it.
  786. if (!isa<Constant>(Object) && Call != Object &&
  787. isNonEscapingLocalObject(Object, &AAQI.IsCapturedCache)) {
  788. // Optimistically assume that call doesn't touch Object and check this
  789. // assumption in the following loop.
  790. ModRefInfo Result = ModRefInfo::NoModRef;
  791. bool IsMustAlias = true;
  792. unsigned OperandNo = 0;
  793. for (auto CI = Call->data_operands_begin(), CE = Call->data_operands_end();
  794. CI != CE; ++CI, ++OperandNo) {
  795. // Only look at the no-capture or byval pointer arguments. If this
  796. // pointer were passed to arguments that were neither of these, then it
  797. // couldn't be no-capture.
  798. if (!(*CI)->getType()->isPointerTy() ||
  799. (!Call->doesNotCapture(OperandNo) &&
  800. OperandNo < Call->getNumArgOperands() &&
  801. !Call->isByValArgument(OperandNo)))
  802. continue;
  803. // Call doesn't access memory through this operand, so we don't care
  804. // if it aliases with Object.
  805. if (Call->doesNotAccessMemory(OperandNo))
  806. continue;
  807. // If this is a no-capture pointer argument, see if we can tell that it
  808. // is impossible to alias the pointer we're checking.
  809. AliasResult AR = getBestAAResults().alias(MemoryLocation(*CI),
  810. MemoryLocation(Object), AAQI);
  811. if (AR != MustAlias)
  812. IsMustAlias = false;
  813. // Operand doesn't alias 'Object', continue looking for other aliases
  814. if (AR == NoAlias)
  815. continue;
  816. // Operand aliases 'Object', but call doesn't modify it. Strengthen
  817. // initial assumption and keep looking in case if there are more aliases.
  818. if (Call->onlyReadsMemory(OperandNo)) {
  819. Result = setRef(Result);
  820. continue;
  821. }
  822. // Operand aliases 'Object' but call only writes into it.
  823. if (Call->doesNotReadMemory(OperandNo)) {
  824. Result = setMod(Result);
  825. continue;
  826. }
  827. // This operand aliases 'Object' and call reads and writes into it.
  828. // Setting ModRef will not yield an early return below, MustAlias is not
  829. // used further.
  830. Result = ModRefInfo::ModRef;
  831. break;
  832. }
  833. // No operand aliases, reset Must bit. Add below if at least one aliases
  834. // and all aliases found are MustAlias.
  835. if (isNoModRef(Result))
  836. IsMustAlias = false;
  837. // Early return if we improved mod ref information
  838. if (!isModAndRefSet(Result)) {
  839. if (isNoModRef(Result))
  840. return ModRefInfo::NoModRef;
  841. return IsMustAlias ? setMust(Result) : clearMust(Result);
  842. }
  843. }
  844. // If the call is to malloc or calloc, we can assume that it doesn't
  845. // modify any IR visible value. This is only valid because we assume these
  846. // routines do not read values visible in the IR. TODO: Consider special
  847. // casing realloc and strdup routines which access only their arguments as
  848. // well. Or alternatively, replace all of this with inaccessiblememonly once
  849. // that's implemented fully.
  850. if (isMallocOrCallocLikeFn(Call, &TLI)) {
  851. // Be conservative if the accessed pointer may alias the allocation -
  852. // fallback to the generic handling below.
  853. if (getBestAAResults().alias(MemoryLocation(Call), Loc, AAQI) == NoAlias)
  854. return ModRefInfo::NoModRef;
  855. }
  856. // The semantics of memcpy intrinsics forbid overlap between their respective
  857. // operands, i.e., source and destination of any given memcpy must no-alias.
  858. // If Loc must-aliases either one of these two locations, then it necessarily
  859. // no-aliases the other.
  860. if (auto *Inst = dyn_cast<AnyMemCpyInst>(Call)) {
  861. AliasResult SrcAA, DestAA;
  862. if ((SrcAA = getBestAAResults().alias(MemoryLocation::getForSource(Inst),
  863. Loc, AAQI)) == MustAlias)
  864. // Loc is exactly the memcpy source thus disjoint from memcpy dest.
  865. return ModRefInfo::Ref;
  866. if ((DestAA = getBestAAResults().alias(MemoryLocation::getForDest(Inst),
  867. Loc, AAQI)) == MustAlias)
  868. // The converse case.
  869. return ModRefInfo::Mod;
  870. // It's also possible for Loc to alias both src and dest, or neither.
  871. ModRefInfo rv = ModRefInfo::NoModRef;
  872. if (SrcAA != NoAlias)
  873. rv = setRef(rv);
  874. if (DestAA != NoAlias)
  875. rv = setMod(rv);
  876. return rv;
  877. }
  878. // While the assume intrinsic is marked as arbitrarily writing so that
  879. // proper control dependencies will be maintained, it never aliases any
  880. // particular memory location.
  881. if (isIntrinsicCall(Call, Intrinsic::assume))
  882. return ModRefInfo::NoModRef;
  883. // Like assumes, guard intrinsics are also marked as arbitrarily writing so
  884. // that proper control dependencies are maintained but they never mods any
  885. // particular memory location.
  886. //
  887. // *Unlike* assumes, guard intrinsics are modeled as reading memory since the
  888. // heap state at the point the guard is issued needs to be consistent in case
  889. // the guard invokes the "deopt" continuation.
  890. if (isIntrinsicCall(Call, Intrinsic::experimental_guard))
  891. return ModRefInfo::Ref;
  892. // Like assumes, invariant.start intrinsics were also marked as arbitrarily
  893. // writing so that proper control dependencies are maintained but they never
  894. // mod any particular memory location visible to the IR.
  895. // *Unlike* assumes (which are now modeled as NoModRef), invariant.start
  896. // intrinsic is now modeled as reading memory. This prevents hoisting the
  897. // invariant.start intrinsic over stores. Consider:
  898. // *ptr = 40;
  899. // *ptr = 50;
  900. // invariant_start(ptr)
  901. // int val = *ptr;
  902. // print(val);
  903. //
  904. // This cannot be transformed to:
  905. //
  906. // *ptr = 40;
  907. // invariant_start(ptr)
  908. // *ptr = 50;
  909. // int val = *ptr;
  910. // print(val);
  911. //
  912. // The transformation will cause the second store to be ignored (based on
  913. // rules of invariant.start) and print 40, while the first program always
  914. // prints 50.
  915. if (isIntrinsicCall(Call, Intrinsic::invariant_start))
  916. return ModRefInfo::Ref;
  917. // The AAResultBase base class has some smarts, lets use them.
  918. return AAResultBase::getModRefInfo(Call, Loc, AAQI);
  919. }
  920. ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call1,
  921. const CallBase *Call2,
  922. AAQueryInfo &AAQI) {
  923. // While the assume intrinsic is marked as arbitrarily writing so that
  924. // proper control dependencies will be maintained, it never aliases any
  925. // particular memory location.
  926. if (isIntrinsicCall(Call1, Intrinsic::assume) ||
  927. isIntrinsicCall(Call2, Intrinsic::assume))
  928. return ModRefInfo::NoModRef;
  929. // Like assumes, guard intrinsics are also marked as arbitrarily writing so
  930. // that proper control dependencies are maintained but they never mod any
  931. // particular memory location.
  932. //
  933. // *Unlike* assumes, guard intrinsics are modeled as reading memory since the
  934. // heap state at the point the guard is issued needs to be consistent in case
  935. // the guard invokes the "deopt" continuation.
  936. // NB! This function is *not* commutative, so we special case two
  937. // possibilities for guard intrinsics.
  938. if (isIntrinsicCall(Call1, Intrinsic::experimental_guard))
  939. return isModSet(createModRefInfo(getModRefBehavior(Call2)))
  940. ? ModRefInfo::Ref
  941. : ModRefInfo::NoModRef;
  942. if (isIntrinsicCall(Call2, Intrinsic::experimental_guard))
  943. return isModSet(createModRefInfo(getModRefBehavior(Call1)))
  944. ? ModRefInfo::Mod
  945. : ModRefInfo::NoModRef;
  946. // The AAResultBase base class has some smarts, lets use them.
  947. return AAResultBase::getModRefInfo(Call1, Call2, AAQI);
  948. }
  949. /// Provide ad-hoc rules to disambiguate accesses through two GEP operators,
  950. /// both having the exact same pointer operand.
  951. static AliasResult aliasSameBasePointerGEPs(const GEPOperator *GEP1,
  952. LocationSize MaybeV1Size,
  953. const GEPOperator *GEP2,
  954. LocationSize MaybeV2Size,
  955. const DataLayout &DL) {
  956. assert(GEP1->getPointerOperand()->stripPointerCastsAndInvariantGroups() ==
  957. GEP2->getPointerOperand()->stripPointerCastsAndInvariantGroups() &&
  958. GEP1->getPointerOperandType() == GEP2->getPointerOperandType() &&
  959. "Expected GEPs with the same pointer operand");
  960. // Try to determine whether GEP1 and GEP2 index through arrays, into structs,
  961. // such that the struct field accesses provably cannot alias.
  962. // We also need at least two indices (the pointer, and the struct field).
  963. if (GEP1->getNumIndices() != GEP2->getNumIndices() ||
  964. GEP1->getNumIndices() < 2)
  965. return MayAlias;
  966. // If we don't know the size of the accesses through both GEPs, we can't
  967. // determine whether the struct fields accessed can't alias.
  968. if (MaybeV1Size == LocationSize::unknown() ||
  969. MaybeV2Size == LocationSize::unknown())
  970. return MayAlias;
  971. const uint64_t V1Size = MaybeV1Size.getValue();
  972. const uint64_t V2Size = MaybeV2Size.getValue();
  973. ConstantInt *C1 =
  974. dyn_cast<ConstantInt>(GEP1->getOperand(GEP1->getNumOperands() - 1));
  975. ConstantInt *C2 =
  976. dyn_cast<ConstantInt>(GEP2->getOperand(GEP2->getNumOperands() - 1));
  977. // If the last (struct) indices are constants and are equal, the other indices
  978. // might be also be dynamically equal, so the GEPs can alias.
  979. if (C1 && C2) {
  980. unsigned BitWidth = std::max(C1->getBitWidth(), C2->getBitWidth());
  981. if (C1->getValue().sextOrSelf(BitWidth) ==
  982. C2->getValue().sextOrSelf(BitWidth))
  983. return MayAlias;
  984. }
  985. // Find the last-indexed type of the GEP, i.e., the type you'd get if
  986. // you stripped the last index.
  987. // On the way, look at each indexed type. If there's something other
  988. // than an array, different indices can lead to different final types.
  989. SmallVector<Value *, 8> IntermediateIndices;
  990. // Insert the first index; we don't need to check the type indexed
  991. // through it as it only drops the pointer indirection.
  992. assert(GEP1->getNumIndices() > 1 && "Not enough GEP indices to examine");
  993. IntermediateIndices.push_back(GEP1->getOperand(1));
  994. // Insert all the remaining indices but the last one.
  995. // Also, check that they all index through arrays.
  996. for (unsigned i = 1, e = GEP1->getNumIndices() - 1; i != e; ++i) {
  997. if (!isa<ArrayType>(GetElementPtrInst::getIndexedType(
  998. GEP1->getSourceElementType(), IntermediateIndices)))
  999. return MayAlias;
  1000. IntermediateIndices.push_back(GEP1->getOperand(i + 1));
  1001. }
  1002. auto *Ty = GetElementPtrInst::getIndexedType(
  1003. GEP1->getSourceElementType(), IntermediateIndices);
  1004. StructType *LastIndexedStruct = dyn_cast<StructType>(Ty);
  1005. if (isa<SequentialType>(Ty)) {
  1006. // We know that:
  1007. // - both GEPs begin indexing from the exact same pointer;
  1008. // - the last indices in both GEPs are constants, indexing into a sequential
  1009. // type (array or pointer);
  1010. // - both GEPs only index through arrays prior to that.
  1011. //
  1012. // Because array indices greater than the number of elements are valid in
  1013. // GEPs, unless we know the intermediate indices are identical between
  1014. // GEP1 and GEP2 we cannot guarantee that the last indexed arrays don't
  1015. // partially overlap. We also need to check that the loaded size matches
  1016. // the element size, otherwise we could still have overlap.
  1017. const uint64_t ElementSize =
  1018. DL.getTypeStoreSize(cast<SequentialType>(Ty)->getElementType());
  1019. if (V1Size != ElementSize || V2Size != ElementSize)
  1020. return MayAlias;
  1021. for (unsigned i = 0, e = GEP1->getNumIndices() - 1; i != e; ++i)
  1022. if (GEP1->getOperand(i + 1) != GEP2->getOperand(i + 1))
  1023. return MayAlias;
  1024. // Now we know that the array/pointer that GEP1 indexes into and that
  1025. // that GEP2 indexes into must either precisely overlap or be disjoint.
  1026. // Because they cannot partially overlap and because fields in an array
  1027. // cannot overlap, if we can prove the final indices are different between
  1028. // GEP1 and GEP2, we can conclude GEP1 and GEP2 don't alias.
  1029. // If the last indices are constants, we've already checked they don't
  1030. // equal each other so we can exit early.
  1031. if (C1 && C2)
  1032. return NoAlias;
  1033. {
  1034. Value *GEP1LastIdx = GEP1->getOperand(GEP1->getNumOperands() - 1);
  1035. Value *GEP2LastIdx = GEP2->getOperand(GEP2->getNumOperands() - 1);
  1036. if (isa<PHINode>(GEP1LastIdx) || isa<PHINode>(GEP2LastIdx)) {
  1037. // If one of the indices is a PHI node, be safe and only use
  1038. // computeKnownBits so we don't make any assumptions about the
  1039. // relationships between the two indices. This is important if we're
  1040. // asking about values from different loop iterations. See PR32314.
  1041. // TODO: We may be able to change the check so we only do this when
  1042. // we definitely looked through a PHINode.
  1043. if (GEP1LastIdx != GEP2LastIdx &&
  1044. GEP1LastIdx->getType() == GEP2LastIdx->getType()) {
  1045. KnownBits Known1 = computeKnownBits(GEP1LastIdx, DL);
  1046. KnownBits Known2 = computeKnownBits(GEP2LastIdx, DL);
  1047. if (Known1.Zero.intersects(Known2.One) ||
  1048. Known1.One.intersects(Known2.Zero))
  1049. return NoAlias;
  1050. }
  1051. } else if (isKnownNonEqual(GEP1LastIdx, GEP2LastIdx, DL))
  1052. return NoAlias;
  1053. }
  1054. return MayAlias;
  1055. } else if (!LastIndexedStruct || !C1 || !C2) {
  1056. return MayAlias;
  1057. }
  1058. if (C1->getValue().getActiveBits() > 64 ||
  1059. C2->getValue().getActiveBits() > 64)
  1060. return MayAlias;
  1061. // We know that:
  1062. // - both GEPs begin indexing from the exact same pointer;
  1063. // - the last indices in both GEPs are constants, indexing into a struct;
  1064. // - said indices are different, hence, the pointed-to fields are different;
  1065. // - both GEPs only index through arrays prior to that.
  1066. //
  1067. // This lets us determine that the struct that GEP1 indexes into and the
  1068. // struct that GEP2 indexes into must either precisely overlap or be
  1069. // completely disjoint. Because they cannot partially overlap, indexing into
  1070. // different non-overlapping fields of the struct will never alias.
  1071. // Therefore, the only remaining thing needed to show that both GEPs can't
  1072. // alias is that the fields are not overlapping.
  1073. const StructLayout *SL = DL.getStructLayout(LastIndexedStruct);
  1074. const uint64_t StructSize = SL->getSizeInBytes();
  1075. const uint64_t V1Off = SL->getElementOffset(C1->getZExtValue());
  1076. const uint64_t V2Off = SL->getElementOffset(C2->getZExtValue());
  1077. auto EltsDontOverlap = [StructSize](uint64_t V1Off, uint64_t V1Size,
  1078. uint64_t V2Off, uint64_t V2Size) {
  1079. return V1Off < V2Off && V1Off + V1Size <= V2Off &&
  1080. ((V2Off + V2Size <= StructSize) ||
  1081. (V2Off + V2Size - StructSize <= V1Off));
  1082. };
  1083. if (EltsDontOverlap(V1Off, V1Size, V2Off, V2Size) ||
  1084. EltsDontOverlap(V2Off, V2Size, V1Off, V1Size))
  1085. return NoAlias;
  1086. return MayAlias;
  1087. }
  1088. // If a we have (a) a GEP and (b) a pointer based on an alloca, and the
  1089. // beginning of the object the GEP points would have a negative offset with
  1090. // repsect to the alloca, that means the GEP can not alias pointer (b).
  1091. // Note that the pointer based on the alloca may not be a GEP. For
  1092. // example, it may be the alloca itself.
  1093. // The same applies if (b) is based on a GlobalVariable. Note that just being
  1094. // based on isIdentifiedObject() is not enough - we need an identified object
  1095. // that does not permit access to negative offsets. For example, a negative
  1096. // offset from a noalias argument or call can be inbounds w.r.t the actual
  1097. // underlying object.
  1098. //
  1099. // For example, consider:
  1100. //
  1101. // struct { int f0, int f1, ...} foo;
  1102. // foo alloca;
  1103. // foo* random = bar(alloca);
  1104. // int *f0 = &alloca.f0
  1105. // int *f1 = &random->f1;
  1106. //
  1107. // Which is lowered, approximately, to:
  1108. //
  1109. // %alloca = alloca %struct.foo
  1110. // %random = call %struct.foo* @random(%struct.foo* %alloca)
  1111. // %f0 = getelementptr inbounds %struct, %struct.foo* %alloca, i32 0, i32 0
  1112. // %f1 = getelementptr inbounds %struct, %struct.foo* %random, i32 0, i32 1
  1113. //
  1114. // Assume %f1 and %f0 alias. Then %f1 would point into the object allocated
  1115. // by %alloca. Since the %f1 GEP is inbounds, that means %random must also
  1116. // point into the same object. But since %f0 points to the beginning of %alloca,
  1117. // the highest %f1 can be is (%alloca + 3). This means %random can not be higher
  1118. // than (%alloca - 1), and so is not inbounds, a contradiction.
  1119. bool BasicAAResult::isGEPBaseAtNegativeOffset(const GEPOperator *GEPOp,
  1120. const DecomposedGEP &DecompGEP, const DecomposedGEP &DecompObject,
  1121. LocationSize MaybeObjectAccessSize) {
  1122. // If the object access size is unknown, or the GEP isn't inbounds, bail.
  1123. if (MaybeObjectAccessSize == LocationSize::unknown() || !GEPOp->isInBounds())
  1124. return false;
  1125. const uint64_t ObjectAccessSize = MaybeObjectAccessSize.getValue();
  1126. // We need the object to be an alloca or a globalvariable, and want to know
  1127. // the offset of the pointer from the object precisely, so no variable
  1128. // indices are allowed.
  1129. if (!(isa<AllocaInst>(DecompObject.Base) ||
  1130. isa<GlobalVariable>(DecompObject.Base)) ||
  1131. !DecompObject.VarIndices.empty())
  1132. return false;
  1133. APInt ObjectBaseOffset = DecompObject.StructOffset +
  1134. DecompObject.OtherOffset;
  1135. // If the GEP has no variable indices, we know the precise offset
  1136. // from the base, then use it. If the GEP has variable indices,
  1137. // we can't get exact GEP offset to identify pointer alias. So return
  1138. // false in that case.
  1139. if (!DecompGEP.VarIndices.empty())
  1140. return false;
  1141. APInt GEPBaseOffset = DecompGEP.StructOffset;
  1142. GEPBaseOffset += DecompGEP.OtherOffset;
  1143. return GEPBaseOffset.sge(ObjectBaseOffset + (int64_t)ObjectAccessSize);
  1144. }
  1145. /// Provides a bunch of ad-hoc rules to disambiguate a GEP instruction against
  1146. /// another pointer.
  1147. ///
  1148. /// We know that V1 is a GEP, but we don't know anything about V2.
  1149. /// UnderlyingV1 is GetUnderlyingObject(GEP1, DL), UnderlyingV2 is the same for
  1150. /// V2.
  1151. AliasResult BasicAAResult::aliasGEP(
  1152. const GEPOperator *GEP1, LocationSize V1Size, const AAMDNodes &V1AAInfo,
  1153. const Value *V2, LocationSize V2Size, const AAMDNodes &V2AAInfo,
  1154. const Value *UnderlyingV1, const Value *UnderlyingV2, AAQueryInfo &AAQI) {
  1155. DecomposedGEP DecompGEP1, DecompGEP2;
  1156. unsigned MaxPointerSize = getMaxPointerSize(DL);
  1157. DecompGEP1.StructOffset = DecompGEP1.OtherOffset = APInt(MaxPointerSize, 0);
  1158. DecompGEP2.StructOffset = DecompGEP2.OtherOffset = APInt(MaxPointerSize, 0);
  1159. bool GEP1MaxLookupReached =
  1160. DecomposeGEPExpression(GEP1, DecompGEP1, DL, &AC, DT);
  1161. bool GEP2MaxLookupReached =
  1162. DecomposeGEPExpression(V2, DecompGEP2, DL, &AC, DT);
  1163. APInt GEP1BaseOffset = DecompGEP1.StructOffset + DecompGEP1.OtherOffset;
  1164. APInt GEP2BaseOffset = DecompGEP2.StructOffset + DecompGEP2.OtherOffset;
  1165. assert(DecompGEP1.Base == UnderlyingV1 && DecompGEP2.Base == UnderlyingV2 &&
  1166. "DecomposeGEPExpression returned a result different from "
  1167. "GetUnderlyingObject");
  1168. // If the GEP's offset relative to its base is such that the base would
  1169. // fall below the start of the object underlying V2, then the GEP and V2
  1170. // cannot alias.
  1171. if (!GEP1MaxLookupReached && !GEP2MaxLookupReached &&
  1172. isGEPBaseAtNegativeOffset(GEP1, DecompGEP1, DecompGEP2, V2Size))
  1173. return NoAlias;
  1174. // If we have two gep instructions with must-alias or not-alias'ing base
  1175. // pointers, figure out if the indexes to the GEP tell us anything about the
  1176. // derived pointer.
  1177. if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
  1178. // Check for the GEP base being at a negative offset, this time in the other
  1179. // direction.
  1180. if (!GEP1MaxLookupReached && !GEP2MaxLookupReached &&
  1181. isGEPBaseAtNegativeOffset(GEP2, DecompGEP2, DecompGEP1, V1Size))
  1182. return NoAlias;
  1183. // Do the base pointers alias?
  1184. AliasResult BaseAlias =
  1185. aliasCheck(UnderlyingV1, LocationSize::unknown(), AAMDNodes(),
  1186. UnderlyingV2, LocationSize::unknown(), AAMDNodes(), AAQI);
  1187. // Check for geps of non-aliasing underlying pointers where the offsets are
  1188. // identical.
  1189. if ((BaseAlias == MayAlias) && V1Size == V2Size) {
  1190. // Do the base pointers alias assuming type and size.
  1191. AliasResult PreciseBaseAlias = aliasCheck(
  1192. UnderlyingV1, V1Size, V1AAInfo, UnderlyingV2, V2Size, V2AAInfo, AAQI);
  1193. if (PreciseBaseAlias == NoAlias) {
  1194. // See if the computed offset from the common pointer tells us about the
  1195. // relation of the resulting pointer.
  1196. // If the max search depth is reached the result is undefined
  1197. if (GEP2MaxLookupReached || GEP1MaxLookupReached)
  1198. return MayAlias;
  1199. // Same offsets.
  1200. if (GEP1BaseOffset == GEP2BaseOffset &&
  1201. DecompGEP1.VarIndices == DecompGEP2.VarIndices)
  1202. return NoAlias;
  1203. }
  1204. }
  1205. // If we get a No or May, then return it immediately, no amount of analysis
  1206. // will improve this situation.
  1207. if (BaseAlias != MustAlias) {
  1208. assert(BaseAlias == NoAlias || BaseAlias == MayAlias);
  1209. return BaseAlias;
  1210. }
  1211. // Otherwise, we have a MustAlias. Since the base pointers alias each other
  1212. // exactly, see if the computed offset from the common pointer tells us
  1213. // about the relation of the resulting pointer.
  1214. // If we know the two GEPs are based off of the exact same pointer (and not
  1215. // just the same underlying object), see if that tells us anything about
  1216. // the resulting pointers.
  1217. if (GEP1->getPointerOperand()->stripPointerCastsAndInvariantGroups() ==
  1218. GEP2->getPointerOperand()->stripPointerCastsAndInvariantGroups() &&
  1219. GEP1->getPointerOperandType() == GEP2->getPointerOperandType()) {
  1220. AliasResult R = aliasSameBasePointerGEPs(GEP1, V1Size, GEP2, V2Size, DL);
  1221. // If we couldn't find anything interesting, don't abandon just yet.
  1222. if (R != MayAlias)
  1223. return R;
  1224. }
  1225. // If the max search depth is reached, the result is undefined
  1226. if (GEP2MaxLookupReached || GEP1MaxLookupReached)
  1227. return MayAlias;
  1228. // Subtract the GEP2 pointer from the GEP1 pointer to find out their
  1229. // symbolic difference.
  1230. GEP1BaseOffset -= GEP2BaseOffset;
  1231. GetIndexDifference(DecompGEP1.VarIndices, DecompGEP2.VarIndices);
  1232. } else {
  1233. // Check to see if these two pointers are related by the getelementptr
  1234. // instruction. If one pointer is a GEP with a non-zero index of the other
  1235. // pointer, we know they cannot alias.
  1236. // If both accesses are unknown size, we can't do anything useful here.
  1237. if (V1Size == LocationSize::unknown() && V2Size == LocationSize::unknown())
  1238. return MayAlias;
  1239. AliasResult R = aliasCheck(UnderlyingV1, LocationSize::unknown(),
  1240. AAMDNodes(), V2, LocationSize::unknown(),
  1241. V2AAInfo, AAQI, nullptr, UnderlyingV2);
  1242. if (R != MustAlias) {
  1243. // If V2 may alias GEP base pointer, conservatively returns MayAlias.
  1244. // If V2 is known not to alias GEP base pointer, then the two values
  1245. // cannot alias per GEP semantics: "Any memory access must be done through
  1246. // a pointer value associated with an address range of the memory access,
  1247. // otherwise the behavior is undefined.".
  1248. assert(R == NoAlias || R == MayAlias);
  1249. return R;
  1250. }
  1251. // If the max search depth is reached the result is undefined
  1252. if (GEP1MaxLookupReached)
  1253. return MayAlias;
  1254. }
  1255. // In the two GEP Case, if there is no difference in the offsets of the
  1256. // computed pointers, the resultant pointers are a must alias. This
  1257. // happens when we have two lexically identical GEP's (for example).
  1258. //
  1259. // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
  1260. // must aliases the GEP, the end result is a must alias also.
  1261. if (GEP1BaseOffset == 0 && DecompGEP1.VarIndices.empty())
  1262. return MustAlias;
  1263. // If there is a constant difference between the pointers, but the difference
  1264. // is less than the size of the associated memory object, then we know
  1265. // that the objects are partially overlapping. If the difference is
  1266. // greater, we know they do not overlap.
  1267. if (GEP1BaseOffset != 0 && DecompGEP1.VarIndices.empty()) {
  1268. if (GEP1BaseOffset.sge(0)) {
  1269. if (V2Size != LocationSize::unknown()) {
  1270. if (GEP1BaseOffset.ult(V2Size.getValue()))
  1271. return PartialAlias;
  1272. return NoAlias;
  1273. }
  1274. } else {
  1275. // We have the situation where:
  1276. // + +
  1277. // | BaseOffset |
  1278. // ---------------->|
  1279. // |-->V1Size |-------> V2Size
  1280. // GEP1 V2
  1281. // We need to know that V2Size is not unknown, otherwise we might have
  1282. // stripped a gep with negative index ('gep <ptr>, -1, ...).
  1283. if (V1Size != LocationSize::unknown() &&
  1284. V2Size != LocationSize::unknown()) {
  1285. if ((-GEP1BaseOffset).ult(V1Size.getValue()))
  1286. return PartialAlias;
  1287. return NoAlias;
  1288. }
  1289. }
  1290. }
  1291. if (!DecompGEP1.VarIndices.empty()) {
  1292. APInt Modulo(MaxPointerSize, 0);
  1293. bool AllPositive = true;
  1294. for (unsigned i = 0, e = DecompGEP1.VarIndices.size(); i != e; ++i) {
  1295. // Try to distinguish something like &A[i][1] against &A[42][0].
  1296. // Grab the least significant bit set in any of the scales. We
  1297. // don't need std::abs here (even if the scale's negative) as we'll
  1298. // be ^'ing Modulo with itself later.
  1299. Modulo |= DecompGEP1.VarIndices[i].Scale;
  1300. if (AllPositive) {
  1301. // If the Value could change between cycles, then any reasoning about
  1302. // the Value this cycle may not hold in the next cycle. We'll just
  1303. // give up if we can't determine conditions that hold for every cycle:
  1304. const Value *V = DecompGEP1.VarIndices[i].V;
  1305. KnownBits Known = computeKnownBits(V, DL, 0, &AC, nullptr, DT);
  1306. bool SignKnownZero = Known.isNonNegative();
  1307. bool SignKnownOne = Known.isNegative();
  1308. // Zero-extension widens the variable, and so forces the sign
  1309. // bit to zero.
  1310. bool IsZExt = DecompGEP1.VarIndices[i].ZExtBits > 0 || isa<ZExtInst>(V);
  1311. SignKnownZero |= IsZExt;
  1312. SignKnownOne &= !IsZExt;
  1313. // If the variable begins with a zero then we know it's
  1314. // positive, regardless of whether the value is signed or
  1315. // unsigned.
  1316. APInt Scale = DecompGEP1.VarIndices[i].Scale;
  1317. AllPositive =
  1318. (SignKnownZero && Scale.sge(0)) || (SignKnownOne && Scale.slt(0));
  1319. }
  1320. }
  1321. Modulo = Modulo ^ (Modulo & (Modulo - 1));
  1322. // We can compute the difference between the two addresses
  1323. // mod Modulo. Check whether that difference guarantees that the
  1324. // two locations do not alias.
  1325. APInt ModOffset = GEP1BaseOffset & (Modulo - 1);
  1326. if (V1Size != LocationSize::unknown() &&
  1327. V2Size != LocationSize::unknown() && ModOffset.uge(V2Size.getValue()) &&
  1328. (Modulo - ModOffset).uge(V1Size.getValue()))
  1329. return NoAlias;
  1330. // If we know all the variables are positive, then GEP1 >= GEP1BasePtr.
  1331. // If GEP1BasePtr > V2 (GEP1BaseOffset > 0) then we know the pointers
  1332. // don't alias if V2Size can fit in the gap between V2 and GEP1BasePtr.
  1333. if (AllPositive && GEP1BaseOffset.sgt(0) &&
  1334. V2Size != LocationSize::unknown() &&
  1335. GEP1BaseOffset.uge(V2Size.getValue()))
  1336. return NoAlias;
  1337. if (constantOffsetHeuristic(DecompGEP1.VarIndices, V1Size, V2Size,
  1338. GEP1BaseOffset, &AC, DT))
  1339. return NoAlias;
  1340. }
  1341. // Statically, we can see that the base objects are the same, but the
  1342. // pointers have dynamic offsets which we can't resolve. And none of our
  1343. // little tricks above worked.
  1344. return MayAlias;
  1345. }
  1346. static AliasResult MergeAliasResults(AliasResult A, AliasResult B) {
  1347. // If the results agree, take it.
  1348. if (A == B)
  1349. return A;
  1350. // A mix of PartialAlias and MustAlias is PartialAlias.
  1351. if ((A == PartialAlias && B == MustAlias) ||
  1352. (B == PartialAlias && A == MustAlias))
  1353. return PartialAlias;
  1354. // Otherwise, we don't know anything.
  1355. return MayAlias;
  1356. }
  1357. /// Provides a bunch of ad-hoc rules to disambiguate a Select instruction
  1358. /// against another.
  1359. AliasResult
  1360. BasicAAResult::aliasSelect(const SelectInst *SI, LocationSize SISize,
  1361. const AAMDNodes &SIAAInfo, const Value *V2,
  1362. LocationSize V2Size, const AAMDNodes &V2AAInfo,
  1363. const Value *UnderV2, AAQueryInfo &AAQI) {
  1364. // If the values are Selects with the same condition, we can do a more precise
  1365. // check: just check for aliases between the values on corresponding arms.
  1366. if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
  1367. if (SI->getCondition() == SI2->getCondition()) {
  1368. AliasResult Alias =
  1369. aliasCheck(SI->getTrueValue(), SISize, SIAAInfo, SI2->getTrueValue(),
  1370. V2Size, V2AAInfo, AAQI);
  1371. if (Alias == MayAlias)
  1372. return MayAlias;
  1373. AliasResult ThisAlias =
  1374. aliasCheck(SI->getFalseValue(), SISize, SIAAInfo,
  1375. SI2->getFalseValue(), V2Size, V2AAInfo, AAQI);
  1376. return MergeAliasResults(ThisAlias, Alias);
  1377. }
  1378. // If both arms of the Select node NoAlias or MustAlias V2, then returns
  1379. // NoAlias / MustAlias. Otherwise, returns MayAlias.
  1380. AliasResult Alias = aliasCheck(V2, V2Size, V2AAInfo, SI->getTrueValue(),
  1381. SISize, SIAAInfo, AAQI, UnderV2);
  1382. if (Alias == MayAlias)
  1383. return MayAlias;
  1384. AliasResult ThisAlias = aliasCheck(V2, V2Size, V2AAInfo, SI->getFalseValue(),
  1385. SISize, SIAAInfo, AAQI, UnderV2);
  1386. return MergeAliasResults(ThisAlias, Alias);
  1387. }
  1388. /// Provide a bunch of ad-hoc rules to disambiguate a PHI instruction against
  1389. /// another.
  1390. AliasResult BasicAAResult::aliasPHI(const PHINode *PN, LocationSize PNSize,
  1391. const AAMDNodes &PNAAInfo, const Value *V2,
  1392. LocationSize V2Size,
  1393. const AAMDNodes &V2AAInfo,
  1394. const Value *UnderV2, AAQueryInfo &AAQI) {
  1395. // Track phi nodes we have visited. We use this information when we determine
  1396. // value equivalence.
  1397. VisitedPhiBBs.insert(PN->getParent());
  1398. // If the values are PHIs in the same block, we can do a more precise
  1399. // as well as efficient check: just check for aliases between the values
  1400. // on corresponding edges.
  1401. if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
  1402. if (PN2->getParent() == PN->getParent()) {
  1403. AAQueryInfo::LocPair Locs(MemoryLocation(PN, PNSize, PNAAInfo),
  1404. MemoryLocation(V2, V2Size, V2AAInfo));
  1405. if (PN > V2)
  1406. std::swap(Locs.first, Locs.second);
  1407. // Analyse the PHIs' inputs under the assumption that the PHIs are
  1408. // NoAlias.
  1409. // If the PHIs are May/MustAlias there must be (recursively) an input
  1410. // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
  1411. // there must be an operation on the PHIs within the PHIs' value cycle
  1412. // that causes a MayAlias.
  1413. // Pretend the phis do not alias.
  1414. AliasResult Alias = NoAlias;
  1415. AliasResult OrigAliasResult;
  1416. {
  1417. // Limited lifetime iterator invalidated by the aliasCheck call below.
  1418. auto CacheIt = AAQI.AliasCache.find(Locs);
  1419. assert((CacheIt != AAQI.AliasCache.end()) &&
  1420. "There must exist an entry for the phi node");
  1421. OrigAliasResult = CacheIt->second;
  1422. CacheIt->second = NoAlias;
  1423. }
  1424. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  1425. AliasResult ThisAlias =
  1426. aliasCheck(PN->getIncomingValue(i), PNSize, PNAAInfo,
  1427. PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
  1428. V2Size, V2AAInfo, AAQI);
  1429. Alias = MergeAliasResults(ThisAlias, Alias);
  1430. if (Alias == MayAlias)
  1431. break;
  1432. }
  1433. // Reset if speculation failed.
  1434. if (Alias != NoAlias) {
  1435. auto Pair =
  1436. AAQI.AliasCache.insert(std::make_pair(Locs, OrigAliasResult));
  1437. assert(!Pair.second && "Entry must have existed");
  1438. Pair.first->second = OrigAliasResult;
  1439. }
  1440. return Alias;
  1441. }
  1442. SmallVector<Value *, 4> V1Srcs;
  1443. bool isRecursive = false;
  1444. if (PV) {
  1445. // If we have PhiValues then use it to get the underlying phi values.
  1446. const PhiValues::ValueSet &PhiValueSet = PV->getValuesForPhi(PN);
  1447. // If we have more phi values than the search depth then return MayAlias
  1448. // conservatively to avoid compile time explosion. The worst possible case
  1449. // is if both sides are PHI nodes. In which case, this is O(m x n) time
  1450. // where 'm' and 'n' are the number of PHI sources.
  1451. if (PhiValueSet.size() > MaxLookupSearchDepth)
  1452. return MayAlias;
  1453. // Add the values to V1Srcs
  1454. for (Value *PV1 : PhiValueSet) {
  1455. if (EnableRecPhiAnalysis) {
  1456. if (GEPOperator *PV1GEP = dyn_cast<GEPOperator>(PV1)) {
  1457. // Check whether the incoming value is a GEP that advances the pointer
  1458. // result of this PHI node (e.g. in a loop). If this is the case, we
  1459. // would recurse and always get a MayAlias. Handle this case specially
  1460. // below.
  1461. if (PV1GEP->getPointerOperand() == PN && PV1GEP->getNumIndices() == 1 &&
  1462. isa<ConstantInt>(PV1GEP->idx_begin())) {
  1463. isRecursive = true;
  1464. continue;
  1465. }
  1466. }
  1467. }
  1468. V1Srcs.push_back(PV1);
  1469. }
  1470. } else {
  1471. // If we don't have PhiInfo then just look at the operands of the phi itself
  1472. // FIXME: Remove this once we can guarantee that we have PhiInfo always
  1473. SmallPtrSet<Value *, 4> UniqueSrc;
  1474. for (Value *PV1 : PN->incoming_values()) {
  1475. if (isa<PHINode>(PV1))
  1476. // If any of the source itself is a PHI, return MayAlias conservatively
  1477. // to avoid compile time explosion. The worst possible case is if both
  1478. // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
  1479. // and 'n' are the number of PHI sources.
  1480. return MayAlias;
  1481. if (EnableRecPhiAnalysis)
  1482. if (GEPOperator *PV1GEP = dyn_cast<GEPOperator>(PV1)) {
  1483. // Check whether the incoming value is a GEP that advances the pointer
  1484. // result of this PHI node (e.g. in a loop). If this is the case, we
  1485. // would recurse and always get a MayAlias. Handle this case specially
  1486. // below.
  1487. if (PV1GEP->getPointerOperand() == PN && PV1GEP->getNumIndices() == 1 &&
  1488. isa<ConstantInt>(PV1GEP->idx_begin())) {
  1489. isRecursive = true;
  1490. continue;
  1491. }
  1492. }
  1493. if (UniqueSrc.insert(PV1).second)
  1494. V1Srcs.push_back(PV1);
  1495. }
  1496. }
  1497. // If V1Srcs is empty then that means that the phi has no underlying non-phi
  1498. // value. This should only be possible in blocks unreachable from the entry
  1499. // block, but return MayAlias just in case.
  1500. if (V1Srcs.empty())
  1501. return MayAlias;
  1502. // If this PHI node is recursive, set the size of the accessed memory to
  1503. // unknown to represent all the possible values the GEP could advance the
  1504. // pointer to.
  1505. if (isRecursive)
  1506. PNSize = LocationSize::unknown();
  1507. AliasResult Alias = aliasCheck(V2, V2Size, V2AAInfo, V1Srcs[0], PNSize,
  1508. PNAAInfo, AAQI, UnderV2);
  1509. // Early exit if the check of the first PHI source against V2 is MayAlias.
  1510. // Other results are not possible.
  1511. if (Alias == MayAlias)
  1512. return MayAlias;
  1513. // If all sources of the PHI node NoAlias or MustAlias V2, then returns
  1514. // NoAlias / MustAlias. Otherwise, returns MayAlias.
  1515. for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
  1516. Value *V = V1Srcs[i];
  1517. AliasResult ThisAlias =
  1518. aliasCheck(V2, V2Size, V2AAInfo, V, PNSize, PNAAInfo, AAQI, UnderV2);
  1519. Alias = MergeAliasResults(ThisAlias, Alias);
  1520. if (Alias == MayAlias)
  1521. break;
  1522. }
  1523. return Alias;
  1524. }
  1525. /// Provides a bunch of ad-hoc rules to disambiguate in common cases, such as
  1526. /// array references.
  1527. AliasResult BasicAAResult::aliasCheck(const Value *V1, LocationSize V1Size,
  1528. AAMDNodes V1AAInfo, const Value *V2,
  1529. LocationSize V2Size, AAMDNodes V2AAInfo,
  1530. AAQueryInfo &AAQI, const Value *O1,
  1531. const Value *O2) {
  1532. // If either of the memory references is empty, it doesn't matter what the
  1533. // pointer values are.
  1534. if (V1Size.isZero() || V2Size.isZero())
  1535. return NoAlias;
  1536. // Strip off any casts if they exist.
  1537. V1 = V1->stripPointerCastsAndInvariantGroups();
  1538. V2 = V2->stripPointerCastsAndInvariantGroups();
  1539. // If V1 or V2 is undef, the result is NoAlias because we can always pick a
  1540. // value for undef that aliases nothing in the program.
  1541. if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
  1542. return NoAlias;
  1543. // Are we checking for alias of the same value?
  1544. // Because we look 'through' phi nodes, we could look at "Value" pointers from
  1545. // different iterations. We must therefore make sure that this is not the
  1546. // case. The function isValueEqualInPotentialCycles ensures that this cannot
  1547. // happen by looking at the visited phi nodes and making sure they cannot
  1548. // reach the value.
  1549. if (isValueEqualInPotentialCycles(V1, V2))
  1550. return MustAlias;
  1551. if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
  1552. return NoAlias; // Scalars cannot alias each other
  1553. // Figure out what objects these things are pointing to if we can.
  1554. if (O1 == nullptr)
  1555. O1 = GetUnderlyingObject(V1, DL, MaxLookupSearchDepth);
  1556. if (O2 == nullptr)
  1557. O2 = GetUnderlyingObject(V2, DL, MaxLookupSearchDepth);
  1558. // Null values in the default address space don't point to any object, so they
  1559. // don't alias any other pointer.
  1560. if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
  1561. if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace()))
  1562. return NoAlias;
  1563. if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
  1564. if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace()))
  1565. return NoAlias;
  1566. if (O1 != O2) {
  1567. // If V1/V2 point to two different objects, we know that we have no alias.
  1568. if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
  1569. return NoAlias;
  1570. // Constant pointers can't alias with non-const isIdentifiedObject objects.
  1571. if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
  1572. (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
  1573. return NoAlias;
  1574. // Function arguments can't alias with things that are known to be
  1575. // unambigously identified at the function level.
  1576. if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
  1577. (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
  1578. return NoAlias;
  1579. // If one pointer is the result of a call/invoke or load and the other is a
  1580. // non-escaping local object within the same function, then we know the
  1581. // object couldn't escape to a point where the call could return it.
  1582. //
  1583. // Note that if the pointers are in different functions, there are a
  1584. // variety of complications. A call with a nocapture argument may still
  1585. // temporary store the nocapture argument's value in a temporary memory
  1586. // location if that memory location doesn't escape. Or it may pass a
  1587. // nocapture value to other functions as long as they don't capture it.
  1588. if (isEscapeSource(O1) &&
  1589. isNonEscapingLocalObject(O2, &AAQI.IsCapturedCache))
  1590. return NoAlias;
  1591. if (isEscapeSource(O2) &&
  1592. isNonEscapingLocalObject(O1, &AAQI.IsCapturedCache))
  1593. return NoAlias;
  1594. }
  1595. // If the size of one access is larger than the entire object on the other
  1596. // side, then we know such behavior is undefined and can assume no alias.
  1597. bool NullIsValidLocation = NullPointerIsDefined(&F);
  1598. if ((isObjectSmallerThan(
  1599. O2, getMinimalExtentFrom(*V1, V1Size, DL, NullIsValidLocation), DL,
  1600. TLI, NullIsValidLocation)) ||
  1601. (isObjectSmallerThan(
  1602. O1, getMinimalExtentFrom(*V2, V2Size, DL, NullIsValidLocation), DL,
  1603. TLI, NullIsValidLocation)))
  1604. return NoAlias;
  1605. // Check the cache before climbing up use-def chains. This also terminates
  1606. // otherwise infinitely recursive queries.
  1607. AAQueryInfo::LocPair Locs(MemoryLocation(V1, V1Size, V1AAInfo),
  1608. MemoryLocation(V2, V2Size, V2AAInfo));
  1609. if (V1 > V2)
  1610. std::swap(Locs.first, Locs.second);
  1611. std::pair<AAQueryInfo::AliasCacheT::iterator, bool> Pair =
  1612. AAQI.AliasCache.try_emplace(Locs, MayAlias);
  1613. if (!Pair.second)
  1614. return Pair.first->second;
  1615. // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
  1616. // GEP can't simplify, we don't even look at the PHI cases.
  1617. if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
  1618. std::swap(V1, V2);
  1619. std::swap(V1Size, V2Size);
  1620. std::swap(O1, O2);
  1621. std::swap(V1AAInfo, V2AAInfo);
  1622. }
  1623. if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
  1624. AliasResult Result =
  1625. aliasGEP(GV1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O1, O2, AAQI);
  1626. if (Result != MayAlias) {
  1627. auto ItInsPair = AAQI.AliasCache.insert(std::make_pair(Locs, Result));
  1628. assert(!ItInsPair.second && "Entry must have existed");
  1629. ItInsPair.first->second = Result;
  1630. return Result;
  1631. }
  1632. }
  1633. if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
  1634. std::swap(V1, V2);
  1635. std::swap(O1, O2);
  1636. std::swap(V1Size, V2Size);
  1637. std::swap(V1AAInfo, V2AAInfo);
  1638. }
  1639. if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
  1640. AliasResult Result =
  1641. aliasPHI(PN, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O2, AAQI);
  1642. if (Result != MayAlias) {
  1643. Pair = AAQI.AliasCache.try_emplace(Locs, Result);
  1644. assert(!Pair.second && "Entry must have existed");
  1645. return Pair.first->second = Result;
  1646. }
  1647. }
  1648. if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
  1649. std::swap(V1, V2);
  1650. std::swap(O1, O2);
  1651. std::swap(V1Size, V2Size);
  1652. std::swap(V1AAInfo, V2AAInfo);
  1653. }
  1654. if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
  1655. AliasResult Result =
  1656. aliasSelect(S1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O2, AAQI);
  1657. if (Result != MayAlias) {
  1658. Pair = AAQI.AliasCache.try_emplace(Locs, Result);
  1659. assert(!Pair.second && "Entry must have existed");
  1660. return Pair.first->second = Result;
  1661. }
  1662. }
  1663. // If both pointers are pointing into the same object and one of them
  1664. // accesses the entire object, then the accesses must overlap in some way.
  1665. if (O1 == O2)
  1666. if (V1Size.isPrecise() && V2Size.isPrecise() &&
  1667. (isObjectSize(O1, V1Size.getValue(), DL, TLI, NullIsValidLocation) ||
  1668. isObjectSize(O2, V2Size.getValue(), DL, TLI, NullIsValidLocation))) {
  1669. Pair = AAQI.AliasCache.try_emplace(Locs, PartialAlias);
  1670. assert(!Pair.second && "Entry must have existed");
  1671. return Pair.first->second = PartialAlias;
  1672. }
  1673. // Recurse back into the best AA results we have, potentially with refined
  1674. // memory locations. We have already ensured that BasicAA has a MayAlias
  1675. // cache result for these, so any recursion back into BasicAA won't loop.
  1676. AliasResult Result = getBestAAResults().alias(Locs.first, Locs.second, AAQI);
  1677. Pair = AAQI.AliasCache.try_emplace(Locs, Result);
  1678. assert(!Pair.second && "Entry must have existed");
  1679. return Pair.first->second = Result;
  1680. }
  1681. /// Check whether two Values can be considered equivalent.
  1682. ///
  1683. /// In addition to pointer equivalence of \p V1 and \p V2 this checks whether
  1684. /// they can not be part of a cycle in the value graph by looking at all
  1685. /// visited phi nodes an making sure that the phis cannot reach the value. We
  1686. /// have to do this because we are looking through phi nodes (That is we say
  1687. /// noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
  1688. bool BasicAAResult::isValueEqualInPotentialCycles(const Value *V,
  1689. const Value *V2) {
  1690. if (V != V2)
  1691. return false;
  1692. const Instruction *Inst = dyn_cast<Instruction>(V);
  1693. if (!Inst)
  1694. return true;
  1695. if (VisitedPhiBBs.empty())
  1696. return true;
  1697. if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
  1698. return false;
  1699. // Make sure that the visited phis cannot reach the Value. This ensures that
  1700. // the Values cannot come from different iterations of a potential cycle the
  1701. // phi nodes could be involved in.
  1702. for (auto *P : VisitedPhiBBs)
  1703. if (isPotentiallyReachable(&P->front(), Inst, nullptr, DT, LI))
  1704. return false;
  1705. return true;
  1706. }
  1707. /// Computes the symbolic difference between two de-composed GEPs.
  1708. ///
  1709. /// Dest and Src are the variable indices from two decomposed GetElementPtr
  1710. /// instructions GEP1 and GEP2 which have common base pointers.
  1711. void BasicAAResult::GetIndexDifference(
  1712. SmallVectorImpl<VariableGEPIndex> &Dest,
  1713. const SmallVectorImpl<VariableGEPIndex> &Src) {
  1714. if (Src.empty())
  1715. return;
  1716. for (unsigned i = 0, e = Src.size(); i != e; ++i) {
  1717. const Value *V = Src[i].V;
  1718. unsigned ZExtBits = Src[i].ZExtBits, SExtBits = Src[i].SExtBits;
  1719. APInt Scale = Src[i].Scale;
  1720. // Find V in Dest. This is N^2, but pointer indices almost never have more
  1721. // than a few variable indexes.
  1722. for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
  1723. if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
  1724. Dest[j].ZExtBits != ZExtBits || Dest[j].SExtBits != SExtBits)
  1725. continue;
  1726. // If we found it, subtract off Scale V's from the entry in Dest. If it
  1727. // goes to zero, remove the entry.
  1728. if (Dest[j].Scale != Scale)
  1729. Dest[j].Scale -= Scale;
  1730. else
  1731. Dest.erase(Dest.begin() + j);
  1732. Scale = 0;
  1733. break;
  1734. }
  1735. // If we didn't consume this entry, add it to the end of the Dest list.
  1736. if (!!Scale) {
  1737. VariableGEPIndex Entry = {V, ZExtBits, SExtBits, -Scale};
  1738. Dest.push_back(Entry);
  1739. }
  1740. }
  1741. }
  1742. bool BasicAAResult::constantOffsetHeuristic(
  1743. const SmallVectorImpl<VariableGEPIndex> &VarIndices,
  1744. LocationSize MaybeV1Size, LocationSize MaybeV2Size, APInt BaseOffset,
  1745. AssumptionCache *AC, DominatorTree *DT) {
  1746. if (VarIndices.size() != 2 || MaybeV1Size == LocationSize::unknown() ||
  1747. MaybeV2Size == LocationSize::unknown())
  1748. return false;
  1749. const uint64_t V1Size = MaybeV1Size.getValue();
  1750. const uint64_t V2Size = MaybeV2Size.getValue();
  1751. const VariableGEPIndex &Var0 = VarIndices[0], &Var1 = VarIndices[1];
  1752. if (Var0.ZExtBits != Var1.ZExtBits || Var0.SExtBits != Var1.SExtBits ||
  1753. Var0.Scale != -Var1.Scale)
  1754. return false;
  1755. unsigned Width = Var1.V->getType()->getIntegerBitWidth();
  1756. // We'll strip off the Extensions of Var0 and Var1 and do another round
  1757. // of GetLinearExpression decomposition. In the example above, if Var0
  1758. // is zext(%x + 1) we should get V1 == %x and V1Offset == 1.
  1759. APInt V0Scale(Width, 0), V0Offset(Width, 0), V1Scale(Width, 0),
  1760. V1Offset(Width, 0);
  1761. bool NSW = true, NUW = true;
  1762. unsigned V0ZExtBits = 0, V0SExtBits = 0, V1ZExtBits = 0, V1SExtBits = 0;
  1763. const Value *V0 = GetLinearExpression(Var0.V, V0Scale, V0Offset, V0ZExtBits,
  1764. V0SExtBits, DL, 0, AC, DT, NSW, NUW);
  1765. NSW = true;
  1766. NUW = true;
  1767. const Value *V1 = GetLinearExpression(Var1.V, V1Scale, V1Offset, V1ZExtBits,
  1768. V1SExtBits, DL, 0, AC, DT, NSW, NUW);
  1769. if (V0Scale != V1Scale || V0ZExtBits != V1ZExtBits ||
  1770. V0SExtBits != V1SExtBits || !isValueEqualInPotentialCycles(V0, V1))
  1771. return false;
  1772. // We have a hit - Var0 and Var1 only differ by a constant offset!
  1773. // If we've been sext'ed then zext'd the maximum difference between Var0 and
  1774. // Var1 is possible to calculate, but we're just interested in the absolute
  1775. // minimum difference between the two. The minimum distance may occur due to
  1776. // wrapping; consider "add i3 %i, 5": if %i == 7 then 7 + 5 mod 8 == 4, and so
  1777. // the minimum distance between %i and %i + 5 is 3.
  1778. APInt MinDiff = V0Offset - V1Offset, Wrapped = -MinDiff;
  1779. MinDiff = APIntOps::umin(MinDiff, Wrapped);
  1780. APInt MinDiffBytes =
  1781. MinDiff.zextOrTrunc(Var0.Scale.getBitWidth()) * Var0.Scale.abs();
  1782. // We can't definitely say whether GEP1 is before or after V2 due to wrapping
  1783. // arithmetic (i.e. for some values of GEP1 and V2 GEP1 < V2, and for other
  1784. // values GEP1 > V2). We'll therefore only declare NoAlias if both V1Size and
  1785. // V2Size can fit in the MinDiffBytes gap.
  1786. return MinDiffBytes.uge(V1Size + BaseOffset.abs()) &&
  1787. MinDiffBytes.uge(V2Size + BaseOffset.abs());
  1788. }
  1789. //===----------------------------------------------------------------------===//
  1790. // BasicAliasAnalysis Pass
  1791. //===----------------------------------------------------------------------===//
  1792. AnalysisKey BasicAA::Key;
  1793. BasicAAResult BasicAA::run(Function &F, FunctionAnalysisManager &AM) {
  1794. return BasicAAResult(F.getParent()->getDataLayout(),
  1795. F,
  1796. AM.getResult<TargetLibraryAnalysis>(F),
  1797. AM.getResult<AssumptionAnalysis>(F),
  1798. &AM.getResult<DominatorTreeAnalysis>(F),
  1799. AM.getCachedResult<LoopAnalysis>(F),
  1800. AM.getCachedResult<PhiValuesAnalysis>(F));
  1801. }
  1802. BasicAAWrapperPass::BasicAAWrapperPass() : FunctionPass(ID) {
  1803. initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry());
  1804. }
  1805. char BasicAAWrapperPass::ID = 0;
  1806. void BasicAAWrapperPass::anchor() {}
  1807. INITIALIZE_PASS_BEGIN(BasicAAWrapperPass, "basicaa",
  1808. "Basic Alias Analysis (stateless AA impl)", false, true)
  1809. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  1810. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  1811. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  1812. INITIALIZE_PASS_END(BasicAAWrapperPass, "basicaa",
  1813. "Basic Alias Analysis (stateless AA impl)", false, true)
  1814. FunctionPass *llvm::createBasicAAWrapperPass() {
  1815. return new BasicAAWrapperPass();
  1816. }
  1817. bool BasicAAWrapperPass::runOnFunction(Function &F) {
  1818. auto &ACT = getAnalysis<AssumptionCacheTracker>();
  1819. auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>();
  1820. auto &DTWP = getAnalysis<DominatorTreeWrapperPass>();
  1821. auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
  1822. auto *PVWP = getAnalysisIfAvailable<PhiValuesWrapperPass>();
  1823. Result.reset(new BasicAAResult(F.getParent()->getDataLayout(), F,
  1824. TLIWP.getTLI(F), ACT.getAssumptionCache(F),
  1825. &DTWP.getDomTree(),
  1826. LIWP ? &LIWP->getLoopInfo() : nullptr,
  1827. PVWP ? &PVWP->getResult() : nullptr));
  1828. return false;
  1829. }
  1830. void BasicAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
  1831. AU.setPreservesAll();
  1832. AU.addRequired<AssumptionCacheTracker>();
  1833. AU.addRequired<DominatorTreeWrapperPass>();
  1834. AU.addRequired<TargetLibraryInfoWrapperPass>();
  1835. AU.addUsedIfAvailable<PhiValuesWrapperPass>();
  1836. }
  1837. BasicAAResult llvm::createLegacyPMBasicAAResult(Pass &P, Function &F) {
  1838. return BasicAAResult(
  1839. F.getParent()->getDataLayout(), F,
  1840. P.getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
  1841. P.getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
  1842. }