ValueTracking.cpp 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760
  1. //===- ValueTracking.cpp - Walk computations to compute properties --------===//
  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 contains routines that help analyze properties that chains of
  11. // computations have.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Analysis/ValueTracking.h"
  15. #include "llvm/ADT/SmallPtrSet.h"
  16. #include "llvm/Analysis/AssumptionCache.h"
  17. #include "llvm/Analysis/InstructionSimplify.h"
  18. #include "llvm/Analysis/MemoryBuiltins.h"
  19. #include "llvm/IR/CallSite.h"
  20. #include "llvm/IR/ConstantRange.h"
  21. #include "llvm/IR/Constants.h"
  22. #include "llvm/IR/DataLayout.h"
  23. #include "llvm/IR/Dominators.h"
  24. #include "llvm/IR/GetElementPtrTypeIterator.h"
  25. #include "llvm/IR/GlobalAlias.h"
  26. #include "llvm/IR/GlobalVariable.h"
  27. #include "llvm/IR/Instructions.h"
  28. #include "llvm/IR/IntrinsicInst.h"
  29. #include "llvm/IR/LLVMContext.h"
  30. #include "llvm/IR/Metadata.h"
  31. #include "llvm/IR/Operator.h"
  32. #include "llvm/IR/PatternMatch.h"
  33. #include "llvm/Support/Debug.h"
  34. #include "llvm/Support/MathExtras.h"
  35. #include <cstring>
  36. using namespace llvm;
  37. using namespace llvm::PatternMatch;
  38. const unsigned MaxDepth = 6;
  39. /// Returns the bitwidth of the given scalar or pointer type (if unknown returns
  40. /// 0). For vector types, returns the element type's bitwidth.
  41. static unsigned getBitWidth(Type *Ty, const DataLayout *TD) {
  42. if (unsigned BitWidth = Ty->getScalarSizeInBits())
  43. return BitWidth;
  44. return TD ? TD->getPointerTypeSizeInBits(Ty) : 0;
  45. }
  46. // Many of these functions have internal versions that take an assumption
  47. // exclusion set. This is because of the potential for mutual recursion to
  48. // cause computeKnownBits to repeatedly visit the same assume intrinsic. The
  49. // classic case of this is assume(x = y), which will attempt to determine
  50. // bits in x from bits in y, which will attempt to determine bits in y from
  51. // bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
  52. // isKnownNonZero, which calls computeKnownBits and ComputeSignBit and
  53. // isKnownToBeAPowerOfTwo (all of which can call computeKnownBits), and so on.
  54. typedef SmallPtrSet<const Value *, 8> ExclInvsSet;
  55. namespace {
  56. // Simplifying using an assume can only be done in a particular control-flow
  57. // context (the context instruction provides that context). If an assume and
  58. // the context instruction are not in the same block then the DT helps in
  59. // figuring out if we can use it.
  60. struct Query {
  61. ExclInvsSet ExclInvs;
  62. AssumptionCache *AC;
  63. const Instruction *CxtI;
  64. const DominatorTree *DT;
  65. Query(AssumptionCache *AC = nullptr, const Instruction *CxtI = nullptr,
  66. const DominatorTree *DT = nullptr)
  67. : AC(AC), CxtI(CxtI), DT(DT) {}
  68. Query(const Query &Q, const Value *NewExcl)
  69. : ExclInvs(Q.ExclInvs), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT) {
  70. ExclInvs.insert(NewExcl);
  71. }
  72. };
  73. } // end anonymous namespace
  74. // Given the provided Value and, potentially, a context instruction, return
  75. // the preferred context instruction (if any).
  76. static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
  77. // If we've been provided with a context instruction, then use that (provided
  78. // it has been inserted).
  79. if (CxtI && CxtI->getParent())
  80. return CxtI;
  81. // If the value is really an already-inserted instruction, then use that.
  82. CxtI = dyn_cast<Instruction>(V);
  83. if (CxtI && CxtI->getParent())
  84. return CxtI;
  85. return nullptr;
  86. }
  87. static void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
  88. const DataLayout *TD, unsigned Depth,
  89. const Query &Q);
  90. void llvm::computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
  91. const DataLayout *TD, unsigned Depth,
  92. AssumptionCache *AC, const Instruction *CxtI,
  93. const DominatorTree *DT) {
  94. ::computeKnownBits(V, KnownZero, KnownOne, TD, Depth,
  95. Query(AC, safeCxtI(V, CxtI), DT));
  96. }
  97. static void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
  98. const DataLayout *TD, unsigned Depth,
  99. const Query &Q);
  100. void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
  101. const DataLayout *TD, unsigned Depth,
  102. AssumptionCache *AC, const Instruction *CxtI,
  103. const DominatorTree *DT) {
  104. ::ComputeSignBit(V, KnownZero, KnownOne, TD, Depth,
  105. Query(AC, safeCxtI(V, CxtI), DT));
  106. }
  107. static bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
  108. const Query &Q);
  109. bool llvm::isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
  110. AssumptionCache *AC, const Instruction *CxtI,
  111. const DominatorTree *DT) {
  112. return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
  113. Query(AC, safeCxtI(V, CxtI), DT));
  114. }
  115. static bool isKnownNonZero(Value *V, const DataLayout *TD, unsigned Depth,
  116. const Query &Q);
  117. bool llvm::isKnownNonZero(Value *V, const DataLayout *TD, unsigned Depth,
  118. AssumptionCache *AC, const Instruction *CxtI,
  119. const DominatorTree *DT) {
  120. return ::isKnownNonZero(V, TD, Depth, Query(AC, safeCxtI(V, CxtI), DT));
  121. }
  122. static bool MaskedValueIsZero(Value *V, const APInt &Mask,
  123. const DataLayout *TD, unsigned Depth,
  124. const Query &Q);
  125. bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout *TD,
  126. unsigned Depth, AssumptionCache *AC,
  127. const Instruction *CxtI, const DominatorTree *DT) {
  128. return ::MaskedValueIsZero(V, Mask, TD, Depth,
  129. Query(AC, safeCxtI(V, CxtI), DT));
  130. }
  131. static unsigned ComputeNumSignBits(Value *V, const DataLayout *TD,
  132. unsigned Depth, const Query &Q);
  133. unsigned llvm::ComputeNumSignBits(Value *V, const DataLayout *TD,
  134. unsigned Depth, AssumptionCache *AC,
  135. const Instruction *CxtI,
  136. const DominatorTree *DT) {
  137. return ::ComputeNumSignBits(V, TD, Depth, Query(AC, safeCxtI(V, CxtI), DT));
  138. }
  139. static void computeKnownBitsAddSub(bool Add, Value *Op0, Value *Op1, bool NSW,
  140. APInt &KnownZero, APInt &KnownOne,
  141. APInt &KnownZero2, APInt &KnownOne2,
  142. const DataLayout *TD, unsigned Depth,
  143. const Query &Q) {
  144. if (!Add) {
  145. if (ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) {
  146. // We know that the top bits of C-X are clear if X contains less bits
  147. // than C (i.e. no wrap-around can happen). For example, 20-X is
  148. // positive if we can prove that X is >= 0 and < 16.
  149. if (!CLHS->getValue().isNegative()) {
  150. unsigned BitWidth = KnownZero.getBitWidth();
  151. unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
  152. // NLZ can't be BitWidth with no sign bit
  153. APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
  154. computeKnownBits(Op1, KnownZero2, KnownOne2, TD, Depth+1, Q);
  155. // If all of the MaskV bits are known to be zero, then we know the
  156. // output top bits are zero, because we now know that the output is
  157. // from [0-C].
  158. if ((KnownZero2 & MaskV) == MaskV) {
  159. unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
  160. // Top bits known zero.
  161. KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
  162. }
  163. }
  164. }
  165. }
  166. unsigned BitWidth = KnownZero.getBitWidth();
  167. // If an initial sequence of bits in the result is not needed, the
  168. // corresponding bits in the operands are not needed.
  169. APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
  170. computeKnownBits(Op0, LHSKnownZero, LHSKnownOne, TD, Depth+1, Q);
  171. computeKnownBits(Op1, KnownZero2, KnownOne2, TD, Depth+1, Q);
  172. // Carry in a 1 for a subtract, rather than a 0.
  173. APInt CarryIn(BitWidth, 0);
  174. if (!Add) {
  175. // Sum = LHS + ~RHS + 1
  176. std::swap(KnownZero2, KnownOne2);
  177. CarryIn.setBit(0);
  178. }
  179. APInt PossibleSumZero = ~LHSKnownZero + ~KnownZero2 + CarryIn;
  180. APInt PossibleSumOne = LHSKnownOne + KnownOne2 + CarryIn;
  181. // Compute known bits of the carry.
  182. APInt CarryKnownZero = ~(PossibleSumZero ^ LHSKnownZero ^ KnownZero2);
  183. APInt CarryKnownOne = PossibleSumOne ^ LHSKnownOne ^ KnownOne2;
  184. // Compute set of known bits (where all three relevant bits are known).
  185. APInt LHSKnown = LHSKnownZero | LHSKnownOne;
  186. APInt RHSKnown = KnownZero2 | KnownOne2;
  187. APInt CarryKnown = CarryKnownZero | CarryKnownOne;
  188. APInt Known = LHSKnown & RHSKnown & CarryKnown;
  189. assert((PossibleSumZero & Known) == (PossibleSumOne & Known) &&
  190. "known bits of sum differ");
  191. // Compute known bits of the result.
  192. KnownZero = ~PossibleSumOne & Known;
  193. KnownOne = PossibleSumOne & Known;
  194. // Are we still trying to solve for the sign bit?
  195. if (!Known.isNegative()) {
  196. if (NSW) {
  197. // Adding two non-negative numbers, or subtracting a negative number from
  198. // a non-negative one, can't wrap into negative.
  199. if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
  200. KnownZero |= APInt::getSignBit(BitWidth);
  201. // Adding two negative numbers, or subtracting a non-negative number from
  202. // a negative one, can't wrap into non-negative.
  203. else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
  204. KnownOne |= APInt::getSignBit(BitWidth);
  205. }
  206. }
  207. }
  208. static void computeKnownBitsMul(Value *Op0, Value *Op1, bool NSW,
  209. APInt &KnownZero, APInt &KnownOne,
  210. APInt &KnownZero2, APInt &KnownOne2,
  211. const DataLayout *TD, unsigned Depth,
  212. const Query &Q) {
  213. unsigned BitWidth = KnownZero.getBitWidth();
  214. computeKnownBits(Op1, KnownZero, KnownOne, TD, Depth+1, Q);
  215. computeKnownBits(Op0, KnownZero2, KnownOne2, TD, Depth+1, Q);
  216. bool isKnownNegative = false;
  217. bool isKnownNonNegative = false;
  218. // If the multiplication is known not to overflow, compute the sign bit.
  219. if (NSW) {
  220. if (Op0 == Op1) {
  221. // The product of a number with itself is non-negative.
  222. isKnownNonNegative = true;
  223. } else {
  224. bool isKnownNonNegativeOp1 = KnownZero.isNegative();
  225. bool isKnownNonNegativeOp0 = KnownZero2.isNegative();
  226. bool isKnownNegativeOp1 = KnownOne.isNegative();
  227. bool isKnownNegativeOp0 = KnownOne2.isNegative();
  228. // The product of two numbers with the same sign is non-negative.
  229. isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
  230. (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
  231. // The product of a negative number and a non-negative number is either
  232. // negative or zero.
  233. if (!isKnownNonNegative)
  234. isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
  235. isKnownNonZero(Op0, TD, Depth, Q)) ||
  236. (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
  237. isKnownNonZero(Op1, TD, Depth, Q));
  238. }
  239. }
  240. // If low bits are zero in either operand, output low known-0 bits.
  241. // Also compute a conserative estimate for high known-0 bits.
  242. // More trickiness is possible, but this is sufficient for the
  243. // interesting case of alignment computation.
  244. KnownOne.clearAllBits();
  245. unsigned TrailZ = KnownZero.countTrailingOnes() +
  246. KnownZero2.countTrailingOnes();
  247. unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
  248. KnownZero2.countLeadingOnes(),
  249. BitWidth) - BitWidth;
  250. TrailZ = std::min(TrailZ, BitWidth);
  251. LeadZ = std::min(LeadZ, BitWidth);
  252. KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
  253. APInt::getHighBitsSet(BitWidth, LeadZ);
  254. // Only make use of no-wrap flags if we failed to compute the sign bit
  255. // directly. This matters if the multiplication always overflows, in
  256. // which case we prefer to follow the result of the direct computation,
  257. // though as the program is invoking undefined behaviour we can choose
  258. // whatever we like here.
  259. if (isKnownNonNegative && !KnownOne.isNegative())
  260. KnownZero.setBit(BitWidth - 1);
  261. else if (isKnownNegative && !KnownZero.isNegative())
  262. KnownOne.setBit(BitWidth - 1);
  263. }
  264. void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
  265. APInt &KnownZero) {
  266. unsigned BitWidth = KnownZero.getBitWidth();
  267. unsigned NumRanges = Ranges.getNumOperands() / 2;
  268. assert(NumRanges >= 1);
  269. // Use the high end of the ranges to find leading zeros.
  270. unsigned MinLeadingZeros = BitWidth;
  271. for (unsigned i = 0; i < NumRanges; ++i) {
  272. ConstantInt *Lower =
  273. mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
  274. ConstantInt *Upper =
  275. mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
  276. ConstantRange Range(Lower->getValue(), Upper->getValue());
  277. if (Range.isWrappedSet())
  278. MinLeadingZeros = 0; // -1 has no zeros
  279. unsigned LeadingZeros = (Upper->getValue() - 1).countLeadingZeros();
  280. MinLeadingZeros = std::min(LeadingZeros, MinLeadingZeros);
  281. }
  282. KnownZero = APInt::getHighBitsSet(BitWidth, MinLeadingZeros);
  283. }
  284. static bool isEphemeralValueOf(Instruction *I, const Value *E) {
  285. SmallVector<const Value *, 16> WorkSet(1, I);
  286. SmallPtrSet<const Value *, 32> Visited;
  287. SmallPtrSet<const Value *, 16> EphValues;
  288. while (!WorkSet.empty()) {
  289. const Value *V = WorkSet.pop_back_val();
  290. if (!Visited.insert(V).second)
  291. continue;
  292. // If all uses of this value are ephemeral, then so is this value.
  293. bool FoundNEUse = false;
  294. for (const User *I : V->users())
  295. if (!EphValues.count(I)) {
  296. FoundNEUse = true;
  297. break;
  298. }
  299. if (!FoundNEUse) {
  300. if (V == E)
  301. return true;
  302. EphValues.insert(V);
  303. if (const User *U = dyn_cast<User>(V))
  304. for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
  305. J != JE; ++J) {
  306. if (isSafeToSpeculativelyExecute(*J))
  307. WorkSet.push_back(*J);
  308. }
  309. }
  310. }
  311. return false;
  312. }
  313. // Is this an intrinsic that cannot be speculated but also cannot trap?
  314. static bool isAssumeLikeIntrinsic(const Instruction *I) {
  315. if (const CallInst *CI = dyn_cast<CallInst>(I))
  316. if (Function *F = CI->getCalledFunction())
  317. switch (F->getIntrinsicID()) {
  318. default: break;
  319. // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
  320. case Intrinsic::assume:
  321. case Intrinsic::dbg_declare:
  322. case Intrinsic::dbg_value:
  323. case Intrinsic::invariant_start:
  324. case Intrinsic::invariant_end:
  325. case Intrinsic::lifetime_start:
  326. case Intrinsic::lifetime_end:
  327. case Intrinsic::objectsize:
  328. case Intrinsic::ptr_annotation:
  329. case Intrinsic::var_annotation:
  330. return true;
  331. }
  332. return false;
  333. }
  334. static bool isValidAssumeForContext(Value *V, const Query &Q,
  335. const DataLayout *DL) {
  336. Instruction *Inv = cast<Instruction>(V);
  337. // There are two restrictions on the use of an assume:
  338. // 1. The assume must dominate the context (or the control flow must
  339. // reach the assume whenever it reaches the context).
  340. // 2. The context must not be in the assume's set of ephemeral values
  341. // (otherwise we will use the assume to prove that the condition
  342. // feeding the assume is trivially true, thus causing the removal of
  343. // the assume).
  344. if (Q.DT) {
  345. if (Q.DT->dominates(Inv, Q.CxtI)) {
  346. return true;
  347. } else if (Inv->getParent() == Q.CxtI->getParent()) {
  348. // The context comes first, but they're both in the same block. Make sure
  349. // there is nothing in between that might interrupt the control flow.
  350. for (BasicBlock::const_iterator I =
  351. std::next(BasicBlock::const_iterator(Q.CxtI)),
  352. IE(Inv); I != IE; ++I)
  353. if (!isSafeToSpeculativelyExecute(I, DL) &&
  354. !isAssumeLikeIntrinsic(I))
  355. return false;
  356. return !isEphemeralValueOf(Inv, Q.CxtI);
  357. }
  358. return false;
  359. }
  360. // When we don't have a DT, we do a limited search...
  361. if (Inv->getParent() == Q.CxtI->getParent()->getSinglePredecessor()) {
  362. return true;
  363. } else if (Inv->getParent() == Q.CxtI->getParent()) {
  364. // Search forward from the assume until we reach the context (or the end
  365. // of the block); the common case is that the assume will come first.
  366. for (BasicBlock::iterator I = std::next(BasicBlock::iterator(Inv)),
  367. IE = Inv->getParent()->end(); I != IE; ++I)
  368. if (I == Q.CxtI)
  369. return true;
  370. // The context must come first...
  371. for (BasicBlock::const_iterator I =
  372. std::next(BasicBlock::const_iterator(Q.CxtI)),
  373. IE(Inv); I != IE; ++I)
  374. if (!isSafeToSpeculativelyExecute(I, DL) &&
  375. !isAssumeLikeIntrinsic(I))
  376. return false;
  377. return !isEphemeralValueOf(Inv, Q.CxtI);
  378. }
  379. return false;
  380. }
  381. bool llvm::isValidAssumeForContext(const Instruction *I,
  382. const Instruction *CxtI,
  383. const DataLayout *DL,
  384. const DominatorTree *DT) {
  385. return ::isValidAssumeForContext(const_cast<Instruction*>(I),
  386. Query(nullptr, CxtI, DT), DL);
  387. }
  388. template<typename LHS, typename RHS>
  389. inline match_combine_or<CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>,
  390. CmpClass_match<RHS, LHS, ICmpInst, ICmpInst::Predicate>>
  391. m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
  392. return m_CombineOr(m_ICmp(Pred, L, R), m_ICmp(Pred, R, L));
  393. }
  394. template<typename LHS, typename RHS>
  395. inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::And>,
  396. BinaryOp_match<RHS, LHS, Instruction::And>>
  397. m_c_And(const LHS &L, const RHS &R) {
  398. return m_CombineOr(m_And(L, R), m_And(R, L));
  399. }
  400. template<typename LHS, typename RHS>
  401. inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Or>,
  402. BinaryOp_match<RHS, LHS, Instruction::Or>>
  403. m_c_Or(const LHS &L, const RHS &R) {
  404. return m_CombineOr(m_Or(L, R), m_Or(R, L));
  405. }
  406. template<typename LHS, typename RHS>
  407. inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Xor>,
  408. BinaryOp_match<RHS, LHS, Instruction::Xor>>
  409. m_c_Xor(const LHS &L, const RHS &R) {
  410. return m_CombineOr(m_Xor(L, R), m_Xor(R, L));
  411. }
  412. static void computeKnownBitsFromAssume(Value *V, APInt &KnownZero,
  413. APInt &KnownOne,
  414. const DataLayout *DL,
  415. unsigned Depth, const Query &Q) {
  416. // Use of assumptions is context-sensitive. If we don't have a context, we
  417. // cannot use them!
  418. if (!Q.AC || !Q.CxtI)
  419. return;
  420. unsigned BitWidth = KnownZero.getBitWidth();
  421. for (auto &AssumeVH : Q.AC->assumptions()) {
  422. if (!AssumeVH)
  423. continue;
  424. CallInst *I = cast<CallInst>(AssumeVH);
  425. assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
  426. "Got assumption for the wrong function!");
  427. if (Q.ExclInvs.count(I))
  428. continue;
  429. // Warning: This loop can end up being somewhat performance sensetive.
  430. // We're running this loop for once for each value queried resulting in a
  431. // runtime of ~O(#assumes * #values).
  432. assert(isa<IntrinsicInst>(I) &&
  433. dyn_cast<IntrinsicInst>(I)->getIntrinsicID() == Intrinsic::assume &&
  434. "must be an assume intrinsic");
  435. Value *Arg = I->getArgOperand(0);
  436. if (Arg == V &&
  437. isValidAssumeForContext(I, Q, DL)) {
  438. assert(BitWidth == 1 && "assume operand is not i1?");
  439. KnownZero.clearAllBits();
  440. KnownOne.setAllBits();
  441. return;
  442. }
  443. // The remaining tests are all recursive, so bail out if we hit the limit.
  444. if (Depth == MaxDepth)
  445. continue;
  446. Value *A, *B;
  447. auto m_V = m_CombineOr(m_Specific(V),
  448. m_CombineOr(m_PtrToInt(m_Specific(V)),
  449. m_BitCast(m_Specific(V))));
  450. CmpInst::Predicate Pred;
  451. ConstantInt *C;
  452. // assume(v = a)
  453. if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
  454. Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
  455. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  456. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  457. KnownZero |= RHSKnownZero;
  458. KnownOne |= RHSKnownOne;
  459. // assume(v & b = a)
  460. } else if (match(Arg, m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)),
  461. m_Value(A))) &&
  462. Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
  463. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  464. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  465. APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
  466. computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
  467. // For those bits in the mask that are known to be one, we can propagate
  468. // known bits from the RHS to V.
  469. KnownZero |= RHSKnownZero & MaskKnownOne;
  470. KnownOne |= RHSKnownOne & MaskKnownOne;
  471. // assume(~(v & b) = a)
  472. } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
  473. m_Value(A))) &&
  474. Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
  475. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  476. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  477. APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
  478. computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
  479. // For those bits in the mask that are known to be one, we can propagate
  480. // inverted known bits from the RHS to V.
  481. KnownZero |= RHSKnownOne & MaskKnownOne;
  482. KnownOne |= RHSKnownZero & MaskKnownOne;
  483. // assume(v | b = a)
  484. } else if (match(Arg, m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)),
  485. m_Value(A))) &&
  486. Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
  487. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  488. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  489. APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
  490. computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
  491. // For those bits in B that are known to be zero, we can propagate known
  492. // bits from the RHS to V.
  493. KnownZero |= RHSKnownZero & BKnownZero;
  494. KnownOne |= RHSKnownOne & BKnownZero;
  495. // assume(~(v | b) = a)
  496. } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
  497. m_Value(A))) &&
  498. Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
  499. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  500. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  501. APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
  502. computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
  503. // For those bits in B that are known to be zero, we can propagate
  504. // inverted known bits from the RHS to V.
  505. KnownZero |= RHSKnownOne & BKnownZero;
  506. KnownOne |= RHSKnownZero & BKnownZero;
  507. // assume(v ^ b = a)
  508. } else if (match(Arg, m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)),
  509. m_Value(A))) &&
  510. Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
  511. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  512. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  513. APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
  514. computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
  515. // For those bits in B that are known to be zero, we can propagate known
  516. // bits from the RHS to V. For those bits in B that are known to be one,
  517. // we can propagate inverted known bits from the RHS to V.
  518. KnownZero |= RHSKnownZero & BKnownZero;
  519. KnownOne |= RHSKnownOne & BKnownZero;
  520. KnownZero |= RHSKnownOne & BKnownOne;
  521. KnownOne |= RHSKnownZero & BKnownOne;
  522. // assume(~(v ^ b) = a)
  523. } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
  524. m_Value(A))) &&
  525. Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
  526. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  527. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  528. APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
  529. computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
  530. // For those bits in B that are known to be zero, we can propagate
  531. // inverted known bits from the RHS to V. For those bits in B that are
  532. // known to be one, we can propagate known bits from the RHS to V.
  533. KnownZero |= RHSKnownOne & BKnownZero;
  534. KnownOne |= RHSKnownZero & BKnownZero;
  535. KnownZero |= RHSKnownZero & BKnownOne;
  536. KnownOne |= RHSKnownOne & BKnownOne;
  537. // assume(v << c = a)
  538. } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
  539. m_Value(A))) &&
  540. Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
  541. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  542. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  543. // For those bits in RHS that are known, we can propagate them to known
  544. // bits in V shifted to the right by C.
  545. KnownZero |= RHSKnownZero.lshr(C->getZExtValue());
  546. KnownOne |= RHSKnownOne.lshr(C->getZExtValue());
  547. // assume(~(v << c) = a)
  548. } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
  549. m_Value(A))) &&
  550. Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
  551. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  552. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  553. // For those bits in RHS that are known, we can propagate them inverted
  554. // to known bits in V shifted to the right by C.
  555. KnownZero |= RHSKnownOne.lshr(C->getZExtValue());
  556. KnownOne |= RHSKnownZero.lshr(C->getZExtValue());
  557. // assume(v >> c = a)
  558. } else if (match(Arg,
  559. m_c_ICmp(Pred, m_CombineOr(m_LShr(m_V, m_ConstantInt(C)),
  560. m_AShr(m_V,
  561. m_ConstantInt(C))),
  562. m_Value(A))) &&
  563. Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
  564. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  565. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  566. // For those bits in RHS that are known, we can propagate them to known
  567. // bits in V shifted to the right by C.
  568. KnownZero |= RHSKnownZero << C->getZExtValue();
  569. KnownOne |= RHSKnownOne << C->getZExtValue();
  570. // assume(~(v >> c) = a)
  571. } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_CombineOr(
  572. m_LShr(m_V, m_ConstantInt(C)),
  573. m_AShr(m_V, m_ConstantInt(C)))),
  574. m_Value(A))) &&
  575. Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
  576. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  577. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  578. // For those bits in RHS that are known, we can propagate them inverted
  579. // to known bits in V shifted to the right by C.
  580. KnownZero |= RHSKnownOne << C->getZExtValue();
  581. KnownOne |= RHSKnownZero << C->getZExtValue();
  582. // assume(v >=_s c) where c is non-negative
  583. } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
  584. Pred == ICmpInst::ICMP_SGE &&
  585. isValidAssumeForContext(I, Q, DL)) {
  586. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  587. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  588. if (RHSKnownZero.isNegative()) {
  589. // We know that the sign bit is zero.
  590. KnownZero |= APInt::getSignBit(BitWidth);
  591. }
  592. // assume(v >_s c) where c is at least -1.
  593. } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
  594. Pred == ICmpInst::ICMP_SGT &&
  595. isValidAssumeForContext(I, Q, DL)) {
  596. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  597. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  598. if (RHSKnownOne.isAllOnesValue() || RHSKnownZero.isNegative()) {
  599. // We know that the sign bit is zero.
  600. KnownZero |= APInt::getSignBit(BitWidth);
  601. }
  602. // assume(v <=_s c) where c is negative
  603. } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
  604. Pred == ICmpInst::ICMP_SLE &&
  605. isValidAssumeForContext(I, Q, DL)) {
  606. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  607. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  608. if (RHSKnownOne.isNegative()) {
  609. // We know that the sign bit is one.
  610. KnownOne |= APInt::getSignBit(BitWidth);
  611. }
  612. // assume(v <_s c) where c is non-positive
  613. } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
  614. Pred == ICmpInst::ICMP_SLT &&
  615. isValidAssumeForContext(I, Q, DL)) {
  616. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  617. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  618. if (RHSKnownZero.isAllOnesValue() || RHSKnownOne.isNegative()) {
  619. // We know that the sign bit is one.
  620. KnownOne |= APInt::getSignBit(BitWidth);
  621. }
  622. // assume(v <=_u c)
  623. } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
  624. Pred == ICmpInst::ICMP_ULE &&
  625. isValidAssumeForContext(I, Q, DL)) {
  626. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  627. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  628. // Whatever high bits in c are zero are known to be zero.
  629. KnownZero |=
  630. APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
  631. // assume(v <_u c)
  632. } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
  633. Pred == ICmpInst::ICMP_ULT &&
  634. isValidAssumeForContext(I, Q, DL)) {
  635. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  636. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  637. // Whatever high bits in c are zero are known to be zero (if c is a power
  638. // of 2, then one more).
  639. if (isKnownToBeAPowerOfTwo(A, false, Depth+1, Query(Q, I)))
  640. KnownZero |=
  641. APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes()+1);
  642. else
  643. KnownZero |=
  644. APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
  645. }
  646. }
  647. }
  648. /// Determine which bits of V are known to be either zero or one and return
  649. /// them in the KnownZero/KnownOne bit sets.
  650. ///
  651. /// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
  652. /// we cannot optimize based on the assumption that it is zero without changing
  653. /// it to be an explicit zero. If we don't change it to zero, other code could
  654. /// optimized based on the contradictory assumption that it is non-zero.
  655. /// Because instcombine aggressively folds operations with undef args anyway,
  656. /// this won't lose us code quality.
  657. ///
  658. /// This function is defined on values with integer type, values with pointer
  659. /// type (but only if TD is non-null), and vectors of integers. In the case
  660. /// where V is a vector, known zero, and known one values are the
  661. /// same width as the vector element, and the bit is set only if it is true
  662. /// for all of the elements in the vector.
  663. void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
  664. const DataLayout *TD, unsigned Depth,
  665. const Query &Q) {
  666. assert(V && "No Value?");
  667. assert(Depth <= MaxDepth && "Limit Search Depth");
  668. unsigned BitWidth = KnownZero.getBitWidth();
  669. assert((V->getType()->isIntOrIntVectorTy() ||
  670. V->getType()->getScalarType()->isPointerTy()) &&
  671. "Not integer or pointer type!");
  672. assert((!TD ||
  673. TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
  674. (!V->getType()->isIntOrIntVectorTy() ||
  675. V->getType()->getScalarSizeInBits() == BitWidth) &&
  676. KnownZero.getBitWidth() == BitWidth &&
  677. KnownOne.getBitWidth() == BitWidth &&
  678. "V, KnownOne and KnownZero should have same BitWidth");
  679. if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  680. // We know all of the bits for a constant!
  681. KnownOne = CI->getValue();
  682. KnownZero = ~KnownOne;
  683. return;
  684. }
  685. // Null and aggregate-zero are all-zeros.
  686. if (isa<ConstantPointerNull>(V) ||
  687. isa<ConstantAggregateZero>(V)) {
  688. KnownOne.clearAllBits();
  689. KnownZero = APInt::getAllOnesValue(BitWidth);
  690. return;
  691. }
  692. // Handle a constant vector by taking the intersection of the known bits of
  693. // each element. There is no real need to handle ConstantVector here, because
  694. // we don't handle undef in any particularly useful way.
  695. if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
  696. // We know that CDS must be a vector of integers. Take the intersection of
  697. // each element.
  698. KnownZero.setAllBits(); KnownOne.setAllBits();
  699. APInt Elt(KnownZero.getBitWidth(), 0);
  700. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  701. Elt = CDS->getElementAsInteger(i);
  702. KnownZero &= ~Elt;
  703. KnownOne &= Elt;
  704. }
  705. return;
  706. }
  707. // The address of an aligned GlobalValue has trailing zeros.
  708. if (auto *GO = dyn_cast<GlobalObject>(V)) {
  709. unsigned Align = GO->getAlignment();
  710. if (Align == 0 && TD) {
  711. if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
  712. Type *ObjectType = GVar->getType()->getElementType();
  713. if (ObjectType->isSized()) {
  714. // If the object is defined in the current Module, we'll be giving
  715. // it the preferred alignment. Otherwise, we have to assume that it
  716. // may only have the minimum ABI alignment.
  717. if (!GVar->isDeclaration() && !GVar->isWeakForLinker())
  718. Align = TD->getPreferredAlignment(GVar);
  719. else
  720. Align = TD->getABITypeAlignment(ObjectType);
  721. }
  722. }
  723. }
  724. if (Align > 0)
  725. KnownZero = APInt::getLowBitsSet(BitWidth,
  726. countTrailingZeros(Align));
  727. else
  728. KnownZero.clearAllBits();
  729. KnownOne.clearAllBits();
  730. return;
  731. }
  732. if (Argument *A = dyn_cast<Argument>(V)) {
  733. unsigned Align = A->getType()->isPointerTy() ? A->getParamAlignment() : 0;
  734. if (!Align && TD && A->hasStructRetAttr()) {
  735. // An sret parameter has at least the ABI alignment of the return type.
  736. Type *EltTy = cast<PointerType>(A->getType())->getElementType();
  737. if (EltTy->isSized())
  738. Align = TD->getABITypeAlignment(EltTy);
  739. }
  740. if (Align)
  741. KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
  742. else
  743. KnownZero.clearAllBits();
  744. KnownOne.clearAllBits();
  745. // Don't give up yet... there might be an assumption that provides more
  746. // information...
  747. computeKnownBitsFromAssume(V, KnownZero, KnownOne, TD, Depth, Q);
  748. return;
  749. }
  750. // Start out not knowing anything.
  751. KnownZero.clearAllBits(); KnownOne.clearAllBits();
  752. // Limit search depth.
  753. // All recursive calls that increase depth must come after this.
  754. if (Depth == MaxDepth)
  755. return;
  756. // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
  757. // the bits of its aliasee.
  758. if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
  759. if (!GA->mayBeOverridden())
  760. computeKnownBits(GA->getAliasee(), KnownZero, KnownOne, TD, Depth + 1, Q);
  761. return;
  762. }
  763. // Check whether a nearby assume intrinsic can determine some known bits.
  764. computeKnownBitsFromAssume(V, KnownZero, KnownOne, TD, Depth, Q);
  765. Operator *I = dyn_cast<Operator>(V);
  766. if (!I) return;
  767. APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
  768. switch (I->getOpcode()) {
  769. default: break;
  770. case Instruction::Load:
  771. if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
  772. computeKnownBitsFromRangeMetadata(*MD, KnownZero);
  773. break;
  774. case Instruction::And: {
  775. // If either the LHS or the RHS are Zero, the result is zero.
  776. computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
  777. computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
  778. // Output known-1 bits are only known if set in both the LHS & RHS.
  779. KnownOne &= KnownOne2;
  780. // Output known-0 are known to be clear if zero in either the LHS | RHS.
  781. KnownZero |= KnownZero2;
  782. break;
  783. }
  784. case Instruction::Or: {
  785. computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
  786. computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
  787. // Output known-0 bits are only known if clear in both the LHS & RHS.
  788. KnownZero &= KnownZero2;
  789. // Output known-1 are known to be set if set in either the LHS | RHS.
  790. KnownOne |= KnownOne2;
  791. break;
  792. }
  793. case Instruction::Xor: {
  794. computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
  795. computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
  796. // Output known-0 bits are known if clear or set in both the LHS & RHS.
  797. APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
  798. // Output known-1 are known to be set if set in only one of the LHS, RHS.
  799. KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
  800. KnownZero = KnownZeroOut;
  801. break;
  802. }
  803. case Instruction::Mul: {
  804. bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
  805. computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW,
  806. KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
  807. Depth, Q);
  808. break;
  809. }
  810. case Instruction::UDiv: {
  811. // For the purposes of computing leading zeros we can conservatively
  812. // treat a udiv as a logical right shift by the power of 2 known to
  813. // be less than the denominator.
  814. computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
  815. unsigned LeadZ = KnownZero2.countLeadingOnes();
  816. KnownOne2.clearAllBits();
  817. KnownZero2.clearAllBits();
  818. computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1, Q);
  819. unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
  820. if (RHSUnknownLeadingOnes != BitWidth)
  821. LeadZ = std::min(BitWidth,
  822. LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
  823. KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
  824. break;
  825. }
  826. case Instruction::Select:
  827. computeKnownBits(I->getOperand(2), KnownZero, KnownOne, TD, Depth+1, Q);
  828. computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1, Q);
  829. // Only known if known in both the LHS and RHS.
  830. KnownOne &= KnownOne2;
  831. KnownZero &= KnownZero2;
  832. break;
  833. case Instruction::FPTrunc:
  834. case Instruction::FPExt:
  835. case Instruction::FPToUI:
  836. case Instruction::FPToSI:
  837. case Instruction::SIToFP:
  838. case Instruction::UIToFP:
  839. break; // Can't work with floating point.
  840. case Instruction::PtrToInt:
  841. case Instruction::IntToPtr:
  842. case Instruction::AddrSpaceCast: // Pointers could be different sizes.
  843. // We can't handle these if we don't know the pointer size.
  844. if (!TD) break;
  845. // FALL THROUGH and handle them the same as zext/trunc.
  846. case Instruction::ZExt:
  847. case Instruction::Trunc: {
  848. Type *SrcTy = I->getOperand(0)->getType();
  849. unsigned SrcBitWidth;
  850. // Note that we handle pointer operands here because of inttoptr/ptrtoint
  851. // which fall through here.
  852. if(TD) {
  853. SrcBitWidth = TD->getTypeSizeInBits(SrcTy->getScalarType());
  854. } else {
  855. SrcBitWidth = SrcTy->getScalarSizeInBits();
  856. if (!SrcBitWidth) break;
  857. }
  858. assert(SrcBitWidth && "SrcBitWidth can't be zero");
  859. KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
  860. KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
  861. computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
  862. KnownZero = KnownZero.zextOrTrunc(BitWidth);
  863. KnownOne = KnownOne.zextOrTrunc(BitWidth);
  864. // Any top bits are known to be zero.
  865. if (BitWidth > SrcBitWidth)
  866. KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
  867. break;
  868. }
  869. case Instruction::BitCast: {
  870. Type *SrcTy = I->getOperand(0)->getType();
  871. if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
  872. // TODO: For now, not handling conversions like:
  873. // (bitcast i64 %x to <2 x i32>)
  874. !I->getType()->isVectorTy()) {
  875. computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
  876. break;
  877. }
  878. break;
  879. }
  880. case Instruction::SExt: {
  881. // Compute the bits in the result that are not present in the input.
  882. unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
  883. KnownZero = KnownZero.trunc(SrcBitWidth);
  884. KnownOne = KnownOne.trunc(SrcBitWidth);
  885. computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
  886. KnownZero = KnownZero.zext(BitWidth);
  887. KnownOne = KnownOne.zext(BitWidth);
  888. // If the sign bit of the input is known set or clear, then we know the
  889. // top bits of the result.
  890. if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
  891. KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
  892. else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
  893. KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
  894. break;
  895. }
  896. case Instruction::Shl:
  897. // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
  898. if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
  899. uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
  900. computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
  901. KnownZero <<= ShiftAmt;
  902. KnownOne <<= ShiftAmt;
  903. KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
  904. }
  905. break;
  906. case Instruction::LShr:
  907. // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
  908. if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
  909. // Compute the new bits that are at the top now.
  910. uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
  911. // Unsigned shift right.
  912. computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
  913. KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
  914. KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
  915. // high bits known zero.
  916. KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
  917. }
  918. break;
  919. case Instruction::AShr:
  920. // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
  921. if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
  922. // Compute the new bits that are at the top now.
  923. uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
  924. // Signed shift right.
  925. computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
  926. KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
  927. KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
  928. APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
  929. if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
  930. KnownZero |= HighBits;
  931. else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
  932. KnownOne |= HighBits;
  933. }
  934. break;
  935. case Instruction::Sub: {
  936. bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
  937. computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
  938. KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
  939. Depth, Q);
  940. break;
  941. }
  942. case Instruction::Add: {
  943. bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
  944. computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
  945. KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
  946. Depth, Q);
  947. break;
  948. }
  949. case Instruction::SRem:
  950. if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
  951. APInt RA = Rem->getValue().abs();
  952. if (RA.isPowerOf2()) {
  953. APInt LowBits = RA - 1;
  954. computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD,
  955. Depth+1, Q);
  956. // The low bits of the first operand are unchanged by the srem.
  957. KnownZero = KnownZero2 & LowBits;
  958. KnownOne = KnownOne2 & LowBits;
  959. // If the first operand is non-negative or has all low bits zero, then
  960. // the upper bits are all zero.
  961. if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
  962. KnownZero |= ~LowBits;
  963. // If the first operand is negative and not all low bits are zero, then
  964. // the upper bits are all one.
  965. if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
  966. KnownOne |= ~LowBits;
  967. assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
  968. }
  969. }
  970. // The sign bit is the LHS's sign bit, except when the result of the
  971. // remainder is zero.
  972. if (KnownZero.isNonNegative()) {
  973. APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
  974. computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, TD,
  975. Depth+1, Q);
  976. // If it's known zero, our sign bit is also zero.
  977. if (LHSKnownZero.isNegative())
  978. KnownZero.setBit(BitWidth - 1);
  979. }
  980. break;
  981. case Instruction::URem: {
  982. if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
  983. APInt RA = Rem->getValue();
  984. if (RA.isPowerOf2()) {
  985. APInt LowBits = (RA - 1);
  986. computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD,
  987. Depth+1, Q);
  988. KnownZero |= ~LowBits;
  989. KnownOne &= LowBits;
  990. break;
  991. }
  992. }
  993. // Since the result is less than or equal to either operand, any leading
  994. // zero bits in either operand must also exist in the result.
  995. computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
  996. computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1, Q);
  997. unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
  998. KnownZero2.countLeadingOnes());
  999. KnownOne.clearAllBits();
  1000. KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
  1001. break;
  1002. }
  1003. case Instruction::Alloca: {
  1004. AllocaInst *AI = cast<AllocaInst>(V);
  1005. unsigned Align = AI->getAlignment();
  1006. if (Align == 0 && TD)
  1007. Align = TD->getABITypeAlignment(AI->getType()->getElementType());
  1008. if (Align > 0)
  1009. KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
  1010. break;
  1011. }
  1012. case Instruction::GetElementPtr: {
  1013. // Analyze all of the subscripts of this getelementptr instruction
  1014. // to determine if we can prove known low zero bits.
  1015. APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
  1016. computeKnownBits(I->getOperand(0), LocalKnownZero, LocalKnownOne, TD,
  1017. Depth+1, Q);
  1018. unsigned TrailZ = LocalKnownZero.countTrailingOnes();
  1019. gep_type_iterator GTI = gep_type_begin(I);
  1020. for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
  1021. Value *Index = I->getOperand(i);
  1022. if (StructType *STy = dyn_cast<StructType>(*GTI)) {
  1023. // Handle struct member offset arithmetic.
  1024. if (!TD) {
  1025. TrailZ = 0;
  1026. break;
  1027. }
  1028. // Handle case when index is vector zeroinitializer
  1029. Constant *CIndex = cast<Constant>(Index);
  1030. if (CIndex->isZeroValue())
  1031. continue;
  1032. if (CIndex->getType()->isVectorTy())
  1033. Index = CIndex->getSplatValue();
  1034. unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
  1035. const StructLayout *SL = TD->getStructLayout(STy);
  1036. uint64_t Offset = SL->getElementOffset(Idx);
  1037. TrailZ = std::min<unsigned>(TrailZ,
  1038. countTrailingZeros(Offset));
  1039. } else {
  1040. // Handle array index arithmetic.
  1041. Type *IndexedTy = GTI.getIndexedType();
  1042. if (!IndexedTy->isSized()) {
  1043. TrailZ = 0;
  1044. break;
  1045. }
  1046. unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
  1047. uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
  1048. LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
  1049. computeKnownBits(Index, LocalKnownZero, LocalKnownOne, TD, Depth+1, Q);
  1050. TrailZ = std::min(TrailZ,
  1051. unsigned(countTrailingZeros(TypeSize) +
  1052. LocalKnownZero.countTrailingOnes()));
  1053. }
  1054. }
  1055. KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ);
  1056. break;
  1057. }
  1058. case Instruction::PHI: {
  1059. PHINode *P = cast<PHINode>(I);
  1060. // Handle the case of a simple two-predecessor recurrence PHI.
  1061. // There's a lot more that could theoretically be done here, but
  1062. // this is sufficient to catch some interesting cases.
  1063. if (P->getNumIncomingValues() == 2) {
  1064. for (unsigned i = 0; i != 2; ++i) {
  1065. Value *L = P->getIncomingValue(i);
  1066. Value *R = P->getIncomingValue(!i);
  1067. Operator *LU = dyn_cast<Operator>(L);
  1068. if (!LU)
  1069. continue;
  1070. unsigned Opcode = LU->getOpcode();
  1071. // Check for operations that have the property that if
  1072. // both their operands have low zero bits, the result
  1073. // will have low zero bits.
  1074. if (Opcode == Instruction::Add ||
  1075. Opcode == Instruction::Sub ||
  1076. Opcode == Instruction::And ||
  1077. Opcode == Instruction::Or ||
  1078. Opcode == Instruction::Mul) {
  1079. Value *LL = LU->getOperand(0);
  1080. Value *LR = LU->getOperand(1);
  1081. // Find a recurrence.
  1082. if (LL == I)
  1083. L = LR;
  1084. else if (LR == I)
  1085. L = LL;
  1086. else
  1087. break;
  1088. // Ok, we have a PHI of the form L op= R. Check for low
  1089. // zero bits.
  1090. computeKnownBits(R, KnownZero2, KnownOne2, TD, Depth+1, Q);
  1091. // We need to take the minimum number of known bits
  1092. APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
  1093. computeKnownBits(L, KnownZero3, KnownOne3, TD, Depth+1, Q);
  1094. KnownZero = APInt::getLowBitsSet(BitWidth,
  1095. std::min(KnownZero2.countTrailingOnes(),
  1096. KnownZero3.countTrailingOnes()));
  1097. break;
  1098. }
  1099. }
  1100. }
  1101. // Unreachable blocks may have zero-operand PHI nodes.
  1102. if (P->getNumIncomingValues() == 0)
  1103. break;
  1104. // Otherwise take the unions of the known bit sets of the operands,
  1105. // taking conservative care to avoid excessive recursion.
  1106. if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
  1107. // Skip if every incoming value references to ourself.
  1108. if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
  1109. break;
  1110. KnownZero = APInt::getAllOnesValue(BitWidth);
  1111. KnownOne = APInt::getAllOnesValue(BitWidth);
  1112. for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
  1113. // Skip direct self references.
  1114. if (P->getIncomingValue(i) == P) continue;
  1115. KnownZero2 = APInt(BitWidth, 0);
  1116. KnownOne2 = APInt(BitWidth, 0);
  1117. // Recurse, but cap the recursion to one level, because we don't
  1118. // want to waste time spinning around in loops.
  1119. computeKnownBits(P->getIncomingValue(i), KnownZero2, KnownOne2, TD,
  1120. MaxDepth-1, Q);
  1121. KnownZero &= KnownZero2;
  1122. KnownOne &= KnownOne2;
  1123. // If all bits have been ruled out, there's no need to check
  1124. // more operands.
  1125. if (!KnownZero && !KnownOne)
  1126. break;
  1127. }
  1128. }
  1129. break;
  1130. }
  1131. case Instruction::Call:
  1132. case Instruction::Invoke:
  1133. if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
  1134. computeKnownBitsFromRangeMetadata(*MD, KnownZero);
  1135. // If a range metadata is attached to this IntrinsicInst, intersect the
  1136. // explicit range specified by the metadata and the implicit range of
  1137. // the intrinsic.
  1138. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
  1139. switch (II->getIntrinsicID()) {
  1140. default: break;
  1141. case Intrinsic::ctlz:
  1142. case Intrinsic::cttz: {
  1143. unsigned LowBits = Log2_32(BitWidth)+1;
  1144. // If this call is undefined for 0, the result will be less than 2^n.
  1145. if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
  1146. LowBits -= 1;
  1147. KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
  1148. break;
  1149. }
  1150. case Intrinsic::ctpop: {
  1151. unsigned LowBits = Log2_32(BitWidth)+1;
  1152. KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
  1153. break;
  1154. }
  1155. case Intrinsic::x86_sse42_crc32_64_64:
  1156. KnownZero |= APInt::getHighBitsSet(64, 32);
  1157. break;
  1158. }
  1159. }
  1160. break;
  1161. case Instruction::ExtractValue:
  1162. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
  1163. ExtractValueInst *EVI = cast<ExtractValueInst>(I);
  1164. if (EVI->getNumIndices() != 1) break;
  1165. if (EVI->getIndices()[0] == 0) {
  1166. switch (II->getIntrinsicID()) {
  1167. default: break;
  1168. case Intrinsic::uadd_with_overflow:
  1169. case Intrinsic::sadd_with_overflow:
  1170. computeKnownBitsAddSub(true, II->getArgOperand(0),
  1171. II->getArgOperand(1), false, KnownZero,
  1172. KnownOne, KnownZero2, KnownOne2, TD, Depth, Q);
  1173. break;
  1174. case Intrinsic::usub_with_overflow:
  1175. case Intrinsic::ssub_with_overflow:
  1176. computeKnownBitsAddSub(false, II->getArgOperand(0),
  1177. II->getArgOperand(1), false, KnownZero,
  1178. KnownOne, KnownZero2, KnownOne2, TD, Depth, Q);
  1179. break;
  1180. case Intrinsic::umul_with_overflow:
  1181. case Intrinsic::smul_with_overflow:
  1182. computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1),
  1183. false, KnownZero, KnownOne,
  1184. KnownZero2, KnownOne2, TD, Depth, Q);
  1185. break;
  1186. }
  1187. }
  1188. }
  1189. }
  1190. assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
  1191. }
  1192. /// Determine whether the sign bit is known to be zero or one.
  1193. /// Convenience wrapper around computeKnownBits.
  1194. void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
  1195. const DataLayout *TD, unsigned Depth,
  1196. const Query &Q) {
  1197. unsigned BitWidth = getBitWidth(V->getType(), TD);
  1198. if (!BitWidth) {
  1199. KnownZero = false;
  1200. KnownOne = false;
  1201. return;
  1202. }
  1203. APInt ZeroBits(BitWidth, 0);
  1204. APInt OneBits(BitWidth, 0);
  1205. computeKnownBits(V, ZeroBits, OneBits, TD, Depth, Q);
  1206. KnownOne = OneBits[BitWidth - 1];
  1207. KnownZero = ZeroBits[BitWidth - 1];
  1208. }
  1209. /// Return true if the given value is known to have exactly one
  1210. /// bit set when defined. For vectors return true if every element is known to
  1211. /// be a power of two when defined. Supports values with integer or pointer
  1212. /// types and vectors of integers.
  1213. bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
  1214. const Query &Q) {
  1215. if (Constant *C = dyn_cast<Constant>(V)) {
  1216. if (C->isNullValue())
  1217. return OrZero;
  1218. if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
  1219. return CI->getValue().isPowerOf2();
  1220. // TODO: Handle vector constants.
  1221. }
  1222. // 1 << X is clearly a power of two if the one is not shifted off the end. If
  1223. // it is shifted off the end then the result is undefined.
  1224. if (match(V, m_Shl(m_One(), m_Value())))
  1225. return true;
  1226. // (signbit) >>l X is clearly a power of two if the one is not shifted off the
  1227. // bottom. If it is shifted off the bottom then the result is undefined.
  1228. if (match(V, m_LShr(m_SignBit(), m_Value())))
  1229. return true;
  1230. // The remaining tests are all recursive, so bail out if we hit the limit.
  1231. if (Depth++ == MaxDepth)
  1232. return false;
  1233. Value *X = nullptr, *Y = nullptr;
  1234. // A shift of a power of two is a power of two or zero.
  1235. if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
  1236. match(V, m_Shr(m_Value(X), m_Value()))))
  1237. return isKnownToBeAPowerOfTwo(X, /*OrZero*/true, Depth, Q);
  1238. if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
  1239. return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
  1240. if (SelectInst *SI = dyn_cast<SelectInst>(V))
  1241. return
  1242. isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
  1243. isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
  1244. if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
  1245. // A power of two and'd with anything is a power of two or zero.
  1246. if (isKnownToBeAPowerOfTwo(X, /*OrZero*/true, Depth, Q) ||
  1247. isKnownToBeAPowerOfTwo(Y, /*OrZero*/true, Depth, Q))
  1248. return true;
  1249. // X & (-X) is always a power of two or zero.
  1250. if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
  1251. return true;
  1252. return false;
  1253. }
  1254. // Adding a power-of-two or zero to the same power-of-two or zero yields
  1255. // either the original power-of-two, a larger power-of-two or zero.
  1256. if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
  1257. OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
  1258. if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
  1259. if (match(X, m_And(m_Specific(Y), m_Value())) ||
  1260. match(X, m_And(m_Value(), m_Specific(Y))))
  1261. if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
  1262. return true;
  1263. if (match(Y, m_And(m_Specific(X), m_Value())) ||
  1264. match(Y, m_And(m_Value(), m_Specific(X))))
  1265. if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
  1266. return true;
  1267. unsigned BitWidth = V->getType()->getScalarSizeInBits();
  1268. APInt LHSZeroBits(BitWidth, 0), LHSOneBits(BitWidth, 0);
  1269. computeKnownBits(X, LHSZeroBits, LHSOneBits, nullptr, Depth, Q);
  1270. APInt RHSZeroBits(BitWidth, 0), RHSOneBits(BitWidth, 0);
  1271. computeKnownBits(Y, RHSZeroBits, RHSOneBits, nullptr, Depth, Q);
  1272. // If i8 V is a power of two or zero:
  1273. // ZeroBits: 1 1 1 0 1 1 1 1
  1274. // ~ZeroBits: 0 0 0 1 0 0 0 0
  1275. if ((~(LHSZeroBits & RHSZeroBits)).isPowerOf2())
  1276. // If OrZero isn't set, we cannot give back a zero result.
  1277. // Make sure either the LHS or RHS has a bit set.
  1278. if (OrZero || RHSOneBits.getBoolValue() || LHSOneBits.getBoolValue())
  1279. return true;
  1280. }
  1281. }
  1282. // An exact divide or right shift can only shift off zero bits, so the result
  1283. // is a power of two only if the first operand is a power of two and not
  1284. // copying a sign bit (sdiv int_min, 2).
  1285. if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
  1286. match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
  1287. return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
  1288. Depth, Q);
  1289. }
  1290. return false;
  1291. }
  1292. /// \brief Test whether a GEP's result is known to be non-null.
  1293. ///
  1294. /// Uses properties inherent in a GEP to try to determine whether it is known
  1295. /// to be non-null.
  1296. ///
  1297. /// Currently this routine does not support vector GEPs.
  1298. static bool isGEPKnownNonNull(GEPOperator *GEP, const DataLayout *DL,
  1299. unsigned Depth, const Query &Q) {
  1300. if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
  1301. return false;
  1302. // FIXME: Support vector-GEPs.
  1303. assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
  1304. // If the base pointer is non-null, we cannot walk to a null address with an
  1305. // inbounds GEP in address space zero.
  1306. if (isKnownNonZero(GEP->getPointerOperand(), DL, Depth, Q))
  1307. return true;
  1308. // Past this, if we don't have DataLayout, we can't do much.
  1309. if (!DL)
  1310. return false;
  1311. // Walk the GEP operands and see if any operand introduces a non-zero offset.
  1312. // If so, then the GEP cannot produce a null pointer, as doing so would
  1313. // inherently violate the inbounds contract within address space zero.
  1314. for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
  1315. GTI != GTE; ++GTI) {
  1316. // Struct types are easy -- they must always be indexed by a constant.
  1317. if (StructType *STy = dyn_cast<StructType>(*GTI)) {
  1318. ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
  1319. unsigned ElementIdx = OpC->getZExtValue();
  1320. const StructLayout *SL = DL->getStructLayout(STy);
  1321. uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
  1322. if (ElementOffset > 0)
  1323. return true;
  1324. continue;
  1325. }
  1326. // If we have a zero-sized type, the index doesn't matter. Keep looping.
  1327. if (DL->getTypeAllocSize(GTI.getIndexedType()) == 0)
  1328. continue;
  1329. // Fast path the constant operand case both for efficiency and so we don't
  1330. // increment Depth when just zipping down an all-constant GEP.
  1331. if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
  1332. if (!OpC->isZero())
  1333. return true;
  1334. continue;
  1335. }
  1336. // We post-increment Depth here because while isKnownNonZero increments it
  1337. // as well, when we pop back up that increment won't persist. We don't want
  1338. // to recurse 10k times just because we have 10k GEP operands. We don't
  1339. // bail completely out because we want to handle constant GEPs regardless
  1340. // of depth.
  1341. if (Depth++ >= MaxDepth)
  1342. continue;
  1343. if (isKnownNonZero(GTI.getOperand(), DL, Depth, Q))
  1344. return true;
  1345. }
  1346. return false;
  1347. }
  1348. /// Does the 'Range' metadata (which must be a valid MD_range operand list)
  1349. /// ensure that the value it's attached to is never Value? 'RangeType' is
  1350. /// is the type of the value described by the range.
  1351. static bool rangeMetadataExcludesValue(MDNode* Ranges,
  1352. const APInt& Value) {
  1353. const unsigned NumRanges = Ranges->getNumOperands() / 2;
  1354. assert(NumRanges >= 1);
  1355. for (unsigned i = 0; i < NumRanges; ++i) {
  1356. ConstantInt *Lower =
  1357. mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
  1358. ConstantInt *Upper =
  1359. mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
  1360. ConstantRange Range(Lower->getValue(), Upper->getValue());
  1361. if (Range.contains(Value))
  1362. return false;
  1363. }
  1364. return true;
  1365. }
  1366. /// Return true if the given value is known to be non-zero when defined.
  1367. /// For vectors return true if every element is known to be non-zero when
  1368. /// defined. Supports values with integer or pointer type and vectors of
  1369. /// integers.
  1370. bool isKnownNonZero(Value *V, const DataLayout *TD, unsigned Depth,
  1371. const Query &Q) {
  1372. if (Constant *C = dyn_cast<Constant>(V)) {
  1373. if (C->isNullValue())
  1374. return false;
  1375. if (isa<ConstantInt>(C))
  1376. // Must be non-zero due to null test above.
  1377. return true;
  1378. // TODO: Handle vectors
  1379. return false;
  1380. }
  1381. if (Instruction* I = dyn_cast<Instruction>(V)) {
  1382. if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
  1383. // If the possible ranges don't contain zero, then the value is
  1384. // definitely non-zero.
  1385. if (IntegerType* Ty = dyn_cast<IntegerType>(V->getType())) {
  1386. const APInt ZeroValue(Ty->getBitWidth(), 0);
  1387. if (rangeMetadataExcludesValue(Ranges, ZeroValue))
  1388. return true;
  1389. }
  1390. }
  1391. }
  1392. // The remaining tests are all recursive, so bail out if we hit the limit.
  1393. if (Depth++ >= MaxDepth)
  1394. return false;
  1395. // Check for pointer simplifications.
  1396. if (V->getType()->isPointerTy()) {
  1397. if (isKnownNonNull(V))
  1398. return true;
  1399. if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
  1400. if (isGEPKnownNonNull(GEP, TD, Depth, Q))
  1401. return true;
  1402. }
  1403. unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), TD);
  1404. // X | Y != 0 if X != 0 or Y != 0.
  1405. Value *X = nullptr, *Y = nullptr;
  1406. if (match(V, m_Or(m_Value(X), m_Value(Y))))
  1407. return isKnownNonZero(X, TD, Depth, Q) ||
  1408. isKnownNonZero(Y, TD, Depth, Q);
  1409. // ext X != 0 if X != 0.
  1410. if (isa<SExtInst>(V) || isa<ZExtInst>(V))
  1411. return isKnownNonZero(cast<Instruction>(V)->getOperand(0), TD, Depth, Q);
  1412. // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
  1413. // if the lowest bit is shifted off the end.
  1414. if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
  1415. // shl nuw can't remove any non-zero bits.
  1416. OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
  1417. if (BO->hasNoUnsignedWrap())
  1418. return isKnownNonZero(X, TD, Depth, Q);
  1419. APInt KnownZero(BitWidth, 0);
  1420. APInt KnownOne(BitWidth, 0);
  1421. computeKnownBits(X, KnownZero, KnownOne, TD, Depth, Q);
  1422. if (KnownOne[0])
  1423. return true;
  1424. }
  1425. // shr X, Y != 0 if X is negative. Note that the value of the shift is not
  1426. // defined if the sign bit is shifted off the end.
  1427. else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
  1428. // shr exact can only shift out zero bits.
  1429. PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
  1430. if (BO->isExact())
  1431. return isKnownNonZero(X, TD, Depth, Q);
  1432. bool XKnownNonNegative, XKnownNegative;
  1433. ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth, Q);
  1434. if (XKnownNegative)
  1435. return true;
  1436. }
  1437. // div exact can only produce a zero if the dividend is zero.
  1438. else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
  1439. return isKnownNonZero(X, TD, Depth, Q);
  1440. }
  1441. // X + Y.
  1442. else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
  1443. bool XKnownNonNegative, XKnownNegative;
  1444. bool YKnownNonNegative, YKnownNegative;
  1445. ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth, Q);
  1446. ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, TD, Depth, Q);
  1447. // If X and Y are both non-negative (as signed values) then their sum is not
  1448. // zero unless both X and Y are zero.
  1449. if (XKnownNonNegative && YKnownNonNegative)
  1450. if (isKnownNonZero(X, TD, Depth, Q) ||
  1451. isKnownNonZero(Y, TD, Depth, Q))
  1452. return true;
  1453. // If X and Y are both negative (as signed values) then their sum is not
  1454. // zero unless both X and Y equal INT_MIN.
  1455. if (BitWidth && XKnownNegative && YKnownNegative) {
  1456. APInt KnownZero(BitWidth, 0);
  1457. APInt KnownOne(BitWidth, 0);
  1458. APInt Mask = APInt::getSignedMaxValue(BitWidth);
  1459. // The sign bit of X is set. If some other bit is set then X is not equal
  1460. // to INT_MIN.
  1461. computeKnownBits(X, KnownZero, KnownOne, TD, Depth, Q);
  1462. if ((KnownOne & Mask) != 0)
  1463. return true;
  1464. // The sign bit of Y is set. If some other bit is set then Y is not equal
  1465. // to INT_MIN.
  1466. computeKnownBits(Y, KnownZero, KnownOne, TD, Depth, Q);
  1467. if ((KnownOne & Mask) != 0)
  1468. return true;
  1469. }
  1470. // The sum of a non-negative number and a power of two is not zero.
  1471. if (XKnownNonNegative &&
  1472. isKnownToBeAPowerOfTwo(Y, /*OrZero*/false, Depth, Q))
  1473. return true;
  1474. if (YKnownNonNegative &&
  1475. isKnownToBeAPowerOfTwo(X, /*OrZero*/false, Depth, Q))
  1476. return true;
  1477. }
  1478. // X * Y.
  1479. else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
  1480. OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
  1481. // If X and Y are non-zero then so is X * Y as long as the multiplication
  1482. // does not overflow.
  1483. if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
  1484. isKnownNonZero(X, TD, Depth, Q) &&
  1485. isKnownNonZero(Y, TD, Depth, Q))
  1486. return true;
  1487. }
  1488. // (C ? X : Y) != 0 if X != 0 and Y != 0.
  1489. else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
  1490. if (isKnownNonZero(SI->getTrueValue(), TD, Depth, Q) &&
  1491. isKnownNonZero(SI->getFalseValue(), TD, Depth, Q))
  1492. return true;
  1493. }
  1494. if (!BitWidth) return false;
  1495. APInt KnownZero(BitWidth, 0);
  1496. APInt KnownOne(BitWidth, 0);
  1497. computeKnownBits(V, KnownZero, KnownOne, TD, Depth, Q);
  1498. return KnownOne != 0;
  1499. }
  1500. /// Return true if 'V & Mask' is known to be zero. We use this predicate to
  1501. /// simplify operations downstream. Mask is known to be zero for bits that V
  1502. /// cannot have.
  1503. ///
  1504. /// This function is defined on values with integer type, values with pointer
  1505. /// type (but only if TD is non-null), and vectors of integers. In the case
  1506. /// where V is a vector, the mask, known zero, and known one values are the
  1507. /// same width as the vector element, and the bit is set only if it is true
  1508. /// for all of the elements in the vector.
  1509. bool MaskedValueIsZero(Value *V, const APInt &Mask,
  1510. const DataLayout *TD, unsigned Depth,
  1511. const Query &Q) {
  1512. APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
  1513. computeKnownBits(V, KnownZero, KnownOne, TD, Depth, Q);
  1514. return (KnownZero & Mask) == Mask;
  1515. }
  1516. /// Return the number of times the sign bit of the register is replicated into
  1517. /// the other bits. We know that at least 1 bit is always equal to the sign bit
  1518. /// (itself), but other cases can give us information. For example, immediately
  1519. /// after an "ashr X, 2", we know that the top 3 bits are all equal to each
  1520. /// other, so we return 3.
  1521. ///
  1522. /// 'Op' must have a scalar integer type.
  1523. ///
  1524. unsigned ComputeNumSignBits(Value *V, const DataLayout *TD,
  1525. unsigned Depth, const Query &Q) {
  1526. assert((TD || V->getType()->isIntOrIntVectorTy()) &&
  1527. "ComputeNumSignBits requires a DataLayout object to operate "
  1528. "on non-integer values!");
  1529. Type *Ty = V->getType();
  1530. unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
  1531. Ty->getScalarSizeInBits();
  1532. unsigned Tmp, Tmp2;
  1533. unsigned FirstAnswer = 1;
  1534. // Note that ConstantInt is handled by the general computeKnownBits case
  1535. // below.
  1536. if (Depth == 6)
  1537. return 1; // Limit search depth.
  1538. Operator *U = dyn_cast<Operator>(V);
  1539. switch (Operator::getOpcode(V)) {
  1540. default: break;
  1541. case Instruction::SExt:
  1542. Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
  1543. return ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q) + Tmp;
  1544. case Instruction::AShr: {
  1545. Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
  1546. // ashr X, C -> adds C sign bits. Vectors too.
  1547. const APInt *ShAmt;
  1548. if (match(U->getOperand(1), m_APInt(ShAmt))) {
  1549. Tmp += ShAmt->getZExtValue();
  1550. if (Tmp > TyBits) Tmp = TyBits;
  1551. }
  1552. return Tmp;
  1553. }
  1554. case Instruction::Shl: {
  1555. const APInt *ShAmt;
  1556. if (match(U->getOperand(1), m_APInt(ShAmt))) {
  1557. // shl destroys sign bits.
  1558. Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
  1559. Tmp2 = ShAmt->getZExtValue();
  1560. if (Tmp2 >= TyBits || // Bad shift.
  1561. Tmp2 >= Tmp) break; // Shifted all sign bits out.
  1562. return Tmp - Tmp2;
  1563. }
  1564. break;
  1565. }
  1566. case Instruction::And:
  1567. case Instruction::Or:
  1568. case Instruction::Xor: // NOT is handled here.
  1569. // Logical binary ops preserve the number of sign bits at the worst.
  1570. Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
  1571. if (Tmp != 1) {
  1572. Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
  1573. FirstAnswer = std::min(Tmp, Tmp2);
  1574. // We computed what we know about the sign bits as our first
  1575. // answer. Now proceed to the generic code that uses
  1576. // computeKnownBits, and pick whichever answer is better.
  1577. }
  1578. break;
  1579. case Instruction::Select:
  1580. Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
  1581. if (Tmp == 1) return 1; // Early out.
  1582. Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1, Q);
  1583. return std::min(Tmp, Tmp2);
  1584. case Instruction::Add:
  1585. // Add can have at most one carry bit. Thus we know that the output
  1586. // is, at worst, one more bit than the inputs.
  1587. Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
  1588. if (Tmp == 1) return 1; // Early out.
  1589. // Special case decrementing a value (ADD X, -1):
  1590. if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
  1591. if (CRHS->isAllOnesValue()) {
  1592. APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
  1593. computeKnownBits(U->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
  1594. // If the input is known to be 0 or 1, the output is 0/-1, which is all
  1595. // sign bits set.
  1596. if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
  1597. return TyBits;
  1598. // If we are subtracting one from a positive number, there is no carry
  1599. // out of the result.
  1600. if (KnownZero.isNegative())
  1601. return Tmp;
  1602. }
  1603. Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
  1604. if (Tmp2 == 1) return 1;
  1605. return std::min(Tmp, Tmp2)-1;
  1606. case Instruction::Sub:
  1607. Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
  1608. if (Tmp2 == 1) return 1;
  1609. // Handle NEG.
  1610. if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
  1611. if (CLHS->isNullValue()) {
  1612. APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
  1613. computeKnownBits(U->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
  1614. // If the input is known to be 0 or 1, the output is 0/-1, which is all
  1615. // sign bits set.
  1616. if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
  1617. return TyBits;
  1618. // If the input is known to be positive (the sign bit is known clear),
  1619. // the output of the NEG has the same number of sign bits as the input.
  1620. if (KnownZero.isNegative())
  1621. return Tmp2;
  1622. // Otherwise, we treat this like a SUB.
  1623. }
  1624. // Sub can have at most one carry bit. Thus we know that the output
  1625. // is, at worst, one more bit than the inputs.
  1626. Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
  1627. if (Tmp == 1) return 1; // Early out.
  1628. return std::min(Tmp, Tmp2)-1;
  1629. case Instruction::PHI: {
  1630. PHINode *PN = cast<PHINode>(U);
  1631. unsigned NumIncomingValues = PN->getNumIncomingValues();
  1632. // Don't analyze large in-degree PHIs.
  1633. if (NumIncomingValues > 4) break;
  1634. // Unreachable blocks may have zero-operand PHI nodes.
  1635. if (NumIncomingValues == 0) break;
  1636. // Take the minimum of all incoming values. This can't infinitely loop
  1637. // because of our depth threshold.
  1638. Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1, Q);
  1639. for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
  1640. if (Tmp == 1) return Tmp;
  1641. Tmp = std::min(Tmp,
  1642. ComputeNumSignBits(PN->getIncomingValue(i), TD,
  1643. Depth+1, Q));
  1644. }
  1645. return Tmp;
  1646. }
  1647. case Instruction::Trunc:
  1648. // FIXME: it's tricky to do anything useful for this, but it is an important
  1649. // case for targets like X86.
  1650. break;
  1651. }
  1652. // Finally, if we can prove that the top bits of the result are 0's or 1's,
  1653. // use this information.
  1654. APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
  1655. APInt Mask;
  1656. computeKnownBits(V, KnownZero, KnownOne, TD, Depth, Q);
  1657. if (KnownZero.isNegative()) { // sign bit is 0
  1658. Mask = KnownZero;
  1659. } else if (KnownOne.isNegative()) { // sign bit is 1;
  1660. Mask = KnownOne;
  1661. } else {
  1662. // Nothing known.
  1663. return FirstAnswer;
  1664. }
  1665. // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
  1666. // the number of identical bits in the top of the input value.
  1667. Mask = ~Mask;
  1668. Mask <<= Mask.getBitWidth()-TyBits;
  1669. // Return # leading zeros. We use 'min' here in case Val was zero before
  1670. // shifting. We don't want to return '64' as for an i32 "0".
  1671. return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
  1672. }
  1673. /// This function computes the integer multiple of Base that equals V.
  1674. /// If successful, it returns true and returns the multiple in
  1675. /// Multiple. If unsuccessful, it returns false. It looks
  1676. /// through SExt instructions only if LookThroughSExt is true.
  1677. bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
  1678. bool LookThroughSExt, unsigned Depth) {
  1679. const unsigned MaxDepth = 6;
  1680. assert(V && "No Value?");
  1681. assert(Depth <= MaxDepth && "Limit Search Depth");
  1682. assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
  1683. Type *T = V->getType();
  1684. ConstantInt *CI = dyn_cast<ConstantInt>(V);
  1685. if (Base == 0)
  1686. return false;
  1687. if (Base == 1) {
  1688. Multiple = V;
  1689. return true;
  1690. }
  1691. ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
  1692. Constant *BaseVal = ConstantInt::get(T, Base);
  1693. if (CO && CO == BaseVal) {
  1694. // Multiple is 1.
  1695. Multiple = ConstantInt::get(T, 1);
  1696. return true;
  1697. }
  1698. if (CI && CI->getZExtValue() % Base == 0) {
  1699. Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
  1700. return true;
  1701. }
  1702. if (Depth == MaxDepth) return false; // Limit search depth.
  1703. Operator *I = dyn_cast<Operator>(V);
  1704. if (!I) return false;
  1705. switch (I->getOpcode()) {
  1706. default: break;
  1707. case Instruction::SExt:
  1708. if (!LookThroughSExt) return false;
  1709. // otherwise fall through to ZExt
  1710. case Instruction::ZExt:
  1711. return ComputeMultiple(I->getOperand(0), Base, Multiple,
  1712. LookThroughSExt, Depth+1);
  1713. case Instruction::Shl:
  1714. case Instruction::Mul: {
  1715. Value *Op0 = I->getOperand(0);
  1716. Value *Op1 = I->getOperand(1);
  1717. if (I->getOpcode() == Instruction::Shl) {
  1718. ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
  1719. if (!Op1CI) return false;
  1720. // Turn Op0 << Op1 into Op0 * 2^Op1
  1721. APInt Op1Int = Op1CI->getValue();
  1722. uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
  1723. APInt API(Op1Int.getBitWidth(), 0);
  1724. API.setBit(BitToSet);
  1725. Op1 = ConstantInt::get(V->getContext(), API);
  1726. }
  1727. Value *Mul0 = nullptr;
  1728. if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
  1729. if (Constant *Op1C = dyn_cast<Constant>(Op1))
  1730. if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
  1731. if (Op1C->getType()->getPrimitiveSizeInBits() <
  1732. MulC->getType()->getPrimitiveSizeInBits())
  1733. Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
  1734. if (Op1C->getType()->getPrimitiveSizeInBits() >
  1735. MulC->getType()->getPrimitiveSizeInBits())
  1736. MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
  1737. // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
  1738. Multiple = ConstantExpr::getMul(MulC, Op1C);
  1739. return true;
  1740. }
  1741. if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
  1742. if (Mul0CI->getValue() == 1) {
  1743. // V == Base * Op1, so return Op1
  1744. Multiple = Op1;
  1745. return true;
  1746. }
  1747. }
  1748. Value *Mul1 = nullptr;
  1749. if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
  1750. if (Constant *Op0C = dyn_cast<Constant>(Op0))
  1751. if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
  1752. if (Op0C->getType()->getPrimitiveSizeInBits() <
  1753. MulC->getType()->getPrimitiveSizeInBits())
  1754. Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
  1755. if (Op0C->getType()->getPrimitiveSizeInBits() >
  1756. MulC->getType()->getPrimitiveSizeInBits())
  1757. MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
  1758. // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
  1759. Multiple = ConstantExpr::getMul(MulC, Op0C);
  1760. return true;
  1761. }
  1762. if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
  1763. if (Mul1CI->getValue() == 1) {
  1764. // V == Base * Op0, so return Op0
  1765. Multiple = Op0;
  1766. return true;
  1767. }
  1768. }
  1769. }
  1770. }
  1771. // We could not determine if V is a multiple of Base.
  1772. return false;
  1773. }
  1774. /// Return true if we can prove that the specified FP value is never equal to
  1775. /// -0.0.
  1776. ///
  1777. /// NOTE: this function will need to be revisited when we support non-default
  1778. /// rounding modes!
  1779. ///
  1780. bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
  1781. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
  1782. return !CFP->getValueAPF().isNegZero();
  1783. if (Depth == 6)
  1784. return 1; // Limit search depth.
  1785. const Operator *I = dyn_cast<Operator>(V);
  1786. if (!I) return false;
  1787. // Check if the nsz fast-math flag is set
  1788. if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
  1789. if (FPO->hasNoSignedZeros())
  1790. return true;
  1791. // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
  1792. if (I->getOpcode() == Instruction::FAdd)
  1793. if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
  1794. if (CFP->isNullValue())
  1795. return true;
  1796. // sitofp and uitofp turn into +0.0 for zero.
  1797. if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
  1798. return true;
  1799. if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
  1800. // sqrt(-0.0) = -0.0, no other negative results are possible.
  1801. if (II->getIntrinsicID() == Intrinsic::sqrt)
  1802. return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
  1803. if (const CallInst *CI = dyn_cast<CallInst>(I))
  1804. if (const Function *F = CI->getCalledFunction()) {
  1805. if (F->isDeclaration()) {
  1806. // abs(x) != -0.0
  1807. if (F->getName() == "abs") return true;
  1808. // fabs[lf](x) != -0.0
  1809. if (F->getName() == "fabs") return true;
  1810. if (F->getName() == "fabsf") return true;
  1811. if (F->getName() == "fabsl") return true;
  1812. if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
  1813. F->getName() == "sqrtl")
  1814. return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
  1815. }
  1816. }
  1817. return false;
  1818. }
  1819. /// If the specified value can be set by repeating the same byte in memory,
  1820. /// return the i8 value that it is represented with. This is
  1821. /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
  1822. /// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
  1823. /// byte store (e.g. i16 0x1234), return null.
  1824. Value *llvm::isBytewiseValue(Value *V) {
  1825. // All byte-wide stores are splatable, even of arbitrary variables.
  1826. if (V->getType()->isIntegerTy(8)) return V;
  1827. // Handle 'null' ConstantArrayZero etc.
  1828. if (Constant *C = dyn_cast<Constant>(V))
  1829. if (C->isNullValue())
  1830. return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
  1831. // Constant float and double values can be handled as integer values if the
  1832. // corresponding integer value is "byteable". An important case is 0.0.
  1833. if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
  1834. if (CFP->getType()->isFloatTy())
  1835. V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
  1836. if (CFP->getType()->isDoubleTy())
  1837. V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
  1838. // Don't handle long double formats, which have strange constraints.
  1839. }
  1840. // We can handle constant integers that are power of two in size and a
  1841. // multiple of 8 bits.
  1842. if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  1843. unsigned Width = CI->getBitWidth();
  1844. if (isPowerOf2_32(Width) && Width > 8) {
  1845. // We can handle this value if the recursive binary decomposition is the
  1846. // same at all levels.
  1847. APInt Val = CI->getValue();
  1848. APInt Val2;
  1849. while (Val.getBitWidth() != 8) {
  1850. unsigned NextWidth = Val.getBitWidth()/2;
  1851. Val2 = Val.lshr(NextWidth);
  1852. Val2 = Val2.trunc(Val.getBitWidth()/2);
  1853. Val = Val.trunc(Val.getBitWidth()/2);
  1854. // If the top/bottom halves aren't the same, reject it.
  1855. if (Val != Val2)
  1856. return nullptr;
  1857. }
  1858. return ConstantInt::get(V->getContext(), Val);
  1859. }
  1860. }
  1861. // A ConstantDataArray/Vector is splatable if all its members are equal and
  1862. // also splatable.
  1863. if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
  1864. Value *Elt = CA->getElementAsConstant(0);
  1865. Value *Val = isBytewiseValue(Elt);
  1866. if (!Val)
  1867. return nullptr;
  1868. for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
  1869. if (CA->getElementAsConstant(I) != Elt)
  1870. return nullptr;
  1871. return Val;
  1872. }
  1873. // Conceptually, we could handle things like:
  1874. // %a = zext i8 %X to i16
  1875. // %b = shl i16 %a, 8
  1876. // %c = or i16 %a, %b
  1877. // but until there is an example that actually needs this, it doesn't seem
  1878. // worth worrying about.
  1879. return nullptr;
  1880. }
  1881. // This is the recursive version of BuildSubAggregate. It takes a few different
  1882. // arguments. Idxs is the index within the nested struct From that we are
  1883. // looking at now (which is of type IndexedType). IdxSkip is the number of
  1884. // indices from Idxs that should be left out when inserting into the resulting
  1885. // struct. To is the result struct built so far, new insertvalue instructions
  1886. // build on that.
  1887. static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
  1888. SmallVectorImpl<unsigned> &Idxs,
  1889. unsigned IdxSkip,
  1890. Instruction *InsertBefore) {
  1891. llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
  1892. if (STy) {
  1893. // Save the original To argument so we can modify it
  1894. Value *OrigTo = To;
  1895. // General case, the type indexed by Idxs is a struct
  1896. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  1897. // Process each struct element recursively
  1898. Idxs.push_back(i);
  1899. Value *PrevTo = To;
  1900. To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
  1901. InsertBefore);
  1902. Idxs.pop_back();
  1903. if (!To) {
  1904. // Couldn't find any inserted value for this index? Cleanup
  1905. while (PrevTo != OrigTo) {
  1906. InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
  1907. PrevTo = Del->getAggregateOperand();
  1908. Del->eraseFromParent();
  1909. }
  1910. // Stop processing elements
  1911. break;
  1912. }
  1913. }
  1914. // If we successfully found a value for each of our subaggregates
  1915. if (To)
  1916. return To;
  1917. }
  1918. // Base case, the type indexed by SourceIdxs is not a struct, or not all of
  1919. // the struct's elements had a value that was inserted directly. In the latter
  1920. // case, perhaps we can't determine each of the subelements individually, but
  1921. // we might be able to find the complete struct somewhere.
  1922. // Find the value that is at that particular spot
  1923. Value *V = FindInsertedValue(From, Idxs);
  1924. if (!V)
  1925. return nullptr;
  1926. // Insert the value in the new (sub) aggregrate
  1927. return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
  1928. "tmp", InsertBefore);
  1929. }
  1930. // This helper takes a nested struct and extracts a part of it (which is again a
  1931. // struct) into a new value. For example, given the struct:
  1932. // { a, { b, { c, d }, e } }
  1933. // and the indices "1, 1" this returns
  1934. // { c, d }.
  1935. //
  1936. // It does this by inserting an insertvalue for each element in the resulting
  1937. // struct, as opposed to just inserting a single struct. This will only work if
  1938. // each of the elements of the substruct are known (ie, inserted into From by an
  1939. // insertvalue instruction somewhere).
  1940. //
  1941. // All inserted insertvalue instructions are inserted before InsertBefore
  1942. static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
  1943. Instruction *InsertBefore) {
  1944. assert(InsertBefore && "Must have someplace to insert!");
  1945. Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
  1946. idx_range);
  1947. Value *To = UndefValue::get(IndexedType);
  1948. SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
  1949. unsigned IdxSkip = Idxs.size();
  1950. return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
  1951. }
  1952. /// Given an aggregrate and an sequence of indices, see if
  1953. /// the scalar value indexed is already around as a register, for example if it
  1954. /// were inserted directly into the aggregrate.
  1955. ///
  1956. /// If InsertBefore is not null, this function will duplicate (modified)
  1957. /// insertvalues when a part of a nested struct is extracted.
  1958. Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
  1959. Instruction *InsertBefore) {
  1960. // Nothing to index? Just return V then (this is useful at the end of our
  1961. // recursion).
  1962. if (idx_range.empty())
  1963. return V;
  1964. // We have indices, so V should have an indexable type.
  1965. assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
  1966. "Not looking at a struct or array?");
  1967. assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
  1968. "Invalid indices for type?");
  1969. if (Constant *C = dyn_cast<Constant>(V)) {
  1970. C = C->getAggregateElement(idx_range[0]);
  1971. if (!C) return nullptr;
  1972. return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
  1973. }
  1974. if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
  1975. // Loop the indices for the insertvalue instruction in parallel with the
  1976. // requested indices
  1977. const unsigned *req_idx = idx_range.begin();
  1978. for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
  1979. i != e; ++i, ++req_idx) {
  1980. if (req_idx == idx_range.end()) {
  1981. // We can't handle this without inserting insertvalues
  1982. if (!InsertBefore)
  1983. return nullptr;
  1984. // The requested index identifies a part of a nested aggregate. Handle
  1985. // this specially. For example,
  1986. // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
  1987. // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
  1988. // %C = extractvalue {i32, { i32, i32 } } %B, 1
  1989. // This can be changed into
  1990. // %A = insertvalue {i32, i32 } undef, i32 10, 0
  1991. // %C = insertvalue {i32, i32 } %A, i32 11, 1
  1992. // which allows the unused 0,0 element from the nested struct to be
  1993. // removed.
  1994. return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
  1995. InsertBefore);
  1996. }
  1997. // This insert value inserts something else than what we are looking for.
  1998. // See if the (aggregrate) value inserted into has the value we are
  1999. // looking for, then.
  2000. if (*req_idx != *i)
  2001. return FindInsertedValue(I->getAggregateOperand(), idx_range,
  2002. InsertBefore);
  2003. }
  2004. // If we end up here, the indices of the insertvalue match with those
  2005. // requested (though possibly only partially). Now we recursively look at
  2006. // the inserted value, passing any remaining indices.
  2007. return FindInsertedValue(I->getInsertedValueOperand(),
  2008. makeArrayRef(req_idx, idx_range.end()),
  2009. InsertBefore);
  2010. }
  2011. if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
  2012. // If we're extracting a value from an aggregrate that was extracted from
  2013. // something else, we can extract from that something else directly instead.
  2014. // However, we will need to chain I's indices with the requested indices.
  2015. // Calculate the number of indices required
  2016. unsigned size = I->getNumIndices() + idx_range.size();
  2017. // Allocate some space to put the new indices in
  2018. SmallVector<unsigned, 5> Idxs;
  2019. Idxs.reserve(size);
  2020. // Add indices from the extract value instruction
  2021. Idxs.append(I->idx_begin(), I->idx_end());
  2022. // Add requested indices
  2023. Idxs.append(idx_range.begin(), idx_range.end());
  2024. assert(Idxs.size() == size
  2025. && "Number of indices added not correct?");
  2026. return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
  2027. }
  2028. // Otherwise, we don't know (such as, extracting from a function return value
  2029. // or load instruction)
  2030. return nullptr;
  2031. }
  2032. /// Analyze the specified pointer to see if it can be expressed as a base
  2033. /// pointer plus a constant offset. Return the base and offset to the caller.
  2034. Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
  2035. const DataLayout *DL) {
  2036. // Without DataLayout, conservatively assume 64-bit offsets, which is
  2037. // the widest we support.
  2038. unsigned BitWidth = DL ? DL->getPointerTypeSizeInBits(Ptr->getType()) : 64;
  2039. APInt ByteOffset(BitWidth, 0);
  2040. while (1) {
  2041. if (Ptr->getType()->isVectorTy())
  2042. break;
  2043. if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
  2044. if (DL) {
  2045. APInt GEPOffset(BitWidth, 0);
  2046. if (!GEP->accumulateConstantOffset(*DL, GEPOffset))
  2047. break;
  2048. ByteOffset += GEPOffset;
  2049. }
  2050. Ptr = GEP->getPointerOperand();
  2051. } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
  2052. Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
  2053. Ptr = cast<Operator>(Ptr)->getOperand(0);
  2054. } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
  2055. if (GA->mayBeOverridden())
  2056. break;
  2057. Ptr = GA->getAliasee();
  2058. } else {
  2059. break;
  2060. }
  2061. }
  2062. Offset = ByteOffset.getSExtValue();
  2063. return Ptr;
  2064. }
  2065. /// This function computes the length of a null-terminated C string pointed to
  2066. /// by V. If successful, it returns true and returns the string in Str.
  2067. /// If unsuccessful, it returns false.
  2068. bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
  2069. uint64_t Offset, bool TrimAtNul) {
  2070. assert(V);
  2071. // Look through bitcast instructions and geps.
  2072. V = V->stripPointerCasts();
  2073. // If the value is a GEP instructionor constant expression, treat it as an
  2074. // offset.
  2075. if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
  2076. // Make sure the GEP has exactly three arguments.
  2077. if (GEP->getNumOperands() != 3)
  2078. return false;
  2079. // Make sure the index-ee is a pointer to array of i8.
  2080. PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
  2081. ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
  2082. if (!AT || !AT->getElementType()->isIntegerTy(8))
  2083. return false;
  2084. // Check to make sure that the first operand of the GEP is an integer and
  2085. // has value 0 so that we are sure we're indexing into the initializer.
  2086. const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
  2087. if (!FirstIdx || !FirstIdx->isZero())
  2088. return false;
  2089. // If the second index isn't a ConstantInt, then this is a variable index
  2090. // into the array. If this occurs, we can't say anything meaningful about
  2091. // the string.
  2092. uint64_t StartIdx = 0;
  2093. if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
  2094. StartIdx = CI->getZExtValue();
  2095. else
  2096. return false;
  2097. return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset);
  2098. }
  2099. // The GEP instruction, constant or instruction, must reference a global
  2100. // variable that is a constant and is initialized. The referenced constant
  2101. // initializer is the array that we'll use for optimization.
  2102. const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
  2103. if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
  2104. return false;
  2105. // Handle the all-zeros case
  2106. if (GV->getInitializer()->isNullValue()) {
  2107. // This is a degenerate case. The initializer is constant zero so the
  2108. // length of the string must be zero.
  2109. Str = "";
  2110. return true;
  2111. }
  2112. // Must be a Constant Array
  2113. const ConstantDataArray *Array =
  2114. dyn_cast<ConstantDataArray>(GV->getInitializer());
  2115. if (!Array || !Array->isString())
  2116. return false;
  2117. // Get the number of elements in the array
  2118. uint64_t NumElts = Array->getType()->getArrayNumElements();
  2119. // Start out with the entire array in the StringRef.
  2120. Str = Array->getAsString();
  2121. if (Offset > NumElts)
  2122. return false;
  2123. // Skip over 'offset' bytes.
  2124. Str = Str.substr(Offset);
  2125. if (TrimAtNul) {
  2126. // Trim off the \0 and anything after it. If the array is not nul
  2127. // terminated, we just return the whole end of string. The client may know
  2128. // some other way that the string is length-bound.
  2129. Str = Str.substr(0, Str.find('\0'));
  2130. }
  2131. return true;
  2132. }
  2133. // These next two are very similar to the above, but also look through PHI
  2134. // nodes.
  2135. // TODO: See if we can integrate these two together.
  2136. /// If we can compute the length of the string pointed to by
  2137. /// the specified pointer, return 'len+1'. If we can't, return 0.
  2138. static uint64_t GetStringLengthH(Value *V, SmallPtrSetImpl<PHINode*> &PHIs) {
  2139. // Look through noop bitcast instructions.
  2140. V = V->stripPointerCasts();
  2141. // If this is a PHI node, there are two cases: either we have already seen it
  2142. // or we haven't.
  2143. if (PHINode *PN = dyn_cast<PHINode>(V)) {
  2144. if (!PHIs.insert(PN).second)
  2145. return ~0ULL; // already in the set.
  2146. // If it was new, see if all the input strings are the same length.
  2147. uint64_t LenSoFar = ~0ULL;
  2148. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  2149. uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
  2150. if (Len == 0) return 0; // Unknown length -> unknown.
  2151. if (Len == ~0ULL) continue;
  2152. if (Len != LenSoFar && LenSoFar != ~0ULL)
  2153. return 0; // Disagree -> unknown.
  2154. LenSoFar = Len;
  2155. }
  2156. // Success, all agree.
  2157. return LenSoFar;
  2158. }
  2159. // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
  2160. if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
  2161. uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
  2162. if (Len1 == 0) return 0;
  2163. uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
  2164. if (Len2 == 0) return 0;
  2165. if (Len1 == ~0ULL) return Len2;
  2166. if (Len2 == ~0ULL) return Len1;
  2167. if (Len1 != Len2) return 0;
  2168. return Len1;
  2169. }
  2170. // Otherwise, see if we can read the string.
  2171. StringRef StrData;
  2172. if (!getConstantStringInfo(V, StrData))
  2173. return 0;
  2174. return StrData.size()+1;
  2175. }
  2176. /// If we can compute the length of the string pointed to by
  2177. /// the specified pointer, return 'len+1'. If we can't, return 0.
  2178. uint64_t llvm::GetStringLength(Value *V) {
  2179. if (!V->getType()->isPointerTy()) return 0;
  2180. SmallPtrSet<PHINode*, 32> PHIs;
  2181. uint64_t Len = GetStringLengthH(V, PHIs);
  2182. // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
  2183. // an empty string as a length.
  2184. return Len == ~0ULL ? 1 : Len;
  2185. }
  2186. Value *
  2187. llvm::GetUnderlyingObject(Value *V, const DataLayout *TD, unsigned MaxLookup) {
  2188. if (!V->getType()->isPointerTy())
  2189. return V;
  2190. for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
  2191. if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
  2192. V = GEP->getPointerOperand();
  2193. } else if (Operator::getOpcode(V) == Instruction::BitCast ||
  2194. Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
  2195. V = cast<Operator>(V)->getOperand(0);
  2196. } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
  2197. if (GA->mayBeOverridden())
  2198. return V;
  2199. V = GA->getAliasee();
  2200. } else {
  2201. // See if InstructionSimplify knows any relevant tricks.
  2202. if (Instruction *I = dyn_cast<Instruction>(V))
  2203. // TODO: Acquire a DominatorTree and AssumptionCache and use them.
  2204. if (Value *Simplified = SimplifyInstruction(I, TD, nullptr)) {
  2205. V = Simplified;
  2206. continue;
  2207. }
  2208. return V;
  2209. }
  2210. assert(V->getType()->isPointerTy() && "Unexpected operand type!");
  2211. }
  2212. return V;
  2213. }
  2214. void
  2215. llvm::GetUnderlyingObjects(Value *V,
  2216. SmallVectorImpl<Value *> &Objects,
  2217. const DataLayout *TD,
  2218. unsigned MaxLookup) {
  2219. SmallPtrSet<Value *, 4> Visited;
  2220. SmallVector<Value *, 4> Worklist;
  2221. Worklist.push_back(V);
  2222. do {
  2223. Value *P = Worklist.pop_back_val();
  2224. P = GetUnderlyingObject(P, TD, MaxLookup);
  2225. if (!Visited.insert(P).second)
  2226. continue;
  2227. if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
  2228. Worklist.push_back(SI->getTrueValue());
  2229. Worklist.push_back(SI->getFalseValue());
  2230. continue;
  2231. }
  2232. if (PHINode *PN = dyn_cast<PHINode>(P)) {
  2233. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  2234. Worklist.push_back(PN->getIncomingValue(i));
  2235. continue;
  2236. }
  2237. Objects.push_back(P);
  2238. } while (!Worklist.empty());
  2239. }
  2240. /// Return true if the only users of this pointer are lifetime markers.
  2241. bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
  2242. for (const User *U : V->users()) {
  2243. const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
  2244. if (!II) return false;
  2245. if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
  2246. II->getIntrinsicID() != Intrinsic::lifetime_end)
  2247. return false;
  2248. }
  2249. return true;
  2250. }
  2251. bool llvm::isSafeToSpeculativelyExecute(const Value *V,
  2252. const DataLayout *TD) {
  2253. const Operator *Inst = dyn_cast<Operator>(V);
  2254. if (!Inst)
  2255. return false;
  2256. for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
  2257. if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
  2258. if (C->canTrap())
  2259. return false;
  2260. switch (Inst->getOpcode()) {
  2261. default:
  2262. return true;
  2263. case Instruction::UDiv:
  2264. case Instruction::URem: {
  2265. // x / y is undefined if y == 0.
  2266. const APInt *V;
  2267. if (match(Inst->getOperand(1), m_APInt(V)))
  2268. return *V != 0;
  2269. return false;
  2270. }
  2271. case Instruction::SDiv:
  2272. case Instruction::SRem: {
  2273. // x / y is undefined if y == 0 or x == INT_MIN and y == -1
  2274. const APInt *X, *Y;
  2275. if (match(Inst->getOperand(1), m_APInt(Y))) {
  2276. if (*Y != 0) {
  2277. if (*Y == -1) {
  2278. // The numerator can't be MinSignedValue if the denominator is -1.
  2279. if (match(Inst->getOperand(0), m_APInt(X)))
  2280. return !Y->isMinSignedValue();
  2281. // The numerator *might* be MinSignedValue.
  2282. return false;
  2283. }
  2284. // The denominator is not 0 or -1, it's safe to proceed.
  2285. return true;
  2286. }
  2287. }
  2288. return false;
  2289. }
  2290. case Instruction::Load: {
  2291. const LoadInst *LI = cast<LoadInst>(Inst);
  2292. if (!LI->isUnordered() ||
  2293. // Speculative load may create a race that did not exist in the source.
  2294. LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
  2295. return false;
  2296. return LI->getPointerOperand()->isDereferenceablePointer(TD);
  2297. }
  2298. case Instruction::Call: {
  2299. if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
  2300. switch (II->getIntrinsicID()) {
  2301. // These synthetic intrinsics have no side-effects and just mark
  2302. // information about their operands.
  2303. // FIXME: There are other no-op synthetic instructions that potentially
  2304. // should be considered at least *safe* to speculate...
  2305. case Intrinsic::dbg_declare:
  2306. case Intrinsic::dbg_value:
  2307. return true;
  2308. case Intrinsic::bswap:
  2309. case Intrinsic::ctlz:
  2310. case Intrinsic::ctpop:
  2311. case Intrinsic::cttz:
  2312. case Intrinsic::objectsize:
  2313. case Intrinsic::sadd_with_overflow:
  2314. case Intrinsic::smul_with_overflow:
  2315. case Intrinsic::ssub_with_overflow:
  2316. case Intrinsic::uadd_with_overflow:
  2317. case Intrinsic::umul_with_overflow:
  2318. case Intrinsic::usub_with_overflow:
  2319. return true;
  2320. // Sqrt should be OK, since the llvm sqrt intrinsic isn't defined to set
  2321. // errno like libm sqrt would.
  2322. case Intrinsic::sqrt:
  2323. case Intrinsic::fma:
  2324. case Intrinsic::fmuladd:
  2325. case Intrinsic::fabs:
  2326. case Intrinsic::minnum:
  2327. case Intrinsic::maxnum:
  2328. return true;
  2329. // TODO: some fp intrinsics are marked as having the same error handling
  2330. // as libm. They're safe to speculate when they won't error.
  2331. // TODO: are convert_{from,to}_fp16 safe?
  2332. // TODO: can we list target-specific intrinsics here?
  2333. default: break;
  2334. }
  2335. }
  2336. return false; // The called function could have undefined behavior or
  2337. // side-effects, even if marked readnone nounwind.
  2338. }
  2339. case Instruction::VAArg:
  2340. case Instruction::Alloca:
  2341. case Instruction::Invoke:
  2342. case Instruction::PHI:
  2343. case Instruction::Store:
  2344. case Instruction::Ret:
  2345. case Instruction::Br:
  2346. case Instruction::IndirectBr:
  2347. case Instruction::Switch:
  2348. case Instruction::Unreachable:
  2349. case Instruction::Fence:
  2350. case Instruction::LandingPad:
  2351. case Instruction::AtomicRMW:
  2352. case Instruction::AtomicCmpXchg:
  2353. case Instruction::Resume:
  2354. return false; // Misc instructions which have effects
  2355. }
  2356. }
  2357. /// Return true if we know that the specified value is never null.
  2358. bool llvm::isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI) {
  2359. // Alloca never returns null, malloc might.
  2360. if (isa<AllocaInst>(V)) return true;
  2361. // A byval, inalloca, or nonnull argument is never null.
  2362. if (const Argument *A = dyn_cast<Argument>(V))
  2363. return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
  2364. // Global values are not null unless extern weak.
  2365. if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
  2366. return !GV->hasExternalWeakLinkage();
  2367. // A Load tagged w/nonnull metadata is never null.
  2368. if (const LoadInst *LI = dyn_cast<LoadInst>(V))
  2369. return LI->getMetadata(LLVMContext::MD_nonnull);
  2370. if (ImmutableCallSite CS = V)
  2371. if (CS.isReturnNonNull())
  2372. return true;
  2373. // operator new never returns null.
  2374. if (isOperatorNewLikeFn(V, TLI, /*LookThroughBitCast=*/true))
  2375. return true;
  2376. return false;
  2377. }
  2378. OverflowResult llvm::computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
  2379. const DataLayout *DL,
  2380. AssumptionCache *AC,
  2381. const Instruction *CxtI,
  2382. const DominatorTree *DT) {
  2383. // Multiplying n * m significant bits yields a result of n + m significant
  2384. // bits. If the total number of significant bits does not exceed the
  2385. // result bit width (minus 1), there is no overflow.
  2386. // This means if we have enough leading zero bits in the operands
  2387. // we can guarantee that the result does not overflow.
  2388. // Ref: "Hacker's Delight" by Henry Warren
  2389. unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
  2390. APInt LHSKnownZero(BitWidth, 0);
  2391. APInt LHSKnownOne(BitWidth, 0);
  2392. APInt RHSKnownZero(BitWidth, 0);
  2393. APInt RHSKnownOne(BitWidth, 0);
  2394. computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
  2395. DT);
  2396. computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
  2397. DT);
  2398. // Note that underestimating the number of zero bits gives a more
  2399. // conservative answer.
  2400. unsigned ZeroBits = LHSKnownZero.countLeadingOnes() +
  2401. RHSKnownZero.countLeadingOnes();
  2402. // First handle the easy case: if we have enough zero bits there's
  2403. // definitely no overflow.
  2404. if (ZeroBits >= BitWidth)
  2405. return OverflowResult::NeverOverflows;
  2406. // Get the largest possible values for each operand.
  2407. APInt LHSMax = ~LHSKnownZero;
  2408. APInt RHSMax = ~RHSKnownZero;
  2409. // We know the multiply operation doesn't overflow if the maximum values for
  2410. // each operand will not overflow after we multiply them together.
  2411. bool MaxOverflow;
  2412. LHSMax.umul_ov(RHSMax, MaxOverflow);
  2413. if (!MaxOverflow)
  2414. return OverflowResult::NeverOverflows;
  2415. // We know it always overflows if multiplying the smallest possible values for
  2416. // the operands also results in overflow.
  2417. bool MinOverflow;
  2418. LHSKnownOne.umul_ov(RHSKnownOne, MinOverflow);
  2419. if (MinOverflow)
  2420. return OverflowResult::AlwaysOverflows;
  2421. return OverflowResult::MayOverflow;
  2422. }
  2423. OverflowResult llvm::computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
  2424. const DataLayout *DL,
  2425. AssumptionCache *AC,
  2426. const Instruction *CxtI,
  2427. const DominatorTree *DT) {
  2428. bool LHSKnownNonNegative, LHSKnownNegative;
  2429. ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0,
  2430. AC, CxtI, DT);
  2431. if (LHSKnownNonNegative || LHSKnownNegative) {
  2432. bool RHSKnownNonNegative, RHSKnownNegative;
  2433. ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0,
  2434. AC, CxtI, DT);
  2435. if (LHSKnownNegative && RHSKnownNegative) {
  2436. // The sign bit is set in both cases: this MUST overflow.
  2437. // Create a simple add instruction, and insert it into the struct.
  2438. return OverflowResult::AlwaysOverflows;
  2439. }
  2440. if (LHSKnownNonNegative && RHSKnownNonNegative) {
  2441. // The sign bit is clear in both cases: this CANNOT overflow.
  2442. // Create a simple add instruction, and insert it into the struct.
  2443. return OverflowResult::NeverOverflows;
  2444. }
  2445. }
  2446. return OverflowResult::MayOverflow;
  2447. }