InstructionSimplify.cpp 170 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511
  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. // HLSL Change - Begin
  3508. // Copied CastInst simplification from LLVM 8
  3509. static
  3510. Constant *foldConstVectorToAPInt(APInt &Result, Type *DestTy,
  3511. Constant *C, Type *SrcEltTy,
  3512. unsigned NumSrcElts,
  3513. const DataLayout &DL) {
  3514. // Now that we know that the input value is a vector of integers, just shift
  3515. // and insert them into our result.
  3516. unsigned BitShift = DL.getTypeSizeInBits(SrcEltTy);
  3517. for (unsigned i = 0; i != NumSrcElts; ++i) {
  3518. Constant *Element;
  3519. if (DL.isLittleEndian())
  3520. Element = C->getAggregateElement(NumSrcElts - i - 1);
  3521. else
  3522. Element = C->getAggregateElement(i);
  3523. if (Element && isa<UndefValue>(Element)) {
  3524. Result <<= BitShift;
  3525. continue;
  3526. }
  3527. auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
  3528. if (!ElementCI)
  3529. return ConstantExpr::getBitCast(C, DestTy);
  3530. Result <<= BitShift;
  3531. Result |= ElementCI->getValue().zextOrSelf(Result.getBitWidth());
  3532. }
  3533. return nullptr;
  3534. }
  3535. /// Constant fold bitcast, symbolically evaluating it with DataLayout.
  3536. /// This always returns a non-null constant, but it may be a
  3537. /// ConstantExpr if unfoldable.
  3538. static
  3539. Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
  3540. // Catch the obvious splat cases.
  3541. if (C->isNullValue() && !DestTy->isX86_MMXTy())
  3542. return Constant::getNullValue(DestTy);
  3543. if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() &&
  3544. !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types!
  3545. return Constant::getAllOnesValue(DestTy);
  3546. if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
  3547. // Handle a vector->scalar integer/fp cast.
  3548. if (isa<IntegerType>(DestTy) || DestTy->isFloatingPointTy()) {
  3549. unsigned NumSrcElts = VTy->getNumElements();
  3550. Type *SrcEltTy = VTy->getElementType();
  3551. // If the vector is a vector of floating point, convert it to vector of int
  3552. // to simplify things.
  3553. if (SrcEltTy->isFloatingPointTy()) {
  3554. unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
  3555. Type *SrcIVTy =
  3556. VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
  3557. // Ask IR to do the conversion now that #elts line up.
  3558. C = ConstantExpr::getBitCast(C, SrcIVTy);
  3559. }
  3560. APInt Result(DL.getTypeSizeInBits(DestTy), 0);
  3561. if (Constant *CE = foldConstVectorToAPInt(Result, DestTy, C,
  3562. SrcEltTy, NumSrcElts, DL))
  3563. return CE;
  3564. if (isa<IntegerType>(DestTy))
  3565. return ConstantInt::get(DestTy, Result);
  3566. APFloat FP(DestTy->getFltSemantics(), Result);
  3567. return ConstantFP::get(DestTy->getContext(), FP);
  3568. }
  3569. }
  3570. // The code below only handles casts to vectors currently.
  3571. auto *DestVTy = dyn_cast<VectorType>(DestTy);
  3572. if (!DestVTy)
  3573. return ConstantExpr::getBitCast(C, DestTy);
  3574. // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
  3575. // vector so the code below can handle it uniformly.
  3576. if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
  3577. Constant *Ops = C; // don't take the address of C!
  3578. return FoldBitCast(ConstantVector::get(Ops), DestTy, DL);
  3579. }
  3580. // If this is a bitcast from constant vector -> vector, fold it.
  3581. if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
  3582. return ConstantExpr::getBitCast(C, DestTy);
  3583. // If the element types match, IR can fold it.
  3584. unsigned NumDstElt = DestVTy->getNumElements();
  3585. unsigned NumSrcElt = C->getType()->getVectorNumElements();
  3586. if (NumDstElt == NumSrcElt)
  3587. return ConstantExpr::getBitCast(C, DestTy);
  3588. Type *SrcEltTy = C->getType()->getVectorElementType();
  3589. Type *DstEltTy = DestVTy->getElementType();
  3590. // Otherwise, we're changing the number of elements in a vector, which
  3591. // requires endianness information to do the right thing. For example,
  3592. // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
  3593. // folds to (little endian):
  3594. // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
  3595. // and to (big endian):
  3596. // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
  3597. // First thing is first. We only want to think about integer here, so if
  3598. // we have something in FP form, recast it as integer.
  3599. if (DstEltTy->isFloatingPointTy()) {
  3600. // Fold to an vector of integers with same size as our FP type.
  3601. unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
  3602. Type *DestIVTy =
  3603. VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
  3604. // Recursively handle this integer conversion, if possible.
  3605. C = FoldBitCast(C, DestIVTy, DL);
  3606. // Finally, IR can handle this now that #elts line up.
  3607. return ConstantExpr::getBitCast(C, DestTy);
  3608. }
  3609. // Okay, we know the destination is integer, if the input is FP, convert
  3610. // it to integer first.
  3611. if (SrcEltTy->isFloatingPointTy()) {
  3612. unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
  3613. Type *SrcIVTy =
  3614. VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
  3615. // Ask IR to do the conversion now that #elts line up.
  3616. C = ConstantExpr::getBitCast(C, SrcIVTy);
  3617. // If IR wasn't able to fold it, bail out.
  3618. if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector.
  3619. !isa<ConstantDataVector>(C))
  3620. return C;
  3621. }
  3622. // Now we know that the input and output vectors are both integer vectors
  3623. // of the same size, and that their #elements is not the same. Do the
  3624. // conversion here, which depends on whether the input or output has
  3625. // more elements.
  3626. bool isLittleEndian = DL.isLittleEndian();
  3627. SmallVector<Constant*, 32> Result;
  3628. if (NumDstElt < NumSrcElt) {
  3629. // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
  3630. Constant *Zero = Constant::getNullValue(DstEltTy);
  3631. unsigned Ratio = NumSrcElt/NumDstElt;
  3632. unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
  3633. unsigned SrcElt = 0;
  3634. for (unsigned i = 0; i != NumDstElt; ++i) {
  3635. // Build each element of the result.
  3636. Constant *Elt = Zero;
  3637. unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
  3638. for (unsigned j = 0; j != Ratio; ++j) {
  3639. Constant *Src = C->getAggregateElement(SrcElt++);
  3640. if (Src && isa<UndefValue>(Src))
  3641. Src = Constant::getNullValue(C->getType()->getVectorElementType());
  3642. else
  3643. Src = dyn_cast_or_null<ConstantInt>(Src);
  3644. if (!Src) // Reject constantexpr elements.
  3645. return ConstantExpr::getBitCast(C, DestTy);
  3646. // Zero extend the element to the right size.
  3647. Src = ConstantExpr::getZExt(Src, Elt->getType());
  3648. // Shift it to the right place, depending on endianness.
  3649. Src = ConstantExpr::getShl(Src,
  3650. ConstantInt::get(Src->getType(), ShiftAmt));
  3651. ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
  3652. // Mix it in.
  3653. Elt = ConstantExpr::getOr(Elt, Src);
  3654. }
  3655. Result.push_back(Elt);
  3656. }
  3657. return ConstantVector::get(Result);
  3658. }
  3659. // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
  3660. unsigned Ratio = NumDstElt/NumSrcElt;
  3661. unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy);
  3662. // Loop over each source value, expanding into multiple results.
  3663. for (unsigned i = 0; i != NumSrcElt; ++i) {
  3664. auto *Element = C->getAggregateElement(i);
  3665. if (!Element) // Reject constantexpr elements.
  3666. return ConstantExpr::getBitCast(C, DestTy);
  3667. if (isa<UndefValue>(Element)) {
  3668. // Correctly Propagate undef values.
  3669. Result.append(Ratio, UndefValue::get(DstEltTy));
  3670. continue;
  3671. }
  3672. auto *Src = dyn_cast<ConstantInt>(Element);
  3673. if (!Src)
  3674. return ConstantExpr::getBitCast(C, DestTy);
  3675. unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
  3676. for (unsigned j = 0; j != Ratio; ++j) {
  3677. // Shift the piece of the value into the right place, depending on
  3678. // endianness.
  3679. Constant *Elt = ConstantExpr::getLShr(Src,
  3680. ConstantInt::get(Src->getType(), ShiftAmt));
  3681. ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
  3682. // Truncate the element to an integer with the same pointer size and
  3683. // convert the element back to a pointer using a inttoptr.
  3684. if (DstEltTy->isPointerTy()) {
  3685. IntegerType *DstIntTy = Type::getIntNTy(C->getContext(), DstBitSize);
  3686. Constant *CE = ConstantExpr::getTrunc(Elt, DstIntTy);
  3687. Result.push_back(ConstantExpr::getIntToPtr(CE, DstEltTy));
  3688. continue;
  3689. }
  3690. // Truncate and remember this piece.
  3691. Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
  3692. }
  3693. }
  3694. return ConstantVector::get(Result);
  3695. }
  3696. static
  3697. Constant *ConstantFoldCastOperand(unsigned Opcode, Constant *C,
  3698. Type *DestTy, const DataLayout &DL) {
  3699. assert(Instruction::isCast(Opcode));
  3700. switch (Opcode) {
  3701. default:
  3702. llvm_unreachable("Missing case");
  3703. case Instruction::PtrToInt:
  3704. // If the input is a inttoptr, eliminate the pair. This requires knowing
  3705. // the width of a pointer, so it can't be done in ConstantExpr::getCast.
  3706. if (auto *CE = dyn_cast<ConstantExpr>(C)) {
  3707. if (CE->getOpcode() == Instruction::IntToPtr) {
  3708. Constant *Input = CE->getOperand(0);
  3709. unsigned InWidth = Input->getType()->getScalarSizeInBits();
  3710. unsigned PtrWidth = DL.getPointerTypeSizeInBits(CE->getType());
  3711. if (PtrWidth < InWidth) {
  3712. Constant *Mask =
  3713. ConstantInt::get(CE->getContext(),
  3714. APInt::getLowBitsSet(InWidth, PtrWidth));
  3715. Input = ConstantExpr::getAnd(Input, Mask);
  3716. }
  3717. // Do a zext or trunc to get to the dest size.
  3718. return ConstantExpr::getIntegerCast(Input, DestTy, false);
  3719. }
  3720. }
  3721. return ConstantExpr::getCast(Opcode, C, DestTy);
  3722. case Instruction::IntToPtr:
  3723. // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
  3724. // the int size is >= the ptr size and the address spaces are the same.
  3725. // This requires knowing the width of a pointer, so it can't be done in
  3726. // ConstantExpr::getCast.
  3727. if (auto *CE = dyn_cast<ConstantExpr>(C)) {
  3728. if (CE->getOpcode() == Instruction::PtrToInt) {
  3729. Constant *SrcPtr = CE->getOperand(0);
  3730. unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType());
  3731. unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
  3732. if (MidIntSize >= SrcPtrSize) {
  3733. unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
  3734. if (SrcAS == DestTy->getPointerAddressSpace())
  3735. return FoldBitCast(CE->getOperand(0), DestTy, DL);
  3736. }
  3737. }
  3738. }
  3739. return ConstantExpr::getCast(Opcode, C, DestTy);
  3740. case Instruction::Trunc:
  3741. case Instruction::ZExt:
  3742. case Instruction::SExt:
  3743. case Instruction::FPTrunc:
  3744. case Instruction::FPExt:
  3745. case Instruction::UIToFP:
  3746. case Instruction::SIToFP:
  3747. case Instruction::FPToUI:
  3748. case Instruction::FPToSI:
  3749. case Instruction::AddrSpaceCast:
  3750. return ConstantExpr::getCast(Opcode, C, DestTy);
  3751. case Instruction::BitCast:
  3752. return FoldBitCast(C, DestTy, DL);
  3753. }
  3754. }
  3755. static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
  3756. Type *Ty, const DataLayout &DL) {
  3757. if (auto *C = dyn_cast<Constant>(Op))
  3758. return ConstantFoldCastOperand(CastOpc, C, Ty, DL);
  3759. if (auto *CI = dyn_cast<CastInst>(Op)) {
  3760. auto *Src = CI->getOperand(0);
  3761. Type *SrcTy = Src->getType();
  3762. Type *MidTy = CI->getType();
  3763. Type *DstTy = Ty;
  3764. if (Src->getType() == Ty) {
  3765. auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
  3766. auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
  3767. Type *SrcIntPtrTy =
  3768. SrcTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(SrcTy) : nullptr;
  3769. Type *MidIntPtrTy =
  3770. MidTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(MidTy) : nullptr;
  3771. Type *DstIntPtrTy =
  3772. DstTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(DstTy) : nullptr;
  3773. if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
  3774. SrcIntPtrTy, MidIntPtrTy,
  3775. DstIntPtrTy) == Instruction::BitCast)
  3776. return Src;
  3777. }
  3778. }
  3779. // bitcast x -> x
  3780. if (CastOpc == Instruction::BitCast)
  3781. if (Op->getType() == Ty)
  3782. return Op;
  3783. return nullptr;
  3784. }
  3785. Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op,
  3786. Type *Ty, const DataLayout &DL) {
  3787. return ::SimplifyCastInst(CastOpc, Op, Ty, DL);
  3788. }
  3789. // HLSL Change - End
  3790. /// SimplifyInstruction - See if we can compute a simplified version of this
  3791. /// instruction. If not, this returns null.
  3792. Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout &DL,
  3793. const TargetLibraryInfo *TLI,
  3794. const DominatorTree *DT, AssumptionCache *AC) {
  3795. Value *Result;
  3796. switch (I->getOpcode()) {
  3797. default:
  3798. Result = ConstantFoldInstruction(I, DL, TLI);
  3799. break;
  3800. case Instruction::FAdd:
  3801. Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
  3802. I->getFastMathFlags(), DL, TLI, DT, AC, I);
  3803. break;
  3804. case Instruction::Add:
  3805. Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
  3806. cast<BinaryOperator>(I)->hasNoSignedWrap(),
  3807. cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
  3808. TLI, DT, AC, I);
  3809. break;
  3810. case Instruction::FSub:
  3811. Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
  3812. I->getFastMathFlags(), DL, TLI, DT, AC, I);
  3813. break;
  3814. case Instruction::Sub:
  3815. Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
  3816. cast<BinaryOperator>(I)->hasNoSignedWrap(),
  3817. cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
  3818. TLI, DT, AC, I);
  3819. break;
  3820. case Instruction::FMul:
  3821. Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
  3822. I->getFastMathFlags(), DL, TLI, DT, AC, I);
  3823. break;
  3824. case Instruction::Mul:
  3825. Result =
  3826. SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
  3827. break;
  3828. case Instruction::SDiv:
  3829. Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
  3830. AC, I);
  3831. break;
  3832. case Instruction::UDiv:
  3833. Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
  3834. AC, I);
  3835. break;
  3836. case Instruction::FDiv:
  3837. Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
  3838. I->getFastMathFlags(), DL, TLI, DT, AC, I);
  3839. break;
  3840. case Instruction::SRem:
  3841. Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
  3842. AC, I);
  3843. break;
  3844. case Instruction::URem:
  3845. Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
  3846. AC, I);
  3847. break;
  3848. case Instruction::FRem:
  3849. Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
  3850. I->getFastMathFlags(), DL, TLI, DT, AC, I);
  3851. break;
  3852. case Instruction::Shl:
  3853. Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
  3854. cast<BinaryOperator>(I)->hasNoSignedWrap(),
  3855. cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
  3856. TLI, DT, AC, I);
  3857. break;
  3858. case Instruction::LShr:
  3859. Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
  3860. cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
  3861. AC, I);
  3862. break;
  3863. case Instruction::AShr:
  3864. Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
  3865. cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
  3866. AC, I);
  3867. break;
  3868. case Instruction::And:
  3869. Result =
  3870. SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
  3871. break;
  3872. case Instruction::Or:
  3873. Result =
  3874. SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
  3875. break;
  3876. case Instruction::Xor:
  3877. Result =
  3878. SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
  3879. break;
  3880. case Instruction::ICmp:
  3881. Result =
  3882. SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), I->getOperand(0),
  3883. I->getOperand(1), DL, TLI, DT, AC, I);
  3884. break;
  3885. case Instruction::FCmp:
  3886. Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
  3887. I->getOperand(0), I->getOperand(1),
  3888. I->getFastMathFlags(), DL, TLI, DT, AC, I);
  3889. break;
  3890. case Instruction::Select:
  3891. Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
  3892. I->getOperand(2), DL, TLI, DT, AC, I);
  3893. break;
  3894. case Instruction::GetElementPtr: {
  3895. SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
  3896. Result = SimplifyGEPInst(Ops, DL, TLI, DT, AC, I);
  3897. break;
  3898. }
  3899. case Instruction::InsertValue: {
  3900. InsertValueInst *IV = cast<InsertValueInst>(I);
  3901. Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
  3902. IV->getInsertedValueOperand(),
  3903. IV->getIndices(), DL, TLI, DT, AC, I);
  3904. break;
  3905. }
  3906. case Instruction::ExtractValue: {
  3907. auto *EVI = cast<ExtractValueInst>(I);
  3908. Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
  3909. EVI->getIndices(), DL, TLI, DT, AC, I);
  3910. break;
  3911. }
  3912. case Instruction::ExtractElement: {
  3913. auto *EEI = cast<ExtractElementInst>(I);
  3914. Result = SimplifyExtractElementInst(
  3915. EEI->getVectorOperand(), EEI->getIndexOperand(), DL, TLI, DT, AC, I);
  3916. break;
  3917. }
  3918. case Instruction::PHI:
  3919. Result = SimplifyPHINode(cast<PHINode>(I), Query(DL, TLI, DT, AC, I));
  3920. break;
  3921. case Instruction::Call: {
  3922. CallSite CS(cast<CallInst>(I));
  3923. // HLSL Change Begin - simplify dxil calls.
  3924. if (Function *Callee = CS.getCalledFunction()) {
  3925. if (hlsl::CanSimplify(Callee)) {
  3926. SmallVector<Value *, 4> Args(CS.arg_begin(), CS.arg_end());
  3927. if (Value *DxilResult = hlsl::SimplifyDxilCall(CS.getCalledFunction(), Args, I, /* MayInsert */ true)) {
  3928. Result = DxilResult;
  3929. break;
  3930. }
  3931. }
  3932. }
  3933. // HLSL Change End.
  3934. Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), DL,
  3935. TLI, DT, AC, I);
  3936. break;
  3937. }
  3938. case Instruction::Trunc:
  3939. Result =
  3940. SimplifyTruncInst(I->getOperand(0), I->getType(), DL, TLI, DT, AC, I);
  3941. break;
  3942. }
  3943. /// If called on unreachable code, the above logic may report that the
  3944. /// instruction simplified to itself. Make life easier for users by
  3945. /// detecting that case here, returning a safe value instead.
  3946. return Result == I ? UndefValue::get(I->getType()) : Result;
  3947. }
  3948. /// \brief Implementation of recursive simplification through an instructions
  3949. /// uses.
  3950. ///
  3951. /// This is the common implementation of the recursive simplification routines.
  3952. /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
  3953. /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
  3954. /// instructions to process and attempt to simplify it using
  3955. /// InstructionSimplify.
  3956. ///
  3957. /// This routine returns 'true' only when *it* simplifies something. The passed
  3958. /// in simplified value does not count toward this.
  3959. static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
  3960. const TargetLibraryInfo *TLI,
  3961. const DominatorTree *DT,
  3962. AssumptionCache *AC) {
  3963. bool Simplified = false;
  3964. SmallSetVector<Instruction *, 8> Worklist;
  3965. const DataLayout &DL = I->getModule()->getDataLayout();
  3966. // If we have an explicit value to collapse to, do that round of the
  3967. // simplification loop by hand initially.
  3968. if (SimpleV) {
  3969. for (User *U : I->users())
  3970. if (U != I)
  3971. Worklist.insert(cast<Instruction>(U));
  3972. // Replace the instruction with its simplified value.
  3973. I->replaceAllUsesWith(SimpleV);
  3974. // Gracefully handle edge cases where the instruction is not wired into any
  3975. // parent block.
  3976. if (I->getParent())
  3977. I->eraseFromParent();
  3978. } else {
  3979. Worklist.insert(I);
  3980. }
  3981. // Note that we must test the size on each iteration, the worklist can grow.
  3982. for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
  3983. I = Worklist[Idx];
  3984. // See if this instruction simplifies.
  3985. SimpleV = SimplifyInstruction(I, DL, TLI, DT, AC);
  3986. if (!SimpleV)
  3987. continue;
  3988. Simplified = true;
  3989. // Stash away all the uses of the old instruction so we can check them for
  3990. // recursive simplifications after a RAUW. This is cheaper than checking all
  3991. // uses of To on the recursive step in most cases.
  3992. for (User *U : I->users())
  3993. Worklist.insert(cast<Instruction>(U));
  3994. // Replace the instruction with its simplified value.
  3995. I->replaceAllUsesWith(SimpleV);
  3996. // Gracefully handle edge cases where the instruction is not wired into any
  3997. // parent block.
  3998. if (I->getParent())
  3999. I->eraseFromParent();
  4000. }
  4001. return Simplified;
  4002. }
  4003. bool llvm::recursivelySimplifyInstruction(Instruction *I,
  4004. const TargetLibraryInfo *TLI,
  4005. const DominatorTree *DT,
  4006. AssumptionCache *AC) {
  4007. return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
  4008. }
  4009. bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
  4010. const TargetLibraryInfo *TLI,
  4011. const DominatorTree *DT,
  4012. AssumptionCache *AC) {
  4013. assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
  4014. assert(SimpleV && "Must provide a simplified value.");
  4015. return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
  4016. }