ValueTracking.cpp 135 KB

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