InstructionSimplify.cpp 158 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170
  1. //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements routines for folding instructions into simpler forms
  11. // that do not require creating new instructions. This does constant folding
  12. // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
  13. // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
  14. // ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been
  15. // simplified: This is usually true and assuming it simplifies the logic (if
  16. // they have not been simplified then results are correct but maybe suboptimal).
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #include "llvm/Analysis/InstructionSimplify.h"
  20. #include "llvm/ADT/SetVector.h"
  21. #include "llvm/ADT/Statistic.h"
  22. #include "llvm/Analysis/AliasAnalysis.h"
  23. #include "llvm/Analysis/ConstantFolding.h"
  24. #include "llvm/Analysis/MemoryBuiltins.h"
  25. #include "llvm/Analysis/ValueTracking.h"
  26. #include "llvm/Analysis/VectorUtils.h"
  27. #include "llvm/IR/ConstantRange.h"
  28. #include "llvm/IR/DataLayout.h"
  29. #include "llvm/IR/Dominators.h"
  30. #include "llvm/IR/GetElementPtrTypeIterator.h"
  31. #include "llvm/IR/GlobalAlias.h"
  32. #include "llvm/IR/Operator.h"
  33. #include "llvm/IR/PatternMatch.h"
  34. #include "llvm/IR/ValueHandle.h"
  35. #include <algorithm>
  36. using namespace llvm;
  37. using namespace llvm::PatternMatch;
  38. #define DEBUG_TYPE "instsimplify"
  39. enum { RecursionLimit = 3 };
  40. STATISTIC(NumExpand, "Number of expansions");
  41. STATISTIC(NumReassoc, "Number of reassociations");
  42. namespace {
  43. struct Query {
  44. const DataLayout &DL;
  45. const TargetLibraryInfo *TLI;
  46. const DominatorTree *DT;
  47. AssumptionCache *AC;
  48. const Instruction *CxtI;
  49. Query(const DataLayout &DL, const TargetLibraryInfo *tli,
  50. const DominatorTree *dt, AssumptionCache *ac = nullptr,
  51. const Instruction *cxti = nullptr)
  52. : DL(DL), TLI(tli), DT(dt), AC(ac), CxtI(cxti) {}
  53. };
  54. } // end anonymous namespace
  55. static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
  56. static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
  57. unsigned);
  58. static Value *SimplifyFPBinOp(unsigned, Value *, Value *, const FastMathFlags &,
  59. const Query &, unsigned);
  60. static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
  61. unsigned);
  62. static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
  63. static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
  64. static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
  65. /// getFalse - For a boolean type, or a vector of boolean type, return false, or
  66. /// a vector with every element false, as appropriate for the type.
  67. static Constant *getFalse(Type *Ty) {
  68. assert(Ty->getScalarType()->isIntegerTy(1) &&
  69. "Expected i1 type or a vector of i1!");
  70. return Constant::getNullValue(Ty);
  71. }
  72. /// getTrue - For a boolean type, or a vector of boolean type, return true, or
  73. /// a vector with every element true, as appropriate for the type.
  74. static Constant *getTrue(Type *Ty) {
  75. assert(Ty->getScalarType()->isIntegerTy(1) &&
  76. "Expected i1 type or a vector of i1!");
  77. return Constant::getAllOnesValue(Ty);
  78. }
  79. /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
  80. static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
  81. Value *RHS) {
  82. CmpInst *Cmp = dyn_cast<CmpInst>(V);
  83. if (!Cmp)
  84. return false;
  85. CmpInst::Predicate CPred = Cmp->getPredicate();
  86. Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
  87. if (CPred == Pred && CLHS == LHS && CRHS == RHS)
  88. return true;
  89. return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
  90. CRHS == LHS;
  91. }
  92. /// ValueDominatesPHI - Does the given value dominate the specified phi node?
  93. static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
  94. Instruction *I = dyn_cast<Instruction>(V);
  95. if (!I)
  96. // Arguments and constants dominate all instructions.
  97. return true;
  98. // If we are processing instructions (and/or basic blocks) that have not been
  99. // fully added to a function, the parent nodes may still be null. Simply
  100. // return the conservative answer in these cases.
  101. if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
  102. return false;
  103. // If we have a DominatorTree then do a precise test.
  104. if (DT) {
  105. if (!DT->isReachableFromEntry(P->getParent()))
  106. return true;
  107. if (!DT->isReachableFromEntry(I->getParent()))
  108. return false;
  109. return DT->dominates(I, P);
  110. }
  111. // Otherwise, if the instruction is in the entry block, and is not an invoke,
  112. // then it obviously dominates all phi nodes.
  113. if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
  114. !isa<InvokeInst>(I))
  115. return true;
  116. return false;
  117. }
  118. /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
  119. /// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
  120. /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
  121. /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
  122. /// Returns the simplified value, or null if no simplification was performed.
  123. static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
  124. unsigned OpcToExpand, const Query &Q,
  125. unsigned MaxRecurse) {
  126. Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
  127. // Recursion is always used, so bail out at once if we already hit the limit.
  128. if (!MaxRecurse--)
  129. return nullptr;
  130. // Check whether the expression has the form "(A op' B) op C".
  131. if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
  132. if (Op0->getOpcode() == OpcodeToExpand) {
  133. // It does! Try turning it into "(A op C) op' (B op C)".
  134. Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
  135. // Do "A op C" and "B op C" both simplify?
  136. if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
  137. if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
  138. // They do! Return "L op' R" if it simplifies or is already available.
  139. // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
  140. if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
  141. && L == B && R == A)) {
  142. ++NumExpand;
  143. return LHS;
  144. }
  145. // Otherwise return "L op' R" if it simplifies.
  146. if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
  147. ++NumExpand;
  148. return V;
  149. }
  150. }
  151. }
  152. // Check whether the expression has the form "A op (B op' C)".
  153. if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
  154. if (Op1->getOpcode() == OpcodeToExpand) {
  155. // It does! Try turning it into "(A op B) op' (A op C)".
  156. Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
  157. // Do "A op B" and "A op C" both simplify?
  158. if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
  159. if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
  160. // They do! Return "L op' R" if it simplifies or is already available.
  161. // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
  162. if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
  163. && L == C && R == B)) {
  164. ++NumExpand;
  165. return RHS;
  166. }
  167. // Otherwise return "L op' R" if it simplifies.
  168. if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
  169. ++NumExpand;
  170. return V;
  171. }
  172. }
  173. }
  174. return nullptr;
  175. }
  176. /// SimplifyAssociativeBinOp - Generic simplifications for associative binary
  177. /// operations. Returns the simpler value, or null if none was found.
  178. static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
  179. const Query &Q, unsigned MaxRecurse) {
  180. Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
  181. assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
  182. // Recursion is always used, so bail out at once if we already hit the limit.
  183. if (!MaxRecurse--)
  184. return nullptr;
  185. BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
  186. BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
  187. // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
  188. if (Op0 && Op0->getOpcode() == Opcode) {
  189. Value *A = Op0->getOperand(0);
  190. Value *B = Op0->getOperand(1);
  191. Value *C = RHS;
  192. // Does "B op C" simplify?
  193. if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
  194. // It does! Return "A op V" if it simplifies or is already available.
  195. // If V equals B then "A op V" is just the LHS.
  196. if (V == B) return LHS;
  197. // Otherwise return "A op V" if it simplifies.
  198. if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
  199. ++NumReassoc;
  200. return W;
  201. }
  202. }
  203. }
  204. // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
  205. if (Op1 && Op1->getOpcode() == Opcode) {
  206. Value *A = LHS;
  207. Value *B = Op1->getOperand(0);
  208. Value *C = Op1->getOperand(1);
  209. // Does "A op B" simplify?
  210. if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
  211. // It does! Return "V op C" if it simplifies or is already available.
  212. // If V equals B then "V op C" is just the RHS.
  213. if (V == B) return RHS;
  214. // Otherwise return "V op C" if it simplifies.
  215. if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
  216. ++NumReassoc;
  217. return W;
  218. }
  219. }
  220. }
  221. // The remaining transforms require commutativity as well as associativity.
  222. if (!Instruction::isCommutative(Opcode))
  223. return nullptr;
  224. // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
  225. if (Op0 && Op0->getOpcode() == Opcode) {
  226. Value *A = Op0->getOperand(0);
  227. Value *B = Op0->getOperand(1);
  228. Value *C = RHS;
  229. // Does "C op A" simplify?
  230. if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
  231. // It does! Return "V op B" if it simplifies or is already available.
  232. // If V equals A then "V op B" is just the LHS.
  233. if (V == A) return LHS;
  234. // Otherwise return "V op B" if it simplifies.
  235. if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
  236. ++NumReassoc;
  237. return W;
  238. }
  239. }
  240. }
  241. // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
  242. if (Op1 && Op1->getOpcode() == Opcode) {
  243. Value *A = LHS;
  244. Value *B = Op1->getOperand(0);
  245. Value *C = Op1->getOperand(1);
  246. // Does "C op A" simplify?
  247. if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
  248. // It does! Return "B op V" if it simplifies or is already available.
  249. // If V equals C then "B op V" is just the RHS.
  250. if (V == C) return RHS;
  251. // Otherwise return "B op V" if it simplifies.
  252. if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
  253. ++NumReassoc;
  254. return W;
  255. }
  256. }
  257. }
  258. return nullptr;
  259. }
  260. /// ThreadBinOpOverSelect - In the case of a binary operation with a select
  261. /// instruction as an operand, try to simplify the binop by seeing whether
  262. /// evaluating it on both branches of the select results in the same value.
  263. /// Returns the common value if so, otherwise returns null.
  264. static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
  265. const Query &Q, unsigned MaxRecurse) {
  266. // Recursion is always used, so bail out at once if we already hit the limit.
  267. if (!MaxRecurse--)
  268. return nullptr;
  269. SelectInst *SI;
  270. if (isa<SelectInst>(LHS)) {
  271. SI = cast<SelectInst>(LHS);
  272. } else {
  273. assert(isa<SelectInst>(RHS) && "No select instruction operand!");
  274. SI = cast<SelectInst>(RHS);
  275. }
  276. // Evaluate the BinOp on the true and false branches of the select.
  277. Value *TV;
  278. Value *FV;
  279. if (SI == LHS) {
  280. TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
  281. FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
  282. } else {
  283. TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
  284. FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
  285. }
  286. // If they simplified to the same value, then return the common value.
  287. // If they both failed to simplify then return null.
  288. if (TV == FV)
  289. return TV;
  290. // If one branch simplified to undef, return the other one.
  291. if (TV && isa<UndefValue>(TV))
  292. return FV;
  293. if (FV && isa<UndefValue>(FV))
  294. return TV;
  295. // If applying the operation did not change the true and false select values,
  296. // then the result of the binop is the select itself.
  297. if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
  298. return SI;
  299. // If one branch simplified and the other did not, and the simplified
  300. // value is equal to the unsimplified one, return the simplified value.
  301. // For example, select (cond, X, X & Z) & Z -> X & Z.
  302. if ((FV && !TV) || (TV && !FV)) {
  303. // Check that the simplified value has the form "X op Y" where "op" is the
  304. // same as the original operation.
  305. Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
  306. if (Simplified && Simplified->getOpcode() == Opcode) {
  307. // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
  308. // We already know that "op" is the same as for the simplified value. See
  309. // if the operands match too. If so, return the simplified value.
  310. Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
  311. Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
  312. Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
  313. if (Simplified->getOperand(0) == UnsimplifiedLHS &&
  314. Simplified->getOperand(1) == UnsimplifiedRHS)
  315. return Simplified;
  316. if (Simplified->isCommutative() &&
  317. Simplified->getOperand(1) == UnsimplifiedLHS &&
  318. Simplified->getOperand(0) == UnsimplifiedRHS)
  319. return Simplified;
  320. }
  321. }
  322. return nullptr;
  323. }
  324. /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
  325. /// try to simplify the comparison by seeing whether both branches of the select
  326. /// result in the same value. Returns the common value if so, otherwise returns
  327. /// null.
  328. static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
  329. Value *RHS, const Query &Q,
  330. unsigned MaxRecurse) {
  331. // Recursion is always used, so bail out at once if we already hit the limit.
  332. if (!MaxRecurse--)
  333. return nullptr;
  334. // Make sure the select is on the LHS.
  335. if (!isa<SelectInst>(LHS)) {
  336. std::swap(LHS, RHS);
  337. Pred = CmpInst::getSwappedPredicate(Pred);
  338. }
  339. assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
  340. SelectInst *SI = cast<SelectInst>(LHS);
  341. Value *Cond = SI->getCondition();
  342. Value *TV = SI->getTrueValue();
  343. Value *FV = SI->getFalseValue();
  344. // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
  345. // Does "cmp TV, RHS" simplify?
  346. Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
  347. if (TCmp == Cond) {
  348. // It not only simplified, it simplified to the select condition. Replace
  349. // it with 'true'.
  350. TCmp = getTrue(Cond->getType());
  351. } else if (!TCmp) {
  352. // It didn't simplify. However if "cmp TV, RHS" is equal to the select
  353. // condition then we can replace it with 'true'. Otherwise give up.
  354. if (!isSameCompare(Cond, Pred, TV, RHS))
  355. return nullptr;
  356. TCmp = getTrue(Cond->getType());
  357. }
  358. // Does "cmp FV, RHS" simplify?
  359. Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
  360. if (FCmp == Cond) {
  361. // It not only simplified, it simplified to the select condition. Replace
  362. // it with 'false'.
  363. FCmp = getFalse(Cond->getType());
  364. } else if (!FCmp) {
  365. // It didn't simplify. However if "cmp FV, RHS" is equal to the select
  366. // condition then we can replace it with 'false'. Otherwise give up.
  367. if (!isSameCompare(Cond, Pred, FV, RHS))
  368. return nullptr;
  369. FCmp = getFalse(Cond->getType());
  370. }
  371. // If both sides simplified to the same value, then use it as the result of
  372. // the original comparison.
  373. if (TCmp == FCmp)
  374. return TCmp;
  375. // The remaining cases only make sense if the select condition has the same
  376. // type as the result of the comparison, so bail out if this is not so.
  377. if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
  378. return nullptr;
  379. // If the false value simplified to false, then the result of the compare
  380. // is equal to "Cond && TCmp". This also catches the case when the false
  381. // value simplified to false and the true value to true, returning "Cond".
  382. if (match(FCmp, m_Zero()))
  383. if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
  384. return V;
  385. // If the true value simplified to true, then the result of the compare
  386. // is equal to "Cond || FCmp".
  387. if (match(TCmp, m_One()))
  388. if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
  389. return V;
  390. // Finally, if the false value simplified to true and the true value to
  391. // false, then the result of the compare is equal to "!Cond".
  392. if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
  393. if (Value *V =
  394. SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
  395. Q, MaxRecurse))
  396. return V;
  397. return nullptr;
  398. }
  399. /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
  400. /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
  401. /// it on the incoming phi values yields the same result for every value. If so
  402. /// returns the common value, otherwise returns null.
  403. static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
  404. const Query &Q, unsigned MaxRecurse) {
  405. // Recursion is always used, so bail out at once if we already hit the limit.
  406. if (!MaxRecurse--)
  407. return nullptr;
  408. PHINode *PI;
  409. if (isa<PHINode>(LHS)) {
  410. PI = cast<PHINode>(LHS);
  411. // Bail out if RHS and the phi may be mutually interdependent due to a loop.
  412. if (!ValueDominatesPHI(RHS, PI, Q.DT))
  413. return nullptr;
  414. } else {
  415. assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
  416. PI = cast<PHINode>(RHS);
  417. // Bail out if LHS and the phi may be mutually interdependent due to a loop.
  418. if (!ValueDominatesPHI(LHS, PI, Q.DT))
  419. return nullptr;
  420. }
  421. // Evaluate the BinOp on the incoming phi values.
  422. Value *CommonValue = nullptr;
  423. for (Value *Incoming : PI->incoming_values()) {
  424. // If the incoming value is the phi node itself, it can safely be skipped.
  425. if (Incoming == PI) continue;
  426. Value *V = PI == LHS ?
  427. SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
  428. SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
  429. // If the operation failed to simplify, or simplified to a different value
  430. // to previously, then give up.
  431. if (!V || (CommonValue && V != CommonValue))
  432. return nullptr;
  433. CommonValue = V;
  434. }
  435. return CommonValue;
  436. }
  437. /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
  438. /// try to simplify the comparison by seeing whether comparing with all of the
  439. /// incoming phi values yields the same result every time. If so returns the
  440. /// common result, otherwise returns null.
  441. static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
  442. const Query &Q, unsigned MaxRecurse) {
  443. // Recursion is always used, so bail out at once if we already hit the limit.
  444. if (!MaxRecurse--)
  445. return nullptr;
  446. // Make sure the phi is on the LHS.
  447. if (!isa<PHINode>(LHS)) {
  448. std::swap(LHS, RHS);
  449. Pred = CmpInst::getSwappedPredicate(Pred);
  450. }
  451. assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
  452. PHINode *PI = cast<PHINode>(LHS);
  453. // Bail out if RHS and the phi may be mutually interdependent due to a loop.
  454. if (!ValueDominatesPHI(RHS, PI, Q.DT))
  455. return nullptr;
  456. // Evaluate the BinOp on the incoming phi values.
  457. Value *CommonValue = nullptr;
  458. for (Value *Incoming : PI->incoming_values()) {
  459. // If the incoming value is the phi node itself, it can safely be skipped.
  460. if (Incoming == PI) continue;
  461. Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
  462. // If the operation failed to simplify, or simplified to a different value
  463. // to previously, then give up.
  464. if (!V || (CommonValue && V != CommonValue))
  465. return nullptr;
  466. CommonValue = V;
  467. }
  468. return CommonValue;
  469. }
  470. /// SimplifyAddInst - Given operands for an Add, see if we can
  471. /// fold the result. If not, this returns null.
  472. static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
  473. const Query &Q, unsigned MaxRecurse) {
  474. if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
  475. if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
  476. Constant *Ops[] = { CLHS, CRHS };
  477. return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(), Ops,
  478. Q.DL, Q.TLI);
  479. }
  480. // Canonicalize the constant to the RHS.
  481. std::swap(Op0, Op1);
  482. }
  483. // X + undef -> undef
  484. if (match(Op1, m_Undef()))
  485. return Op1;
  486. // X + 0 -> X
  487. if (match(Op1, m_Zero()))
  488. return Op0;
  489. // X + (Y - X) -> Y
  490. // (Y - X) + X -> Y
  491. // Eg: X + -X -> 0
  492. Value *Y = nullptr;
  493. if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
  494. match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
  495. return Y;
  496. // X + ~X -> -1 since ~X = -X-1
  497. if (match(Op0, m_Not(m_Specific(Op1))) ||
  498. match(Op1, m_Not(m_Specific(Op0))))
  499. return Constant::getAllOnesValue(Op0->getType());
  500. /// i1 add -> xor.
  501. if (MaxRecurse && Op0->getType()->isIntegerTy(1))
  502. if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
  503. return V;
  504. // Try some generic simplifications for associative operations.
  505. if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
  506. MaxRecurse))
  507. return V;
  508. // Threading Add over selects and phi nodes is pointless, so don't bother.
  509. // Threading over the select in "A + select(cond, B, C)" means evaluating
  510. // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
  511. // only if B and C are equal. If B and C are equal then (since we assume
  512. // that operands have already been simplified) "select(cond, B, C)" should
  513. // have been simplified to the common value of B and C already. Analysing
  514. // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
  515. // for threading over phi nodes.
  516. return nullptr;
  517. }
  518. Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
  519. const DataLayout &DL, const TargetLibraryInfo *TLI,
  520. const DominatorTree *DT, AssumptionCache *AC,
  521. const Instruction *CxtI) {
  522. return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
  523. RecursionLimit);
  524. }
  525. /// \brief Compute the base pointer and cumulative constant offsets for V.
  526. ///
  527. /// This strips all constant offsets off of V, leaving it the base pointer, and
  528. /// accumulates the total constant offset applied in the returned constant. It
  529. /// returns 0 if V is not a pointer, and returns the constant '0' if there are
  530. /// no constant offsets applied.
  531. ///
  532. /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
  533. /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
  534. /// folding.
  535. static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
  536. bool AllowNonInbounds = false) {
  537. assert(V->getType()->getScalarType()->isPointerTy());
  538. Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
  539. APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
  540. // Even though we don't look through PHI nodes, we could be called on an
  541. // instruction in an unreachable block, which may be on a cycle.
  542. SmallPtrSet<Value *, 4> Visited;
  543. Visited.insert(V);
  544. do {
  545. if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
  546. if ((!AllowNonInbounds && !GEP->isInBounds()) ||
  547. !GEP->accumulateConstantOffset(DL, Offset))
  548. break;
  549. V = GEP->getPointerOperand();
  550. } else if (Operator::getOpcode(V) == Instruction::BitCast) {
  551. V = cast<Operator>(V)->getOperand(0);
  552. } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
  553. if (GA->mayBeOverridden())
  554. break;
  555. V = GA->getAliasee();
  556. } else {
  557. break;
  558. }
  559. assert(V->getType()->getScalarType()->isPointerTy() &&
  560. "Unexpected operand type!");
  561. } while (Visited.insert(V).second);
  562. Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
  563. if (V->getType()->isVectorTy())
  564. return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
  565. OffsetIntPtr);
  566. return OffsetIntPtr;
  567. }
  568. /// \brief Compute the constant difference between two pointer values.
  569. /// If the difference is not a constant, returns zero.
  570. static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
  571. Value *RHS) {
  572. Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
  573. Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
  574. // If LHS and RHS are not related via constant offsets to the same base
  575. // value, there is nothing we can do here.
  576. if (LHS != RHS)
  577. return nullptr;
  578. // Otherwise, the difference of LHS - RHS can be computed as:
  579. // LHS - RHS
  580. // = (LHSOffset + Base) - (RHSOffset + Base)
  581. // = LHSOffset - RHSOffset
  582. return ConstantExpr::getSub(LHSOffset, RHSOffset);
  583. }
  584. /// SimplifySubInst - Given operands for a Sub, see if we can
  585. /// fold the result. If not, this returns null.
  586. static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
  587. const Query &Q, unsigned MaxRecurse) {
  588. if (Constant *CLHS = dyn_cast<Constant>(Op0))
  589. if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
  590. Constant *Ops[] = { CLHS, CRHS };
  591. return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
  592. Ops, Q.DL, Q.TLI);
  593. }
  594. // X - undef -> undef
  595. // undef - X -> undef
  596. if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
  597. return UndefValue::get(Op0->getType());
  598. // X - 0 -> X
  599. if (match(Op1, m_Zero()))
  600. return Op0;
  601. // X - X -> 0
  602. if (Op0 == Op1)
  603. return Constant::getNullValue(Op0->getType());
  604. // 0 - X -> 0 if the sub is NUW.
  605. if (isNUW && match(Op0, m_Zero()))
  606. return Op0;
  607. // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
  608. // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
  609. Value *X = nullptr, *Y = nullptr, *Z = Op1;
  610. if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
  611. // See if "V === Y - Z" simplifies.
  612. if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
  613. // It does! Now see if "X + V" simplifies.
  614. if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
  615. // It does, we successfully reassociated!
  616. ++NumReassoc;
  617. return W;
  618. }
  619. // See if "V === X - Z" simplifies.
  620. if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
  621. // It does! Now see if "Y + V" simplifies.
  622. if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
  623. // It does, we successfully reassociated!
  624. ++NumReassoc;
  625. return W;
  626. }
  627. }
  628. // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
  629. // For example, X - (X + 1) -> -1
  630. X = Op0;
  631. if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
  632. // See if "V === X - Y" simplifies.
  633. if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
  634. // It does! Now see if "V - Z" simplifies.
  635. if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
  636. // It does, we successfully reassociated!
  637. ++NumReassoc;
  638. return W;
  639. }
  640. // See if "V === X - Z" simplifies.
  641. if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
  642. // It does! Now see if "V - Y" simplifies.
  643. if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
  644. // It does, we successfully reassociated!
  645. ++NumReassoc;
  646. return W;
  647. }
  648. }
  649. // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
  650. // For example, X - (X - Y) -> Y.
  651. Z = Op0;
  652. if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
  653. // See if "V === Z - X" simplifies.
  654. if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
  655. // It does! Now see if "V + Y" simplifies.
  656. if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
  657. // It does, we successfully reassociated!
  658. ++NumReassoc;
  659. return W;
  660. }
  661. // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
  662. if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
  663. match(Op1, m_Trunc(m_Value(Y))))
  664. if (X->getType() == Y->getType())
  665. // See if "V === X - Y" simplifies.
  666. if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
  667. // It does! Now see if "trunc V" simplifies.
  668. if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
  669. // It does, return the simplified "trunc V".
  670. return W;
  671. // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
  672. if (match(Op0, m_PtrToInt(m_Value(X))) &&
  673. match(Op1, m_PtrToInt(m_Value(Y))))
  674. if (Constant *Result = computePointerDifference(Q.DL, X, Y))
  675. return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
  676. // i1 sub -> xor.
  677. if (MaxRecurse && Op0->getType()->isIntegerTy(1))
  678. if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
  679. return V;
  680. // Threading Sub over selects and phi nodes is pointless, so don't bother.
  681. // Threading over the select in "A - select(cond, B, C)" means evaluating
  682. // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
  683. // only if B and C are equal. If B and C are equal then (since we assume
  684. // that operands have already been simplified) "select(cond, B, C)" should
  685. // have been simplified to the common value of B and C already. Analysing
  686. // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
  687. // for threading over phi nodes.
  688. return nullptr;
  689. }
  690. Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
  691. const DataLayout &DL, const TargetLibraryInfo *TLI,
  692. const DominatorTree *DT, AssumptionCache *AC,
  693. const Instruction *CxtI) {
  694. return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
  695. RecursionLimit);
  696. }
  697. /// Given operands for an FAdd, see if we can fold the result. If not, this
  698. /// returns null.
  699. static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
  700. const Query &Q, unsigned MaxRecurse) {
  701. if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
  702. if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
  703. Constant *Ops[] = { CLHS, CRHS };
  704. return ConstantFoldInstOperands(Instruction::FAdd, CLHS->getType(),
  705. Ops, Q.DL, Q.TLI);
  706. }
  707. // HLSL Change Begins.
  708. if (ConstantFP *FP = dyn_cast<ConstantFP>(Op0))
  709. if (FP->getValueAPF().isNaN())
  710. return Op0;
  711. // HLSL Change Ends.
  712. // Canonicalize the constant to the RHS.
  713. std::swap(Op0, Op1);
  714. }
  715. // HLSL Change Begins.
  716. if (ConstantFP *FP = dyn_cast<ConstantFP>(Op0))
  717. if (FP->getValueAPF().isNaN())
  718. return Op0;
  719. // HLSL Change Ends.
  720. // fadd X, -0 ==> X
  721. if (match(Op1, m_NegZero()))
  722. return Op0;
  723. // fadd X, 0 ==> X, when we know X is not -0
  724. if (match(Op1, m_Zero()) &&
  725. (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
  726. return Op0;
  727. // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
  728. // where nnan and ninf have to occur at least once somewhere in this
  729. // expression
  730. Value *SubOp = nullptr;
  731. if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
  732. SubOp = Op1;
  733. else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
  734. SubOp = Op0;
  735. if (SubOp) {
  736. Instruction *FSub = cast<Instruction>(SubOp);
  737. if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
  738. (FMF.noInfs() || FSub->hasNoInfs()))
  739. return Constant::getNullValue(Op0->getType());
  740. }
  741. return nullptr;
  742. }
  743. /// Given operands for an FSub, see if we can fold the result. If not, this
  744. /// returns null.
  745. static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
  746. const Query &Q, unsigned MaxRecurse) {
  747. if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
  748. if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
  749. Constant *Ops[] = { CLHS, CRHS };
  750. return ConstantFoldInstOperands(Instruction::FSub, CLHS->getType(),
  751. Ops, Q.DL, Q.TLI);
  752. }
  753. // HLSL Change Begins.
  754. if (ConstantFP *FP = dyn_cast<ConstantFP>(Op0))
  755. if (FP->getValueAPF().isNaN())
  756. return Op0;
  757. // HLSL Change Ends.
  758. }
  759. // HLSL Change Begins.
  760. if (ConstantFP *FP = dyn_cast<ConstantFP>(Op1))
  761. if (FP->getValueAPF().isNaN())
  762. return Op1;
  763. // HLSL Change Ends.
  764. // fsub X, 0 ==> X
  765. if (match(Op1, m_Zero()))
  766. return Op0;
  767. // fsub X, -0 ==> X, when we know X is not -0
  768. if (match(Op1, m_NegZero()) &&
  769. (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
  770. return Op0;
  771. // fsub 0, (fsub -0.0, X) ==> X
  772. Value *X;
  773. if (match(Op0, m_AnyZero())) {
  774. if (match(Op1, m_FSub(m_NegZero(), m_Value(X))))
  775. return X;
  776. if (FMF.noSignedZeros() && match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
  777. return X;
  778. }
  779. // fsub nnan x, x ==> 0.0
  780. if (FMF.noNaNs() && Op0 == Op1)
  781. return Constant::getNullValue(Op0->getType());
  782. return nullptr;
  783. }
  784. /// Given the operands for an FMul, see if we can fold the result
  785. static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
  786. FastMathFlags FMF,
  787. const Query &Q,
  788. unsigned MaxRecurse) {
  789. if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
  790. if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
  791. Constant *Ops[] = {CLHS, CRHS};
  792. return ConstantFoldInstOperands(Instruction::FMul, CLHS->getType(), Ops,
  793. Q.DL, Q.TLI);
  794. }
  795. // HLSL Change Begins.
  796. if (ConstantFP *FP = dyn_cast<ConstantFP>(Op0))
  797. if (FP->getValueAPF().isNaN())
  798. return Op0;
  799. // HLSL Change Ends.
  800. // Canonicalize the constant to the RHS.
  801. std::swap(Op0, Op1);
  802. }
  803. // HLSL Change Begins.
  804. if (ConstantFP *FP = dyn_cast<ConstantFP>(Op0))
  805. if (FP->getValueAPF().isNaN())
  806. return Op0;
  807. // HLSL Change Ends.
  808. // fmul X, 1.0 ==> X
  809. if (match(Op1, m_FPOne()))
  810. return Op0;
  811. // fmul nnan nsz X, 0 ==> 0
  812. if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
  813. return Op1;
  814. return nullptr;
  815. }
  816. /// SimplifyMulInst - Given operands for a Mul, see if we can
  817. /// fold the result. If not, this returns null.
  818. static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
  819. unsigned MaxRecurse) {
  820. if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
  821. if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
  822. Constant *Ops[] = { CLHS, CRHS };
  823. return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
  824. Ops, Q.DL, Q.TLI);
  825. }
  826. // Canonicalize the constant to the RHS.
  827. std::swap(Op0, Op1);
  828. }
  829. // X * undef -> 0
  830. if (match(Op1, m_Undef()))
  831. return Constant::getNullValue(Op0->getType());
  832. // X * 0 -> 0
  833. if (match(Op1, m_Zero()))
  834. return Op1;
  835. // X * 1 -> X
  836. if (match(Op1, m_One()))
  837. return Op0;
  838. // (X / Y) * Y -> X if the division is exact.
  839. Value *X = nullptr;
  840. if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
  841. match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
  842. return X;
  843. // i1 mul -> and.
  844. if (MaxRecurse && Op0->getType()->isIntegerTy(1))
  845. if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
  846. return V;
  847. // Try some generic simplifications for associative operations.
  848. if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
  849. MaxRecurse))
  850. return V;
  851. // Mul distributes over Add. Try some generic simplifications based on this.
  852. if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
  853. Q, MaxRecurse))
  854. return V;
  855. // If the operation is with the result of a select instruction, check whether
  856. // operating on either branch of the select always yields the same value.
  857. if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
  858. if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
  859. MaxRecurse))
  860. return V;
  861. // If the operation is with the result of a phi instruction, check whether
  862. // operating on all incoming values of the phi always yields the same value.
  863. if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
  864. if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
  865. MaxRecurse))
  866. return V;
  867. return nullptr;
  868. }
  869. Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
  870. const DataLayout &DL,
  871. const TargetLibraryInfo *TLI,
  872. const DominatorTree *DT, AssumptionCache *AC,
  873. const Instruction *CxtI) {
  874. return ::SimplifyFAddInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
  875. RecursionLimit);
  876. }
  877. Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
  878. const DataLayout &DL,
  879. const TargetLibraryInfo *TLI,
  880. const DominatorTree *DT, AssumptionCache *AC,
  881. const Instruction *CxtI) {
  882. return ::SimplifyFSubInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
  883. RecursionLimit);
  884. }
  885. Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
  886. const DataLayout &DL,
  887. const TargetLibraryInfo *TLI,
  888. const DominatorTree *DT, AssumptionCache *AC,
  889. const Instruction *CxtI) {
  890. return ::SimplifyFMulInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
  891. RecursionLimit);
  892. }
  893. Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout &DL,
  894. const TargetLibraryInfo *TLI,
  895. const DominatorTree *DT, AssumptionCache *AC,
  896. const Instruction *CxtI) {
  897. return ::SimplifyMulInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
  898. RecursionLimit);
  899. }
  900. /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
  901. /// fold the result. If not, this returns null.
  902. static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
  903. const Query &Q, unsigned MaxRecurse) {
  904. if (Constant *C0 = dyn_cast<Constant>(Op0)) {
  905. if (Constant *C1 = dyn_cast<Constant>(Op1)) {
  906. Constant *Ops[] = { C0, C1 };
  907. return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
  908. }
  909. }
  910. bool isSigned = Opcode == Instruction::SDiv;
  911. // X / undef -> undef
  912. if (match(Op1, m_Undef()))
  913. return Op1;
  914. // X / 0 -> undef, we don't need to preserve faults!
  915. if (match(Op1, m_Zero()))
  916. return UndefValue::get(Op1->getType());
  917. // undef / X -> 0
  918. if (match(Op0, m_Undef()))
  919. return Constant::getNullValue(Op0->getType());
  920. // 0 / X -> 0, we don't need to preserve faults!
  921. if (match(Op0, m_Zero()))
  922. return Op0;
  923. // X / 1 -> X
  924. if (match(Op1, m_One()))
  925. return Op0;
  926. if (Op0->getType()->isIntegerTy(1))
  927. // It can't be division by zero, hence it must be division by one.
  928. return Op0;
  929. // X / X -> 1
  930. if (Op0 == Op1)
  931. return ConstantInt::get(Op0->getType(), 1);
  932. // (X * Y) / Y -> X if the multiplication does not overflow.
  933. Value *X = nullptr, *Y = nullptr;
  934. if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
  935. if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
  936. OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
  937. // If the Mul knows it does not overflow, then we are good to go.
  938. if ((isSigned && Mul->hasNoSignedWrap()) ||
  939. (!isSigned && Mul->hasNoUnsignedWrap()))
  940. return X;
  941. // If X has the form X = A / Y then X * Y cannot overflow.
  942. if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
  943. if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
  944. return X;
  945. }
  946. // (X rem Y) / Y -> 0
  947. if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
  948. (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
  949. return Constant::getNullValue(Op0->getType());
  950. // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
  951. ConstantInt *C1, *C2;
  952. if (!isSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
  953. match(Op1, m_ConstantInt(C2))) {
  954. bool Overflow;
  955. C1->getValue().umul_ov(C2->getValue(), Overflow);
  956. if (Overflow)
  957. return Constant::getNullValue(Op0->getType());
  958. }
  959. // If the operation is with the result of a select instruction, check whether
  960. // operating on either branch of the select always yields the same value.
  961. if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
  962. if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
  963. return V;
  964. // If the operation is with the result of a phi instruction, check whether
  965. // operating on all incoming values of the phi always yields the same value.
  966. if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
  967. if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
  968. return V;
  969. return nullptr;
  970. }
  971. /// SimplifySDivInst - Given operands for an SDiv, see if we can
  972. /// fold the result. If not, this returns null.
  973. static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
  974. unsigned MaxRecurse) {
  975. if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
  976. return V;
  977. return nullptr;
  978. }
  979. Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
  980. const TargetLibraryInfo *TLI,
  981. const DominatorTree *DT, AssumptionCache *AC,
  982. const Instruction *CxtI) {
  983. return ::SimplifySDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
  984. RecursionLimit);
  985. }
  986. /// SimplifyUDivInst - Given operands for a UDiv, see if we can
  987. /// fold the result. If not, this returns null.
  988. static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
  989. unsigned MaxRecurse) {
  990. if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
  991. return V;
  992. return nullptr;
  993. }
  994. Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
  995. const TargetLibraryInfo *TLI,
  996. const DominatorTree *DT, AssumptionCache *AC,
  997. const Instruction *CxtI) {
  998. return ::SimplifyUDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
  999. RecursionLimit);
  1000. }
  1001. static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
  1002. const Query &Q, unsigned) {
  1003. // HLSL Change Begins.
  1004. if (Constant *C0 = dyn_cast<Constant>(Op0)) {
  1005. if (Constant *C1 = dyn_cast<Constant>(Op1)) {
  1006. Constant *Ops[] = {C0, C1};
  1007. return ConstantFoldInstOperands(Instruction::FDiv, C0->getType(), Ops,
  1008. Q.DL, Q.TLI);
  1009. }
  1010. if (ConstantFP *FP = dyn_cast<ConstantFP>(C0))
  1011. if (FP->getValueAPF().isNaN())
  1012. return Op0;
  1013. }
  1014. if (ConstantFP *FP = dyn_cast<ConstantFP>(Op1))
  1015. if (FP->getValueAPF().isNaN())
  1016. return Op1;
  1017. // HLSL Change Ends.
  1018. // undef / X -> undef (the undef could be a snan).
  1019. if (match(Op0, m_Undef()))
  1020. return Op0;
  1021. // X / undef -> undef
  1022. if (match(Op1, m_Undef()))
  1023. return Op1;
  1024. // 0 / X -> 0
  1025. // Requires that NaNs are off (X could be zero) and signed zeroes are
  1026. // ignored (X could be positive or negative, so the output sign is unknown).
  1027. if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
  1028. return Op0;
  1029. if (FMF.noNaNs()) {
  1030. // X / X -> 1.0 is legal when NaNs are ignored.
  1031. if (Op0 == Op1)
  1032. return ConstantFP::get(Op0->getType(), 1.0);
  1033. // -X / X -> -1.0 and
  1034. // X / -X -> -1.0 are legal when NaNs are ignored.
  1035. // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
  1036. if ((BinaryOperator::isFNeg(Op0, /*IgnoreZeroSign=*/true) &&
  1037. BinaryOperator::getFNegArgument(Op0) == Op1) ||
  1038. (BinaryOperator::isFNeg(Op1, /*IgnoreZeroSign=*/true) &&
  1039. BinaryOperator::getFNegArgument(Op1) == Op0))
  1040. return ConstantFP::get(Op0->getType(), -1.0);
  1041. }
  1042. return nullptr;
  1043. }
  1044. Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
  1045. const DataLayout &DL,
  1046. const TargetLibraryInfo *TLI,
  1047. const DominatorTree *DT, AssumptionCache *AC,
  1048. const Instruction *CxtI) {
  1049. return ::SimplifyFDivInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
  1050. RecursionLimit);
  1051. }
  1052. /// SimplifyRem - Given operands for an SRem or URem, see if we can
  1053. /// fold the result. If not, this returns null.
  1054. static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
  1055. const Query &Q, unsigned MaxRecurse) {
  1056. if (Constant *C0 = dyn_cast<Constant>(Op0)) {
  1057. if (Constant *C1 = dyn_cast<Constant>(Op1)) {
  1058. Constant *Ops[] = { C0, C1 };
  1059. return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
  1060. }
  1061. }
  1062. // X % undef -> undef
  1063. if (match(Op1, m_Undef()))
  1064. return Op1;
  1065. // undef % X -> 0
  1066. if (match(Op0, m_Undef()))
  1067. return Constant::getNullValue(Op0->getType());
  1068. // 0 % X -> 0, we don't need to preserve faults!
  1069. if (match(Op0, m_Zero()))
  1070. return Op0;
  1071. // X % 0 -> undef, we don't need to preserve faults!
  1072. if (match(Op1, m_Zero()))
  1073. return UndefValue::get(Op0->getType());
  1074. // X % 1 -> 0
  1075. if (match(Op1, m_One()))
  1076. return Constant::getNullValue(Op0->getType());
  1077. if (Op0->getType()->isIntegerTy(1))
  1078. // It can't be remainder by zero, hence it must be remainder by one.
  1079. return Constant::getNullValue(Op0->getType());
  1080. // X % X -> 0
  1081. if (Op0 == Op1)
  1082. return Constant::getNullValue(Op0->getType());
  1083. // (X % Y) % Y -> X % Y
  1084. if ((Opcode == Instruction::SRem &&
  1085. match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
  1086. (Opcode == Instruction::URem &&
  1087. match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
  1088. return Op0;
  1089. // If the operation is with the result of a select instruction, check whether
  1090. // operating on either branch of the select always yields the same value.
  1091. if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
  1092. if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
  1093. return V;
  1094. // If the operation is with the result of a phi instruction, check whether
  1095. // operating on all incoming values of the phi always yields the same value.
  1096. if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
  1097. if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
  1098. return V;
  1099. return nullptr;
  1100. }
  1101. /// SimplifySRemInst - Given operands for an SRem, see if we can
  1102. /// fold the result. If not, this returns null.
  1103. static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
  1104. unsigned MaxRecurse) {
  1105. if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
  1106. return V;
  1107. return nullptr;
  1108. }
  1109. Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout &DL,
  1110. const TargetLibraryInfo *TLI,
  1111. const DominatorTree *DT, AssumptionCache *AC,
  1112. const Instruction *CxtI) {
  1113. return ::SimplifySRemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
  1114. RecursionLimit);
  1115. }
  1116. /// SimplifyURemInst - Given operands for a URem, see if we can
  1117. /// fold the result. If not, this returns null.
  1118. static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
  1119. unsigned MaxRecurse) {
  1120. if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
  1121. return V;
  1122. return nullptr;
  1123. }
  1124. Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout &DL,
  1125. const TargetLibraryInfo *TLI,
  1126. const DominatorTree *DT, AssumptionCache *AC,
  1127. const Instruction *CxtI) {
  1128. return ::SimplifyURemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
  1129. RecursionLimit);
  1130. }
  1131. static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
  1132. const Query &Q, unsigned) {
  1133. // HLSL Change Begins.
  1134. if (Constant *C0 = dyn_cast<Constant>(Op0)) {
  1135. if (Constant *C1 = dyn_cast<Constant>(Op1)) {
  1136. Constant *Ops[] = {C0, C1};
  1137. return ConstantFoldInstOperands(Instruction::FRem, C0->getType(), Ops,
  1138. Q.DL, Q.TLI);
  1139. }
  1140. if (ConstantFP *FP = dyn_cast<ConstantFP>(C0))
  1141. if (FP->getValueAPF().isNaN())
  1142. return Op0;
  1143. }
  1144. if (ConstantFP *FP = dyn_cast<ConstantFP>(Op1))
  1145. if (FP->getValueAPF().isNaN())
  1146. return Op1;
  1147. // HLSL Change Ends.
  1148. // undef % X -> undef (the undef could be a snan).
  1149. if (match(Op0, m_Undef()))
  1150. return Op0;
  1151. // X % undef -> undef
  1152. if (match(Op1, m_Undef()))
  1153. return Op1;
  1154. // 0 % X -> 0
  1155. // Requires that NaNs are off (X could be zero) and signed zeroes are
  1156. // ignored (X could be positive or negative, so the output sign is unknown).
  1157. if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
  1158. return Op0;
  1159. return nullptr;
  1160. }
  1161. Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
  1162. const DataLayout &DL,
  1163. const TargetLibraryInfo *TLI,
  1164. const DominatorTree *DT, AssumptionCache *AC,
  1165. const Instruction *CxtI) {
  1166. return ::SimplifyFRemInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
  1167. RecursionLimit);
  1168. }
  1169. /// isUndefShift - Returns true if a shift by \c Amount always yields undef.
  1170. static bool isUndefShift(Value *Amount) {
  1171. Constant *C = dyn_cast<Constant>(Amount);
  1172. if (!C)
  1173. return false;
  1174. // X shift by undef -> undef because it may shift by the bitwidth.
  1175. if (isa<UndefValue>(C))
  1176. return true;
  1177. // Shifting by the bitwidth or more is undefined.
  1178. if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
  1179. if (CI->getValue().getLimitedValue() >=
  1180. CI->getType()->getScalarSizeInBits())
  1181. return true;
  1182. // If all lanes of a vector shift are undefined the whole shift is.
  1183. if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
  1184. for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
  1185. if (!isUndefShift(C->getAggregateElement(I)))
  1186. return false;
  1187. return true;
  1188. }
  1189. return false;
  1190. }
  1191. /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
  1192. /// fold the result. If not, this returns null.
  1193. static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
  1194. const Query &Q, unsigned MaxRecurse) {
  1195. if (Constant *C0 = dyn_cast<Constant>(Op0)) {
  1196. if (Constant *C1 = dyn_cast<Constant>(Op1)) {
  1197. Constant *Ops[] = { C0, C1 };
  1198. return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
  1199. }
  1200. }
  1201. // 0 shift by X -> 0
  1202. if (match(Op0, m_Zero()))
  1203. return Op0;
  1204. // X shift by 0 -> X
  1205. if (match(Op1, m_Zero()))
  1206. return Op0;
  1207. // Fold undefined shifts.
  1208. if (isUndefShift(Op1))
  1209. return UndefValue::get(Op0->getType());
  1210. // If the operation is with the result of a select instruction, check whether
  1211. // operating on either branch of the select always yields the same value.
  1212. if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
  1213. if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
  1214. return V;
  1215. // If the operation is with the result of a phi instruction, check whether
  1216. // operating on all incoming values of the phi always yields the same value.
  1217. if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
  1218. if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
  1219. return V;
  1220. return nullptr;
  1221. }
  1222. /// \brief Given operands for an Shl, LShr or AShr, see if we can
  1223. /// fold the result. If not, this returns null.
  1224. static Value *SimplifyRightShift(unsigned Opcode, Value *Op0, Value *Op1,
  1225. bool isExact, const Query &Q,
  1226. unsigned MaxRecurse) {
  1227. if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
  1228. return V;
  1229. // X >> X -> 0
  1230. if (Op0 == Op1)
  1231. return Constant::getNullValue(Op0->getType());
  1232. // undef >> X -> 0
  1233. // undef >> X -> undef (if it's exact)
  1234. if (match(Op0, m_Undef()))
  1235. return isExact ? Op0 : Constant::getNullValue(Op0->getType());
  1236. // The low bit cannot be shifted out of an exact shift if it is set.
  1237. if (isExact) {
  1238. unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
  1239. APInt Op0KnownZero(BitWidth, 0);
  1240. APInt Op0KnownOne(BitWidth, 0);
  1241. computeKnownBits(Op0, Op0KnownZero, Op0KnownOne, Q.DL, /*Depth=*/0, Q.AC,
  1242. Q.CxtI, Q.DT);
  1243. if (Op0KnownOne[0])
  1244. return Op0;
  1245. }
  1246. return nullptr;
  1247. }
  1248. /// SimplifyShlInst - Given operands for an Shl, see if we can
  1249. /// fold the result. If not, this returns null.
  1250. static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
  1251. const Query &Q, unsigned MaxRecurse) {
  1252. if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
  1253. return V;
  1254. // undef << X -> 0
  1255. // undef << X -> undef if (if it's NSW/NUW)
  1256. if (match(Op0, m_Undef()))
  1257. return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
  1258. // (X >> A) << A -> X
  1259. Value *X;
  1260. if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
  1261. return X;
  1262. return nullptr;
  1263. }
  1264. Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
  1265. const DataLayout &DL, const TargetLibraryInfo *TLI,
  1266. const DominatorTree *DT, AssumptionCache *AC,
  1267. const Instruction *CxtI) {
  1268. return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
  1269. RecursionLimit);
  1270. }
  1271. /// SimplifyLShrInst - Given operands for an LShr, see if we can
  1272. /// fold the result. If not, this returns null.
  1273. static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
  1274. const Query &Q, unsigned MaxRecurse) {
  1275. if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
  1276. MaxRecurse))
  1277. return V;
  1278. // (X << A) >> A -> X
  1279. Value *X;
  1280. if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
  1281. return X;
  1282. return nullptr;
  1283. }
  1284. Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
  1285. const DataLayout &DL,
  1286. const TargetLibraryInfo *TLI,
  1287. const DominatorTree *DT, AssumptionCache *AC,
  1288. const Instruction *CxtI) {
  1289. return ::SimplifyLShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
  1290. RecursionLimit);
  1291. }
  1292. /// SimplifyAShrInst - Given operands for an AShr, see if we can
  1293. /// fold the result. If not, this returns null.
  1294. static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
  1295. const Query &Q, unsigned MaxRecurse) {
  1296. if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
  1297. MaxRecurse))
  1298. return V;
  1299. // all ones >>a X -> all ones
  1300. if (match(Op0, m_AllOnes()))
  1301. return Op0;
  1302. // (X << A) >> A -> X
  1303. Value *X;
  1304. if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
  1305. return X;
  1306. // Arithmetic shifting an all-sign-bit value is a no-op.
  1307. unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
  1308. if (NumSignBits == Op0->getType()->getScalarSizeInBits())
  1309. return Op0;
  1310. return nullptr;
  1311. }
  1312. Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
  1313. const DataLayout &DL,
  1314. const TargetLibraryInfo *TLI,
  1315. const DominatorTree *DT, AssumptionCache *AC,
  1316. const Instruction *CxtI) {
  1317. return ::SimplifyAShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
  1318. RecursionLimit);
  1319. }
  1320. static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
  1321. ICmpInst *UnsignedICmp, bool IsAnd) {
  1322. Value *X, *Y;
  1323. ICmpInst::Predicate EqPred;
  1324. if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
  1325. !ICmpInst::isEquality(EqPred))
  1326. return nullptr;
  1327. ICmpInst::Predicate UnsignedPred;
  1328. if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
  1329. ICmpInst::isUnsigned(UnsignedPred))
  1330. ;
  1331. else if (match(UnsignedICmp,
  1332. m_ICmp(UnsignedPred, m_Value(Y), m_Specific(X))) &&
  1333. ICmpInst::isUnsigned(UnsignedPred))
  1334. UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
  1335. else
  1336. return nullptr;
  1337. // X < Y && Y != 0 --> X < Y
  1338. // X < Y || Y != 0 --> Y != 0
  1339. if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
  1340. return IsAnd ? UnsignedICmp : ZeroICmp;
  1341. // X >= Y || Y != 0 --> true
  1342. // X >= Y || Y == 0 --> X >= Y
  1343. if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
  1344. if (EqPred == ICmpInst::ICMP_NE)
  1345. return getTrue(UnsignedICmp->getType());
  1346. return UnsignedICmp;
  1347. }
  1348. // X < Y && Y == 0 --> false
  1349. if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
  1350. IsAnd)
  1351. return getFalse(UnsignedICmp->getType());
  1352. return nullptr;
  1353. }
  1354. // Simplify (and (icmp ...) (icmp ...)) to true when we can tell that the range
  1355. // of possible values cannot be satisfied.
  1356. static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
  1357. ICmpInst::Predicate Pred0, Pred1;
  1358. ConstantInt *CI1, *CI2;
  1359. Value *V;
  1360. if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
  1361. return X;
  1362. if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
  1363. m_ConstantInt(CI2))))
  1364. return nullptr;
  1365. if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
  1366. return nullptr;
  1367. Type *ITy = Op0->getType();
  1368. auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
  1369. bool isNSW = AddInst->hasNoSignedWrap();
  1370. bool isNUW = AddInst->hasNoUnsignedWrap();
  1371. const APInt &CI1V = CI1->getValue();
  1372. const APInt &CI2V = CI2->getValue();
  1373. const APInt Delta = CI2V - CI1V;
  1374. if (CI1V.isStrictlyPositive()) {
  1375. if (Delta == 2) {
  1376. if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
  1377. return getFalse(ITy);
  1378. if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
  1379. return getFalse(ITy);
  1380. }
  1381. if (Delta == 1) {
  1382. if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
  1383. return getFalse(ITy);
  1384. if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
  1385. return getFalse(ITy);
  1386. }
  1387. }
  1388. if (CI1V.getBoolValue() && isNUW) {
  1389. if (Delta == 2)
  1390. if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
  1391. return getFalse(ITy);
  1392. if (Delta == 1)
  1393. if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
  1394. return getFalse(ITy);
  1395. }
  1396. return nullptr;
  1397. }
  1398. /// SimplifyAndInst - Given operands for an And, see if we can
  1399. /// fold the result. If not, this returns null.
  1400. static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
  1401. unsigned MaxRecurse) {
  1402. if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
  1403. if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
  1404. Constant *Ops[] = { CLHS, CRHS };
  1405. return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
  1406. Ops, Q.DL, Q.TLI);
  1407. }
  1408. // Canonicalize the constant to the RHS.
  1409. std::swap(Op0, Op1);
  1410. }
  1411. // X & undef -> 0
  1412. if (match(Op1, m_Undef()))
  1413. return Constant::getNullValue(Op0->getType());
  1414. // X & X = X
  1415. if (Op0 == Op1)
  1416. return Op0;
  1417. // X & 0 = 0
  1418. if (match(Op1, m_Zero()))
  1419. return Op1;
  1420. // X & -1 = X
  1421. if (match(Op1, m_AllOnes()))
  1422. return Op0;
  1423. // A & ~A = ~A & A = 0
  1424. if (match(Op0, m_Not(m_Specific(Op1))) ||
  1425. match(Op1, m_Not(m_Specific(Op0))))
  1426. return Constant::getNullValue(Op0->getType());
  1427. // (A | ?) & A = A
  1428. Value *A = nullptr, *B = nullptr;
  1429. if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
  1430. (A == Op1 || B == Op1))
  1431. return Op1;
  1432. // A & (A | ?) = A
  1433. if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
  1434. (A == Op0 || B == Op0))
  1435. return Op0;
  1436. // A & (-A) = A if A is a power of two or zero.
  1437. if (match(Op0, m_Neg(m_Specific(Op1))) ||
  1438. match(Op1, m_Neg(m_Specific(Op0)))) {
  1439. if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
  1440. Q.DT))
  1441. return Op0;
  1442. if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
  1443. Q.DT))
  1444. return Op1;
  1445. }
  1446. if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
  1447. if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
  1448. if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
  1449. return V;
  1450. if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
  1451. return V;
  1452. }
  1453. }
  1454. // Try some generic simplifications for associative operations.
  1455. if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
  1456. MaxRecurse))
  1457. return V;
  1458. // And distributes over Or. Try some generic simplifications based on this.
  1459. if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
  1460. Q, MaxRecurse))
  1461. return V;
  1462. // And distributes over Xor. Try some generic simplifications based on this.
  1463. if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
  1464. Q, MaxRecurse))
  1465. return V;
  1466. // If the operation is with the result of a select instruction, check whether
  1467. // operating on either branch of the select always yields the same value.
  1468. if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
  1469. if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
  1470. MaxRecurse))
  1471. return V;
  1472. // If the operation is with the result of a phi instruction, check whether
  1473. // operating on all incoming values of the phi always yields the same value.
  1474. if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
  1475. if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
  1476. MaxRecurse))
  1477. return V;
  1478. return nullptr;
  1479. }
  1480. Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout &DL,
  1481. const TargetLibraryInfo *TLI,
  1482. const DominatorTree *DT, AssumptionCache *AC,
  1483. const Instruction *CxtI) {
  1484. return ::SimplifyAndInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
  1485. RecursionLimit);
  1486. }
  1487. // Simplify (or (icmp ...) (icmp ...)) to true when we can tell that the union
  1488. // contains all possible values.
  1489. static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
  1490. ICmpInst::Predicate Pred0, Pred1;
  1491. ConstantInt *CI1, *CI2;
  1492. Value *V;
  1493. if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
  1494. return X;
  1495. if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
  1496. m_ConstantInt(CI2))))
  1497. return nullptr;
  1498. if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
  1499. return nullptr;
  1500. Type *ITy = Op0->getType();
  1501. auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
  1502. bool isNSW = AddInst->hasNoSignedWrap();
  1503. bool isNUW = AddInst->hasNoUnsignedWrap();
  1504. const APInt &CI1V = CI1->getValue();
  1505. const APInt &CI2V = CI2->getValue();
  1506. const APInt Delta = CI2V - CI1V;
  1507. if (CI1V.isStrictlyPositive()) {
  1508. if (Delta == 2) {
  1509. if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
  1510. return getTrue(ITy);
  1511. if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
  1512. return getTrue(ITy);
  1513. }
  1514. if (Delta == 1) {
  1515. if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
  1516. return getTrue(ITy);
  1517. if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
  1518. return getTrue(ITy);
  1519. }
  1520. }
  1521. if (CI1V.getBoolValue() && isNUW) {
  1522. if (Delta == 2)
  1523. if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
  1524. return getTrue(ITy);
  1525. if (Delta == 1)
  1526. if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
  1527. return getTrue(ITy);
  1528. }
  1529. return nullptr;
  1530. }
  1531. /// SimplifyOrInst - Given operands for an Or, see if we can
  1532. /// fold the result. If not, this returns null.
  1533. static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
  1534. unsigned MaxRecurse) {
  1535. if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
  1536. if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
  1537. Constant *Ops[] = { CLHS, CRHS };
  1538. return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
  1539. Ops, Q.DL, Q.TLI);
  1540. }
  1541. // Canonicalize the constant to the RHS.
  1542. std::swap(Op0, Op1);
  1543. }
  1544. // X | undef -> -1
  1545. if (match(Op1, m_Undef()))
  1546. return Constant::getAllOnesValue(Op0->getType());
  1547. // X | X = X
  1548. if (Op0 == Op1)
  1549. return Op0;
  1550. // X | 0 = X
  1551. if (match(Op1, m_Zero()))
  1552. return Op0;
  1553. // X | -1 = -1
  1554. if (match(Op1, m_AllOnes()))
  1555. return Op1;
  1556. // A | ~A = ~A | A = -1
  1557. if (match(Op0, m_Not(m_Specific(Op1))) ||
  1558. match(Op1, m_Not(m_Specific(Op0))))
  1559. return Constant::getAllOnesValue(Op0->getType());
  1560. // (A & ?) | A = A
  1561. Value *A = nullptr, *B = nullptr;
  1562. if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
  1563. (A == Op1 || B == Op1))
  1564. return Op1;
  1565. // A | (A & ?) = A
  1566. if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
  1567. (A == Op0 || B == Op0))
  1568. return Op0;
  1569. // ~(A & ?) | A = -1
  1570. if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
  1571. (A == Op1 || B == Op1))
  1572. return Constant::getAllOnesValue(Op1->getType());
  1573. // A | ~(A & ?) = -1
  1574. if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
  1575. (A == Op0 || B == Op0))
  1576. return Constant::getAllOnesValue(Op0->getType());
  1577. if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
  1578. if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
  1579. if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
  1580. return V;
  1581. if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
  1582. return V;
  1583. }
  1584. }
  1585. // Try some generic simplifications for associative operations.
  1586. if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
  1587. MaxRecurse))
  1588. return V;
  1589. // Or distributes over And. Try some generic simplifications based on this.
  1590. if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
  1591. MaxRecurse))
  1592. return V;
  1593. // If the operation is with the result of a select instruction, check whether
  1594. // operating on either branch of the select always yields the same value.
  1595. if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
  1596. if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
  1597. MaxRecurse))
  1598. return V;
  1599. // (A & C)|(B & D)
  1600. Value *C = nullptr, *D = nullptr;
  1601. if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
  1602. match(Op1, m_And(m_Value(B), m_Value(D)))) {
  1603. ConstantInt *C1 = dyn_cast<ConstantInt>(C);
  1604. ConstantInt *C2 = dyn_cast<ConstantInt>(D);
  1605. if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
  1606. // (A & C1)|(B & C2)
  1607. // If we have: ((V + N) & C1) | (V & C2)
  1608. // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
  1609. // replace with V+N.
  1610. Value *V1, *V2;
  1611. if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
  1612. match(A, m_Add(m_Value(V1), m_Value(V2)))) {
  1613. // Add commutes, try both ways.
  1614. if (V1 == B &&
  1615. MaskedValueIsZero(V2, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
  1616. return A;
  1617. if (V2 == B &&
  1618. MaskedValueIsZero(V1, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
  1619. return A;
  1620. }
  1621. // Or commutes, try both ways.
  1622. if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
  1623. match(B, m_Add(m_Value(V1), m_Value(V2)))) {
  1624. // Add commutes, try both ways.
  1625. if (V1 == A &&
  1626. MaskedValueIsZero(V2, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
  1627. return B;
  1628. if (V2 == A &&
  1629. MaskedValueIsZero(V1, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
  1630. return B;
  1631. }
  1632. }
  1633. }
  1634. // If the operation is with the result of a phi instruction, check whether
  1635. // operating on all incoming values of the phi always yields the same value.
  1636. if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
  1637. if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
  1638. return V;
  1639. return nullptr;
  1640. }
  1641. Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout &DL,
  1642. const TargetLibraryInfo *TLI,
  1643. const DominatorTree *DT, AssumptionCache *AC,
  1644. const Instruction *CxtI) {
  1645. return ::SimplifyOrInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
  1646. RecursionLimit);
  1647. }
  1648. /// SimplifyXorInst - Given operands for a Xor, see if we can
  1649. /// fold the result. If not, this returns null.
  1650. static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
  1651. unsigned MaxRecurse) {
  1652. if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
  1653. if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
  1654. Constant *Ops[] = { CLHS, CRHS };
  1655. return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
  1656. Ops, Q.DL, Q.TLI);
  1657. }
  1658. // Canonicalize the constant to the RHS.
  1659. std::swap(Op0, Op1);
  1660. }
  1661. // A ^ undef -> undef
  1662. if (match(Op1, m_Undef()))
  1663. return Op1;
  1664. // A ^ 0 = A
  1665. if (match(Op1, m_Zero()))
  1666. return Op0;
  1667. // A ^ A = 0
  1668. if (Op0 == Op1)
  1669. return Constant::getNullValue(Op0->getType());
  1670. // A ^ ~A = ~A ^ A = -1
  1671. if (match(Op0, m_Not(m_Specific(Op1))) ||
  1672. match(Op1, m_Not(m_Specific(Op0))))
  1673. return Constant::getAllOnesValue(Op0->getType());
  1674. // Try some generic simplifications for associative operations.
  1675. if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
  1676. MaxRecurse))
  1677. return V;
  1678. // Threading Xor over selects and phi nodes is pointless, so don't bother.
  1679. // Threading over the select in "A ^ select(cond, B, C)" means evaluating
  1680. // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
  1681. // only if B and C are equal. If B and C are equal then (since we assume
  1682. // that operands have already been simplified) "select(cond, B, C)" should
  1683. // have been simplified to the common value of B and C already. Analysing
  1684. // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
  1685. // for threading over phi nodes.
  1686. return nullptr;
  1687. }
  1688. Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout &DL,
  1689. const TargetLibraryInfo *TLI,
  1690. const DominatorTree *DT, AssumptionCache *AC,
  1691. const Instruction *CxtI) {
  1692. return ::SimplifyXorInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
  1693. RecursionLimit);
  1694. }
  1695. static Type *GetCompareTy(Value *Op) {
  1696. return CmpInst::makeCmpResultType(Op->getType());
  1697. }
  1698. /// ExtractEquivalentCondition - Rummage around inside V looking for something
  1699. /// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
  1700. /// otherwise return null. Helper function for analyzing max/min idioms.
  1701. static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
  1702. Value *LHS, Value *RHS) {
  1703. SelectInst *SI = dyn_cast<SelectInst>(V);
  1704. if (!SI)
  1705. return nullptr;
  1706. CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
  1707. if (!Cmp)
  1708. return nullptr;
  1709. Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
  1710. if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
  1711. return Cmp;
  1712. if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
  1713. LHS == CmpRHS && RHS == CmpLHS)
  1714. return Cmp;
  1715. return nullptr;
  1716. }
  1717. // A significant optimization not implemented here is assuming that alloca
  1718. // addresses are not equal to incoming argument values. They don't *alias*,
  1719. // as we say, but that doesn't mean they aren't equal, so we take a
  1720. // conservative approach.
  1721. //
  1722. // This is inspired in part by C++11 5.10p1:
  1723. // "Two pointers of the same type compare equal if and only if they are both
  1724. // null, both point to the same function, or both represent the same
  1725. // address."
  1726. //
  1727. // This is pretty permissive.
  1728. //
  1729. // It's also partly due to C11 6.5.9p6:
  1730. // "Two pointers compare equal if and only if both are null pointers, both are
  1731. // pointers to the same object (including a pointer to an object and a
  1732. // subobject at its beginning) or function, both are pointers to one past the
  1733. // last element of the same array object, or one is a pointer to one past the
  1734. // end of one array object and the other is a pointer to the start of a
  1735. // different array object that happens to immediately follow the first array
  1736. // object in the address space.)
  1737. //
  1738. // C11's version is more restrictive, however there's no reason why an argument
  1739. // couldn't be a one-past-the-end value for a stack object in the caller and be
  1740. // equal to the beginning of a stack object in the callee.
  1741. //
  1742. // If the C and C++ standards are ever made sufficiently restrictive in this
  1743. // area, it may be possible to update LLVM's semantics accordingly and reinstate
  1744. // this optimization.
  1745. static Constant *computePointerICmp(const DataLayout &DL,
  1746. const TargetLibraryInfo *TLI,
  1747. CmpInst::Predicate Pred, Value *LHS,
  1748. Value *RHS) {
  1749. // First, skip past any trivial no-ops.
  1750. LHS = LHS->stripPointerCasts();
  1751. RHS = RHS->stripPointerCasts();
  1752. // A non-null pointer is not equal to a null pointer.
  1753. if (llvm::isKnownNonNull(LHS, TLI) && isa<ConstantPointerNull>(RHS) &&
  1754. (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
  1755. return ConstantInt::get(GetCompareTy(LHS),
  1756. !CmpInst::isTrueWhenEqual(Pred));
  1757. // We can only fold certain predicates on pointer comparisons.
  1758. switch (Pred) {
  1759. default:
  1760. return nullptr;
  1761. // Equality comaprisons are easy to fold.
  1762. case CmpInst::ICMP_EQ:
  1763. case CmpInst::ICMP_NE:
  1764. break;
  1765. // We can only handle unsigned relational comparisons because 'inbounds' on
  1766. // a GEP only protects against unsigned wrapping.
  1767. case CmpInst::ICMP_UGT:
  1768. case CmpInst::ICMP_UGE:
  1769. case CmpInst::ICMP_ULT:
  1770. case CmpInst::ICMP_ULE:
  1771. // However, we have to switch them to their signed variants to handle
  1772. // negative indices from the base pointer.
  1773. Pred = ICmpInst::getSignedPredicate(Pred);
  1774. break;
  1775. }
  1776. // Strip off any constant offsets so that we can reason about them.
  1777. // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
  1778. // here and compare base addresses like AliasAnalysis does, however there are
  1779. // numerous hazards. AliasAnalysis and its utilities rely on special rules
  1780. // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
  1781. // doesn't need to guarantee pointer inequality when it says NoAlias.
  1782. Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
  1783. Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
  1784. // If LHS and RHS are related via constant offsets to the same base
  1785. // value, we can replace it with an icmp which just compares the offsets.
  1786. if (LHS == RHS)
  1787. return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
  1788. // Various optimizations for (in)equality comparisons.
  1789. if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
  1790. // Different non-empty allocations that exist at the same time have
  1791. // different addresses (if the program can tell). Global variables always
  1792. // exist, so they always exist during the lifetime of each other and all
  1793. // allocas. Two different allocas usually have different addresses...
  1794. //
  1795. // However, if there's an @llvm.stackrestore dynamically in between two
  1796. // allocas, they may have the same address. It's tempting to reduce the
  1797. // scope of the problem by only looking at *static* allocas here. That would
  1798. // cover the majority of allocas while significantly reducing the likelihood
  1799. // of having an @llvm.stackrestore pop up in the middle. However, it's not
  1800. // actually impossible for an @llvm.stackrestore to pop up in the middle of
  1801. // an entry block. Also, if we have a block that's not attached to a
  1802. // function, we can't tell if it's "static" under the current definition.
  1803. // Theoretically, this problem could be fixed by creating a new kind of
  1804. // instruction kind specifically for static allocas. Such a new instruction
  1805. // could be required to be at the top of the entry block, thus preventing it
  1806. // from being subject to a @llvm.stackrestore. Instcombine could even
  1807. // convert regular allocas into these special allocas. It'd be nifty.
  1808. // However, until then, this problem remains open.
  1809. //
  1810. // So, we'll assume that two non-empty allocas have different addresses
  1811. // for now.
  1812. //
  1813. // With all that, if the offsets are within the bounds of their allocations
  1814. // (and not one-past-the-end! so we can't use inbounds!), and their
  1815. // allocations aren't the same, the pointers are not equal.
  1816. //
  1817. // Note that it's not necessary to check for LHS being a global variable
  1818. // address, due to canonicalization and constant folding.
  1819. if (isa<AllocaInst>(LHS) &&
  1820. (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
  1821. ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
  1822. ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
  1823. uint64_t LHSSize, RHSSize;
  1824. if (LHSOffsetCI && RHSOffsetCI &&
  1825. getObjectSize(LHS, LHSSize, DL, TLI) &&
  1826. getObjectSize(RHS, RHSSize, DL, TLI)) {
  1827. const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
  1828. const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
  1829. if (!LHSOffsetValue.isNegative() &&
  1830. !RHSOffsetValue.isNegative() &&
  1831. LHSOffsetValue.ult(LHSSize) &&
  1832. RHSOffsetValue.ult(RHSSize)) {
  1833. return ConstantInt::get(GetCompareTy(LHS),
  1834. !CmpInst::isTrueWhenEqual(Pred));
  1835. }
  1836. }
  1837. // Repeat the above check but this time without depending on DataLayout
  1838. // or being able to compute a precise size.
  1839. if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
  1840. !cast<PointerType>(RHS->getType())->isEmptyTy() &&
  1841. LHSOffset->isNullValue() &&
  1842. RHSOffset->isNullValue())
  1843. return ConstantInt::get(GetCompareTy(LHS),
  1844. !CmpInst::isTrueWhenEqual(Pred));
  1845. }
  1846. // Even if an non-inbounds GEP occurs along the path we can still optimize
  1847. // equality comparisons concerning the result. We avoid walking the whole
  1848. // chain again by starting where the last calls to
  1849. // stripAndComputeConstantOffsets left off and accumulate the offsets.
  1850. Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
  1851. Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
  1852. if (LHS == RHS)
  1853. return ConstantExpr::getICmp(Pred,
  1854. ConstantExpr::getAdd(LHSOffset, LHSNoBound),
  1855. ConstantExpr::getAdd(RHSOffset, RHSNoBound));
  1856. // If one side of the equality comparison must come from a noalias call
  1857. // (meaning a system memory allocation function), and the other side must
  1858. // come from a pointer that cannot overlap with dynamically-allocated
  1859. // memory within the lifetime of the current function (allocas, byval
  1860. // arguments, globals), then determine the comparison result here.
  1861. SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
  1862. GetUnderlyingObjects(LHS, LHSUObjs, DL);
  1863. GetUnderlyingObjects(RHS, RHSUObjs, DL);
  1864. // Is the set of underlying objects all noalias calls?
  1865. auto IsNAC = [](SmallVectorImpl<Value *> &Objects) {
  1866. return std::all_of(Objects.begin(), Objects.end(),
  1867. [](Value *V){ return isNoAliasCall(V); });
  1868. };
  1869. // Is the set of underlying objects all things which must be disjoint from
  1870. // noalias calls. For allocas, we consider only static ones (dynamic
  1871. // allocas might be transformed into calls to malloc not simultaneously
  1872. // live with the compared-to allocation). For globals, we exclude symbols
  1873. // that might be resolve lazily to symbols in another dynamically-loaded
  1874. // library (and, thus, could be malloc'ed by the implementation).
  1875. auto IsAllocDisjoint = [](SmallVectorImpl<Value *> &Objects) {
  1876. return std::all_of(Objects.begin(), Objects.end(),
  1877. [](Value *V){
  1878. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
  1879. return AI->getParent() && AI->getParent()->getParent() &&
  1880. AI->isStaticAlloca();
  1881. if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
  1882. return (GV->hasLocalLinkage() ||
  1883. GV->hasHiddenVisibility() ||
  1884. GV->hasProtectedVisibility() ||
  1885. GV->hasUnnamedAddr()) &&
  1886. !GV->isThreadLocal();
  1887. if (const Argument *A = dyn_cast<Argument>(V))
  1888. return A->hasByValAttr();
  1889. return false;
  1890. });
  1891. };
  1892. if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
  1893. (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
  1894. return ConstantInt::get(GetCompareTy(LHS),
  1895. !CmpInst::isTrueWhenEqual(Pred));
  1896. }
  1897. // Otherwise, fail.
  1898. return nullptr;
  1899. }
  1900. /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
  1901. /// fold the result. If not, this returns null.
  1902. static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
  1903. const Query &Q, unsigned MaxRecurse) {
  1904. CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
  1905. assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
  1906. if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
  1907. if (Constant *CRHS = dyn_cast<Constant>(RHS))
  1908. return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
  1909. // If we have a constant, make sure it is on the RHS.
  1910. std::swap(LHS, RHS);
  1911. Pred = CmpInst::getSwappedPredicate(Pred);
  1912. }
  1913. Type *ITy = GetCompareTy(LHS); // The return type.
  1914. Type *OpTy = LHS->getType(); // The operand type.
  1915. // icmp X, X -> true/false
  1916. // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
  1917. // because X could be 0.
  1918. if (LHS == RHS || isa<UndefValue>(RHS))
  1919. return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
  1920. // Special case logic when the operands have i1 type.
  1921. if (OpTy->getScalarType()->isIntegerTy(1)) {
  1922. switch (Pred) {
  1923. default: break;
  1924. case ICmpInst::ICMP_EQ:
  1925. // X == 1 -> X
  1926. if (match(RHS, m_One()))
  1927. return LHS;
  1928. break;
  1929. case ICmpInst::ICMP_NE:
  1930. // X != 0 -> X
  1931. if (match(RHS, m_Zero()))
  1932. return LHS;
  1933. break;
  1934. case ICmpInst::ICMP_UGT:
  1935. // X >u 0 -> X
  1936. if (match(RHS, m_Zero()))
  1937. return LHS;
  1938. break;
  1939. case ICmpInst::ICMP_UGE:
  1940. // X >=u 1 -> X
  1941. if (match(RHS, m_One()))
  1942. return LHS;
  1943. break;
  1944. case ICmpInst::ICMP_SLT:
  1945. // X <s 0 -> X
  1946. if (match(RHS, m_Zero()))
  1947. return LHS;
  1948. break;
  1949. case ICmpInst::ICMP_SLE:
  1950. // X <=s -1 -> X
  1951. if (match(RHS, m_One()))
  1952. return LHS;
  1953. break;
  1954. }
  1955. }
  1956. // If we are comparing with zero then try hard since this is a common case.
  1957. if (match(RHS, m_Zero())) {
  1958. bool LHSKnownNonNegative, LHSKnownNegative;
  1959. switch (Pred) {
  1960. default: llvm_unreachable("Unknown ICmp predicate!");
  1961. case ICmpInst::ICMP_ULT:
  1962. return getFalse(ITy);
  1963. case ICmpInst::ICMP_UGE:
  1964. return getTrue(ITy);
  1965. case ICmpInst::ICMP_EQ:
  1966. case ICmpInst::ICMP_ULE:
  1967. if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
  1968. return getFalse(ITy);
  1969. break;
  1970. case ICmpInst::ICMP_NE:
  1971. case ICmpInst::ICMP_UGT:
  1972. if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
  1973. return getTrue(ITy);
  1974. break;
  1975. case ICmpInst::ICMP_SLT:
  1976. ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
  1977. Q.CxtI, Q.DT);
  1978. if (LHSKnownNegative)
  1979. return getTrue(ITy);
  1980. if (LHSKnownNonNegative)
  1981. return getFalse(ITy);
  1982. break;
  1983. case ICmpInst::ICMP_SLE:
  1984. ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
  1985. Q.CxtI, Q.DT);
  1986. if (LHSKnownNegative)
  1987. return getTrue(ITy);
  1988. if (LHSKnownNonNegative &&
  1989. isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
  1990. return getFalse(ITy);
  1991. break;
  1992. case ICmpInst::ICMP_SGE:
  1993. ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
  1994. Q.CxtI, Q.DT);
  1995. if (LHSKnownNegative)
  1996. return getFalse(ITy);
  1997. if (LHSKnownNonNegative)
  1998. return getTrue(ITy);
  1999. break;
  2000. case ICmpInst::ICMP_SGT:
  2001. ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
  2002. Q.CxtI, Q.DT);
  2003. if (LHSKnownNegative)
  2004. return getFalse(ITy);
  2005. if (LHSKnownNonNegative &&
  2006. isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
  2007. return getTrue(ITy);
  2008. break;
  2009. }
  2010. }
  2011. // See if we are doing a comparison with a constant integer.
  2012. if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
  2013. // Rule out tautological comparisons (eg., ult 0 or uge 0).
  2014. ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
  2015. if (RHS_CR.isEmptySet())
  2016. return ConstantInt::getFalse(CI->getContext());
  2017. if (RHS_CR.isFullSet())
  2018. return ConstantInt::getTrue(CI->getContext());
  2019. // Many binary operators with constant RHS have easy to compute constant
  2020. // range. Use them to check whether the comparison is a tautology.
  2021. unsigned Width = CI->getBitWidth();
  2022. APInt Lower = APInt(Width, 0);
  2023. APInt Upper = APInt(Width, 0);
  2024. ConstantInt *CI2;
  2025. if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
  2026. // 'urem x, CI2' produces [0, CI2).
  2027. Upper = CI2->getValue();
  2028. } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
  2029. // 'srem x, CI2' produces (-|CI2|, |CI2|).
  2030. Upper = CI2->getValue().abs();
  2031. Lower = (-Upper) + 1;
  2032. } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
  2033. // 'udiv CI2, x' produces [0, CI2].
  2034. Upper = CI2->getValue() + 1;
  2035. } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
  2036. // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
  2037. APInt NegOne = APInt::getAllOnesValue(Width);
  2038. if (!CI2->isZero())
  2039. Upper = NegOne.udiv(CI2->getValue()) + 1;
  2040. } else if (match(LHS, m_SDiv(m_ConstantInt(CI2), m_Value()))) {
  2041. if (CI2->isMinSignedValue()) {
  2042. // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
  2043. Lower = CI2->getValue();
  2044. Upper = Lower.lshr(1) + 1;
  2045. } else {
  2046. // 'sdiv CI2, x' produces [-|CI2|, |CI2|].
  2047. Upper = CI2->getValue().abs() + 1;
  2048. Lower = (-Upper) + 1;
  2049. }
  2050. } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
  2051. APInt IntMin = APInt::getSignedMinValue(Width);
  2052. APInt IntMax = APInt::getSignedMaxValue(Width);
  2053. APInt Val = CI2->getValue();
  2054. if (Val.isAllOnesValue()) {
  2055. // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
  2056. // where CI2 != -1 and CI2 != 0 and CI2 != 1
  2057. Lower = IntMin + 1;
  2058. Upper = IntMax + 1;
  2059. } else if (Val.countLeadingZeros() < Width - 1) {
  2060. // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2]
  2061. // where CI2 != -1 and CI2 != 0 and CI2 != 1
  2062. Lower = IntMin.sdiv(Val);
  2063. Upper = IntMax.sdiv(Val);
  2064. if (Lower.sgt(Upper))
  2065. std::swap(Lower, Upper);
  2066. Upper = Upper + 1;
  2067. assert(Upper != Lower && "Upper part of range has wrapped!");
  2068. }
  2069. } else if (match(LHS, m_NUWShl(m_ConstantInt(CI2), m_Value()))) {
  2070. // 'shl nuw CI2, x' produces [CI2, CI2 << CLZ(CI2)]
  2071. Lower = CI2->getValue();
  2072. Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
  2073. } else if (match(LHS, m_NSWShl(m_ConstantInt(CI2), m_Value()))) {
  2074. if (CI2->isNegative()) {
  2075. // 'shl nsw CI2, x' produces [CI2 << CLO(CI2)-1, CI2]
  2076. unsigned ShiftAmount = CI2->getValue().countLeadingOnes() - 1;
  2077. Lower = CI2->getValue().shl(ShiftAmount);
  2078. Upper = CI2->getValue() + 1;
  2079. } else {
  2080. // 'shl nsw CI2, x' produces [CI2, CI2 << CLZ(CI2)-1]
  2081. unsigned ShiftAmount = CI2->getValue().countLeadingZeros() - 1;
  2082. Lower = CI2->getValue();
  2083. Upper = CI2->getValue().shl(ShiftAmount) + 1;
  2084. }
  2085. } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
  2086. // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
  2087. APInt NegOne = APInt::getAllOnesValue(Width);
  2088. if (CI2->getValue().ult(Width))
  2089. Upper = NegOne.lshr(CI2->getValue()) + 1;
  2090. } else if (match(LHS, m_LShr(m_ConstantInt(CI2), m_Value()))) {
  2091. // 'lshr CI2, x' produces [CI2 >> (Width-1), CI2].
  2092. unsigned ShiftAmount = Width - 1;
  2093. if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
  2094. ShiftAmount = CI2->getValue().countTrailingZeros();
  2095. Lower = CI2->getValue().lshr(ShiftAmount);
  2096. Upper = CI2->getValue() + 1;
  2097. } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
  2098. // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
  2099. APInt IntMin = APInt::getSignedMinValue(Width);
  2100. APInt IntMax = APInt::getSignedMaxValue(Width);
  2101. if (CI2->getValue().ult(Width)) {
  2102. Lower = IntMin.ashr(CI2->getValue());
  2103. Upper = IntMax.ashr(CI2->getValue()) + 1;
  2104. }
  2105. } else if (match(LHS, m_AShr(m_ConstantInt(CI2), m_Value()))) {
  2106. unsigned ShiftAmount = Width - 1;
  2107. if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
  2108. ShiftAmount = CI2->getValue().countTrailingZeros();
  2109. if (CI2->isNegative()) {
  2110. // 'ashr CI2, x' produces [CI2, CI2 >> (Width-1)]
  2111. Lower = CI2->getValue();
  2112. Upper = CI2->getValue().ashr(ShiftAmount) + 1;
  2113. } else {
  2114. // 'ashr CI2, x' produces [CI2 >> (Width-1), CI2]
  2115. Lower = CI2->getValue().ashr(ShiftAmount);
  2116. Upper = CI2->getValue() + 1;
  2117. }
  2118. } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
  2119. // 'or x, CI2' produces [CI2, UINT_MAX].
  2120. Lower = CI2->getValue();
  2121. } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
  2122. // 'and x, CI2' produces [0, CI2].
  2123. Upper = CI2->getValue() + 1;
  2124. }
  2125. if (Lower != Upper) {
  2126. ConstantRange LHS_CR = ConstantRange(Lower, Upper);
  2127. if (RHS_CR.contains(LHS_CR))
  2128. return ConstantInt::getTrue(RHS->getContext());
  2129. if (RHS_CR.inverse().contains(LHS_CR))
  2130. return ConstantInt::getFalse(RHS->getContext());
  2131. }
  2132. }
  2133. // Compare of cast, for example (zext X) != 0 -> X != 0
  2134. if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
  2135. Instruction *LI = cast<CastInst>(LHS);
  2136. Value *SrcOp = LI->getOperand(0);
  2137. Type *SrcTy = SrcOp->getType();
  2138. Type *DstTy = LI->getType();
  2139. // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
  2140. // if the integer type is the same size as the pointer type.
  2141. if (MaxRecurse && isa<PtrToIntInst>(LI) &&
  2142. Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
  2143. if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
  2144. // Transfer the cast to the constant.
  2145. if (Value *V = SimplifyICmpInst(Pred, SrcOp,
  2146. ConstantExpr::getIntToPtr(RHSC, SrcTy),
  2147. Q, MaxRecurse-1))
  2148. return V;
  2149. } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
  2150. if (RI->getOperand(0)->getType() == SrcTy)
  2151. // Compare without the cast.
  2152. if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
  2153. Q, MaxRecurse-1))
  2154. return V;
  2155. }
  2156. }
  2157. if (isa<ZExtInst>(LHS)) {
  2158. // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
  2159. // same type.
  2160. if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
  2161. if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
  2162. // Compare X and Y. Note that signed predicates become unsigned.
  2163. if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
  2164. SrcOp, RI->getOperand(0), Q,
  2165. MaxRecurse-1))
  2166. return V;
  2167. }
  2168. // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
  2169. // too. If not, then try to deduce the result of the comparison.
  2170. else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
  2171. // Compute the constant that would happen if we truncated to SrcTy then
  2172. // reextended to DstTy.
  2173. Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
  2174. Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
  2175. // If the re-extended constant didn't change then this is effectively
  2176. // also a case of comparing two zero-extended values.
  2177. if (RExt == CI && MaxRecurse)
  2178. if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
  2179. SrcOp, Trunc, Q, MaxRecurse-1))
  2180. return V;
  2181. // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
  2182. // there. Use this to work out the result of the comparison.
  2183. if (RExt != CI) {
  2184. switch (Pred) {
  2185. default: llvm_unreachable("Unknown ICmp predicate!");
  2186. // LHS <u RHS.
  2187. case ICmpInst::ICMP_EQ:
  2188. case ICmpInst::ICMP_UGT:
  2189. case ICmpInst::ICMP_UGE:
  2190. return ConstantInt::getFalse(CI->getContext());
  2191. case ICmpInst::ICMP_NE:
  2192. case ICmpInst::ICMP_ULT:
  2193. case ICmpInst::ICMP_ULE:
  2194. return ConstantInt::getTrue(CI->getContext());
  2195. // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
  2196. // is non-negative then LHS <s RHS.
  2197. case ICmpInst::ICMP_SGT:
  2198. case ICmpInst::ICMP_SGE:
  2199. return CI->getValue().isNegative() ?
  2200. ConstantInt::getTrue(CI->getContext()) :
  2201. ConstantInt::getFalse(CI->getContext());
  2202. case ICmpInst::ICMP_SLT:
  2203. case ICmpInst::ICMP_SLE:
  2204. return CI->getValue().isNegative() ?
  2205. ConstantInt::getFalse(CI->getContext()) :
  2206. ConstantInt::getTrue(CI->getContext());
  2207. }
  2208. }
  2209. }
  2210. }
  2211. if (isa<SExtInst>(LHS)) {
  2212. // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
  2213. // same type.
  2214. if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
  2215. if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
  2216. // Compare X and Y. Note that the predicate does not change.
  2217. if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
  2218. Q, MaxRecurse-1))
  2219. return V;
  2220. }
  2221. // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
  2222. // too. If not, then try to deduce the result of the comparison.
  2223. else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
  2224. // Compute the constant that would happen if we truncated to SrcTy then
  2225. // reextended to DstTy.
  2226. Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
  2227. Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
  2228. // If the re-extended constant didn't change then this is effectively
  2229. // also a case of comparing two sign-extended values.
  2230. if (RExt == CI && MaxRecurse)
  2231. if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
  2232. return V;
  2233. // Otherwise the upper bits of LHS are all equal, while RHS has varying
  2234. // bits there. Use this to work out the result of the comparison.
  2235. if (RExt != CI) {
  2236. switch (Pred) {
  2237. default: llvm_unreachable("Unknown ICmp predicate!");
  2238. case ICmpInst::ICMP_EQ:
  2239. return ConstantInt::getFalse(CI->getContext());
  2240. case ICmpInst::ICMP_NE:
  2241. return ConstantInt::getTrue(CI->getContext());
  2242. // If RHS is non-negative then LHS <s RHS. If RHS is negative then
  2243. // LHS >s RHS.
  2244. case ICmpInst::ICMP_SGT:
  2245. case ICmpInst::ICMP_SGE:
  2246. return CI->getValue().isNegative() ?
  2247. ConstantInt::getTrue(CI->getContext()) :
  2248. ConstantInt::getFalse(CI->getContext());
  2249. case ICmpInst::ICMP_SLT:
  2250. case ICmpInst::ICMP_SLE:
  2251. return CI->getValue().isNegative() ?
  2252. ConstantInt::getFalse(CI->getContext()) :
  2253. ConstantInt::getTrue(CI->getContext());
  2254. // If LHS is non-negative then LHS <u RHS. If LHS is negative then
  2255. // LHS >u RHS.
  2256. case ICmpInst::ICMP_UGT:
  2257. case ICmpInst::ICMP_UGE:
  2258. // Comparison is true iff the LHS <s 0.
  2259. if (MaxRecurse)
  2260. if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
  2261. Constant::getNullValue(SrcTy),
  2262. Q, MaxRecurse-1))
  2263. return V;
  2264. break;
  2265. case ICmpInst::ICMP_ULT:
  2266. case ICmpInst::ICMP_ULE:
  2267. // Comparison is true iff the LHS >=s 0.
  2268. if (MaxRecurse)
  2269. if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
  2270. Constant::getNullValue(SrcTy),
  2271. Q, MaxRecurse-1))
  2272. return V;
  2273. break;
  2274. }
  2275. }
  2276. }
  2277. }
  2278. }
  2279. // Special logic for binary operators.
  2280. BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
  2281. BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
  2282. if (MaxRecurse && (LBO || RBO)) {
  2283. // Analyze the case when either LHS or RHS is an add instruction.
  2284. Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
  2285. // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
  2286. bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
  2287. if (LBO && LBO->getOpcode() == Instruction::Add) {
  2288. A = LBO->getOperand(0); B = LBO->getOperand(1);
  2289. NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
  2290. (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
  2291. (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
  2292. }
  2293. if (RBO && RBO->getOpcode() == Instruction::Add) {
  2294. C = RBO->getOperand(0); D = RBO->getOperand(1);
  2295. NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
  2296. (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
  2297. (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
  2298. }
  2299. // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
  2300. if ((A == RHS || B == RHS) && NoLHSWrapProblem)
  2301. if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
  2302. Constant::getNullValue(RHS->getType()),
  2303. Q, MaxRecurse-1))
  2304. return V;
  2305. // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
  2306. if ((C == LHS || D == LHS) && NoRHSWrapProblem)
  2307. if (Value *V = SimplifyICmpInst(Pred,
  2308. Constant::getNullValue(LHS->getType()),
  2309. C == LHS ? D : C, Q, MaxRecurse-1))
  2310. return V;
  2311. // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
  2312. if (A && C && (A == C || A == D || B == C || B == D) &&
  2313. NoLHSWrapProblem && NoRHSWrapProblem) {
  2314. // Determine Y and Z in the form icmp (X+Y), (X+Z).
  2315. Value *Y, *Z;
  2316. if (A == C) {
  2317. // C + B == C + D -> B == D
  2318. Y = B;
  2319. Z = D;
  2320. } else if (A == D) {
  2321. // D + B == C + D -> B == C
  2322. Y = B;
  2323. Z = C;
  2324. } else if (B == C) {
  2325. // A + C == C + D -> A == D
  2326. Y = A;
  2327. Z = D;
  2328. } else {
  2329. assert(B == D);
  2330. // A + D == C + D -> A == C
  2331. Y = A;
  2332. Z = C;
  2333. }
  2334. if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
  2335. return V;
  2336. }
  2337. }
  2338. // icmp pred (or X, Y), X
  2339. if (LBO && match(LBO, m_CombineOr(m_Or(m_Value(), m_Specific(RHS)),
  2340. m_Or(m_Specific(RHS), m_Value())))) {
  2341. if (Pred == ICmpInst::ICMP_ULT)
  2342. return getFalse(ITy);
  2343. if (Pred == ICmpInst::ICMP_UGE)
  2344. return getTrue(ITy);
  2345. }
  2346. // icmp pred X, (or X, Y)
  2347. if (RBO && match(RBO, m_CombineOr(m_Or(m_Value(), m_Specific(LHS)),
  2348. m_Or(m_Specific(LHS), m_Value())))) {
  2349. if (Pred == ICmpInst::ICMP_ULE)
  2350. return getTrue(ITy);
  2351. if (Pred == ICmpInst::ICMP_UGT)
  2352. return getFalse(ITy);
  2353. }
  2354. // icmp pred (and X, Y), X
  2355. if (LBO && match(LBO, m_CombineOr(m_And(m_Value(), m_Specific(RHS)),
  2356. m_And(m_Specific(RHS), m_Value())))) {
  2357. if (Pred == ICmpInst::ICMP_UGT)
  2358. return getFalse(ITy);
  2359. if (Pred == ICmpInst::ICMP_ULE)
  2360. return getTrue(ITy);
  2361. }
  2362. // icmp pred X, (and X, Y)
  2363. if (RBO && match(RBO, m_CombineOr(m_And(m_Value(), m_Specific(LHS)),
  2364. m_And(m_Specific(LHS), m_Value())))) {
  2365. if (Pred == ICmpInst::ICMP_UGE)
  2366. return getTrue(ITy);
  2367. if (Pred == ICmpInst::ICMP_ULT)
  2368. return getFalse(ITy);
  2369. }
  2370. // 0 - (zext X) pred C
  2371. if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
  2372. if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
  2373. if (RHSC->getValue().isStrictlyPositive()) {
  2374. if (Pred == ICmpInst::ICMP_SLT)
  2375. return ConstantInt::getTrue(RHSC->getContext());
  2376. if (Pred == ICmpInst::ICMP_SGE)
  2377. return ConstantInt::getFalse(RHSC->getContext());
  2378. if (Pred == ICmpInst::ICMP_EQ)
  2379. return ConstantInt::getFalse(RHSC->getContext());
  2380. if (Pred == ICmpInst::ICMP_NE)
  2381. return ConstantInt::getTrue(RHSC->getContext());
  2382. }
  2383. if (RHSC->getValue().isNonNegative()) {
  2384. if (Pred == ICmpInst::ICMP_SLE)
  2385. return ConstantInt::getTrue(RHSC->getContext());
  2386. if (Pred == ICmpInst::ICMP_SGT)
  2387. return ConstantInt::getFalse(RHSC->getContext());
  2388. }
  2389. }
  2390. }
  2391. // icmp pred (urem X, Y), Y
  2392. if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
  2393. bool KnownNonNegative, KnownNegative;
  2394. switch (Pred) {
  2395. default:
  2396. break;
  2397. case ICmpInst::ICMP_SGT:
  2398. case ICmpInst::ICMP_SGE:
  2399. ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
  2400. Q.CxtI, Q.DT);
  2401. if (!KnownNonNegative)
  2402. break;
  2403. // fall-through
  2404. case ICmpInst::ICMP_EQ:
  2405. case ICmpInst::ICMP_UGT:
  2406. case ICmpInst::ICMP_UGE:
  2407. return getFalse(ITy);
  2408. case ICmpInst::ICMP_SLT:
  2409. case ICmpInst::ICMP_SLE:
  2410. ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
  2411. Q.CxtI, Q.DT);
  2412. if (!KnownNonNegative)
  2413. break;
  2414. // fall-through
  2415. case ICmpInst::ICMP_NE:
  2416. case ICmpInst::ICMP_ULT:
  2417. case ICmpInst::ICMP_ULE:
  2418. return getTrue(ITy);
  2419. }
  2420. }
  2421. // icmp pred X, (urem Y, X)
  2422. if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
  2423. bool KnownNonNegative, KnownNegative;
  2424. switch (Pred) {
  2425. default:
  2426. break;
  2427. case ICmpInst::ICMP_SGT:
  2428. case ICmpInst::ICMP_SGE:
  2429. ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
  2430. Q.CxtI, Q.DT);
  2431. if (!KnownNonNegative)
  2432. break;
  2433. // fall-through
  2434. case ICmpInst::ICMP_NE:
  2435. case ICmpInst::ICMP_UGT:
  2436. case ICmpInst::ICMP_UGE:
  2437. return getTrue(ITy);
  2438. case ICmpInst::ICMP_SLT:
  2439. case ICmpInst::ICMP_SLE:
  2440. ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
  2441. Q.CxtI, Q.DT);
  2442. if (!KnownNonNegative)
  2443. break;
  2444. // fall-through
  2445. case ICmpInst::ICMP_EQ:
  2446. case ICmpInst::ICMP_ULT:
  2447. case ICmpInst::ICMP_ULE:
  2448. return getFalse(ITy);
  2449. }
  2450. }
  2451. // x udiv y <=u x.
  2452. if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
  2453. // icmp pred (X /u Y), X
  2454. if (Pred == ICmpInst::ICMP_UGT)
  2455. return getFalse(ITy);
  2456. if (Pred == ICmpInst::ICMP_ULE)
  2457. return getTrue(ITy);
  2458. }
  2459. // handle:
  2460. // CI2 << X == CI
  2461. // CI2 << X != CI
  2462. //
  2463. // where CI2 is a power of 2 and CI isn't
  2464. if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
  2465. const APInt *CI2Val, *CIVal = &CI->getValue();
  2466. if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
  2467. CI2Val->isPowerOf2()) {
  2468. if (!CIVal->isPowerOf2()) {
  2469. // CI2 << X can equal zero in some circumstances,
  2470. // this simplification is unsafe if CI is zero.
  2471. //
  2472. // We know it is safe if:
  2473. // - The shift is nsw, we can't shift out the one bit.
  2474. // - The shift is nuw, we can't shift out the one bit.
  2475. // - CI2 is one
  2476. // - CI isn't zero
  2477. if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
  2478. *CI2Val == 1 || !CI->isZero()) {
  2479. if (Pred == ICmpInst::ICMP_EQ)
  2480. return ConstantInt::getFalse(RHS->getContext());
  2481. if (Pred == ICmpInst::ICMP_NE)
  2482. return ConstantInt::getTrue(RHS->getContext());
  2483. }
  2484. }
  2485. if (CIVal->isSignBit() && *CI2Val == 1) {
  2486. if (Pred == ICmpInst::ICMP_UGT)
  2487. return ConstantInt::getFalse(RHS->getContext());
  2488. if (Pred == ICmpInst::ICMP_ULE)
  2489. return ConstantInt::getTrue(RHS->getContext());
  2490. }
  2491. }
  2492. }
  2493. if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
  2494. LBO->getOperand(1) == RBO->getOperand(1)) {
  2495. switch (LBO->getOpcode()) {
  2496. default: break;
  2497. case Instruction::UDiv:
  2498. case Instruction::LShr:
  2499. if (ICmpInst::isSigned(Pred))
  2500. break;
  2501. // fall-through
  2502. case Instruction::SDiv:
  2503. case Instruction::AShr:
  2504. if (!LBO->isExact() || !RBO->isExact())
  2505. break;
  2506. if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
  2507. RBO->getOperand(0), Q, MaxRecurse-1))
  2508. return V;
  2509. break;
  2510. case Instruction::Shl: {
  2511. bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
  2512. bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
  2513. if (!NUW && !NSW)
  2514. break;
  2515. if (!NSW && ICmpInst::isSigned(Pred))
  2516. break;
  2517. if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
  2518. RBO->getOperand(0), Q, MaxRecurse-1))
  2519. return V;
  2520. break;
  2521. }
  2522. }
  2523. }
  2524. // Simplify comparisons involving max/min.
  2525. Value *A, *B;
  2526. CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
  2527. CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
  2528. // Signed variants on "max(a,b)>=a -> true".
  2529. if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
  2530. if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
  2531. EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
  2532. // We analyze this as smax(A, B) pred A.
  2533. P = Pred;
  2534. } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
  2535. (A == LHS || B == LHS)) {
  2536. if (A != LHS) std::swap(A, B); // A pred smax(A, B).
  2537. EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
  2538. // We analyze this as smax(A, B) swapped-pred A.
  2539. P = CmpInst::getSwappedPredicate(Pred);
  2540. } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
  2541. (A == RHS || B == RHS)) {
  2542. if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
  2543. EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
  2544. // We analyze this as smax(-A, -B) swapped-pred -A.
  2545. // Note that we do not need to actually form -A or -B thanks to EqP.
  2546. P = CmpInst::getSwappedPredicate(Pred);
  2547. } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
  2548. (A == LHS || B == LHS)) {
  2549. if (A != LHS) std::swap(A, B); // A pred smin(A, B).
  2550. EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
  2551. // We analyze this as smax(-A, -B) pred -A.
  2552. // Note that we do not need to actually form -A or -B thanks to EqP.
  2553. P = Pred;
  2554. }
  2555. if (P != CmpInst::BAD_ICMP_PREDICATE) {
  2556. // Cases correspond to "max(A, B) p A".
  2557. switch (P) {
  2558. default:
  2559. break;
  2560. case CmpInst::ICMP_EQ:
  2561. case CmpInst::ICMP_SLE:
  2562. // Equivalent to "A EqP B". This may be the same as the condition tested
  2563. // in the max/min; if so, we can just return that.
  2564. if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
  2565. return V;
  2566. if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
  2567. return V;
  2568. // Otherwise, see if "A EqP B" simplifies.
  2569. if (MaxRecurse)
  2570. if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
  2571. return V;
  2572. break;
  2573. case CmpInst::ICMP_NE:
  2574. case CmpInst::ICMP_SGT: {
  2575. CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
  2576. // Equivalent to "A InvEqP B". This may be the same as the condition
  2577. // tested in the max/min; if so, we can just return that.
  2578. if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
  2579. return V;
  2580. if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
  2581. return V;
  2582. // Otherwise, see if "A InvEqP B" simplifies.
  2583. if (MaxRecurse)
  2584. if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
  2585. return V;
  2586. break;
  2587. }
  2588. case CmpInst::ICMP_SGE:
  2589. // Always true.
  2590. return getTrue(ITy);
  2591. case CmpInst::ICMP_SLT:
  2592. // Always false.
  2593. return getFalse(ITy);
  2594. }
  2595. }
  2596. // Unsigned variants on "max(a,b)>=a -> true".
  2597. P = CmpInst::BAD_ICMP_PREDICATE;
  2598. if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
  2599. if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
  2600. EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
  2601. // We analyze this as umax(A, B) pred A.
  2602. P = Pred;
  2603. } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
  2604. (A == LHS || B == LHS)) {
  2605. if (A != LHS) std::swap(A, B); // A pred umax(A, B).
  2606. EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
  2607. // We analyze this as umax(A, B) swapped-pred A.
  2608. P = CmpInst::getSwappedPredicate(Pred);
  2609. } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
  2610. (A == RHS || B == RHS)) {
  2611. if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
  2612. EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
  2613. // We analyze this as umax(-A, -B) swapped-pred -A.
  2614. // Note that we do not need to actually form -A or -B thanks to EqP.
  2615. P = CmpInst::getSwappedPredicate(Pred);
  2616. } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
  2617. (A == LHS || B == LHS)) {
  2618. if (A != LHS) std::swap(A, B); // A pred umin(A, B).
  2619. EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
  2620. // We analyze this as umax(-A, -B) pred -A.
  2621. // Note that we do not need to actually form -A or -B thanks to EqP.
  2622. P = Pred;
  2623. }
  2624. if (P != CmpInst::BAD_ICMP_PREDICATE) {
  2625. // Cases correspond to "max(A, B) p A".
  2626. switch (P) {
  2627. default:
  2628. break;
  2629. case CmpInst::ICMP_EQ:
  2630. case CmpInst::ICMP_ULE:
  2631. // Equivalent to "A EqP B". This may be the same as the condition tested
  2632. // in the max/min; if so, we can just return that.
  2633. if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
  2634. return V;
  2635. if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
  2636. return V;
  2637. // Otherwise, see if "A EqP B" simplifies.
  2638. if (MaxRecurse)
  2639. if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
  2640. return V;
  2641. break;
  2642. case CmpInst::ICMP_NE:
  2643. case CmpInst::ICMP_UGT: {
  2644. CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
  2645. // Equivalent to "A InvEqP B". This may be the same as the condition
  2646. // tested in the max/min; if so, we can just return that.
  2647. if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
  2648. return V;
  2649. if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
  2650. return V;
  2651. // Otherwise, see if "A InvEqP B" simplifies.
  2652. if (MaxRecurse)
  2653. if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
  2654. return V;
  2655. break;
  2656. }
  2657. case CmpInst::ICMP_UGE:
  2658. // Always true.
  2659. return getTrue(ITy);
  2660. case CmpInst::ICMP_ULT:
  2661. // Always false.
  2662. return getFalse(ITy);
  2663. }
  2664. }
  2665. // Variants on "max(x,y) >= min(x,z)".
  2666. Value *C, *D;
  2667. if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
  2668. match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
  2669. (A == C || A == D || B == C || B == D)) {
  2670. // max(x, ?) pred min(x, ?).
  2671. if (Pred == CmpInst::ICMP_SGE)
  2672. // Always true.
  2673. return getTrue(ITy);
  2674. if (Pred == CmpInst::ICMP_SLT)
  2675. // Always false.
  2676. return getFalse(ITy);
  2677. } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
  2678. match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
  2679. (A == C || A == D || B == C || B == D)) {
  2680. // min(x, ?) pred max(x, ?).
  2681. if (Pred == CmpInst::ICMP_SLE)
  2682. // Always true.
  2683. return getTrue(ITy);
  2684. if (Pred == CmpInst::ICMP_SGT)
  2685. // Always false.
  2686. return getFalse(ITy);
  2687. } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
  2688. match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
  2689. (A == C || A == D || B == C || B == D)) {
  2690. // max(x, ?) pred min(x, ?).
  2691. if (Pred == CmpInst::ICMP_UGE)
  2692. // Always true.
  2693. return getTrue(ITy);
  2694. if (Pred == CmpInst::ICMP_ULT)
  2695. // Always false.
  2696. return getFalse(ITy);
  2697. } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
  2698. match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
  2699. (A == C || A == D || B == C || B == D)) {
  2700. // min(x, ?) pred max(x, ?).
  2701. if (Pred == CmpInst::ICMP_ULE)
  2702. // Always true.
  2703. return getTrue(ITy);
  2704. if (Pred == CmpInst::ICMP_UGT)
  2705. // Always false.
  2706. return getFalse(ITy);
  2707. }
  2708. // Simplify comparisons of related pointers using a powerful, recursive
  2709. // GEP-walk when we have target data available..
  2710. if (LHS->getType()->isPointerTy())
  2711. if (Constant *C = computePointerICmp(Q.DL, Q.TLI, Pred, LHS, RHS))
  2712. return C;
  2713. if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
  2714. if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
  2715. if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
  2716. GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
  2717. (ICmpInst::isEquality(Pred) ||
  2718. (GLHS->isInBounds() && GRHS->isInBounds() &&
  2719. Pred == ICmpInst::getSignedPredicate(Pred)))) {
  2720. // The bases are equal and the indices are constant. Build a constant
  2721. // expression GEP with the same indices and a null base pointer to see
  2722. // what constant folding can make out of it.
  2723. Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
  2724. SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
  2725. Constant *NewLHS = ConstantExpr::getGetElementPtr(
  2726. GLHS->getSourceElementType(), Null, IndicesLHS);
  2727. SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
  2728. Constant *NewRHS = ConstantExpr::getGetElementPtr(
  2729. GLHS->getSourceElementType(), Null, IndicesRHS);
  2730. return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
  2731. }
  2732. }
  2733. }
  2734. // If a bit is known to be zero for A and known to be one for B,
  2735. // then A and B cannot be equal.
  2736. if (ICmpInst::isEquality(Pred)) {
  2737. if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
  2738. uint32_t BitWidth = CI->getBitWidth();
  2739. APInt LHSKnownZero(BitWidth, 0);
  2740. APInt LHSKnownOne(BitWidth, 0);
  2741. computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL, /*Depth=*/0, Q.AC,
  2742. Q.CxtI, Q.DT);
  2743. const APInt &RHSVal = CI->getValue();
  2744. if (((LHSKnownZero & RHSVal) != 0) || ((LHSKnownOne & ~RHSVal) != 0))
  2745. return Pred == ICmpInst::ICMP_EQ
  2746. ? ConstantInt::getFalse(CI->getContext())
  2747. : ConstantInt::getTrue(CI->getContext());
  2748. }
  2749. }
  2750. // If the comparison is with the result of a select instruction, check whether
  2751. // comparing with either branch of the select always yields the same value.
  2752. if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
  2753. if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
  2754. return V;
  2755. // If the comparison is with the result of a phi instruction, check whether
  2756. // doing the compare with each incoming phi value yields a common result.
  2757. if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
  2758. if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
  2759. return V;
  2760. return nullptr;
  2761. }
  2762. Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
  2763. const DataLayout &DL,
  2764. const TargetLibraryInfo *TLI,
  2765. const DominatorTree *DT, AssumptionCache *AC,
  2766. Instruction *CxtI) {
  2767. return ::SimplifyICmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
  2768. RecursionLimit);
  2769. }
  2770. /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
  2771. /// fold the result. If not, this returns null.
  2772. static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
  2773. FastMathFlags FMF, const Query &Q,
  2774. unsigned MaxRecurse) {
  2775. CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
  2776. assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
  2777. if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
  2778. if (Constant *CRHS = dyn_cast<Constant>(RHS))
  2779. return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
  2780. // If we have a constant, make sure it is on the RHS.
  2781. std::swap(LHS, RHS);
  2782. Pred = CmpInst::getSwappedPredicate(Pred);
  2783. }
  2784. // Fold trivial predicates.
  2785. if (Pred == FCmpInst::FCMP_FALSE)
  2786. return ConstantInt::get(GetCompareTy(LHS), 0);
  2787. if (Pred == FCmpInst::FCMP_TRUE)
  2788. return ConstantInt::get(GetCompareTy(LHS), 1);
  2789. // UNO/ORD predicates can be trivially folded if NaNs are ignored.
  2790. if (FMF.noNaNs()) {
  2791. if (Pred == FCmpInst::FCMP_UNO)
  2792. return ConstantInt::get(GetCompareTy(LHS), 0);
  2793. if (Pred == FCmpInst::FCMP_ORD)
  2794. return ConstantInt::get(GetCompareTy(LHS), 1);
  2795. }
  2796. // fcmp pred x, undef and fcmp pred undef, x
  2797. // fold to true if unordered, false if ordered
  2798. if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
  2799. // Choosing NaN for the undef will always make unordered comparison succeed
  2800. // and ordered comparison fail.
  2801. return ConstantInt::get(GetCompareTy(LHS), CmpInst::isUnordered(Pred));
  2802. }
  2803. // fcmp x,x -> true/false. Not all compares are foldable.
  2804. if (LHS == RHS) {
  2805. if (CmpInst::isTrueWhenEqual(Pred))
  2806. return ConstantInt::get(GetCompareTy(LHS), 1);
  2807. if (CmpInst::isFalseWhenEqual(Pred))
  2808. return ConstantInt::get(GetCompareTy(LHS), 0);
  2809. }
  2810. // Handle fcmp with constant RHS
  2811. if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
  2812. // If the constant is a nan, see if we can fold the comparison based on it.
  2813. if (CFP->getValueAPF().isNaN()) {
  2814. if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
  2815. return ConstantInt::getFalse(CFP->getContext());
  2816. assert(FCmpInst::isUnordered(Pred) &&
  2817. "Comparison must be either ordered or unordered!");
  2818. // True if unordered.
  2819. return ConstantInt::getTrue(CFP->getContext());
  2820. }
  2821. // Check whether the constant is an infinity.
  2822. if (CFP->getValueAPF().isInfinity()) {
  2823. if (CFP->getValueAPF().isNegative()) {
  2824. switch (Pred) {
  2825. case FCmpInst::FCMP_OLT:
  2826. // No value is ordered and less than negative infinity.
  2827. return ConstantInt::getFalse(CFP->getContext());
  2828. case FCmpInst::FCMP_UGE:
  2829. // All values are unordered with or at least negative infinity.
  2830. return ConstantInt::getTrue(CFP->getContext());
  2831. default:
  2832. break;
  2833. }
  2834. } else {
  2835. switch (Pred) {
  2836. case FCmpInst::FCMP_OGT:
  2837. // No value is ordered and greater than infinity.
  2838. return ConstantInt::getFalse(CFP->getContext());
  2839. case FCmpInst::FCMP_ULE:
  2840. // All values are unordered with and at most infinity.
  2841. return ConstantInt::getTrue(CFP->getContext());
  2842. default:
  2843. break;
  2844. }
  2845. }
  2846. }
  2847. if (CFP->getValueAPF().isZero()) {
  2848. switch (Pred) {
  2849. case FCmpInst::FCMP_UGE:
  2850. if (CannotBeOrderedLessThanZero(LHS))
  2851. return ConstantInt::getTrue(CFP->getContext());
  2852. break;
  2853. case FCmpInst::FCMP_OLT:
  2854. // X < 0
  2855. if (CannotBeOrderedLessThanZero(LHS))
  2856. return ConstantInt::getFalse(CFP->getContext());
  2857. break;
  2858. default:
  2859. break;
  2860. }
  2861. }
  2862. }
  2863. // If the comparison is with the result of a select instruction, check whether
  2864. // comparing with either branch of the select always yields the same value.
  2865. if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
  2866. if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
  2867. return V;
  2868. // If the comparison is with the result of a phi instruction, check whether
  2869. // doing the compare with each incoming phi value yields a common result.
  2870. if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
  2871. if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
  2872. return V;
  2873. return nullptr;
  2874. }
  2875. Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
  2876. FastMathFlags FMF, const DataLayout &DL,
  2877. const TargetLibraryInfo *TLI,
  2878. const DominatorTree *DT, AssumptionCache *AC,
  2879. const Instruction *CxtI) {
  2880. return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF,
  2881. Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
  2882. }
  2883. /// SimplifyWithOpReplaced - See if V simplifies when its operand Op is
  2884. /// replaced with RepOp.
  2885. static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
  2886. const Query &Q,
  2887. unsigned MaxRecurse) {
  2888. // Trivial replacement.
  2889. if (V == Op)
  2890. return RepOp;
  2891. auto *I = dyn_cast<Instruction>(V);
  2892. if (!I)
  2893. return nullptr;
  2894. // If this is a binary operator, try to simplify it with the replaced op.
  2895. if (auto *B = dyn_cast<BinaryOperator>(I)) {
  2896. // Consider:
  2897. // %cmp = icmp eq i32 %x, 2147483647
  2898. // %add = add nsw i32 %x, 1
  2899. // %sel = select i1 %cmp, i32 -2147483648, i32 %add
  2900. //
  2901. // We can't replace %sel with %add unless we strip away the flags.
  2902. if (isa<OverflowingBinaryOperator>(B))
  2903. if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
  2904. return nullptr;
  2905. if (isa<PossiblyExactOperator>(B))
  2906. if (B->isExact())
  2907. return nullptr;
  2908. if (MaxRecurse) {
  2909. if (B->getOperand(0) == Op)
  2910. return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
  2911. MaxRecurse - 1);
  2912. if (B->getOperand(1) == Op)
  2913. return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
  2914. MaxRecurse - 1);
  2915. }
  2916. }
  2917. // Same for CmpInsts.
  2918. if (CmpInst *C = dyn_cast<CmpInst>(I)) {
  2919. if (MaxRecurse) {
  2920. if (C->getOperand(0) == Op)
  2921. return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
  2922. MaxRecurse - 1);
  2923. if (C->getOperand(1) == Op)
  2924. return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
  2925. MaxRecurse - 1);
  2926. }
  2927. }
  2928. // TODO: We could hand off more cases to instsimplify here.
  2929. // If all operands are constant after substituting Op for RepOp then we can
  2930. // constant fold the instruction.
  2931. if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
  2932. // Build a list of all constant operands.
  2933. SmallVector<Constant *, 8> ConstOps;
  2934. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  2935. if (I->getOperand(i) == Op)
  2936. ConstOps.push_back(CRepOp);
  2937. else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
  2938. ConstOps.push_back(COp);
  2939. else
  2940. break;
  2941. }
  2942. // All operands were constants, fold it.
  2943. if (ConstOps.size() == I->getNumOperands()) {
  2944. if (CmpInst *C = dyn_cast<CmpInst>(I))
  2945. return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
  2946. ConstOps[1], Q.DL, Q.TLI);
  2947. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  2948. if (!LI->isVolatile())
  2949. return ConstantFoldLoadFromConstPtr(ConstOps[0], Q.DL);
  2950. return ConstantFoldInstOperands(I->getOpcode(), I->getType(), ConstOps,
  2951. Q.DL, Q.TLI);
  2952. }
  2953. }
  2954. return nullptr;
  2955. }
  2956. /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
  2957. /// the result. If not, this returns null.
  2958. static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
  2959. Value *FalseVal, const Query &Q,
  2960. unsigned MaxRecurse) {
  2961. // select true, X, Y -> X
  2962. // select false, X, Y -> Y
  2963. if (Constant *CB = dyn_cast<Constant>(CondVal)) {
  2964. if (CB->isAllOnesValue())
  2965. return TrueVal;
  2966. if (CB->isNullValue())
  2967. return FalseVal;
  2968. }
  2969. // select C, X, X -> X
  2970. if (TrueVal == FalseVal)
  2971. return TrueVal;
  2972. if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
  2973. if (isa<Constant>(TrueVal))
  2974. return TrueVal;
  2975. return FalseVal;
  2976. }
  2977. if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
  2978. return FalseVal;
  2979. if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
  2980. return TrueVal;
  2981. if (const auto *ICI = dyn_cast<ICmpInst>(CondVal)) {
  2982. unsigned BitWidth = Q.DL.getTypeSizeInBits(TrueVal->getType());
  2983. ICmpInst::Predicate Pred = ICI->getPredicate();
  2984. Value *CmpLHS = ICI->getOperand(0);
  2985. Value *CmpRHS = ICI->getOperand(1);
  2986. APInt MinSignedValue = APInt::getSignBit(BitWidth);
  2987. Value *X;
  2988. const APInt *Y;
  2989. bool TrueWhenUnset;
  2990. bool IsBitTest = false;
  2991. if (ICmpInst::isEquality(Pred) &&
  2992. match(CmpLHS, m_And(m_Value(X), m_APInt(Y))) &&
  2993. match(CmpRHS, m_Zero())) {
  2994. IsBitTest = true;
  2995. TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
  2996. } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
  2997. X = CmpLHS;
  2998. Y = &MinSignedValue;
  2999. IsBitTest = true;
  3000. TrueWhenUnset = false;
  3001. } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
  3002. X = CmpLHS;
  3003. Y = &MinSignedValue;
  3004. IsBitTest = true;
  3005. TrueWhenUnset = true;
  3006. }
  3007. if (IsBitTest) {
  3008. const APInt *C;
  3009. // (X & Y) == 0 ? X & ~Y : X --> X
  3010. // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
  3011. if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
  3012. *Y == ~*C)
  3013. return TrueWhenUnset ? FalseVal : TrueVal;
  3014. // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
  3015. // (X & Y) != 0 ? X : X & ~Y --> X
  3016. if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
  3017. *Y == ~*C)
  3018. return TrueWhenUnset ? FalseVal : TrueVal;
  3019. if (Y->isPowerOf2()) {
  3020. // (X & Y) == 0 ? X | Y : X --> X | Y
  3021. // (X & Y) != 0 ? X | Y : X --> X
  3022. if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
  3023. *Y == *C)
  3024. return TrueWhenUnset ? TrueVal : FalseVal;
  3025. // (X & Y) == 0 ? X : X | Y --> X
  3026. // (X & Y) != 0 ? X : X | Y --> X | Y
  3027. if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
  3028. *Y == *C)
  3029. return TrueWhenUnset ? TrueVal : FalseVal;
  3030. }
  3031. }
  3032. if (ICI->hasOneUse()) {
  3033. const APInt *C;
  3034. if (match(CmpRHS, m_APInt(C))) {
  3035. // X < MIN ? T : F --> F
  3036. if (Pred == ICmpInst::ICMP_SLT && C->isMinSignedValue())
  3037. return FalseVal;
  3038. // X < MIN ? T : F --> F
  3039. if (Pred == ICmpInst::ICMP_ULT && C->isMinValue())
  3040. return FalseVal;
  3041. // X > MAX ? T : F --> F
  3042. if (Pred == ICmpInst::ICMP_SGT && C->isMaxSignedValue())
  3043. return FalseVal;
  3044. // X > MAX ? T : F --> F
  3045. if (Pred == ICmpInst::ICMP_UGT && C->isMaxValue())
  3046. return FalseVal;
  3047. }
  3048. }
  3049. // If we have an equality comparison then we know the value in one of the
  3050. // arms of the select. See if substituting this value into the arm and
  3051. // simplifying the result yields the same value as the other arm.
  3052. if (Pred == ICmpInst::ICMP_EQ) {
  3053. if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
  3054. TrueVal ||
  3055. SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
  3056. TrueVal)
  3057. return FalseVal;
  3058. if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
  3059. FalseVal ||
  3060. SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
  3061. FalseVal)
  3062. return FalseVal;
  3063. } else if (Pred == ICmpInst::ICMP_NE) {
  3064. if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
  3065. FalseVal ||
  3066. SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
  3067. FalseVal)
  3068. return TrueVal;
  3069. if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
  3070. TrueVal ||
  3071. SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
  3072. TrueVal)
  3073. return TrueVal;
  3074. }
  3075. }
  3076. return nullptr;
  3077. }
  3078. Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
  3079. const DataLayout &DL,
  3080. const TargetLibraryInfo *TLI,
  3081. const DominatorTree *DT, AssumptionCache *AC,
  3082. const Instruction *CxtI) {
  3083. return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
  3084. Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
  3085. }
  3086. /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
  3087. /// fold the result. If not, this returns null.
  3088. static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
  3089. const Query &Q, unsigned) {
  3090. // The type of the GEP pointer operand.
  3091. unsigned AS =
  3092. cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
  3093. // getelementptr P -> P.
  3094. if (Ops.size() == 1)
  3095. return Ops[0];
  3096. // Compute the (pointer) type returned by the GEP instruction.
  3097. Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
  3098. Type *GEPTy = PointerType::get(LastType, AS);
  3099. if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
  3100. GEPTy = VectorType::get(GEPTy, VT->getNumElements());
  3101. if (isa<UndefValue>(Ops[0]))
  3102. return UndefValue::get(GEPTy);
  3103. if (Ops.size() == 2) {
  3104. // getelementptr P, 0 -> P.
  3105. if (match(Ops[1], m_Zero()))
  3106. return Ops[0];
  3107. Type *Ty = SrcTy;
  3108. if (Ty->isSized()) {
  3109. Value *P;
  3110. uint64_t C;
  3111. uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
  3112. // getelementptr P, N -> P if P points to a type of zero size.
  3113. if (TyAllocSize == 0)
  3114. return Ops[0];
  3115. // The following transforms are only safe if the ptrtoint cast
  3116. // doesn't truncate the pointers.
  3117. if (Ops[1]->getType()->getScalarSizeInBits() ==
  3118. Q.DL.getPointerSizeInBits(AS)) {
  3119. auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
  3120. if (match(P, m_Zero()))
  3121. return Constant::getNullValue(GEPTy);
  3122. Value *Temp;
  3123. if (match(P, m_PtrToInt(m_Value(Temp))))
  3124. if (Temp->getType() == GEPTy)
  3125. return Temp;
  3126. return nullptr;
  3127. };
  3128. // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
  3129. if (TyAllocSize == 1 &&
  3130. match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
  3131. if (Value *R = PtrToIntOrZero(P))
  3132. return R;
  3133. // getelementptr V, (ashr (sub P, V), C) -> Q
  3134. // if P points to a type of size 1 << C.
  3135. if (match(Ops[1],
  3136. m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
  3137. m_ConstantInt(C))) &&
  3138. TyAllocSize == 1ULL << C)
  3139. if (Value *R = PtrToIntOrZero(P))
  3140. return R;
  3141. // getelementptr V, (sdiv (sub P, V), C) -> Q
  3142. // if P points to a type of size C.
  3143. if (match(Ops[1],
  3144. m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
  3145. m_SpecificInt(TyAllocSize))))
  3146. if (Value *R = PtrToIntOrZero(P))
  3147. return R;
  3148. }
  3149. }
  3150. }
  3151. // Check to see if this is constant foldable.
  3152. for (unsigned i = 0, e = Ops.size(); i != e; ++i)
  3153. if (!isa<Constant>(Ops[i]))
  3154. return nullptr;
  3155. return ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
  3156. Ops.slice(1));
  3157. }
  3158. Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const DataLayout &DL,
  3159. const TargetLibraryInfo *TLI,
  3160. const DominatorTree *DT, AssumptionCache *AC,
  3161. const Instruction *CxtI) {
  3162. return ::SimplifyGEPInst(
  3163. cast<PointerType>(Ops[0]->getType()->getScalarType())->getElementType(),
  3164. Ops, Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
  3165. }
  3166. /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
  3167. /// can fold the result. If not, this returns null.
  3168. static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
  3169. ArrayRef<unsigned> Idxs, const Query &Q,
  3170. unsigned) {
  3171. if (Constant *CAgg = dyn_cast<Constant>(Agg))
  3172. if (Constant *CVal = dyn_cast<Constant>(Val))
  3173. return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
  3174. // insertvalue x, undef, n -> x
  3175. if (match(Val, m_Undef()))
  3176. return Agg;
  3177. // insertvalue x, (extractvalue y, n), n
  3178. if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
  3179. if (EV->getAggregateOperand()->getType() == Agg->getType() &&
  3180. EV->getIndices() == Idxs) {
  3181. // insertvalue undef, (extractvalue y, n), n -> y
  3182. if (match(Agg, m_Undef()))
  3183. return EV->getAggregateOperand();
  3184. // insertvalue y, (extractvalue y, n), n -> y
  3185. if (Agg == EV->getAggregateOperand())
  3186. return Agg;
  3187. }
  3188. return nullptr;
  3189. }
  3190. Value *llvm::SimplifyInsertValueInst(
  3191. Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, const DataLayout &DL,
  3192. const TargetLibraryInfo *TLI, const DominatorTree *DT, AssumptionCache *AC,
  3193. const Instruction *CxtI) {
  3194. return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query(DL, TLI, DT, AC, CxtI),
  3195. RecursionLimit);
  3196. }
  3197. /// SimplifyExtractValueInst - Given operands for an ExtractValueInst, see if we
  3198. /// can fold the result. If not, this returns null.
  3199. static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
  3200. const Query &, unsigned) {
  3201. if (auto *CAgg = dyn_cast<Constant>(Agg))
  3202. return ConstantFoldExtractValueInstruction(CAgg, Idxs);
  3203. // extractvalue x, (insertvalue y, elt, n), n -> elt
  3204. unsigned NumIdxs = Idxs.size();
  3205. for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
  3206. IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
  3207. ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
  3208. unsigned NumInsertValueIdxs = InsertValueIdxs.size();
  3209. unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
  3210. if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
  3211. Idxs.slice(0, NumCommonIdxs)) {
  3212. if (NumIdxs == NumInsertValueIdxs)
  3213. return IVI->getInsertedValueOperand();
  3214. break;
  3215. }
  3216. }
  3217. return nullptr;
  3218. }
  3219. Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
  3220. const DataLayout &DL,
  3221. const TargetLibraryInfo *TLI,
  3222. const DominatorTree *DT,
  3223. AssumptionCache *AC,
  3224. const Instruction *CxtI) {
  3225. return ::SimplifyExtractValueInst(Agg, Idxs, Query(DL, TLI, DT, AC, CxtI),
  3226. RecursionLimit);
  3227. }
  3228. /// SimplifyExtractElementInst - Given operands for an ExtractElementInst, see if we
  3229. /// can fold the result. If not, this returns null.
  3230. static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const Query &,
  3231. unsigned) {
  3232. if (auto *CVec = dyn_cast<Constant>(Vec)) {
  3233. if (auto *CIdx = dyn_cast<Constant>(Idx))
  3234. return ConstantFoldExtractElementInstruction(CVec, CIdx);
  3235. // The index is not relevant if our vector is a splat.
  3236. if (auto *Splat = CVec->getSplatValue())
  3237. return Splat;
  3238. if (isa<UndefValue>(Vec))
  3239. return UndefValue::get(Vec->getType()->getVectorElementType());
  3240. }
  3241. // If extracting a specified index from the vector, see if we can recursively
  3242. // find a previously computed scalar that was inserted into the vector.
  3243. if (auto *IdxC = dyn_cast<ConstantInt>(Idx))
  3244. if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
  3245. return Elt;
  3246. return nullptr;
  3247. }
  3248. Value *llvm::SimplifyExtractElementInst(
  3249. Value *Vec, Value *Idx, const DataLayout &DL, const TargetLibraryInfo *TLI,
  3250. const DominatorTree *DT, AssumptionCache *AC, const Instruction *CxtI) {
  3251. return ::SimplifyExtractElementInst(Vec, Idx, Query(DL, TLI, DT, AC, CxtI),
  3252. RecursionLimit);
  3253. }
  3254. /// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
  3255. static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
  3256. // If all of the PHI's incoming values are the same then replace the PHI node
  3257. // with the common value.
  3258. Value *CommonValue = nullptr;
  3259. bool HasUndefInput = false;
  3260. for (Value *Incoming : PN->incoming_values()) {
  3261. // If the incoming value is the phi node itself, it can safely be skipped.
  3262. if (Incoming == PN) continue;
  3263. if (isa<UndefValue>(Incoming)) {
  3264. // Remember that we saw an undef value, but otherwise ignore them.
  3265. HasUndefInput = true;
  3266. continue;
  3267. }
  3268. if (CommonValue && Incoming != CommonValue)
  3269. return nullptr; // Not the same, bail out.
  3270. CommonValue = Incoming;
  3271. }
  3272. // If CommonValue is null then all of the incoming values were either undef or
  3273. // equal to the phi node itself.
  3274. if (!CommonValue)
  3275. return UndefValue::get(PN->getType());
  3276. // If we have a PHI node like phi(X, undef, X), where X is defined by some
  3277. // instruction, we cannot return X as the result of the PHI node unless it
  3278. // dominates the PHI block.
  3279. if (HasUndefInput)
  3280. return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
  3281. return CommonValue;
  3282. }
  3283. static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
  3284. if (Constant *C = dyn_cast<Constant>(Op))
  3285. return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.DL, Q.TLI);
  3286. return nullptr;
  3287. }
  3288. Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout &DL,
  3289. const TargetLibraryInfo *TLI,
  3290. const DominatorTree *DT, AssumptionCache *AC,
  3291. const Instruction *CxtI) {
  3292. return ::SimplifyTruncInst(Op, Ty, Query(DL, TLI, DT, AC, CxtI),
  3293. RecursionLimit);
  3294. }
  3295. //=== Helper functions for higher up the class hierarchy.
  3296. /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
  3297. /// fold the result. If not, this returns null.
  3298. static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
  3299. const Query &Q, unsigned MaxRecurse) {
  3300. switch (Opcode) {
  3301. case Instruction::Add:
  3302. return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
  3303. Q, MaxRecurse);
  3304. case Instruction::FAdd:
  3305. return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
  3306. case Instruction::Sub:
  3307. return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
  3308. Q, MaxRecurse);
  3309. case Instruction::FSub:
  3310. return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
  3311. case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
  3312. case Instruction::FMul:
  3313. return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
  3314. case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
  3315. case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
  3316. case Instruction::FDiv:
  3317. return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
  3318. case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
  3319. case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
  3320. case Instruction::FRem:
  3321. return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
  3322. case Instruction::Shl:
  3323. return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
  3324. Q, MaxRecurse);
  3325. case Instruction::LShr:
  3326. return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
  3327. case Instruction::AShr:
  3328. return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
  3329. case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
  3330. case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
  3331. case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
  3332. default:
  3333. if (Constant *CLHS = dyn_cast<Constant>(LHS))
  3334. if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
  3335. Constant *COps[] = {CLHS, CRHS};
  3336. return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.DL,
  3337. Q.TLI);
  3338. }
  3339. // If the operation is associative, try some generic simplifications.
  3340. if (Instruction::isAssociative(Opcode))
  3341. if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
  3342. return V;
  3343. // If the operation is with the result of a select instruction check whether
  3344. // operating on either branch of the select always yields the same value.
  3345. if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
  3346. if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
  3347. return V;
  3348. // If the operation is with the result of a phi instruction, check whether
  3349. // operating on all incoming values of the phi always yields the same value.
  3350. if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
  3351. if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
  3352. return V;
  3353. return nullptr;
  3354. }
  3355. }
  3356. /// SimplifyFPBinOp - Given operands for a BinaryOperator, see if we can
  3357. /// fold the result. If not, this returns null.
  3358. /// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
  3359. /// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
  3360. static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
  3361. const FastMathFlags &FMF, const Query &Q,
  3362. unsigned MaxRecurse) {
  3363. switch (Opcode) {
  3364. case Instruction::FAdd:
  3365. return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
  3366. case Instruction::FSub:
  3367. return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
  3368. case Instruction::FMul:
  3369. return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
  3370. default:
  3371. return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
  3372. }
  3373. }
  3374. Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
  3375. const DataLayout &DL, const TargetLibraryInfo *TLI,
  3376. const DominatorTree *DT, AssumptionCache *AC,
  3377. const Instruction *CxtI) {
  3378. return ::SimplifyBinOp(Opcode, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
  3379. RecursionLimit);
  3380. }
  3381. Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
  3382. const FastMathFlags &FMF, const DataLayout &DL,
  3383. const TargetLibraryInfo *TLI,
  3384. const DominatorTree *DT, AssumptionCache *AC,
  3385. const Instruction *CxtI) {
  3386. return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Query(DL, TLI, DT, AC, CxtI),
  3387. RecursionLimit);
  3388. }
  3389. /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
  3390. /// fold the result.
  3391. static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
  3392. const Query &Q, unsigned MaxRecurse) {
  3393. if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
  3394. return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
  3395. return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
  3396. }
  3397. Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
  3398. const DataLayout &DL, const TargetLibraryInfo *TLI,
  3399. const DominatorTree *DT, AssumptionCache *AC,
  3400. const Instruction *CxtI) {
  3401. return ::SimplifyCmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
  3402. RecursionLimit);
  3403. }
  3404. static bool IsIdempotent(Intrinsic::ID ID) {
  3405. switch (ID) {
  3406. default: return false;
  3407. // Unary idempotent: f(f(x)) = f(x)
  3408. case Intrinsic::fabs:
  3409. case Intrinsic::floor:
  3410. case Intrinsic::ceil:
  3411. case Intrinsic::trunc:
  3412. case Intrinsic::rint:
  3413. case Intrinsic::nearbyint:
  3414. case Intrinsic::round:
  3415. return true;
  3416. }
  3417. }
  3418. template <typename IterTy>
  3419. static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
  3420. const Query &Q, unsigned MaxRecurse) {
  3421. Intrinsic::ID IID = F->getIntrinsicID();
  3422. unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
  3423. Type *ReturnType = F->getReturnType();
  3424. // Binary Ops
  3425. if (NumOperands == 2) {
  3426. Value *LHS = *ArgBegin;
  3427. Value *RHS = *(ArgBegin + 1);
  3428. if (IID == Intrinsic::usub_with_overflow ||
  3429. IID == Intrinsic::ssub_with_overflow) {
  3430. // X - X -> { 0, false }
  3431. if (LHS == RHS)
  3432. return Constant::getNullValue(ReturnType);
  3433. // X - undef -> undef
  3434. // undef - X -> undef
  3435. if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
  3436. return UndefValue::get(ReturnType);
  3437. }
  3438. if (IID == Intrinsic::uadd_with_overflow ||
  3439. IID == Intrinsic::sadd_with_overflow) {
  3440. // X + undef -> undef
  3441. if (isa<UndefValue>(RHS))
  3442. return UndefValue::get(ReturnType);
  3443. }
  3444. if (IID == Intrinsic::umul_with_overflow ||
  3445. IID == Intrinsic::smul_with_overflow) {
  3446. // X * 0 -> { 0, false }
  3447. if (match(RHS, m_Zero()))
  3448. return Constant::getNullValue(ReturnType);
  3449. // X * undef -> { 0, false }
  3450. if (match(RHS, m_Undef()))
  3451. return Constant::getNullValue(ReturnType);
  3452. }
  3453. }
  3454. // Perform idempotent optimizations
  3455. if (!IsIdempotent(IID))
  3456. return nullptr;
  3457. // Unary Ops
  3458. if (NumOperands == 1)
  3459. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
  3460. if (II->getIntrinsicID() == IID)
  3461. return II;
  3462. return nullptr;
  3463. }
  3464. template <typename IterTy>
  3465. static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
  3466. const Query &Q, unsigned MaxRecurse) {
  3467. Type *Ty = V->getType();
  3468. if (PointerType *PTy = dyn_cast<PointerType>(Ty))
  3469. Ty = PTy->getElementType();
  3470. FunctionType *FTy = cast<FunctionType>(Ty);
  3471. // call undef -> undef
  3472. if (isa<UndefValue>(V))
  3473. return UndefValue::get(FTy->getReturnType());
  3474. Function *F = dyn_cast<Function>(V);
  3475. if (!F)
  3476. return nullptr;
  3477. if (F->isIntrinsic())
  3478. if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse))
  3479. return Ret;
  3480. if (!canConstantFoldCallTo(F))
  3481. return nullptr;
  3482. SmallVector<Constant *, 4> ConstantArgs;
  3483. ConstantArgs.reserve(ArgEnd - ArgBegin);
  3484. for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
  3485. Constant *C = dyn_cast<Constant>(*I);
  3486. if (!C)
  3487. return nullptr;
  3488. ConstantArgs.push_back(C);
  3489. }
  3490. return ConstantFoldCall(F, ConstantArgs, Q.TLI);
  3491. }
  3492. Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
  3493. User::op_iterator ArgEnd, const DataLayout &DL,
  3494. const TargetLibraryInfo *TLI, const DominatorTree *DT,
  3495. AssumptionCache *AC, const Instruction *CxtI) {
  3496. return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AC, CxtI),
  3497. RecursionLimit);
  3498. }
  3499. Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
  3500. const DataLayout &DL, const TargetLibraryInfo *TLI,
  3501. const DominatorTree *DT, AssumptionCache *AC,
  3502. const Instruction *CxtI) {
  3503. return ::SimplifyCall(V, Args.begin(), Args.end(),
  3504. Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
  3505. }
  3506. /// SimplifyInstruction - See if we can compute a simplified version of this
  3507. /// instruction. If not, this returns null.
  3508. Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout &DL,
  3509. const TargetLibraryInfo *TLI,
  3510. const DominatorTree *DT, AssumptionCache *AC) {
  3511. Value *Result;
  3512. switch (I->getOpcode()) {
  3513. default:
  3514. Result = ConstantFoldInstruction(I, DL, TLI);
  3515. break;
  3516. case Instruction::FAdd:
  3517. Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
  3518. I->getFastMathFlags(), DL, TLI, DT, AC, I);
  3519. break;
  3520. case Instruction::Add:
  3521. Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
  3522. cast<BinaryOperator>(I)->hasNoSignedWrap(),
  3523. cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
  3524. TLI, DT, AC, I);
  3525. break;
  3526. case Instruction::FSub:
  3527. Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
  3528. I->getFastMathFlags(), DL, TLI, DT, AC, I);
  3529. break;
  3530. case Instruction::Sub:
  3531. Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
  3532. cast<BinaryOperator>(I)->hasNoSignedWrap(),
  3533. cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
  3534. TLI, DT, AC, I);
  3535. break;
  3536. case Instruction::FMul:
  3537. Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
  3538. I->getFastMathFlags(), DL, TLI, DT, AC, I);
  3539. break;
  3540. case Instruction::Mul:
  3541. Result =
  3542. SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
  3543. break;
  3544. case Instruction::SDiv:
  3545. Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
  3546. AC, I);
  3547. break;
  3548. case Instruction::UDiv:
  3549. Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
  3550. AC, I);
  3551. break;
  3552. case Instruction::FDiv:
  3553. Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
  3554. I->getFastMathFlags(), DL, TLI, DT, AC, I);
  3555. break;
  3556. case Instruction::SRem:
  3557. Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
  3558. AC, I);
  3559. break;
  3560. case Instruction::URem:
  3561. Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
  3562. AC, I);
  3563. break;
  3564. case Instruction::FRem:
  3565. Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
  3566. I->getFastMathFlags(), DL, TLI, DT, AC, I);
  3567. break;
  3568. case Instruction::Shl:
  3569. Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
  3570. cast<BinaryOperator>(I)->hasNoSignedWrap(),
  3571. cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
  3572. TLI, DT, AC, I);
  3573. break;
  3574. case Instruction::LShr:
  3575. Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
  3576. cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
  3577. AC, I);
  3578. break;
  3579. case Instruction::AShr:
  3580. Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
  3581. cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
  3582. AC, I);
  3583. break;
  3584. case Instruction::And:
  3585. Result =
  3586. SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
  3587. break;
  3588. case Instruction::Or:
  3589. Result =
  3590. SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
  3591. break;
  3592. case Instruction::Xor:
  3593. Result =
  3594. SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
  3595. break;
  3596. case Instruction::ICmp:
  3597. Result =
  3598. SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), I->getOperand(0),
  3599. I->getOperand(1), DL, TLI, DT, AC, I);
  3600. break;
  3601. case Instruction::FCmp:
  3602. Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
  3603. I->getOperand(0), I->getOperand(1),
  3604. I->getFastMathFlags(), DL, TLI, DT, AC, I);
  3605. break;
  3606. case Instruction::Select:
  3607. Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
  3608. I->getOperand(2), DL, TLI, DT, AC, I);
  3609. break;
  3610. case Instruction::GetElementPtr: {
  3611. SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
  3612. Result = SimplifyGEPInst(Ops, DL, TLI, DT, AC, I);
  3613. break;
  3614. }
  3615. case Instruction::InsertValue: {
  3616. InsertValueInst *IV = cast<InsertValueInst>(I);
  3617. Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
  3618. IV->getInsertedValueOperand(),
  3619. IV->getIndices(), DL, TLI, DT, AC, I);
  3620. break;
  3621. }
  3622. case Instruction::ExtractValue: {
  3623. auto *EVI = cast<ExtractValueInst>(I);
  3624. Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
  3625. EVI->getIndices(), DL, TLI, DT, AC, I);
  3626. break;
  3627. }
  3628. case Instruction::ExtractElement: {
  3629. auto *EEI = cast<ExtractElementInst>(I);
  3630. Result = SimplifyExtractElementInst(
  3631. EEI->getVectorOperand(), EEI->getIndexOperand(), DL, TLI, DT, AC, I);
  3632. break;
  3633. }
  3634. case Instruction::PHI:
  3635. Result = SimplifyPHINode(cast<PHINode>(I), Query(DL, TLI, DT, AC, I));
  3636. break;
  3637. case Instruction::Call: {
  3638. CallSite CS(cast<CallInst>(I));
  3639. Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), DL,
  3640. TLI, DT, AC, I);
  3641. break;
  3642. }
  3643. case Instruction::Trunc:
  3644. Result =
  3645. SimplifyTruncInst(I->getOperand(0), I->getType(), DL, TLI, DT, AC, I);
  3646. break;
  3647. }
  3648. /// If called on unreachable code, the above logic may report that the
  3649. /// instruction simplified to itself. Make life easier for users by
  3650. /// detecting that case here, returning a safe value instead.
  3651. return Result == I ? UndefValue::get(I->getType()) : Result;
  3652. }
  3653. /// \brief Implementation of recursive simplification through an instructions
  3654. /// uses.
  3655. ///
  3656. /// This is the common implementation of the recursive simplification routines.
  3657. /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
  3658. /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
  3659. /// instructions to process and attempt to simplify it using
  3660. /// InstructionSimplify.
  3661. ///
  3662. /// This routine returns 'true' only when *it* simplifies something. The passed
  3663. /// in simplified value does not count toward this.
  3664. static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
  3665. const TargetLibraryInfo *TLI,
  3666. const DominatorTree *DT,
  3667. AssumptionCache *AC) {
  3668. bool Simplified = false;
  3669. SmallSetVector<Instruction *, 8> Worklist;
  3670. const DataLayout &DL = I->getModule()->getDataLayout();
  3671. // If we have an explicit value to collapse to, do that round of the
  3672. // simplification loop by hand initially.
  3673. if (SimpleV) {
  3674. for (User *U : I->users())
  3675. if (U != I)
  3676. Worklist.insert(cast<Instruction>(U));
  3677. // Replace the instruction with its simplified value.
  3678. I->replaceAllUsesWith(SimpleV);
  3679. // Gracefully handle edge cases where the instruction is not wired into any
  3680. // parent block.
  3681. if (I->getParent())
  3682. I->eraseFromParent();
  3683. } else {
  3684. Worklist.insert(I);
  3685. }
  3686. // Note that we must test the size on each iteration, the worklist can grow.
  3687. for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
  3688. I = Worklist[Idx];
  3689. // See if this instruction simplifies.
  3690. SimpleV = SimplifyInstruction(I, DL, TLI, DT, AC);
  3691. if (!SimpleV)
  3692. continue;
  3693. Simplified = true;
  3694. // Stash away all the uses of the old instruction so we can check them for
  3695. // recursive simplifications after a RAUW. This is cheaper than checking all
  3696. // uses of To on the recursive step in most cases.
  3697. for (User *U : I->users())
  3698. Worklist.insert(cast<Instruction>(U));
  3699. // Replace the instruction with its simplified value.
  3700. I->replaceAllUsesWith(SimpleV);
  3701. // Gracefully handle edge cases where the instruction is not wired into any
  3702. // parent block.
  3703. if (I->getParent())
  3704. I->eraseFromParent();
  3705. }
  3706. return Simplified;
  3707. }
  3708. bool llvm::recursivelySimplifyInstruction(Instruction *I,
  3709. const TargetLibraryInfo *TLI,
  3710. const DominatorTree *DT,
  3711. AssumptionCache *AC) {
  3712. return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
  3713. }
  3714. bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
  3715. const TargetLibraryInfo *TLI,
  3716. const DominatorTree *DT,
  3717. AssumptionCache *AC) {
  3718. assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
  3719. assert(SimpleV && "Must provide a simplified value.");
  3720. return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
  3721. }