BasicAliasAnalysis.cpp 82 KB

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