InstructionSimplify.cpp 158 KB

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