InstCombineAndOrXor.cpp 151 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799
  1. //===- InstCombineAndOrXor.cpp --------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the visitAnd, visitOr, and visitXor functions.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "InstCombineInternal.h"
  13. #include "llvm/Analysis/CmpInstAnalysis.h"
  14. #include "llvm/Analysis/InstructionSimplify.h"
  15. #include "llvm/IR/ConstantRange.h"
  16. #include "llvm/IR/Intrinsics.h"
  17. #include "llvm/IR/PatternMatch.h"
  18. #include "llvm/Transforms/InstCombine/InstCombiner.h"
  19. #include "llvm/Transforms/Utils/Local.h"
  20. using namespace llvm;
  21. using namespace PatternMatch;
  22. #define DEBUG_TYPE "instcombine"
  23. /// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into
  24. /// a four bit mask.
  25. static unsigned getFCmpCode(FCmpInst::Predicate CC) {
  26. assert(FCmpInst::FCMP_FALSE <= CC && CC <= FCmpInst::FCMP_TRUE &&
  27. "Unexpected FCmp predicate!");
  28. // Take advantage of the bit pattern of FCmpInst::Predicate here.
  29. // U L G E
  30. static_assert(FCmpInst::FCMP_FALSE == 0, ""); // 0 0 0 0
  31. static_assert(FCmpInst::FCMP_OEQ == 1, ""); // 0 0 0 1
  32. static_assert(FCmpInst::FCMP_OGT == 2, ""); // 0 0 1 0
  33. static_assert(FCmpInst::FCMP_OGE == 3, ""); // 0 0 1 1
  34. static_assert(FCmpInst::FCMP_OLT == 4, ""); // 0 1 0 0
  35. static_assert(FCmpInst::FCMP_OLE == 5, ""); // 0 1 0 1
  36. static_assert(FCmpInst::FCMP_ONE == 6, ""); // 0 1 1 0
  37. static_assert(FCmpInst::FCMP_ORD == 7, ""); // 0 1 1 1
  38. static_assert(FCmpInst::FCMP_UNO == 8, ""); // 1 0 0 0
  39. static_assert(FCmpInst::FCMP_UEQ == 9, ""); // 1 0 0 1
  40. static_assert(FCmpInst::FCMP_UGT == 10, ""); // 1 0 1 0
  41. static_assert(FCmpInst::FCMP_UGE == 11, ""); // 1 0 1 1
  42. static_assert(FCmpInst::FCMP_ULT == 12, ""); // 1 1 0 0
  43. static_assert(FCmpInst::FCMP_ULE == 13, ""); // 1 1 0 1
  44. static_assert(FCmpInst::FCMP_UNE == 14, ""); // 1 1 1 0
  45. static_assert(FCmpInst::FCMP_TRUE == 15, ""); // 1 1 1 1
  46. return CC;
  47. }
  48. /// This is the complement of getICmpCode, which turns an opcode and two
  49. /// operands into either a constant true or false, or a brand new ICmp
  50. /// instruction. The sign is passed in to determine which kind of predicate to
  51. /// use in the new icmp instruction.
  52. static Value *getNewICmpValue(unsigned Code, bool Sign, Value *LHS, Value *RHS,
  53. InstCombiner::BuilderTy &Builder) {
  54. ICmpInst::Predicate NewPred;
  55. if (Constant *TorF = getPredForICmpCode(Code, Sign, LHS->getType(), NewPred))
  56. return TorF;
  57. return Builder.CreateICmp(NewPred, LHS, RHS);
  58. }
  59. /// This is the complement of getFCmpCode, which turns an opcode and two
  60. /// operands into either a FCmp instruction, or a true/false constant.
  61. static Value *getFCmpValue(unsigned Code, Value *LHS, Value *RHS,
  62. InstCombiner::BuilderTy &Builder) {
  63. const auto Pred = static_cast<FCmpInst::Predicate>(Code);
  64. assert(FCmpInst::FCMP_FALSE <= Pred && Pred <= FCmpInst::FCMP_TRUE &&
  65. "Unexpected FCmp predicate!");
  66. if (Pred == FCmpInst::FCMP_FALSE)
  67. return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
  68. if (Pred == FCmpInst::FCMP_TRUE)
  69. return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
  70. return Builder.CreateFCmp(Pred, LHS, RHS);
  71. }
  72. /// Transform BITWISE_OP(BSWAP(A),BSWAP(B)) or
  73. /// BITWISE_OP(BSWAP(A), Constant) to BSWAP(BITWISE_OP(A, B))
  74. /// \param I Binary operator to transform.
  75. /// \return Pointer to node that must replace the original binary operator, or
  76. /// null pointer if no transformation was made.
  77. static Value *SimplifyBSwap(BinaryOperator &I,
  78. InstCombiner::BuilderTy &Builder) {
  79. assert(I.isBitwiseLogicOp() && "Unexpected opcode for bswap simplifying");
  80. Value *OldLHS = I.getOperand(0);
  81. Value *OldRHS = I.getOperand(1);
  82. Value *NewLHS;
  83. if (!match(OldLHS, m_BSwap(m_Value(NewLHS))))
  84. return nullptr;
  85. Value *NewRHS;
  86. const APInt *C;
  87. if (match(OldRHS, m_BSwap(m_Value(NewRHS)))) {
  88. // OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
  89. if (!OldLHS->hasOneUse() && !OldRHS->hasOneUse())
  90. return nullptr;
  91. // NewRHS initialized by the matcher.
  92. } else if (match(OldRHS, m_APInt(C))) {
  93. // OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
  94. if (!OldLHS->hasOneUse())
  95. return nullptr;
  96. NewRHS = ConstantInt::get(I.getType(), C->byteSwap());
  97. } else
  98. return nullptr;
  99. Value *BinOp = Builder.CreateBinOp(I.getOpcode(), NewLHS, NewRHS);
  100. Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap,
  101. I.getType());
  102. return Builder.CreateCall(F, BinOp);
  103. }
  104. /// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
  105. /// (V < Lo || V >= Hi). This method expects that Lo < Hi. IsSigned indicates
  106. /// whether to treat V, Lo, and Hi as signed or not.
  107. Value *InstCombinerImpl::insertRangeTest(Value *V, const APInt &Lo,
  108. const APInt &Hi, bool isSigned,
  109. bool Inside) {
  110. assert((isSigned ? Lo.slt(Hi) : Lo.ult(Hi)) &&
  111. "Lo is not < Hi in range emission code!");
  112. Type *Ty = V->getType();
  113. // V >= Min && V < Hi --> V < Hi
  114. // V < Min || V >= Hi --> V >= Hi
  115. ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
  116. if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
  117. Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
  118. return Builder.CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
  119. }
  120. // V >= Lo && V < Hi --> V - Lo u< Hi - Lo
  121. // V < Lo || V >= Hi --> V - Lo u>= Hi - Lo
  122. Value *VMinusLo =
  123. Builder.CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
  124. Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
  125. return Builder.CreateICmp(Pred, VMinusLo, HiMinusLo);
  126. }
  127. /// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
  128. /// that can be simplified.
  129. /// One of A and B is considered the mask. The other is the value. This is
  130. /// described as the "AMask" or "BMask" part of the enum. If the enum contains
  131. /// only "Mask", then both A and B can be considered masks. If A is the mask,
  132. /// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
  133. /// If both A and C are constants, this proof is also easy.
  134. /// For the following explanations, we assume that A is the mask.
  135. ///
  136. /// "AllOnes" declares that the comparison is true only if (A & B) == A or all
  137. /// bits of A are set in B.
  138. /// Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
  139. ///
  140. /// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
  141. /// bits of A are cleared in B.
  142. /// Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
  143. ///
  144. /// "Mixed" declares that (A & B) == C and C might or might not contain any
  145. /// number of one bits and zero bits.
  146. /// Example: (icmp eq (A & 3), 1) -> AMask_Mixed
  147. ///
  148. /// "Not" means that in above descriptions "==" should be replaced by "!=".
  149. /// Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
  150. ///
  151. /// If the mask A contains a single bit, then the following is equivalent:
  152. /// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
  153. /// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
  154. enum MaskedICmpType {
  155. AMask_AllOnes = 1,
  156. AMask_NotAllOnes = 2,
  157. BMask_AllOnes = 4,
  158. BMask_NotAllOnes = 8,
  159. Mask_AllZeros = 16,
  160. Mask_NotAllZeros = 32,
  161. AMask_Mixed = 64,
  162. AMask_NotMixed = 128,
  163. BMask_Mixed = 256,
  164. BMask_NotMixed = 512
  165. };
  166. /// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
  167. /// satisfies.
  168. static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
  169. ICmpInst::Predicate Pred) {
  170. const APInt *ConstA = nullptr, *ConstB = nullptr, *ConstC = nullptr;
  171. match(A, m_APInt(ConstA));
  172. match(B, m_APInt(ConstB));
  173. match(C, m_APInt(ConstC));
  174. bool IsEq = (Pred == ICmpInst::ICMP_EQ);
  175. bool IsAPow2 = ConstA && ConstA->isPowerOf2();
  176. bool IsBPow2 = ConstB && ConstB->isPowerOf2();
  177. unsigned MaskVal = 0;
  178. if (ConstC && ConstC->isZero()) {
  179. // if C is zero, then both A and B qualify as mask
  180. MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
  181. : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
  182. if (IsAPow2)
  183. MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
  184. : (AMask_AllOnes | AMask_Mixed));
  185. if (IsBPow2)
  186. MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
  187. : (BMask_AllOnes | BMask_Mixed));
  188. return MaskVal;
  189. }
  190. if (A == C) {
  191. MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
  192. : (AMask_NotAllOnes | AMask_NotMixed));
  193. if (IsAPow2)
  194. MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
  195. : (Mask_AllZeros | AMask_Mixed));
  196. } else if (ConstA && ConstC && ConstC->isSubsetOf(*ConstA)) {
  197. MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
  198. }
  199. if (B == C) {
  200. MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
  201. : (BMask_NotAllOnes | BMask_NotMixed));
  202. if (IsBPow2)
  203. MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
  204. : (Mask_AllZeros | BMask_Mixed));
  205. } else if (ConstB && ConstC && ConstC->isSubsetOf(*ConstB)) {
  206. MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
  207. }
  208. return MaskVal;
  209. }
  210. /// Convert an analysis of a masked ICmp into its equivalent if all boolean
  211. /// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
  212. /// is adjacent to the corresponding normal flag (recording ==), this just
  213. /// involves swapping those bits over.
  214. static unsigned conjugateICmpMask(unsigned Mask) {
  215. unsigned NewMask;
  216. NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
  217. AMask_Mixed | BMask_Mixed))
  218. << 1;
  219. NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
  220. AMask_NotMixed | BMask_NotMixed))
  221. >> 1;
  222. return NewMask;
  223. }
  224. // Adapts the external decomposeBitTestICmp for local use.
  225. static bool decomposeBitTestICmp(Value *LHS, Value *RHS, CmpInst::Predicate &Pred,
  226. Value *&X, Value *&Y, Value *&Z) {
  227. APInt Mask;
  228. if (!llvm::decomposeBitTestICmp(LHS, RHS, Pred, X, Mask))
  229. return false;
  230. Y = ConstantInt::get(X->getType(), Mask);
  231. Z = ConstantInt::get(X->getType(), 0);
  232. return true;
  233. }
  234. /// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
  235. /// Return the pattern classes (from MaskedICmpType) for the left hand side and
  236. /// the right hand side as a pair.
  237. /// LHS and RHS are the left hand side and the right hand side ICmps and PredL
  238. /// and PredR are their predicates, respectively.
  239. static
  240. Optional<std::pair<unsigned, unsigned>>
  241. getMaskedTypeForICmpPair(Value *&A, Value *&B, Value *&C,
  242. Value *&D, Value *&E, ICmpInst *LHS,
  243. ICmpInst *RHS,
  244. ICmpInst::Predicate &PredL,
  245. ICmpInst::Predicate &PredR) {
  246. // Don't allow pointers. Splat vectors are fine.
  247. if (!LHS->getOperand(0)->getType()->isIntOrIntVectorTy() ||
  248. !RHS->getOperand(0)->getType()->isIntOrIntVectorTy())
  249. return None;
  250. // Here comes the tricky part:
  251. // LHS might be of the form L11 & L12 == X, X == L21 & L22,
  252. // and L11 & L12 == L21 & L22. The same goes for RHS.
  253. // Now we must find those components L** and R**, that are equal, so
  254. // that we can extract the parameters A, B, C, D, and E for the canonical
  255. // above.
  256. Value *L1 = LHS->getOperand(0);
  257. Value *L2 = LHS->getOperand(1);
  258. Value *L11, *L12, *L21, *L22;
  259. // Check whether the icmp can be decomposed into a bit test.
  260. if (decomposeBitTestICmp(L1, L2, PredL, L11, L12, L2)) {
  261. L21 = L22 = L1 = nullptr;
  262. } else {
  263. // Look for ANDs in the LHS icmp.
  264. if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
  265. // Any icmp can be viewed as being trivially masked; if it allows us to
  266. // remove one, it's worth it.
  267. L11 = L1;
  268. L12 = Constant::getAllOnesValue(L1->getType());
  269. }
  270. if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
  271. L21 = L2;
  272. L22 = Constant::getAllOnesValue(L2->getType());
  273. }
  274. }
  275. // Bail if LHS was a icmp that can't be decomposed into an equality.
  276. if (!ICmpInst::isEquality(PredL))
  277. return None;
  278. Value *R1 = RHS->getOperand(0);
  279. Value *R2 = RHS->getOperand(1);
  280. Value *R11, *R12;
  281. bool Ok = false;
  282. if (decomposeBitTestICmp(R1, R2, PredR, R11, R12, R2)) {
  283. if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
  284. A = R11;
  285. D = R12;
  286. } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
  287. A = R12;
  288. D = R11;
  289. } else {
  290. return None;
  291. }
  292. E = R2;
  293. R1 = nullptr;
  294. Ok = true;
  295. } else {
  296. if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
  297. // As before, model no mask as a trivial mask if it'll let us do an
  298. // optimization.
  299. R11 = R1;
  300. R12 = Constant::getAllOnesValue(R1->getType());
  301. }
  302. if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
  303. A = R11;
  304. D = R12;
  305. E = R2;
  306. Ok = true;
  307. } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
  308. A = R12;
  309. D = R11;
  310. E = R2;
  311. Ok = true;
  312. }
  313. }
  314. // Bail if RHS was a icmp that can't be decomposed into an equality.
  315. if (!ICmpInst::isEquality(PredR))
  316. return None;
  317. // Look for ANDs on the right side of the RHS icmp.
  318. if (!Ok) {
  319. if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
  320. R11 = R2;
  321. R12 = Constant::getAllOnesValue(R2->getType());
  322. }
  323. if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
  324. A = R11;
  325. D = R12;
  326. E = R1;
  327. Ok = true;
  328. } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
  329. A = R12;
  330. D = R11;
  331. E = R1;
  332. Ok = true;
  333. } else {
  334. return None;
  335. }
  336. assert(Ok && "Failed to find AND on the right side of the RHS icmp.");
  337. }
  338. if (L11 == A) {
  339. B = L12;
  340. C = L2;
  341. } else if (L12 == A) {
  342. B = L11;
  343. C = L2;
  344. } else if (L21 == A) {
  345. B = L22;
  346. C = L1;
  347. } else if (L22 == A) {
  348. B = L21;
  349. C = L1;
  350. }
  351. unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
  352. unsigned RightType = getMaskedICmpType(A, D, E, PredR);
  353. return Optional<std::pair<unsigned, unsigned>>(std::make_pair(LeftType, RightType));
  354. }
  355. /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E) into a single
  356. /// (icmp(A & X) ==/!= Y), where the left-hand side is of type Mask_NotAllZeros
  357. /// and the right hand side is of type BMask_Mixed. For example,
  358. /// (icmp (A & 12) != 0) & (icmp (A & 15) == 8) -> (icmp (A & 15) == 8).
  359. static Value *foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
  360. ICmpInst *LHS, ICmpInst *RHS, bool IsAnd, Value *A, Value *B, Value *C,
  361. Value *D, Value *E, ICmpInst::Predicate PredL, ICmpInst::Predicate PredR,
  362. InstCombiner::BuilderTy &Builder) {
  363. // We are given the canonical form:
  364. // (icmp ne (A & B), 0) & (icmp eq (A & D), E).
  365. // where D & E == E.
  366. //
  367. // If IsAnd is false, we get it in negated form:
  368. // (icmp eq (A & B), 0) | (icmp ne (A & D), E) ->
  369. // !((icmp ne (A & B), 0) & (icmp eq (A & D), E)).
  370. //
  371. // We currently handle the case of B, C, D, E are constant.
  372. //
  373. ConstantInt *BCst, *CCst, *DCst, *ECst;
  374. if (!match(B, m_ConstantInt(BCst)) || !match(C, m_ConstantInt(CCst)) ||
  375. !match(D, m_ConstantInt(DCst)) || !match(E, m_ConstantInt(ECst)))
  376. return nullptr;
  377. ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
  378. // Update E to the canonical form when D is a power of two and RHS is
  379. // canonicalized as,
  380. // (icmp ne (A & D), 0) -> (icmp eq (A & D), D) or
  381. // (icmp ne (A & D), D) -> (icmp eq (A & D), 0).
  382. if (PredR != NewCC)
  383. ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
  384. // If B or D is zero, skip because if LHS or RHS can be trivially folded by
  385. // other folding rules and this pattern won't apply any more.
  386. if (BCst->getValue() == 0 || DCst->getValue() == 0)
  387. return nullptr;
  388. // If B and D don't intersect, ie. (B & D) == 0, no folding because we can't
  389. // deduce anything from it.
  390. // For example,
  391. // (icmp ne (A & 12), 0) & (icmp eq (A & 3), 1) -> no folding.
  392. if ((BCst->getValue() & DCst->getValue()) == 0)
  393. return nullptr;
  394. // If the following two conditions are met:
  395. //
  396. // 1. mask B covers only a single bit that's not covered by mask D, that is,
  397. // (B & (B ^ D)) is a power of 2 (in other words, B minus the intersection of
  398. // B and D has only one bit set) and,
  399. //
  400. // 2. RHS (and E) indicates that the rest of B's bits are zero (in other
  401. // words, the intersection of B and D is zero), that is, ((B & D) & E) == 0
  402. //
  403. // then that single bit in B must be one and thus the whole expression can be
  404. // folded to
  405. // (A & (B | D)) == (B & (B ^ D)) | E.
  406. //
  407. // For example,
  408. // (icmp ne (A & 12), 0) & (icmp eq (A & 7), 1) -> (icmp eq (A & 15), 9)
  409. // (icmp ne (A & 15), 0) & (icmp eq (A & 7), 0) -> (icmp eq (A & 15), 8)
  410. if ((((BCst->getValue() & DCst->getValue()) & ECst->getValue()) == 0) &&
  411. (BCst->getValue() & (BCst->getValue() ^ DCst->getValue())).isPowerOf2()) {
  412. APInt BorD = BCst->getValue() | DCst->getValue();
  413. APInt BandBxorDorE = (BCst->getValue() & (BCst->getValue() ^ DCst->getValue())) |
  414. ECst->getValue();
  415. Value *NewMask = ConstantInt::get(BCst->getType(), BorD);
  416. Value *NewMaskedValue = ConstantInt::get(BCst->getType(), BandBxorDorE);
  417. Value *NewAnd = Builder.CreateAnd(A, NewMask);
  418. return Builder.CreateICmp(NewCC, NewAnd, NewMaskedValue);
  419. }
  420. auto IsSubSetOrEqual = [](ConstantInt *C1, ConstantInt *C2) {
  421. return (C1->getValue() & C2->getValue()) == C1->getValue();
  422. };
  423. auto IsSuperSetOrEqual = [](ConstantInt *C1, ConstantInt *C2) {
  424. return (C1->getValue() & C2->getValue()) == C2->getValue();
  425. };
  426. // In the following, we consider only the cases where B is a superset of D, B
  427. // is a subset of D, or B == D because otherwise there's at least one bit
  428. // covered by B but not D, in which case we can't deduce much from it, so
  429. // no folding (aside from the single must-be-one bit case right above.)
  430. // For example,
  431. // (icmp ne (A & 14), 0) & (icmp eq (A & 3), 1) -> no folding.
  432. if (!IsSubSetOrEqual(BCst, DCst) && !IsSuperSetOrEqual(BCst, DCst))
  433. return nullptr;
  434. // At this point, either B is a superset of D, B is a subset of D or B == D.
  435. // If E is zero, if B is a subset of (or equal to) D, LHS and RHS contradict
  436. // and the whole expression becomes false (or true if negated), otherwise, no
  437. // folding.
  438. // For example,
  439. // (icmp ne (A & 3), 0) & (icmp eq (A & 7), 0) -> false.
  440. // (icmp ne (A & 15), 0) & (icmp eq (A & 3), 0) -> no folding.
  441. if (ECst->isZero()) {
  442. if (IsSubSetOrEqual(BCst, DCst))
  443. return ConstantInt::get(LHS->getType(), !IsAnd);
  444. return nullptr;
  445. }
  446. // At this point, B, D, E aren't zero and (B & D) == B, (B & D) == D or B ==
  447. // D. If B is a superset of (or equal to) D, since E is not zero, LHS is
  448. // subsumed by RHS (RHS implies LHS.) So the whole expression becomes
  449. // RHS. For example,
  450. // (icmp ne (A & 255), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
  451. // (icmp ne (A & 15), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
  452. if (IsSuperSetOrEqual(BCst, DCst))
  453. return RHS;
  454. // Otherwise, B is a subset of D. If B and E have a common bit set,
  455. // ie. (B & E) != 0, then LHS is subsumed by RHS. For example.
  456. // (icmp ne (A & 12), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
  457. assert(IsSubSetOrEqual(BCst, DCst) && "Precondition due to above code");
  458. if ((BCst->getValue() & ECst->getValue()) != 0)
  459. return RHS;
  460. // Otherwise, LHS and RHS contradict and the whole expression becomes false
  461. // (or true if negated.) For example,
  462. // (icmp ne (A & 7), 0) & (icmp eq (A & 15), 8) -> false.
  463. // (icmp ne (A & 6), 0) & (icmp eq (A & 15), 8) -> false.
  464. return ConstantInt::get(LHS->getType(), !IsAnd);
  465. }
  466. /// Try to fold (icmp(A & B) ==/!= 0) &/| (icmp(A & D) ==/!= E) into a single
  467. /// (icmp(A & X) ==/!= Y), where the left-hand side and the right hand side
  468. /// aren't of the common mask pattern type.
  469. static Value *foldLogOpOfMaskedICmpsAsymmetric(
  470. ICmpInst *LHS, ICmpInst *RHS, bool IsAnd, Value *A, Value *B, Value *C,
  471. Value *D, Value *E, ICmpInst::Predicate PredL, ICmpInst::Predicate PredR,
  472. unsigned LHSMask, unsigned RHSMask, InstCombiner::BuilderTy &Builder) {
  473. assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
  474. "Expected equality predicates for masked type of icmps.");
  475. // Handle Mask_NotAllZeros-BMask_Mixed cases.
  476. // (icmp ne/eq (A & B), C) &/| (icmp eq/ne (A & D), E), or
  477. // (icmp eq/ne (A & B), C) &/| (icmp ne/eq (A & D), E)
  478. // which gets swapped to
  479. // (icmp ne/eq (A & D), E) &/| (icmp eq/ne (A & B), C).
  480. if (!IsAnd) {
  481. LHSMask = conjugateICmpMask(LHSMask);
  482. RHSMask = conjugateICmpMask(RHSMask);
  483. }
  484. if ((LHSMask & Mask_NotAllZeros) && (RHSMask & BMask_Mixed)) {
  485. if (Value *V = foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
  486. LHS, RHS, IsAnd, A, B, C, D, E,
  487. PredL, PredR, Builder)) {
  488. return V;
  489. }
  490. } else if ((LHSMask & BMask_Mixed) && (RHSMask & Mask_NotAllZeros)) {
  491. if (Value *V = foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
  492. RHS, LHS, IsAnd, A, D, E, B, C,
  493. PredR, PredL, Builder)) {
  494. return V;
  495. }
  496. }
  497. return nullptr;
  498. }
  499. /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
  500. /// into a single (icmp(A & X) ==/!= Y).
  501. static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
  502. InstCombiner::BuilderTy &Builder) {
  503. Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
  504. ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
  505. Optional<std::pair<unsigned, unsigned>> MaskPair =
  506. getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
  507. if (!MaskPair)
  508. return nullptr;
  509. assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
  510. "Expected equality predicates for masked type of icmps.");
  511. unsigned LHSMask = MaskPair->first;
  512. unsigned RHSMask = MaskPair->second;
  513. unsigned Mask = LHSMask & RHSMask;
  514. if (Mask == 0) {
  515. // Even if the two sides don't share a common pattern, check if folding can
  516. // still happen.
  517. if (Value *V = foldLogOpOfMaskedICmpsAsymmetric(
  518. LHS, RHS, IsAnd, A, B, C, D, E, PredL, PredR, LHSMask, RHSMask,
  519. Builder))
  520. return V;
  521. return nullptr;
  522. }
  523. // In full generality:
  524. // (icmp (A & B) Op C) | (icmp (A & D) Op E)
  525. // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
  526. //
  527. // If the latter can be converted into (icmp (A & X) Op Y) then the former is
  528. // equivalent to (icmp (A & X) !Op Y).
  529. //
  530. // Therefore, we can pretend for the rest of this function that we're dealing
  531. // with the conjunction, provided we flip the sense of any comparisons (both
  532. // input and output).
  533. // In most cases we're going to produce an EQ for the "&&" case.
  534. ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
  535. if (!IsAnd) {
  536. // Convert the masking analysis into its equivalent with negated
  537. // comparisons.
  538. Mask = conjugateICmpMask(Mask);
  539. }
  540. if (Mask & Mask_AllZeros) {
  541. // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
  542. // -> (icmp eq (A & (B|D)), 0)
  543. Value *NewOr = Builder.CreateOr(B, D);
  544. Value *NewAnd = Builder.CreateAnd(A, NewOr);
  545. // We can't use C as zero because we might actually handle
  546. // (icmp ne (A & B), B) & (icmp ne (A & D), D)
  547. // with B and D, having a single bit set.
  548. Value *Zero = Constant::getNullValue(A->getType());
  549. return Builder.CreateICmp(NewCC, NewAnd, Zero);
  550. }
  551. if (Mask & BMask_AllOnes) {
  552. // (icmp eq (A & B), B) & (icmp eq (A & D), D)
  553. // -> (icmp eq (A & (B|D)), (B|D))
  554. Value *NewOr = Builder.CreateOr(B, D);
  555. Value *NewAnd = Builder.CreateAnd(A, NewOr);
  556. return Builder.CreateICmp(NewCC, NewAnd, NewOr);
  557. }
  558. if (Mask & AMask_AllOnes) {
  559. // (icmp eq (A & B), A) & (icmp eq (A & D), A)
  560. // -> (icmp eq (A & (B&D)), A)
  561. Value *NewAnd1 = Builder.CreateAnd(B, D);
  562. Value *NewAnd2 = Builder.CreateAnd(A, NewAnd1);
  563. return Builder.CreateICmp(NewCC, NewAnd2, A);
  564. }
  565. // Remaining cases assume at least that B and D are constant, and depend on
  566. // their actual values. This isn't strictly necessary, just a "handle the
  567. // easy cases for now" decision.
  568. const APInt *ConstB, *ConstD;
  569. if (!match(B, m_APInt(ConstB)) || !match(D, m_APInt(ConstD)))
  570. return nullptr;
  571. if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
  572. // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
  573. // (icmp ne (A & B), B) & (icmp ne (A & D), D)
  574. // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
  575. // Only valid if one of the masks is a superset of the other (check "B&D" is
  576. // the same as either B or D).
  577. APInt NewMask = *ConstB & *ConstD;
  578. if (NewMask == *ConstB)
  579. return LHS;
  580. else if (NewMask == *ConstD)
  581. return RHS;
  582. }
  583. if (Mask & AMask_NotAllOnes) {
  584. // (icmp ne (A & B), B) & (icmp ne (A & D), D)
  585. // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
  586. // Only valid if one of the masks is a superset of the other (check "B|D" is
  587. // the same as either B or D).
  588. APInt NewMask = *ConstB | *ConstD;
  589. if (NewMask == *ConstB)
  590. return LHS;
  591. else if (NewMask == *ConstD)
  592. return RHS;
  593. }
  594. if (Mask & BMask_Mixed) {
  595. // (icmp eq (A & B), C) & (icmp eq (A & D), E)
  596. // We already know that B & C == C && D & E == E.
  597. // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
  598. // C and E, which are shared by both the mask B and the mask D, don't
  599. // contradict, then we can transform to
  600. // -> (icmp eq (A & (B|D)), (C|E))
  601. // Currently, we only handle the case of B, C, D, and E being constant.
  602. // We can't simply use C and E because we might actually handle
  603. // (icmp ne (A & B), B) & (icmp eq (A & D), D)
  604. // with B and D, having a single bit set.
  605. const APInt *OldConstC, *OldConstE;
  606. if (!match(C, m_APInt(OldConstC)) || !match(E, m_APInt(OldConstE)))
  607. return nullptr;
  608. const APInt ConstC = PredL != NewCC ? *ConstB ^ *OldConstC : *OldConstC;
  609. const APInt ConstE = PredR != NewCC ? *ConstD ^ *OldConstE : *OldConstE;
  610. // If there is a conflict, we should actually return a false for the
  611. // whole construct.
  612. if (((*ConstB & *ConstD) & (ConstC ^ ConstE)).getBoolValue())
  613. return ConstantInt::get(LHS->getType(), !IsAnd);
  614. Value *NewOr1 = Builder.CreateOr(B, D);
  615. Value *NewAnd = Builder.CreateAnd(A, NewOr1);
  616. Constant *NewOr2 = ConstantInt::get(A->getType(), ConstC | ConstE);
  617. return Builder.CreateICmp(NewCC, NewAnd, NewOr2);
  618. }
  619. return nullptr;
  620. }
  621. /// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
  622. /// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
  623. /// If \p Inverted is true then the check is for the inverted range, e.g.
  624. /// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
  625. Value *InstCombinerImpl::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
  626. bool Inverted) {
  627. // Check the lower range comparison, e.g. x >= 0
  628. // InstCombine already ensured that if there is a constant it's on the RHS.
  629. ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
  630. if (!RangeStart)
  631. return nullptr;
  632. ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
  633. Cmp0->getPredicate());
  634. // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
  635. if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
  636. (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
  637. return nullptr;
  638. ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
  639. Cmp1->getPredicate());
  640. Value *Input = Cmp0->getOperand(0);
  641. Value *RangeEnd;
  642. if (Cmp1->getOperand(0) == Input) {
  643. // For the upper range compare we have: icmp x, n
  644. RangeEnd = Cmp1->getOperand(1);
  645. } else if (Cmp1->getOperand(1) == Input) {
  646. // For the upper range compare we have: icmp n, x
  647. RangeEnd = Cmp1->getOperand(0);
  648. Pred1 = ICmpInst::getSwappedPredicate(Pred1);
  649. } else {
  650. return nullptr;
  651. }
  652. // Check the upper range comparison, e.g. x < n
  653. ICmpInst::Predicate NewPred;
  654. switch (Pred1) {
  655. case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
  656. case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
  657. default: return nullptr;
  658. }
  659. // This simplification is only valid if the upper range is not negative.
  660. KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1);
  661. if (!Known.isNonNegative())
  662. return nullptr;
  663. if (Inverted)
  664. NewPred = ICmpInst::getInversePredicate(NewPred);
  665. return Builder.CreateICmp(NewPred, Input, RangeEnd);
  666. }
  667. static Value *
  668. foldAndOrOfEqualityCmpsWithConstants(ICmpInst *LHS, ICmpInst *RHS,
  669. bool JoinedByAnd,
  670. InstCombiner::BuilderTy &Builder) {
  671. Value *X = LHS->getOperand(0);
  672. if (X != RHS->getOperand(0))
  673. return nullptr;
  674. const APInt *C1, *C2;
  675. if (!match(LHS->getOperand(1), m_APInt(C1)) ||
  676. !match(RHS->getOperand(1), m_APInt(C2)))
  677. return nullptr;
  678. // We only handle (X != C1 && X != C2) and (X == C1 || X == C2).
  679. ICmpInst::Predicate Pred = LHS->getPredicate();
  680. if (Pred != RHS->getPredicate())
  681. return nullptr;
  682. if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
  683. return nullptr;
  684. if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
  685. return nullptr;
  686. // The larger unsigned constant goes on the right.
  687. if (C1->ugt(*C2))
  688. std::swap(C1, C2);
  689. APInt Xor = *C1 ^ *C2;
  690. if (Xor.isPowerOf2()) {
  691. // If LHSC and RHSC differ by only one bit, then set that bit in X and
  692. // compare against the larger constant:
  693. // (X == C1 || X == C2) --> (X | (C1 ^ C2)) == C2
  694. // (X != C1 && X != C2) --> (X | (C1 ^ C2)) != C2
  695. // We choose an 'or' with a Pow2 constant rather than the inverse mask with
  696. // 'and' because that may lead to smaller codegen from a smaller constant.
  697. Value *Or = Builder.CreateOr(X, ConstantInt::get(X->getType(), Xor));
  698. return Builder.CreateICmp(Pred, Or, ConstantInt::get(X->getType(), *C2));
  699. }
  700. return nullptr;
  701. }
  702. // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
  703. // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
  704. Value *InstCombinerImpl::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS,
  705. ICmpInst *RHS,
  706. Instruction *CxtI,
  707. bool IsAnd,
  708. bool IsLogical) {
  709. CmpInst::Predicate Pred = IsAnd ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
  710. if (LHS->getPredicate() != Pred || RHS->getPredicate() != Pred)
  711. return nullptr;
  712. if (!match(LHS->getOperand(1), m_Zero()) ||
  713. !match(RHS->getOperand(1), m_Zero()))
  714. return nullptr;
  715. Value *L1, *L2, *R1, *R2;
  716. if (match(LHS->getOperand(0), m_And(m_Value(L1), m_Value(L2))) &&
  717. match(RHS->getOperand(0), m_And(m_Value(R1), m_Value(R2)))) {
  718. if (L1 == R2 || L2 == R2)
  719. std::swap(R1, R2);
  720. if (L2 == R1)
  721. std::swap(L1, L2);
  722. if (L1 == R1 &&
  723. isKnownToBeAPowerOfTwo(L2, false, 0, CxtI) &&
  724. isKnownToBeAPowerOfTwo(R2, false, 0, CxtI)) {
  725. // If this is a logical and/or, then we must prevent propagation of a
  726. // poison value from the RHS by inserting freeze.
  727. if (IsLogical)
  728. R2 = Builder.CreateFreeze(R2);
  729. Value *Mask = Builder.CreateOr(L2, R2);
  730. Value *Masked = Builder.CreateAnd(L1, Mask);
  731. auto NewPred = IsAnd ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
  732. return Builder.CreateICmp(NewPred, Masked, Mask);
  733. }
  734. }
  735. return nullptr;
  736. }
  737. /// General pattern:
  738. /// X & Y
  739. ///
  740. /// Where Y is checking that all the high bits (covered by a mask 4294967168)
  741. /// are uniform, i.e. %arg & 4294967168 can be either 4294967168 or 0
  742. /// Pattern can be one of:
  743. /// %t = add i32 %arg, 128
  744. /// %r = icmp ult i32 %t, 256
  745. /// Or
  746. /// %t0 = shl i32 %arg, 24
  747. /// %t1 = ashr i32 %t0, 24
  748. /// %r = icmp eq i32 %t1, %arg
  749. /// Or
  750. /// %t0 = trunc i32 %arg to i8
  751. /// %t1 = sext i8 %t0 to i32
  752. /// %r = icmp eq i32 %t1, %arg
  753. /// This pattern is a signed truncation check.
  754. ///
  755. /// And X is checking that some bit in that same mask is zero.
  756. /// I.e. can be one of:
  757. /// %r = icmp sgt i32 %arg, -1
  758. /// Or
  759. /// %t = and i32 %arg, 2147483648
  760. /// %r = icmp eq i32 %t, 0
  761. ///
  762. /// Since we are checking that all the bits in that mask are the same,
  763. /// and a particular bit is zero, what we are really checking is that all the
  764. /// masked bits are zero.
  765. /// So this should be transformed to:
  766. /// %r = icmp ult i32 %arg, 128
  767. static Value *foldSignedTruncationCheck(ICmpInst *ICmp0, ICmpInst *ICmp1,
  768. Instruction &CxtI,
  769. InstCombiner::BuilderTy &Builder) {
  770. assert(CxtI.getOpcode() == Instruction::And);
  771. // Match icmp ult (add %arg, C01), C1 (C1 == C01 << 1; powers of two)
  772. auto tryToMatchSignedTruncationCheck = [](ICmpInst *ICmp, Value *&X,
  773. APInt &SignBitMask) -> bool {
  774. CmpInst::Predicate Pred;
  775. const APInt *I01, *I1; // powers of two; I1 == I01 << 1
  776. if (!(match(ICmp,
  777. m_ICmp(Pred, m_Add(m_Value(X), m_Power2(I01)), m_Power2(I1))) &&
  778. Pred == ICmpInst::ICMP_ULT && I1->ugt(*I01) && I01->shl(1) == *I1))
  779. return false;
  780. // Which bit is the new sign bit as per the 'signed truncation' pattern?
  781. SignBitMask = *I01;
  782. return true;
  783. };
  784. // One icmp needs to be 'signed truncation check'.
  785. // We need to match this first, else we will mismatch commutative cases.
  786. Value *X1;
  787. APInt HighestBit;
  788. ICmpInst *OtherICmp;
  789. if (tryToMatchSignedTruncationCheck(ICmp1, X1, HighestBit))
  790. OtherICmp = ICmp0;
  791. else if (tryToMatchSignedTruncationCheck(ICmp0, X1, HighestBit))
  792. OtherICmp = ICmp1;
  793. else
  794. return nullptr;
  795. assert(HighestBit.isPowerOf2() && "expected to be power of two (non-zero)");
  796. // Try to match/decompose into: icmp eq (X & Mask), 0
  797. auto tryToDecompose = [](ICmpInst *ICmp, Value *&X,
  798. APInt &UnsetBitsMask) -> bool {
  799. CmpInst::Predicate Pred = ICmp->getPredicate();
  800. // Can it be decomposed into icmp eq (X & Mask), 0 ?
  801. if (llvm::decomposeBitTestICmp(ICmp->getOperand(0), ICmp->getOperand(1),
  802. Pred, X, UnsetBitsMask,
  803. /*LookThroughTrunc=*/false) &&
  804. Pred == ICmpInst::ICMP_EQ)
  805. return true;
  806. // Is it icmp eq (X & Mask), 0 already?
  807. const APInt *Mask;
  808. if (match(ICmp, m_ICmp(Pred, m_And(m_Value(X), m_APInt(Mask)), m_Zero())) &&
  809. Pred == ICmpInst::ICMP_EQ) {
  810. UnsetBitsMask = *Mask;
  811. return true;
  812. }
  813. return false;
  814. };
  815. // And the other icmp needs to be decomposable into a bit test.
  816. Value *X0;
  817. APInt UnsetBitsMask;
  818. if (!tryToDecompose(OtherICmp, X0, UnsetBitsMask))
  819. return nullptr;
  820. assert(!UnsetBitsMask.isZero() && "empty mask makes no sense.");
  821. // Are they working on the same value?
  822. Value *X;
  823. if (X1 == X0) {
  824. // Ok as is.
  825. X = X1;
  826. } else if (match(X0, m_Trunc(m_Specific(X1)))) {
  827. UnsetBitsMask = UnsetBitsMask.zext(X1->getType()->getScalarSizeInBits());
  828. X = X1;
  829. } else
  830. return nullptr;
  831. // So which bits should be uniform as per the 'signed truncation check'?
  832. // (all the bits starting with (i.e. including) HighestBit)
  833. APInt SignBitsMask = ~(HighestBit - 1U);
  834. // UnsetBitsMask must have some common bits with SignBitsMask,
  835. if (!UnsetBitsMask.intersects(SignBitsMask))
  836. return nullptr;
  837. // Does UnsetBitsMask contain any bits outside of SignBitsMask?
  838. if (!UnsetBitsMask.isSubsetOf(SignBitsMask)) {
  839. APInt OtherHighestBit = (~UnsetBitsMask) + 1U;
  840. if (!OtherHighestBit.isPowerOf2())
  841. return nullptr;
  842. HighestBit = APIntOps::umin(HighestBit, OtherHighestBit);
  843. }
  844. // Else, if it does not, then all is ok as-is.
  845. // %r = icmp ult %X, SignBit
  846. return Builder.CreateICmpULT(X, ConstantInt::get(X->getType(), HighestBit),
  847. CxtI.getName() + ".simplified");
  848. }
  849. /// Reduce a pair of compares that check if a value has exactly 1 bit set.
  850. static Value *foldIsPowerOf2(ICmpInst *Cmp0, ICmpInst *Cmp1, bool JoinedByAnd,
  851. InstCombiner::BuilderTy &Builder) {
  852. // Handle 'and' / 'or' commutation: make the equality check the first operand.
  853. if (JoinedByAnd && Cmp1->getPredicate() == ICmpInst::ICMP_NE)
  854. std::swap(Cmp0, Cmp1);
  855. else if (!JoinedByAnd && Cmp1->getPredicate() == ICmpInst::ICMP_EQ)
  856. std::swap(Cmp0, Cmp1);
  857. // (X != 0) && (ctpop(X) u< 2) --> ctpop(X) == 1
  858. CmpInst::Predicate Pred0, Pred1;
  859. Value *X;
  860. if (JoinedByAnd && match(Cmp0, m_ICmp(Pred0, m_Value(X), m_ZeroInt())) &&
  861. match(Cmp1, m_ICmp(Pred1, m_Intrinsic<Intrinsic::ctpop>(m_Specific(X)),
  862. m_SpecificInt(2))) &&
  863. Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_ULT) {
  864. Value *CtPop = Cmp1->getOperand(0);
  865. return Builder.CreateICmpEQ(CtPop, ConstantInt::get(CtPop->getType(), 1));
  866. }
  867. // (X == 0) || (ctpop(X) u> 1) --> ctpop(X) != 1
  868. if (!JoinedByAnd && match(Cmp0, m_ICmp(Pred0, m_Value(X), m_ZeroInt())) &&
  869. match(Cmp1, m_ICmp(Pred1, m_Intrinsic<Intrinsic::ctpop>(m_Specific(X)),
  870. m_SpecificInt(1))) &&
  871. Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_UGT) {
  872. Value *CtPop = Cmp1->getOperand(0);
  873. return Builder.CreateICmpNE(CtPop, ConstantInt::get(CtPop->getType(), 1));
  874. }
  875. return nullptr;
  876. }
  877. /// Commuted variants are assumed to be handled by calling this function again
  878. /// with the parameters swapped.
  879. static Value *foldUnsignedUnderflowCheck(ICmpInst *ZeroICmp,
  880. ICmpInst *UnsignedICmp, bool IsAnd,
  881. const SimplifyQuery &Q,
  882. InstCombiner::BuilderTy &Builder) {
  883. Value *ZeroCmpOp;
  884. ICmpInst::Predicate EqPred;
  885. if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(ZeroCmpOp), m_Zero())) ||
  886. !ICmpInst::isEquality(EqPred))
  887. return nullptr;
  888. auto IsKnownNonZero = [&](Value *V) {
  889. return isKnownNonZero(V, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
  890. };
  891. ICmpInst::Predicate UnsignedPred;
  892. Value *A, *B;
  893. if (match(UnsignedICmp,
  894. m_c_ICmp(UnsignedPred, m_Specific(ZeroCmpOp), m_Value(A))) &&
  895. match(ZeroCmpOp, m_c_Add(m_Specific(A), m_Value(B))) &&
  896. (ZeroICmp->hasOneUse() || UnsignedICmp->hasOneUse())) {
  897. auto GetKnownNonZeroAndOther = [&](Value *&NonZero, Value *&Other) {
  898. if (!IsKnownNonZero(NonZero))
  899. std::swap(NonZero, Other);
  900. return IsKnownNonZero(NonZero);
  901. };
  902. // Given ZeroCmpOp = (A + B)
  903. // ZeroCmpOp <= A && ZeroCmpOp != 0 --> (0-B) < A
  904. // ZeroCmpOp > A || ZeroCmpOp == 0 --> (0-B) >= A
  905. //
  906. // ZeroCmpOp < A && ZeroCmpOp != 0 --> (0-X) < Y iff
  907. // ZeroCmpOp >= A || ZeroCmpOp == 0 --> (0-X) >= Y iff
  908. // with X being the value (A/B) that is known to be non-zero,
  909. // and Y being remaining value.
  910. if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE &&
  911. IsAnd)
  912. return Builder.CreateICmpULT(Builder.CreateNeg(B), A);
  913. if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE &&
  914. IsAnd && GetKnownNonZeroAndOther(B, A))
  915. return Builder.CreateICmpULT(Builder.CreateNeg(B), A);
  916. if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ &&
  917. !IsAnd)
  918. return Builder.CreateICmpUGE(Builder.CreateNeg(B), A);
  919. if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_EQ &&
  920. !IsAnd && GetKnownNonZeroAndOther(B, A))
  921. return Builder.CreateICmpUGE(Builder.CreateNeg(B), A);
  922. }
  923. Value *Base, *Offset;
  924. if (!match(ZeroCmpOp, m_Sub(m_Value(Base), m_Value(Offset))))
  925. return nullptr;
  926. if (!match(UnsignedICmp,
  927. m_c_ICmp(UnsignedPred, m_Specific(Base), m_Specific(Offset))) ||
  928. !ICmpInst::isUnsigned(UnsignedPred))
  929. return nullptr;
  930. // Base >=/> Offset && (Base - Offset) != 0 <--> Base > Offset
  931. // (no overflow and not null)
  932. if ((UnsignedPred == ICmpInst::ICMP_UGE ||
  933. UnsignedPred == ICmpInst::ICMP_UGT) &&
  934. EqPred == ICmpInst::ICMP_NE && IsAnd)
  935. return Builder.CreateICmpUGT(Base, Offset);
  936. // Base <=/< Offset || (Base - Offset) == 0 <--> Base <= Offset
  937. // (overflow or null)
  938. if ((UnsignedPred == ICmpInst::ICMP_ULE ||
  939. UnsignedPred == ICmpInst::ICMP_ULT) &&
  940. EqPred == ICmpInst::ICMP_EQ && !IsAnd)
  941. return Builder.CreateICmpULE(Base, Offset);
  942. // Base <= Offset && (Base - Offset) != 0 --> Base < Offset
  943. if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE &&
  944. IsAnd)
  945. return Builder.CreateICmpULT(Base, Offset);
  946. // Base > Offset || (Base - Offset) == 0 --> Base >= Offset
  947. if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ &&
  948. !IsAnd)
  949. return Builder.CreateICmpUGE(Base, Offset);
  950. return nullptr;
  951. }
  952. struct IntPart {
  953. Value *From;
  954. unsigned StartBit;
  955. unsigned NumBits;
  956. };
  957. /// Match an extraction of bits from an integer.
  958. static Optional<IntPart> matchIntPart(Value *V) {
  959. Value *X;
  960. if (!match(V, m_OneUse(m_Trunc(m_Value(X)))))
  961. return None;
  962. unsigned NumOriginalBits = X->getType()->getScalarSizeInBits();
  963. unsigned NumExtractedBits = V->getType()->getScalarSizeInBits();
  964. Value *Y;
  965. const APInt *Shift;
  966. // For a trunc(lshr Y, Shift) pattern, make sure we're only extracting bits
  967. // from Y, not any shifted-in zeroes.
  968. if (match(X, m_OneUse(m_LShr(m_Value(Y), m_APInt(Shift)))) &&
  969. Shift->ule(NumOriginalBits - NumExtractedBits))
  970. return {{Y, (unsigned)Shift->getZExtValue(), NumExtractedBits}};
  971. return {{X, 0, NumExtractedBits}};
  972. }
  973. /// Materialize an extraction of bits from an integer in IR.
  974. static Value *extractIntPart(const IntPart &P, IRBuilderBase &Builder) {
  975. Value *V = P.From;
  976. if (P.StartBit)
  977. V = Builder.CreateLShr(V, P.StartBit);
  978. Type *TruncTy = V->getType()->getWithNewBitWidth(P.NumBits);
  979. if (TruncTy != V->getType())
  980. V = Builder.CreateTrunc(V, TruncTy);
  981. return V;
  982. }
  983. /// (icmp eq X0, Y0) & (icmp eq X1, Y1) -> icmp eq X01, Y01
  984. /// (icmp ne X0, Y0) | (icmp ne X1, Y1) -> icmp ne X01, Y01
  985. /// where X0, X1 and Y0, Y1 are adjacent parts extracted from an integer.
  986. Value *InstCombinerImpl::foldEqOfParts(ICmpInst *Cmp0, ICmpInst *Cmp1,
  987. bool IsAnd) {
  988. if (!Cmp0->hasOneUse() || !Cmp1->hasOneUse())
  989. return nullptr;
  990. CmpInst::Predicate Pred = IsAnd ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
  991. if (Cmp0->getPredicate() != Pred || Cmp1->getPredicate() != Pred)
  992. return nullptr;
  993. Optional<IntPart> L0 = matchIntPart(Cmp0->getOperand(0));
  994. Optional<IntPart> R0 = matchIntPart(Cmp0->getOperand(1));
  995. Optional<IntPart> L1 = matchIntPart(Cmp1->getOperand(0));
  996. Optional<IntPart> R1 = matchIntPart(Cmp1->getOperand(1));
  997. if (!L0 || !R0 || !L1 || !R1)
  998. return nullptr;
  999. // Make sure the LHS/RHS compare a part of the same value, possibly after
  1000. // an operand swap.
  1001. if (L0->From != L1->From || R0->From != R1->From) {
  1002. if (L0->From != R1->From || R0->From != L1->From)
  1003. return nullptr;
  1004. std::swap(L1, R1);
  1005. }
  1006. // Make sure the extracted parts are adjacent, canonicalizing to L0/R0 being
  1007. // the low part and L1/R1 being the high part.
  1008. if (L0->StartBit + L0->NumBits != L1->StartBit ||
  1009. R0->StartBit + R0->NumBits != R1->StartBit) {
  1010. if (L1->StartBit + L1->NumBits != L0->StartBit ||
  1011. R1->StartBit + R1->NumBits != R0->StartBit)
  1012. return nullptr;
  1013. std::swap(L0, L1);
  1014. std::swap(R0, R1);
  1015. }
  1016. // We can simplify to a comparison of these larger parts of the integers.
  1017. IntPart L = {L0->From, L0->StartBit, L0->NumBits + L1->NumBits};
  1018. IntPart R = {R0->From, R0->StartBit, R0->NumBits + R1->NumBits};
  1019. Value *LValue = extractIntPart(L, Builder);
  1020. Value *RValue = extractIntPart(R, Builder);
  1021. return Builder.CreateICmp(Pred, LValue, RValue);
  1022. }
  1023. /// Reduce logic-of-compares with equality to a constant by substituting a
  1024. /// common operand with the constant. Callers are expected to call this with
  1025. /// Cmp0/Cmp1 switched to handle logic op commutativity.
  1026. static Value *foldAndOrOfICmpsWithConstEq(ICmpInst *Cmp0, ICmpInst *Cmp1,
  1027. BinaryOperator &Logic,
  1028. InstCombiner::BuilderTy &Builder,
  1029. const SimplifyQuery &Q) {
  1030. bool IsAnd = Logic.getOpcode() == Instruction::And;
  1031. assert((IsAnd || Logic.getOpcode() == Instruction::Or) && "Wrong logic op");
  1032. // Match an equality compare with a non-poison constant as Cmp0.
  1033. // Also, give up if the compare can be constant-folded to avoid looping.
  1034. ICmpInst::Predicate Pred0;
  1035. Value *X;
  1036. Constant *C;
  1037. if (!match(Cmp0, m_ICmp(Pred0, m_Value(X), m_Constant(C))) ||
  1038. !isGuaranteedNotToBeUndefOrPoison(C) || isa<Constant>(X))
  1039. return nullptr;
  1040. if ((IsAnd && Pred0 != ICmpInst::ICMP_EQ) ||
  1041. (!IsAnd && Pred0 != ICmpInst::ICMP_NE))
  1042. return nullptr;
  1043. // The other compare must include a common operand (X). Canonicalize the
  1044. // common operand as operand 1 (Pred1 is swapped if the common operand was
  1045. // operand 0).
  1046. Value *Y;
  1047. ICmpInst::Predicate Pred1;
  1048. if (!match(Cmp1, m_c_ICmp(Pred1, m_Value(Y), m_Deferred(X))))
  1049. return nullptr;
  1050. // Replace variable with constant value equivalence to remove a variable use:
  1051. // (X == C) && (Y Pred1 X) --> (X == C) && (Y Pred1 C)
  1052. // (X != C) || (Y Pred1 X) --> (X != C) || (Y Pred1 C)
  1053. // Can think of the 'or' substitution with the 'and' bool equivalent:
  1054. // A || B --> A || (!A && B)
  1055. Value *SubstituteCmp = SimplifyICmpInst(Pred1, Y, C, Q);
  1056. if (!SubstituteCmp) {
  1057. // If we need to create a new instruction, require that the old compare can
  1058. // be removed.
  1059. if (!Cmp1->hasOneUse())
  1060. return nullptr;
  1061. SubstituteCmp = Builder.CreateICmp(Pred1, Y, C);
  1062. }
  1063. return Builder.CreateBinOp(Logic.getOpcode(), Cmp0, SubstituteCmp);
  1064. }
  1065. /// Fold (icmp Pred1 V1, C1) & (icmp Pred2 V2, C2)
  1066. /// or (icmp Pred1 V1, C1) | (icmp Pred2 V2, C2)
  1067. /// into a single comparison using range-based reasoning.
  1068. static Value *foldAndOrOfICmpsUsingRanges(
  1069. ICmpInst::Predicate Pred1, Value *V1, const APInt &C1,
  1070. ICmpInst::Predicate Pred2, Value *V2, const APInt &C2,
  1071. IRBuilderBase &Builder, bool IsAnd) {
  1072. // Look through add of a constant offset on V1, V2, or both operands. This
  1073. // allows us to interpret the V + C' < C'' range idiom into a proper range.
  1074. const APInt *Offset1 = nullptr, *Offset2 = nullptr;
  1075. if (V1 != V2) {
  1076. Value *X;
  1077. if (match(V1, m_Add(m_Value(X), m_APInt(Offset1))))
  1078. V1 = X;
  1079. if (match(V2, m_Add(m_Value(X), m_APInt(Offset2))))
  1080. V2 = X;
  1081. }
  1082. if (V1 != V2)
  1083. return nullptr;
  1084. ConstantRange CR1 = ConstantRange::makeExactICmpRegion(Pred1, C1);
  1085. if (Offset1)
  1086. CR1 = CR1.subtract(*Offset1);
  1087. ConstantRange CR2 = ConstantRange::makeExactICmpRegion(Pred2, C2);
  1088. if (Offset2)
  1089. CR2 = CR2.subtract(*Offset2);
  1090. Optional<ConstantRange> CR =
  1091. IsAnd ? CR1.exactIntersectWith(CR2) : CR1.exactUnionWith(CR2);
  1092. if (!CR)
  1093. return nullptr;
  1094. CmpInst::Predicate NewPred;
  1095. APInt NewC, Offset;
  1096. CR->getEquivalentICmp(NewPred, NewC, Offset);
  1097. Type *Ty = V1->getType();
  1098. Value *NewV = V1;
  1099. if (Offset != 0)
  1100. NewV = Builder.CreateAdd(NewV, ConstantInt::get(Ty, Offset));
  1101. return Builder.CreateICmp(NewPred, NewV, ConstantInt::get(Ty, NewC));
  1102. }
  1103. /// Fold (icmp)&(icmp) if possible.
  1104. Value *InstCombinerImpl::foldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS,
  1105. BinaryOperator &And) {
  1106. const SimplifyQuery Q = SQ.getWithInstruction(&And);
  1107. // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
  1108. // if K1 and K2 are a one-bit mask.
  1109. if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, &And,
  1110. /* IsAnd */ true))
  1111. return V;
  1112. ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
  1113. // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
  1114. if (predicatesFoldable(PredL, PredR)) {
  1115. if (LHS->getOperand(0) == RHS->getOperand(1) &&
  1116. LHS->getOperand(1) == RHS->getOperand(0))
  1117. LHS->swapOperands();
  1118. if (LHS->getOperand(0) == RHS->getOperand(0) &&
  1119. LHS->getOperand(1) == RHS->getOperand(1)) {
  1120. Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
  1121. unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
  1122. bool IsSigned = LHS->isSigned() || RHS->isSigned();
  1123. return getNewICmpValue(Code, IsSigned, Op0, Op1, Builder);
  1124. }
  1125. }
  1126. // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
  1127. if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
  1128. return V;
  1129. if (Value *V = foldAndOrOfICmpsWithConstEq(LHS, RHS, And, Builder, Q))
  1130. return V;
  1131. if (Value *V = foldAndOrOfICmpsWithConstEq(RHS, LHS, And, Builder, Q))
  1132. return V;
  1133. // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
  1134. if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
  1135. return V;
  1136. // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
  1137. if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
  1138. return V;
  1139. if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, true, Builder))
  1140. return V;
  1141. if (Value *V = foldSignedTruncationCheck(LHS, RHS, And, Builder))
  1142. return V;
  1143. if (Value *V = foldIsPowerOf2(LHS, RHS, true /* JoinedByAnd */, Builder))
  1144. return V;
  1145. if (Value *X =
  1146. foldUnsignedUnderflowCheck(LHS, RHS, /*IsAnd=*/true, Q, Builder))
  1147. return X;
  1148. if (Value *X =
  1149. foldUnsignedUnderflowCheck(RHS, LHS, /*IsAnd=*/true, Q, Builder))
  1150. return X;
  1151. if (Value *X = foldEqOfParts(LHS, RHS, /*IsAnd=*/true))
  1152. return X;
  1153. // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
  1154. Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
  1155. // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
  1156. // TODO: Remove this when foldLogOpOfMaskedICmps can handle undefs.
  1157. if (PredL == ICmpInst::ICMP_EQ && match(LHS->getOperand(1), m_ZeroInt()) &&
  1158. PredR == ICmpInst::ICMP_EQ && match(RHS->getOperand(1), m_ZeroInt()) &&
  1159. LHS0->getType() == RHS0->getType()) {
  1160. Value *NewOr = Builder.CreateOr(LHS0, RHS0);
  1161. return Builder.CreateICmp(PredL, NewOr,
  1162. Constant::getNullValue(NewOr->getType()));
  1163. }
  1164. const APInt *LHSC, *RHSC;
  1165. if (!match(LHS->getOperand(1), m_APInt(LHSC)) ||
  1166. !match(RHS->getOperand(1), m_APInt(RHSC)))
  1167. return nullptr;
  1168. // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
  1169. // where CMAX is the all ones value for the truncated type,
  1170. // iff the lower bits of C2 and CA are zero.
  1171. if (PredL == ICmpInst::ICMP_EQ && PredL == PredR && LHS->hasOneUse() &&
  1172. RHS->hasOneUse()) {
  1173. Value *V;
  1174. const APInt *AndC, *SmallC = nullptr, *BigC = nullptr;
  1175. // (trunc x) == C1 & (and x, CA) == C2
  1176. // (and x, CA) == C2 & (trunc x) == C1
  1177. if (match(RHS0, m_Trunc(m_Value(V))) &&
  1178. match(LHS0, m_And(m_Specific(V), m_APInt(AndC)))) {
  1179. SmallC = RHSC;
  1180. BigC = LHSC;
  1181. } else if (match(LHS0, m_Trunc(m_Value(V))) &&
  1182. match(RHS0, m_And(m_Specific(V), m_APInt(AndC)))) {
  1183. SmallC = LHSC;
  1184. BigC = RHSC;
  1185. }
  1186. if (SmallC && BigC) {
  1187. unsigned BigBitSize = BigC->getBitWidth();
  1188. unsigned SmallBitSize = SmallC->getBitWidth();
  1189. // Check that the low bits are zero.
  1190. APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
  1191. if ((Low & *AndC).isZero() && (Low & *BigC).isZero()) {
  1192. Value *NewAnd = Builder.CreateAnd(V, Low | *AndC);
  1193. APInt N = SmallC->zext(BigBitSize) | *BigC;
  1194. Value *NewVal = ConstantInt::get(NewAnd->getType(), N);
  1195. return Builder.CreateICmp(PredL, NewAnd, NewVal);
  1196. }
  1197. }
  1198. }
  1199. return foldAndOrOfICmpsUsingRanges(PredL, LHS0, *LHSC, PredR, RHS0, *RHSC,
  1200. Builder, /* IsAnd */ true);
  1201. }
  1202. Value *InstCombinerImpl::foldLogicOfFCmps(FCmpInst *LHS, FCmpInst *RHS,
  1203. bool IsAnd) {
  1204. Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
  1205. Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
  1206. FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
  1207. if (LHS0 == RHS1 && RHS0 == LHS1) {
  1208. // Swap RHS operands to match LHS.
  1209. PredR = FCmpInst::getSwappedPredicate(PredR);
  1210. std::swap(RHS0, RHS1);
  1211. }
  1212. // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
  1213. // Suppose the relation between x and y is R, where R is one of
  1214. // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
  1215. // testing the desired relations.
  1216. //
  1217. // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
  1218. // bool(R & CC0) && bool(R & CC1)
  1219. // = bool((R & CC0) & (R & CC1))
  1220. // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
  1221. //
  1222. // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
  1223. // bool(R & CC0) || bool(R & CC1)
  1224. // = bool((R & CC0) | (R & CC1))
  1225. // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
  1226. if (LHS0 == RHS0 && LHS1 == RHS1) {
  1227. unsigned FCmpCodeL = getFCmpCode(PredL);
  1228. unsigned FCmpCodeR = getFCmpCode(PredR);
  1229. unsigned NewPred = IsAnd ? FCmpCodeL & FCmpCodeR : FCmpCodeL | FCmpCodeR;
  1230. return getFCmpValue(NewPred, LHS0, LHS1, Builder);
  1231. }
  1232. if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
  1233. (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) {
  1234. if (LHS0->getType() != RHS0->getType())
  1235. return nullptr;
  1236. // FCmp canonicalization ensures that (fcmp ord/uno X, X) and
  1237. // (fcmp ord/uno X, C) will be transformed to (fcmp X, +0.0).
  1238. if (match(LHS1, m_PosZeroFP()) && match(RHS1, m_PosZeroFP()))
  1239. // Ignore the constants because they are obviously not NANs:
  1240. // (fcmp ord x, 0.0) & (fcmp ord y, 0.0) -> (fcmp ord x, y)
  1241. // (fcmp uno x, 0.0) | (fcmp uno y, 0.0) -> (fcmp uno x, y)
  1242. return Builder.CreateFCmp(PredL, LHS0, RHS0);
  1243. }
  1244. return nullptr;
  1245. }
  1246. /// This a limited reassociation for a special case (see above) where we are
  1247. /// checking if two values are either both NAN (unordered) or not-NAN (ordered).
  1248. /// This could be handled more generally in '-reassociation', but it seems like
  1249. /// an unlikely pattern for a large number of logic ops and fcmps.
  1250. static Instruction *reassociateFCmps(BinaryOperator &BO,
  1251. InstCombiner::BuilderTy &Builder) {
  1252. Instruction::BinaryOps Opcode = BO.getOpcode();
  1253. assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
  1254. "Expecting and/or op for fcmp transform");
  1255. // There are 4 commuted variants of the pattern. Canonicalize operands of this
  1256. // logic op so an fcmp is operand 0 and a matching logic op is operand 1.
  1257. Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1), *X;
  1258. FCmpInst::Predicate Pred;
  1259. if (match(Op1, m_FCmp(Pred, m_Value(), m_AnyZeroFP())))
  1260. std::swap(Op0, Op1);
  1261. // Match inner binop and the predicate for combining 2 NAN checks into 1.
  1262. Value *BO10, *BO11;
  1263. FCmpInst::Predicate NanPred = Opcode == Instruction::And ? FCmpInst::FCMP_ORD
  1264. : FCmpInst::FCMP_UNO;
  1265. if (!match(Op0, m_FCmp(Pred, m_Value(X), m_AnyZeroFP())) || Pred != NanPred ||
  1266. !match(Op1, m_BinOp(Opcode, m_Value(BO10), m_Value(BO11))))
  1267. return nullptr;
  1268. // The inner logic op must have a matching fcmp operand.
  1269. Value *Y;
  1270. if (!match(BO10, m_FCmp(Pred, m_Value(Y), m_AnyZeroFP())) ||
  1271. Pred != NanPred || X->getType() != Y->getType())
  1272. std::swap(BO10, BO11);
  1273. if (!match(BO10, m_FCmp(Pred, m_Value(Y), m_AnyZeroFP())) ||
  1274. Pred != NanPred || X->getType() != Y->getType())
  1275. return nullptr;
  1276. // and (fcmp ord X, 0), (and (fcmp ord Y, 0), Z) --> and (fcmp ord X, Y), Z
  1277. // or (fcmp uno X, 0), (or (fcmp uno Y, 0), Z) --> or (fcmp uno X, Y), Z
  1278. Value *NewFCmp = Builder.CreateFCmp(Pred, X, Y);
  1279. if (auto *NewFCmpInst = dyn_cast<FCmpInst>(NewFCmp)) {
  1280. // Intersect FMF from the 2 source fcmps.
  1281. NewFCmpInst->copyIRFlags(Op0);
  1282. NewFCmpInst->andIRFlags(BO10);
  1283. }
  1284. return BinaryOperator::Create(Opcode, NewFCmp, BO11);
  1285. }
  1286. /// Match variations of De Morgan's Laws:
  1287. /// (~A & ~B) == (~(A | B))
  1288. /// (~A | ~B) == (~(A & B))
  1289. static Instruction *matchDeMorgansLaws(BinaryOperator &I,
  1290. InstCombiner::BuilderTy &Builder) {
  1291. const Instruction::BinaryOps Opcode = I.getOpcode();
  1292. assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
  1293. "Trying to match De Morgan's Laws with something other than and/or");
  1294. // Flip the logic operation.
  1295. const Instruction::BinaryOps FlippedOpcode =
  1296. (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
  1297. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  1298. Value *A, *B;
  1299. if (match(Op0, m_OneUse(m_Not(m_Value(A)))) &&
  1300. match(Op1, m_OneUse(m_Not(m_Value(B)))) &&
  1301. !InstCombiner::isFreeToInvert(A, A->hasOneUse()) &&
  1302. !InstCombiner::isFreeToInvert(B, B->hasOneUse())) {
  1303. Value *AndOr =
  1304. Builder.CreateBinOp(FlippedOpcode, A, B, I.getName() + ".demorgan");
  1305. return BinaryOperator::CreateNot(AndOr);
  1306. }
  1307. // The 'not' ops may require reassociation.
  1308. // (A & ~B) & ~C --> A & ~(B | C)
  1309. // (~B & A) & ~C --> A & ~(B | C)
  1310. // (A | ~B) | ~C --> A | ~(B & C)
  1311. // (~B | A) | ~C --> A | ~(B & C)
  1312. Value *C;
  1313. if (match(Op0, m_OneUse(m_c_BinOp(Opcode, m_Value(A), m_Not(m_Value(B))))) &&
  1314. match(Op1, m_Not(m_Value(C)))) {
  1315. Value *FlippedBO = Builder.CreateBinOp(FlippedOpcode, B, C);
  1316. return BinaryOperator::Create(Opcode, A, Builder.CreateNot(FlippedBO));
  1317. }
  1318. return nullptr;
  1319. }
  1320. bool InstCombinerImpl::shouldOptimizeCast(CastInst *CI) {
  1321. Value *CastSrc = CI->getOperand(0);
  1322. // Noop casts and casts of constants should be eliminated trivially.
  1323. if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
  1324. return false;
  1325. // If this cast is paired with another cast that can be eliminated, we prefer
  1326. // to have it eliminated.
  1327. if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
  1328. if (isEliminableCastPair(PrecedingCI, CI))
  1329. return false;
  1330. return true;
  1331. }
  1332. /// Fold {and,or,xor} (cast X), C.
  1333. static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
  1334. InstCombiner::BuilderTy &Builder) {
  1335. Constant *C = dyn_cast<Constant>(Logic.getOperand(1));
  1336. if (!C)
  1337. return nullptr;
  1338. auto LogicOpc = Logic.getOpcode();
  1339. Type *DestTy = Logic.getType();
  1340. Type *SrcTy = Cast->getSrcTy();
  1341. // Move the logic operation ahead of a zext or sext if the constant is
  1342. // unchanged in the smaller source type. Performing the logic in a smaller
  1343. // type may provide more information to later folds, and the smaller logic
  1344. // instruction may be cheaper (particularly in the case of vectors).
  1345. Value *X;
  1346. if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
  1347. Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
  1348. Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
  1349. if (ZextTruncC == C) {
  1350. // LogicOpc (zext X), C --> zext (LogicOpc X, C)
  1351. Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
  1352. return new ZExtInst(NewOp, DestTy);
  1353. }
  1354. }
  1355. if (match(Cast, m_OneUse(m_SExt(m_Value(X))))) {
  1356. Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
  1357. Constant *SextTruncC = ConstantExpr::getSExt(TruncC, DestTy);
  1358. if (SextTruncC == C) {
  1359. // LogicOpc (sext X), C --> sext (LogicOpc X, C)
  1360. Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
  1361. return new SExtInst(NewOp, DestTy);
  1362. }
  1363. }
  1364. return nullptr;
  1365. }
  1366. /// Fold {and,or,xor} (cast X), Y.
  1367. Instruction *InstCombinerImpl::foldCastedBitwiseLogic(BinaryOperator &I) {
  1368. auto LogicOpc = I.getOpcode();
  1369. assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
  1370. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  1371. CastInst *Cast0 = dyn_cast<CastInst>(Op0);
  1372. if (!Cast0)
  1373. return nullptr;
  1374. // This must be a cast from an integer or integer vector source type to allow
  1375. // transformation of the logic operation to the source type.
  1376. Type *DestTy = I.getType();
  1377. Type *SrcTy = Cast0->getSrcTy();
  1378. if (!SrcTy->isIntOrIntVectorTy())
  1379. return nullptr;
  1380. if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
  1381. return Ret;
  1382. CastInst *Cast1 = dyn_cast<CastInst>(Op1);
  1383. if (!Cast1)
  1384. return nullptr;
  1385. // Both operands of the logic operation are casts. The casts must be of the
  1386. // same type for reduction.
  1387. auto CastOpcode = Cast0->getOpcode();
  1388. if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
  1389. return nullptr;
  1390. Value *Cast0Src = Cast0->getOperand(0);
  1391. Value *Cast1Src = Cast1->getOperand(0);
  1392. // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
  1393. if (shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
  1394. Value *NewOp = Builder.CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
  1395. I.getName());
  1396. return CastInst::Create(CastOpcode, NewOp, DestTy);
  1397. }
  1398. // For now, only 'and'/'or' have optimizations after this.
  1399. if (LogicOpc == Instruction::Xor)
  1400. return nullptr;
  1401. // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
  1402. // cast is otherwise not optimizable. This happens for vector sexts.
  1403. ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
  1404. ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
  1405. if (ICmp0 && ICmp1) {
  1406. Value *Res = LogicOpc == Instruction::And ? foldAndOfICmps(ICmp0, ICmp1, I)
  1407. : foldOrOfICmps(ICmp0, ICmp1, I);
  1408. if (Res)
  1409. return CastInst::Create(CastOpcode, Res, DestTy);
  1410. return nullptr;
  1411. }
  1412. // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
  1413. // cast is otherwise not optimizable. This happens for vector sexts.
  1414. FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
  1415. FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
  1416. if (FCmp0 && FCmp1)
  1417. if (Value *R = foldLogicOfFCmps(FCmp0, FCmp1, LogicOpc == Instruction::And))
  1418. return CastInst::Create(CastOpcode, R, DestTy);
  1419. return nullptr;
  1420. }
  1421. static Instruction *foldAndToXor(BinaryOperator &I,
  1422. InstCombiner::BuilderTy &Builder) {
  1423. assert(I.getOpcode() == Instruction::And);
  1424. Value *Op0 = I.getOperand(0);
  1425. Value *Op1 = I.getOperand(1);
  1426. Value *A, *B;
  1427. // Operand complexity canonicalization guarantees that the 'or' is Op0.
  1428. // (A | B) & ~(A & B) --> A ^ B
  1429. // (A | B) & ~(B & A) --> A ^ B
  1430. if (match(&I, m_BinOp(m_Or(m_Value(A), m_Value(B)),
  1431. m_Not(m_c_And(m_Deferred(A), m_Deferred(B))))))
  1432. return BinaryOperator::CreateXor(A, B);
  1433. // (A | ~B) & (~A | B) --> ~(A ^ B)
  1434. // (A | ~B) & (B | ~A) --> ~(A ^ B)
  1435. // (~B | A) & (~A | B) --> ~(A ^ B)
  1436. // (~B | A) & (B | ~A) --> ~(A ^ B)
  1437. if (Op0->hasOneUse() || Op1->hasOneUse())
  1438. if (match(&I, m_BinOp(m_c_Or(m_Value(A), m_Not(m_Value(B))),
  1439. m_c_Or(m_Not(m_Deferred(A)), m_Deferred(B)))))
  1440. return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
  1441. return nullptr;
  1442. }
  1443. static Instruction *foldOrToXor(BinaryOperator &I,
  1444. InstCombiner::BuilderTy &Builder) {
  1445. assert(I.getOpcode() == Instruction::Or);
  1446. Value *Op0 = I.getOperand(0);
  1447. Value *Op1 = I.getOperand(1);
  1448. Value *A, *B;
  1449. // Operand complexity canonicalization guarantees that the 'and' is Op0.
  1450. // (A & B) | ~(A | B) --> ~(A ^ B)
  1451. // (A & B) | ~(B | A) --> ~(A ^ B)
  1452. if (Op0->hasOneUse() || Op1->hasOneUse())
  1453. if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
  1454. match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
  1455. return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
  1456. // Operand complexity canonicalization guarantees that the 'xor' is Op0.
  1457. // (A ^ B) | ~(A | B) --> ~(A & B)
  1458. // (A ^ B) | ~(B | A) --> ~(A & B)
  1459. if (Op0->hasOneUse() || Op1->hasOneUse())
  1460. if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
  1461. match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
  1462. return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
  1463. // (A & ~B) | (~A & B) --> A ^ B
  1464. // (A & ~B) | (B & ~A) --> A ^ B
  1465. // (~B & A) | (~A & B) --> A ^ B
  1466. // (~B & A) | (B & ~A) --> A ^ B
  1467. if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
  1468. match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))
  1469. return BinaryOperator::CreateXor(A, B);
  1470. return nullptr;
  1471. }
  1472. /// Return true if a constant shift amount is always less than the specified
  1473. /// bit-width. If not, the shift could create poison in the narrower type.
  1474. static bool canNarrowShiftAmt(Constant *C, unsigned BitWidth) {
  1475. APInt Threshold(C->getType()->getScalarSizeInBits(), BitWidth);
  1476. return match(C, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, Threshold));
  1477. }
  1478. /// Try to use narrower ops (sink zext ops) for an 'and' with binop operand and
  1479. /// a common zext operand: and (binop (zext X), C), (zext X).
  1480. Instruction *InstCombinerImpl::narrowMaskedBinOp(BinaryOperator &And) {
  1481. // This transform could also apply to {or, and, xor}, but there are better
  1482. // folds for those cases, so we don't expect those patterns here. AShr is not
  1483. // handled because it should always be transformed to LShr in this sequence.
  1484. // The subtract transform is different because it has a constant on the left.
  1485. // Add/mul commute the constant to RHS; sub with constant RHS becomes add.
  1486. Value *Op0 = And.getOperand(0), *Op1 = And.getOperand(1);
  1487. Constant *C;
  1488. if (!match(Op0, m_OneUse(m_Add(m_Specific(Op1), m_Constant(C)))) &&
  1489. !match(Op0, m_OneUse(m_Mul(m_Specific(Op1), m_Constant(C)))) &&
  1490. !match(Op0, m_OneUse(m_LShr(m_Specific(Op1), m_Constant(C)))) &&
  1491. !match(Op0, m_OneUse(m_Shl(m_Specific(Op1), m_Constant(C)))) &&
  1492. !match(Op0, m_OneUse(m_Sub(m_Constant(C), m_Specific(Op1)))))
  1493. return nullptr;
  1494. Value *X;
  1495. if (!match(Op1, m_ZExt(m_Value(X))) || Op1->hasNUsesOrMore(3))
  1496. return nullptr;
  1497. Type *Ty = And.getType();
  1498. if (!isa<VectorType>(Ty) && !shouldChangeType(Ty, X->getType()))
  1499. return nullptr;
  1500. // If we're narrowing a shift, the shift amount must be safe (less than the
  1501. // width) in the narrower type. If the shift amount is greater, instsimplify
  1502. // usually handles that case, but we can't guarantee/assert it.
  1503. Instruction::BinaryOps Opc = cast<BinaryOperator>(Op0)->getOpcode();
  1504. if (Opc == Instruction::LShr || Opc == Instruction::Shl)
  1505. if (!canNarrowShiftAmt(C, X->getType()->getScalarSizeInBits()))
  1506. return nullptr;
  1507. // and (sub C, (zext X)), (zext X) --> zext (and (sub C', X), X)
  1508. // and (binop (zext X), C), (zext X) --> zext (and (binop X, C'), X)
  1509. Value *NewC = ConstantExpr::getTrunc(C, X->getType());
  1510. Value *NewBO = Opc == Instruction::Sub ? Builder.CreateBinOp(Opc, NewC, X)
  1511. : Builder.CreateBinOp(Opc, X, NewC);
  1512. return new ZExtInst(Builder.CreateAnd(NewBO, X), Ty);
  1513. }
  1514. /// Try folding relatively complex patterns for both And and Or operations
  1515. /// with all And and Or swapped.
  1516. static Instruction *foldComplexAndOrPatterns(BinaryOperator &I,
  1517. InstCombiner::BuilderTy &Builder) {
  1518. const Instruction::BinaryOps Opcode = I.getOpcode();
  1519. assert(Opcode == Instruction::And || Opcode == Instruction::Or);
  1520. // Flip the logic operation.
  1521. const Instruction::BinaryOps FlippedOpcode =
  1522. (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
  1523. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  1524. Value *A, *B, *C, *X, *Y, *Dummy;
  1525. // Match following expressions:
  1526. // (~(A | B) & C)
  1527. // (~(A & B) | C)
  1528. // Captures X = ~(A | B) or ~(A & B)
  1529. const auto matchNotOrAnd =
  1530. [Opcode, FlippedOpcode](Value *Op, auto m_A, auto m_B, auto m_C,
  1531. Value *&X, bool CountUses = false) -> bool {
  1532. if (CountUses && !Op->hasOneUse())
  1533. return false;
  1534. if (match(Op, m_c_BinOp(FlippedOpcode,
  1535. m_CombineAnd(m_Value(X),
  1536. m_Not(m_c_BinOp(Opcode, m_A, m_B))),
  1537. m_C)))
  1538. return !CountUses || X->hasOneUse();
  1539. return false;
  1540. };
  1541. // (~(A | B) & C) | ... --> ...
  1542. // (~(A & B) | C) & ... --> ...
  1543. // TODO: One use checks are conservative. We just need to check that a total
  1544. // number of multiple used values does not exceed reduction
  1545. // in operations.
  1546. if (matchNotOrAnd(Op0, m_Value(A), m_Value(B), m_Value(C), X)) {
  1547. // (~(A | B) & C) | (~(A | C) & B) --> (B ^ C) & ~A
  1548. // (~(A & B) | C) & (~(A & C) | B) --> ~((B ^ C) & A)
  1549. if (matchNotOrAnd(Op1, m_Specific(A), m_Specific(C), m_Specific(B), Dummy,
  1550. true)) {
  1551. Value *Xor = Builder.CreateXor(B, C);
  1552. return (Opcode == Instruction::Or)
  1553. ? BinaryOperator::CreateAnd(Xor, Builder.CreateNot(A))
  1554. : BinaryOperator::CreateNot(Builder.CreateAnd(Xor, A));
  1555. }
  1556. // (~(A | B) & C) | (~(B | C) & A) --> (A ^ C) & ~B
  1557. // (~(A & B) | C) & (~(B & C) | A) --> ~((A ^ C) & B)
  1558. if (matchNotOrAnd(Op1, m_Specific(B), m_Specific(C), m_Specific(A), Dummy,
  1559. true)) {
  1560. Value *Xor = Builder.CreateXor(A, C);
  1561. return (Opcode == Instruction::Or)
  1562. ? BinaryOperator::CreateAnd(Xor, Builder.CreateNot(B))
  1563. : BinaryOperator::CreateNot(Builder.CreateAnd(Xor, B));
  1564. }
  1565. // (~(A | B) & C) | ~(A | C) --> ~((B & C) | A)
  1566. // (~(A & B) | C) & ~(A & C) --> ~((B | C) & A)
  1567. if (match(Op1, m_OneUse(m_Not(m_OneUse(
  1568. m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)))))))
  1569. return BinaryOperator::CreateNot(Builder.CreateBinOp(
  1570. Opcode, Builder.CreateBinOp(FlippedOpcode, B, C), A));
  1571. // (~(A | B) & C) | ~(B | C) --> ~((A & C) | B)
  1572. // (~(A & B) | C) & ~(B & C) --> ~((A | C) & B)
  1573. if (match(Op1, m_OneUse(m_Not(m_OneUse(
  1574. m_c_BinOp(Opcode, m_Specific(B), m_Specific(C)))))))
  1575. return BinaryOperator::CreateNot(Builder.CreateBinOp(
  1576. Opcode, Builder.CreateBinOp(FlippedOpcode, A, C), B));
  1577. // (~(A | B) & C) | ~(C | (A ^ B)) --> ~((A | B) & (C | (A ^ B)))
  1578. // Note, the pattern with swapped and/or is not handled because the
  1579. // result is more undefined than a source:
  1580. // (~(A & B) | C) & ~(C & (A ^ B)) --> (A ^ B ^ C) | ~(A | C) is invalid.
  1581. if (Opcode == Instruction::Or && Op0->hasOneUse() &&
  1582. match(Op1, m_OneUse(m_Not(m_CombineAnd(
  1583. m_Value(Y),
  1584. m_c_BinOp(Opcode, m_Specific(C),
  1585. m_c_Xor(m_Specific(A), m_Specific(B)))))))) {
  1586. // X = ~(A | B)
  1587. // Y = (C | (A ^ B)
  1588. Value *Or = cast<BinaryOperator>(X)->getOperand(0);
  1589. return BinaryOperator::CreateNot(Builder.CreateAnd(Or, Y));
  1590. }
  1591. }
  1592. // (~A & B & C) | ... --> ...
  1593. // (~A | B | C) | ... --> ...
  1594. // TODO: One use checks are conservative. We just need to check that a total
  1595. // number of multiple used values does not exceed reduction
  1596. // in operations.
  1597. if (match(Op0,
  1598. m_OneUse(m_c_BinOp(FlippedOpcode,
  1599. m_BinOp(FlippedOpcode, m_Value(B), m_Value(C)),
  1600. m_CombineAnd(m_Value(X), m_Not(m_Value(A)))))) ||
  1601. match(Op0, m_OneUse(m_c_BinOp(
  1602. FlippedOpcode,
  1603. m_c_BinOp(FlippedOpcode, m_Value(C),
  1604. m_CombineAnd(m_Value(X), m_Not(m_Value(A)))),
  1605. m_Value(B))))) {
  1606. // X = ~A
  1607. // (~A & B & C) | ~(A | B | C) --> ~(A | (B ^ C))
  1608. // (~A | B | C) & ~(A & B & C) --> (~A | (B ^ C))
  1609. if (match(Op1, m_OneUse(m_Not(m_c_BinOp(
  1610. Opcode, m_c_BinOp(Opcode, m_Specific(A), m_Specific(B)),
  1611. m_Specific(C))))) ||
  1612. match(Op1, m_OneUse(m_Not(m_c_BinOp(
  1613. Opcode, m_c_BinOp(Opcode, m_Specific(B), m_Specific(C)),
  1614. m_Specific(A))))) ||
  1615. match(Op1, m_OneUse(m_Not(m_c_BinOp(
  1616. Opcode, m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)),
  1617. m_Specific(B)))))) {
  1618. Value *Xor = Builder.CreateXor(B, C);
  1619. return (Opcode == Instruction::Or)
  1620. ? BinaryOperator::CreateNot(Builder.CreateOr(Xor, A))
  1621. : BinaryOperator::CreateOr(Xor, X);
  1622. }
  1623. // (~A & B & C) | ~(A | B) --> (C | ~B) & ~A
  1624. // (~A | B | C) & ~(A & B) --> (C & ~B) | ~A
  1625. if (match(Op1, m_OneUse(m_Not(m_OneUse(
  1626. m_c_BinOp(Opcode, m_Specific(A), m_Specific(B)))))))
  1627. return BinaryOperator::Create(
  1628. FlippedOpcode, Builder.CreateBinOp(Opcode, C, Builder.CreateNot(B)),
  1629. X);
  1630. // (~A & B & C) | ~(A | C) --> (B | ~C) & ~A
  1631. // (~A | B | C) & ~(A & C) --> (B & ~C) | ~A
  1632. if (match(Op1, m_OneUse(m_Not(m_OneUse(
  1633. m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)))))))
  1634. return BinaryOperator::Create(
  1635. FlippedOpcode, Builder.CreateBinOp(Opcode, B, Builder.CreateNot(C)),
  1636. X);
  1637. }
  1638. return nullptr;
  1639. }
  1640. // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
  1641. // here. We should standardize that construct where it is needed or choose some
  1642. // other way to ensure that commutated variants of patterns are not missed.
  1643. Instruction *InstCombinerImpl::visitAnd(BinaryOperator &I) {
  1644. Type *Ty = I.getType();
  1645. if (Value *V = SimplifyAndInst(I.getOperand(0), I.getOperand(1),
  1646. SQ.getWithInstruction(&I)))
  1647. return replaceInstUsesWith(I, V);
  1648. if (SimplifyAssociativeOrCommutative(I))
  1649. return &I;
  1650. if (Instruction *X = foldVectorBinop(I))
  1651. return X;
  1652. if (Instruction *Phi = foldBinopWithPhiOperands(I))
  1653. return Phi;
  1654. // See if we can simplify any instructions used by the instruction whose sole
  1655. // purpose is to compute bits we don't care about.
  1656. if (SimplifyDemandedInstructionBits(I))
  1657. return &I;
  1658. // Do this before using distributive laws to catch simple and/or/not patterns.
  1659. if (Instruction *Xor = foldAndToXor(I, Builder))
  1660. return Xor;
  1661. if (Instruction *X = foldComplexAndOrPatterns(I, Builder))
  1662. return X;
  1663. // (A|B)&(A|C) -> A|(B&C) etc
  1664. if (Value *V = SimplifyUsingDistributiveLaws(I))
  1665. return replaceInstUsesWith(I, V);
  1666. if (Value *V = SimplifyBSwap(I, Builder))
  1667. return replaceInstUsesWith(I, V);
  1668. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  1669. Value *X, *Y;
  1670. if (match(Op0, m_OneUse(m_LogicalShift(m_One(), m_Value(X)))) &&
  1671. match(Op1, m_One())) {
  1672. // (1 << X) & 1 --> zext(X == 0)
  1673. // (1 >> X) & 1 --> zext(X == 0)
  1674. Value *IsZero = Builder.CreateICmpEQ(X, ConstantInt::get(Ty, 0));
  1675. return new ZExtInst(IsZero, Ty);
  1676. }
  1677. const APInt *C;
  1678. if (match(Op1, m_APInt(C))) {
  1679. const APInt *XorC;
  1680. if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_APInt(XorC))))) {
  1681. // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
  1682. Constant *NewC = ConstantInt::get(Ty, *C & *XorC);
  1683. Value *And = Builder.CreateAnd(X, Op1);
  1684. And->takeName(Op0);
  1685. return BinaryOperator::CreateXor(And, NewC);
  1686. }
  1687. const APInt *OrC;
  1688. if (match(Op0, m_OneUse(m_Or(m_Value(X), m_APInt(OrC))))) {
  1689. // (X | C1) & C2 --> (X & C2^(C1&C2)) | (C1&C2)
  1690. // NOTE: This reduces the number of bits set in the & mask, which
  1691. // can expose opportunities for store narrowing for scalars.
  1692. // NOTE: SimplifyDemandedBits should have already removed bits from C1
  1693. // that aren't set in C2. Meaning we can replace (C1&C2) with C1 in
  1694. // above, but this feels safer.
  1695. APInt Together = *C & *OrC;
  1696. Value *And = Builder.CreateAnd(X, ConstantInt::get(Ty, Together ^ *C));
  1697. And->takeName(Op0);
  1698. return BinaryOperator::CreateOr(And, ConstantInt::get(Ty, Together));
  1699. }
  1700. // If the mask is only needed on one incoming arm, push the 'and' op up.
  1701. if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_Value(Y)))) ||
  1702. match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
  1703. APInt NotAndMask(~(*C));
  1704. BinaryOperator::BinaryOps BinOp = cast<BinaryOperator>(Op0)->getOpcode();
  1705. if (MaskedValueIsZero(X, NotAndMask, 0, &I)) {
  1706. // Not masking anything out for the LHS, move mask to RHS.
  1707. // and ({x}or X, Y), C --> {x}or X, (and Y, C)
  1708. Value *NewRHS = Builder.CreateAnd(Y, Op1, Y->getName() + ".masked");
  1709. return BinaryOperator::Create(BinOp, X, NewRHS);
  1710. }
  1711. if (!isa<Constant>(Y) && MaskedValueIsZero(Y, NotAndMask, 0, &I)) {
  1712. // Not masking anything out for the RHS, move mask to LHS.
  1713. // and ({x}or X, Y), C --> {x}or (and X, C), Y
  1714. Value *NewLHS = Builder.CreateAnd(X, Op1, X->getName() + ".masked");
  1715. return BinaryOperator::Create(BinOp, NewLHS, Y);
  1716. }
  1717. }
  1718. unsigned Width = Ty->getScalarSizeInBits();
  1719. const APInt *ShiftC;
  1720. if (match(Op0, m_OneUse(m_SExt(m_AShr(m_Value(X), m_APInt(ShiftC)))))) {
  1721. if (*C == APInt::getLowBitsSet(Width, Width - ShiftC->getZExtValue())) {
  1722. // We are clearing high bits that were potentially set by sext+ashr:
  1723. // and (sext (ashr X, ShiftC)), C --> lshr (sext X), ShiftC
  1724. Value *Sext = Builder.CreateSExt(X, Ty);
  1725. Constant *ShAmtC = ConstantInt::get(Ty, ShiftC->zext(Width));
  1726. return BinaryOperator::CreateLShr(Sext, ShAmtC);
  1727. }
  1728. }
  1729. // If this 'and' clears the sign-bits added by ashr, replace with lshr:
  1730. // and (ashr X, ShiftC), C --> lshr X, ShiftC
  1731. if (match(Op0, m_AShr(m_Value(X), m_APInt(ShiftC))) && ShiftC->ult(Width) &&
  1732. C->isMask(Width - ShiftC->getZExtValue()))
  1733. return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, *ShiftC));
  1734. const APInt *AddC;
  1735. if (match(Op0, m_Add(m_Value(X), m_APInt(AddC)))) {
  1736. // If we add zeros to every bit below a mask, the add has no effect:
  1737. // (X + AddC) & LowMaskC --> X & LowMaskC
  1738. unsigned Ctlz = C->countLeadingZeros();
  1739. APInt LowMask(APInt::getLowBitsSet(Width, Width - Ctlz));
  1740. if ((*AddC & LowMask).isZero())
  1741. return BinaryOperator::CreateAnd(X, Op1);
  1742. // If we are masking the result of the add down to exactly one bit and
  1743. // the constant we are adding has no bits set below that bit, then the
  1744. // add is flipping a single bit. Example:
  1745. // (X + 4) & 4 --> (X & 4) ^ 4
  1746. if (Op0->hasOneUse() && C->isPowerOf2() && (*AddC & (*C - 1)) == 0) {
  1747. assert((*C & *AddC) != 0 && "Expected common bit");
  1748. Value *NewAnd = Builder.CreateAnd(X, Op1);
  1749. return BinaryOperator::CreateXor(NewAnd, Op1);
  1750. }
  1751. }
  1752. // ((C1 OP zext(X)) & C2) -> zext((C1 OP X) & C2) if C2 fits in the
  1753. // bitwidth of X and OP behaves well when given trunc(C1) and X.
  1754. auto isSuitableBinOpcode = [](BinaryOperator *B) {
  1755. switch (B->getOpcode()) {
  1756. case Instruction::Xor:
  1757. case Instruction::Or:
  1758. case Instruction::Mul:
  1759. case Instruction::Add:
  1760. case Instruction::Sub:
  1761. return true;
  1762. default:
  1763. return false;
  1764. }
  1765. };
  1766. BinaryOperator *BO;
  1767. if (match(Op0, m_OneUse(m_BinOp(BO))) && isSuitableBinOpcode(BO)) {
  1768. Value *X;
  1769. const APInt *C1;
  1770. // TODO: The one-use restrictions could be relaxed a little if the AND
  1771. // is going to be removed.
  1772. if (match(BO, m_c_BinOp(m_OneUse(m_ZExt(m_Value(X))), m_APInt(C1))) &&
  1773. C->isIntN(X->getType()->getScalarSizeInBits())) {
  1774. unsigned XWidth = X->getType()->getScalarSizeInBits();
  1775. Constant *TruncC1 = ConstantInt::get(X->getType(), C1->trunc(XWidth));
  1776. Value *BinOp = isa<ZExtInst>(BO->getOperand(0))
  1777. ? Builder.CreateBinOp(BO->getOpcode(), X, TruncC1)
  1778. : Builder.CreateBinOp(BO->getOpcode(), TruncC1, X);
  1779. Constant *TruncC = ConstantInt::get(X->getType(), C->trunc(XWidth));
  1780. Value *And = Builder.CreateAnd(BinOp, TruncC);
  1781. return new ZExtInst(And, Ty);
  1782. }
  1783. }
  1784. }
  1785. if (match(&I, m_And(m_OneUse(m_Shl(m_ZExt(m_Value(X)), m_Value(Y))),
  1786. m_SignMask())) &&
  1787. match(Y, m_SpecificInt_ICMP(
  1788. ICmpInst::Predicate::ICMP_EQ,
  1789. APInt(Ty->getScalarSizeInBits(),
  1790. Ty->getScalarSizeInBits() -
  1791. X->getType()->getScalarSizeInBits())))) {
  1792. auto *SExt = Builder.CreateSExt(X, Ty, X->getName() + ".signext");
  1793. auto *SanitizedSignMask = cast<Constant>(Op1);
  1794. // We must be careful with the undef elements of the sign bit mask, however:
  1795. // the mask elt can be undef iff the shift amount for that lane was undef,
  1796. // otherwise we need to sanitize undef masks to zero.
  1797. SanitizedSignMask = Constant::replaceUndefsWith(
  1798. SanitizedSignMask, ConstantInt::getNullValue(Ty->getScalarType()));
  1799. SanitizedSignMask =
  1800. Constant::mergeUndefsWith(SanitizedSignMask, cast<Constant>(Y));
  1801. return BinaryOperator::CreateAnd(SExt, SanitizedSignMask);
  1802. }
  1803. if (Instruction *Z = narrowMaskedBinOp(I))
  1804. return Z;
  1805. if (I.getType()->isIntOrIntVectorTy(1)) {
  1806. if (auto *SI0 = dyn_cast<SelectInst>(Op0)) {
  1807. if (auto *I =
  1808. foldAndOrOfSelectUsingImpliedCond(Op1, *SI0, /* IsAnd */ true))
  1809. return I;
  1810. }
  1811. if (auto *SI1 = dyn_cast<SelectInst>(Op1)) {
  1812. if (auto *I =
  1813. foldAndOrOfSelectUsingImpliedCond(Op0, *SI1, /* IsAnd */ true))
  1814. return I;
  1815. }
  1816. }
  1817. if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
  1818. return FoldedLogic;
  1819. if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
  1820. return DeMorgan;
  1821. {
  1822. Value *A, *B, *C;
  1823. // A & (A ^ B) --> A & ~B
  1824. if (match(Op1, m_OneUse(m_c_Xor(m_Specific(Op0), m_Value(B)))))
  1825. return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(B));
  1826. // (A ^ B) & A --> A & ~B
  1827. if (match(Op0, m_OneUse(m_c_Xor(m_Specific(Op1), m_Value(B)))))
  1828. return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(B));
  1829. // A & ~(A ^ B) --> A & B
  1830. if (match(Op1, m_Not(m_c_Xor(m_Specific(Op0), m_Value(B)))))
  1831. return BinaryOperator::CreateAnd(Op0, B);
  1832. // ~(A ^ B) & A --> A & B
  1833. if (match(Op0, m_Not(m_c_Xor(m_Specific(Op1), m_Value(B)))))
  1834. return BinaryOperator::CreateAnd(Op1, B);
  1835. // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
  1836. if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
  1837. if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
  1838. if (Op1->hasOneUse() || isFreeToInvert(C, C->hasOneUse()))
  1839. return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(C));
  1840. // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
  1841. if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
  1842. if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
  1843. if (Op0->hasOneUse() || isFreeToInvert(C, C->hasOneUse()))
  1844. return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(C));
  1845. // (A | B) & (~A ^ B) -> A & B
  1846. // (A | B) & (B ^ ~A) -> A & B
  1847. // (B | A) & (~A ^ B) -> A & B
  1848. // (B | A) & (B ^ ~A) -> A & B
  1849. if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
  1850. match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
  1851. return BinaryOperator::CreateAnd(A, B);
  1852. // (~A ^ B) & (A | B) -> A & B
  1853. // (~A ^ B) & (B | A) -> A & B
  1854. // (B ^ ~A) & (A | B) -> A & B
  1855. // (B ^ ~A) & (B | A) -> A & B
  1856. if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
  1857. match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
  1858. return BinaryOperator::CreateAnd(A, B);
  1859. // (~A | B) & (A ^ B) -> ~A & B
  1860. // (~A | B) & (B ^ A) -> ~A & B
  1861. // (B | ~A) & (A ^ B) -> ~A & B
  1862. // (B | ~A) & (B ^ A) -> ~A & B
  1863. if (match(Op0, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
  1864. match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
  1865. return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
  1866. // (A ^ B) & (~A | B) -> ~A & B
  1867. // (B ^ A) & (~A | B) -> ~A & B
  1868. // (A ^ B) & (B | ~A) -> ~A & B
  1869. // (B ^ A) & (B | ~A) -> ~A & B
  1870. if (match(Op1, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
  1871. match(Op0, m_c_Xor(m_Specific(A), m_Specific(B))))
  1872. return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
  1873. }
  1874. {
  1875. ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
  1876. ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
  1877. if (LHS && RHS)
  1878. if (Value *Res = foldAndOfICmps(LHS, RHS, I))
  1879. return replaceInstUsesWith(I, Res);
  1880. // TODO: Make this recursive; it's a little tricky because an arbitrary
  1881. // number of 'and' instructions might have to be created.
  1882. if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
  1883. if (auto *Cmp = dyn_cast<ICmpInst>(X))
  1884. if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
  1885. return replaceInstUsesWith(I, Builder.CreateAnd(Res, Y));
  1886. if (auto *Cmp = dyn_cast<ICmpInst>(Y))
  1887. if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
  1888. return replaceInstUsesWith(I, Builder.CreateAnd(Res, X));
  1889. }
  1890. if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
  1891. if (auto *Cmp = dyn_cast<ICmpInst>(X))
  1892. if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
  1893. return replaceInstUsesWith(I, Builder.CreateAnd(Res, Y));
  1894. if (auto *Cmp = dyn_cast<ICmpInst>(Y))
  1895. if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
  1896. return replaceInstUsesWith(I, Builder.CreateAnd(Res, X));
  1897. }
  1898. }
  1899. if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
  1900. if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
  1901. if (Value *Res = foldLogicOfFCmps(LHS, RHS, true))
  1902. return replaceInstUsesWith(I, Res);
  1903. if (Instruction *FoldedFCmps = reassociateFCmps(I, Builder))
  1904. return FoldedFCmps;
  1905. if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
  1906. return CastedAnd;
  1907. if (Instruction *Sel = foldBinopOfSextBoolToSelect(I))
  1908. return Sel;
  1909. // and(sext(A), B) / and(B, sext(A)) --> A ? B : 0, where A is i1 or <N x i1>.
  1910. // TODO: Move this into foldBinopOfSextBoolToSelect as a more generalized fold
  1911. // with binop identity constant. But creating a select with non-constant
  1912. // arm may not be reversible due to poison semantics. Is that a good
  1913. // canonicalization?
  1914. Value *A;
  1915. if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
  1916. A->getType()->isIntOrIntVectorTy(1))
  1917. return SelectInst::Create(A, Op1, Constant::getNullValue(Ty));
  1918. if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
  1919. A->getType()->isIntOrIntVectorTy(1))
  1920. return SelectInst::Create(A, Op0, Constant::getNullValue(Ty));
  1921. // (iN X s>> (N-1)) & Y --> (X s< 0) ? Y : 0
  1922. unsigned FullShift = Ty->getScalarSizeInBits() - 1;
  1923. if (match(&I, m_c_And(m_OneUse(m_AShr(m_Value(X), m_SpecificInt(FullShift))),
  1924. m_Value(Y)))) {
  1925. Constant *Zero = ConstantInt::getNullValue(Ty);
  1926. Value *Cmp = Builder.CreateICmpSLT(X, Zero, "isneg");
  1927. return SelectInst::Create(Cmp, Y, Zero);
  1928. }
  1929. // If there's a 'not' of the shifted value, swap the select operands:
  1930. // ~(iN X s>> (N-1)) & Y --> (X s< 0) ? 0 : Y
  1931. if (match(&I, m_c_And(m_OneUse(m_Not(
  1932. m_AShr(m_Value(X), m_SpecificInt(FullShift)))),
  1933. m_Value(Y)))) {
  1934. Constant *Zero = ConstantInt::getNullValue(Ty);
  1935. Value *Cmp = Builder.CreateICmpSLT(X, Zero, "isneg");
  1936. return SelectInst::Create(Cmp, Zero, Y);
  1937. }
  1938. // (~x) & y --> ~(x | (~y)) iff that gets rid of inversions
  1939. if (sinkNotIntoOtherHandOfAndOrOr(I))
  1940. return &I;
  1941. // An and recurrence w/loop invariant step is equivelent to (and start, step)
  1942. PHINode *PN = nullptr;
  1943. Value *Start = nullptr, *Step = nullptr;
  1944. if (matchSimpleRecurrence(&I, PN, Start, Step) && DT.dominates(Step, PN))
  1945. return replaceInstUsesWith(I, Builder.CreateAnd(Start, Step));
  1946. return nullptr;
  1947. }
  1948. Instruction *InstCombinerImpl::matchBSwapOrBitReverse(Instruction &I,
  1949. bool MatchBSwaps,
  1950. bool MatchBitReversals) {
  1951. SmallVector<Instruction *, 4> Insts;
  1952. if (!recognizeBSwapOrBitReverseIdiom(&I, MatchBSwaps, MatchBitReversals,
  1953. Insts))
  1954. return nullptr;
  1955. Instruction *LastInst = Insts.pop_back_val();
  1956. LastInst->removeFromParent();
  1957. for (auto *Inst : Insts)
  1958. Worklist.push(Inst);
  1959. return LastInst;
  1960. }
  1961. /// Match UB-safe variants of the funnel shift intrinsic.
  1962. static Instruction *matchFunnelShift(Instruction &Or, InstCombinerImpl &IC) {
  1963. // TODO: Can we reduce the code duplication between this and the related
  1964. // rotate matching code under visitSelect and visitTrunc?
  1965. unsigned Width = Or.getType()->getScalarSizeInBits();
  1966. // First, find an or'd pair of opposite shifts:
  1967. // or (lshr ShVal0, ShAmt0), (shl ShVal1, ShAmt1)
  1968. BinaryOperator *Or0, *Or1;
  1969. if (!match(Or.getOperand(0), m_BinOp(Or0)) ||
  1970. !match(Or.getOperand(1), m_BinOp(Or1)))
  1971. return nullptr;
  1972. Value *ShVal0, *ShVal1, *ShAmt0, *ShAmt1;
  1973. if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(ShVal0), m_Value(ShAmt0)))) ||
  1974. !match(Or1, m_OneUse(m_LogicalShift(m_Value(ShVal1), m_Value(ShAmt1)))) ||
  1975. Or0->getOpcode() == Or1->getOpcode())
  1976. return nullptr;
  1977. // Canonicalize to or(shl(ShVal0, ShAmt0), lshr(ShVal1, ShAmt1)).
  1978. if (Or0->getOpcode() == BinaryOperator::LShr) {
  1979. std::swap(Or0, Or1);
  1980. std::swap(ShVal0, ShVal1);
  1981. std::swap(ShAmt0, ShAmt1);
  1982. }
  1983. assert(Or0->getOpcode() == BinaryOperator::Shl &&
  1984. Or1->getOpcode() == BinaryOperator::LShr &&
  1985. "Illegal or(shift,shift) pair");
  1986. // Match the shift amount operands for a funnel shift pattern. This always
  1987. // matches a subtraction on the R operand.
  1988. auto matchShiftAmount = [&](Value *L, Value *R, unsigned Width) -> Value * {
  1989. // Check for constant shift amounts that sum to the bitwidth.
  1990. const APInt *LI, *RI;
  1991. if (match(L, m_APIntAllowUndef(LI)) && match(R, m_APIntAllowUndef(RI)))
  1992. if (LI->ult(Width) && RI->ult(Width) && (*LI + *RI) == Width)
  1993. return ConstantInt::get(L->getType(), *LI);
  1994. Constant *LC, *RC;
  1995. if (match(L, m_Constant(LC)) && match(R, m_Constant(RC)) &&
  1996. match(L, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) &&
  1997. match(R, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) &&
  1998. match(ConstantExpr::getAdd(LC, RC), m_SpecificIntAllowUndef(Width)))
  1999. return ConstantExpr::mergeUndefsWith(LC, RC);
  2000. // (shl ShVal, X) | (lshr ShVal, (Width - x)) iff X < Width.
  2001. // We limit this to X < Width in case the backend re-expands the intrinsic,
  2002. // and has to reintroduce a shift modulo operation (InstCombine might remove
  2003. // it after this fold). This still doesn't guarantee that the final codegen
  2004. // will match this original pattern.
  2005. if (match(R, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(L))))) {
  2006. KnownBits KnownL = IC.computeKnownBits(L, /*Depth*/ 0, &Or);
  2007. return KnownL.getMaxValue().ult(Width) ? L : nullptr;
  2008. }
  2009. // For non-constant cases, the following patterns currently only work for
  2010. // rotation patterns.
  2011. // TODO: Add general funnel-shift compatible patterns.
  2012. if (ShVal0 != ShVal1)
  2013. return nullptr;
  2014. // For non-constant cases we don't support non-pow2 shift masks.
  2015. // TODO: Is it worth matching urem as well?
  2016. if (!isPowerOf2_32(Width))
  2017. return nullptr;
  2018. // The shift amount may be masked with negation:
  2019. // (shl ShVal, (X & (Width - 1))) | (lshr ShVal, ((-X) & (Width - 1)))
  2020. Value *X;
  2021. unsigned Mask = Width - 1;
  2022. if (match(L, m_And(m_Value(X), m_SpecificInt(Mask))) &&
  2023. match(R, m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask))))
  2024. return X;
  2025. // Similar to above, but the shift amount may be extended after masking,
  2026. // so return the extended value as the parameter for the intrinsic.
  2027. if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) &&
  2028. match(R, m_And(m_Neg(m_ZExt(m_And(m_Specific(X), m_SpecificInt(Mask)))),
  2029. m_SpecificInt(Mask))))
  2030. return L;
  2031. if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) &&
  2032. match(R, m_ZExt(m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask)))))
  2033. return L;
  2034. return nullptr;
  2035. };
  2036. Value *ShAmt = matchShiftAmount(ShAmt0, ShAmt1, Width);
  2037. bool IsFshl = true; // Sub on LSHR.
  2038. if (!ShAmt) {
  2039. ShAmt = matchShiftAmount(ShAmt1, ShAmt0, Width);
  2040. IsFshl = false; // Sub on SHL.
  2041. }
  2042. if (!ShAmt)
  2043. return nullptr;
  2044. Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
  2045. Function *F = Intrinsic::getDeclaration(Or.getModule(), IID, Or.getType());
  2046. return CallInst::Create(F, {ShVal0, ShVal1, ShAmt});
  2047. }
  2048. /// Attempt to combine or(zext(x),shl(zext(y),bw/2) concat packing patterns.
  2049. static Instruction *matchOrConcat(Instruction &Or,
  2050. InstCombiner::BuilderTy &Builder) {
  2051. assert(Or.getOpcode() == Instruction::Or && "bswap requires an 'or'");
  2052. Value *Op0 = Or.getOperand(0), *Op1 = Or.getOperand(1);
  2053. Type *Ty = Or.getType();
  2054. unsigned Width = Ty->getScalarSizeInBits();
  2055. if ((Width & 1) != 0)
  2056. return nullptr;
  2057. unsigned HalfWidth = Width / 2;
  2058. // Canonicalize zext (lower half) to LHS.
  2059. if (!isa<ZExtInst>(Op0))
  2060. std::swap(Op0, Op1);
  2061. // Find lower/upper half.
  2062. Value *LowerSrc, *ShlVal, *UpperSrc;
  2063. const APInt *C;
  2064. if (!match(Op0, m_OneUse(m_ZExt(m_Value(LowerSrc)))) ||
  2065. !match(Op1, m_OneUse(m_Shl(m_Value(ShlVal), m_APInt(C)))) ||
  2066. !match(ShlVal, m_OneUse(m_ZExt(m_Value(UpperSrc)))))
  2067. return nullptr;
  2068. if (*C != HalfWidth || LowerSrc->getType() != UpperSrc->getType() ||
  2069. LowerSrc->getType()->getScalarSizeInBits() != HalfWidth)
  2070. return nullptr;
  2071. auto ConcatIntrinsicCalls = [&](Intrinsic::ID id, Value *Lo, Value *Hi) {
  2072. Value *NewLower = Builder.CreateZExt(Lo, Ty);
  2073. Value *NewUpper = Builder.CreateZExt(Hi, Ty);
  2074. NewUpper = Builder.CreateShl(NewUpper, HalfWidth);
  2075. Value *BinOp = Builder.CreateOr(NewLower, NewUpper);
  2076. Function *F = Intrinsic::getDeclaration(Or.getModule(), id, Ty);
  2077. return Builder.CreateCall(F, BinOp);
  2078. };
  2079. // BSWAP: Push the concat down, swapping the lower/upper sources.
  2080. // concat(bswap(x),bswap(y)) -> bswap(concat(x,y))
  2081. Value *LowerBSwap, *UpperBSwap;
  2082. if (match(LowerSrc, m_BSwap(m_Value(LowerBSwap))) &&
  2083. match(UpperSrc, m_BSwap(m_Value(UpperBSwap))))
  2084. return ConcatIntrinsicCalls(Intrinsic::bswap, UpperBSwap, LowerBSwap);
  2085. // BITREVERSE: Push the concat down, swapping the lower/upper sources.
  2086. // concat(bitreverse(x),bitreverse(y)) -> bitreverse(concat(x,y))
  2087. Value *LowerBRev, *UpperBRev;
  2088. if (match(LowerSrc, m_BitReverse(m_Value(LowerBRev))) &&
  2089. match(UpperSrc, m_BitReverse(m_Value(UpperBRev))))
  2090. return ConcatIntrinsicCalls(Intrinsic::bitreverse, UpperBRev, LowerBRev);
  2091. return nullptr;
  2092. }
  2093. /// If all elements of two constant vectors are 0/-1 and inverses, return true.
  2094. static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
  2095. unsigned NumElts = cast<FixedVectorType>(C1->getType())->getNumElements();
  2096. for (unsigned i = 0; i != NumElts; ++i) {
  2097. Constant *EltC1 = C1->getAggregateElement(i);
  2098. Constant *EltC2 = C2->getAggregateElement(i);
  2099. if (!EltC1 || !EltC2)
  2100. return false;
  2101. // One element must be all ones, and the other must be all zeros.
  2102. if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
  2103. (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
  2104. return false;
  2105. }
  2106. return true;
  2107. }
  2108. /// We have an expression of the form (A & C) | (B & D). If A is a scalar or
  2109. /// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
  2110. /// B, it can be used as the condition operand of a select instruction.
  2111. Value *InstCombinerImpl::getSelectCondition(Value *A, Value *B) {
  2112. // We may have peeked through bitcasts in the caller.
  2113. // Exit immediately if we don't have (vector) integer types.
  2114. Type *Ty = A->getType();
  2115. if (!Ty->isIntOrIntVectorTy() || !B->getType()->isIntOrIntVectorTy())
  2116. return nullptr;
  2117. // If A is the 'not' operand of B and has enough signbits, we have our answer.
  2118. if (match(B, m_Not(m_Specific(A)))) {
  2119. // If these are scalars or vectors of i1, A can be used directly.
  2120. if (Ty->isIntOrIntVectorTy(1))
  2121. return A;
  2122. // If we look through a vector bitcast, the caller will bitcast the operands
  2123. // to match the condition's number of bits (N x i1).
  2124. // To make this poison-safe, disallow bitcast from wide element to narrow
  2125. // element. That could allow poison in lanes where it was not present in the
  2126. // original code.
  2127. A = peekThroughBitcast(A);
  2128. if (A->getType()->isIntOrIntVectorTy()) {
  2129. unsigned NumSignBits = ComputeNumSignBits(A);
  2130. if (NumSignBits == A->getType()->getScalarSizeInBits() &&
  2131. NumSignBits <= Ty->getScalarSizeInBits())
  2132. return Builder.CreateTrunc(A, CmpInst::makeCmpResultType(A->getType()));
  2133. }
  2134. return nullptr;
  2135. }
  2136. // If both operands are constants, see if the constants are inverse bitmasks.
  2137. Constant *AConst, *BConst;
  2138. if (match(A, m_Constant(AConst)) && match(B, m_Constant(BConst)))
  2139. if (AConst == ConstantExpr::getNot(BConst) &&
  2140. ComputeNumSignBits(A) == Ty->getScalarSizeInBits())
  2141. return Builder.CreateZExtOrTrunc(A, CmpInst::makeCmpResultType(Ty));
  2142. // Look for more complex patterns. The 'not' op may be hidden behind various
  2143. // casts. Look through sexts and bitcasts to find the booleans.
  2144. Value *Cond;
  2145. Value *NotB;
  2146. if (match(A, m_SExt(m_Value(Cond))) &&
  2147. Cond->getType()->isIntOrIntVectorTy(1)) {
  2148. // A = sext i1 Cond; B = sext (not (i1 Cond))
  2149. if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
  2150. return Cond;
  2151. // A = sext i1 Cond; B = not ({bitcast} (sext (i1 Cond)))
  2152. // TODO: The one-use checks are unnecessary or misplaced. If the caller
  2153. // checked for uses on logic ops/casts, that should be enough to
  2154. // make this transform worthwhile.
  2155. if (match(B, m_OneUse(m_Not(m_Value(NotB))))) {
  2156. NotB = peekThroughBitcast(NotB, true);
  2157. if (match(NotB, m_SExt(m_Specific(Cond))))
  2158. return Cond;
  2159. }
  2160. }
  2161. // All scalar (and most vector) possibilities should be handled now.
  2162. // Try more matches that only apply to non-splat constant vectors.
  2163. if (!Ty->isVectorTy())
  2164. return nullptr;
  2165. // If both operands are xor'd with constants using the same sexted boolean
  2166. // operand, see if the constants are inverse bitmasks.
  2167. // TODO: Use ConstantExpr::getNot()?
  2168. if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AConst)))) &&
  2169. match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BConst)))) &&
  2170. Cond->getType()->isIntOrIntVectorTy(1) &&
  2171. areInverseVectorBitmasks(AConst, BConst)) {
  2172. AConst = ConstantExpr::getTrunc(AConst, CmpInst::makeCmpResultType(Ty));
  2173. return Builder.CreateXor(Cond, AConst);
  2174. }
  2175. return nullptr;
  2176. }
  2177. /// We have an expression of the form (A & C) | (B & D). Try to simplify this
  2178. /// to "A' ? C : D", where A' is a boolean or vector of booleans.
  2179. Value *InstCombinerImpl::matchSelectFromAndOr(Value *A, Value *C, Value *B,
  2180. Value *D) {
  2181. // The potential condition of the select may be bitcasted. In that case, look
  2182. // through its bitcast and the corresponding bitcast of the 'not' condition.
  2183. Type *OrigType = A->getType();
  2184. A = peekThroughBitcast(A, true);
  2185. B = peekThroughBitcast(B, true);
  2186. if (Value *Cond = getSelectCondition(A, B)) {
  2187. // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
  2188. // If this is a vector, we may need to cast to match the condition's length.
  2189. // The bitcasts will either all exist or all not exist. The builder will
  2190. // not create unnecessary casts if the types already match.
  2191. Type *SelTy = A->getType();
  2192. if (auto *VecTy = dyn_cast<VectorType>(Cond->getType())) {
  2193. // For a fixed or scalable vector get N from <{vscale x} N x iM>
  2194. unsigned Elts = VecTy->getElementCount().getKnownMinValue();
  2195. // For a fixed or scalable vector, get the size in bits of N x iM; for a
  2196. // scalar this is just M.
  2197. unsigned SelEltSize = SelTy->getPrimitiveSizeInBits().getKnownMinSize();
  2198. Type *EltTy = Builder.getIntNTy(SelEltSize / Elts);
  2199. SelTy = VectorType::get(EltTy, VecTy->getElementCount());
  2200. }
  2201. Value *BitcastC = Builder.CreateBitCast(C, SelTy);
  2202. Value *BitcastD = Builder.CreateBitCast(D, SelTy);
  2203. Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
  2204. return Builder.CreateBitCast(Select, OrigType);
  2205. }
  2206. return nullptr;
  2207. }
  2208. /// Fold (icmp)|(icmp) if possible.
  2209. Value *InstCombinerImpl::foldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
  2210. BinaryOperator &Or) {
  2211. const SimplifyQuery Q = SQ.getWithInstruction(&Or);
  2212. // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
  2213. // if K1 and K2 are a one-bit mask.
  2214. if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, &Or,
  2215. /* IsAnd */ false))
  2216. return V;
  2217. ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
  2218. Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
  2219. Value *LHS1 = LHS->getOperand(1), *RHS1 = RHS->getOperand(1);
  2220. const APInt *LHSC = nullptr, *RHSC = nullptr;
  2221. match(LHS1, m_APInt(LHSC));
  2222. match(RHS1, m_APInt(RHSC));
  2223. // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
  2224. // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
  2225. // The original condition actually refers to the following two ranges:
  2226. // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
  2227. // We can fold these two ranges if:
  2228. // 1) C1 and C2 is unsigned greater than C3.
  2229. // 2) The two ranges are separated.
  2230. // 3) C1 ^ C2 is one-bit mask.
  2231. // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
  2232. // This implies all values in the two ranges differ by exactly one bit.
  2233. if ((PredL == ICmpInst::ICMP_ULT || PredL == ICmpInst::ICMP_ULE) &&
  2234. PredL == PredR && LHSC && RHSC && LHS->hasOneUse() && RHS->hasOneUse() &&
  2235. LHSC->getBitWidth() == RHSC->getBitWidth() && *LHSC == *RHSC) {
  2236. Value *AddOpnd;
  2237. const APInt *LAddC, *RAddC;
  2238. if (match(LHS0, m_Add(m_Value(AddOpnd), m_APInt(LAddC))) &&
  2239. match(RHS0, m_Add(m_Specific(AddOpnd), m_APInt(RAddC))) &&
  2240. LAddC->ugt(*LHSC) && RAddC->ugt(*LHSC)) {
  2241. APInt DiffC = *LAddC ^ *RAddC;
  2242. if (DiffC.isPowerOf2()) {
  2243. const APInt *MaxAddC = nullptr;
  2244. if (LAddC->ult(*RAddC))
  2245. MaxAddC = RAddC;
  2246. else
  2247. MaxAddC = LAddC;
  2248. APInt RRangeLow = -*RAddC;
  2249. APInt RRangeHigh = RRangeLow + *LHSC;
  2250. APInt LRangeLow = -*LAddC;
  2251. APInt LRangeHigh = LRangeLow + *LHSC;
  2252. APInt LowRangeDiff = RRangeLow ^ LRangeLow;
  2253. APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
  2254. APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
  2255. : RRangeLow - LRangeLow;
  2256. if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
  2257. RangeDiff.ugt(*LHSC)) {
  2258. Type *Ty = AddOpnd->getType();
  2259. Value *MaskC = ConstantInt::get(Ty, ~DiffC);
  2260. Value *NewAnd = Builder.CreateAnd(AddOpnd, MaskC);
  2261. Value *NewAdd = Builder.CreateAdd(NewAnd,
  2262. ConstantInt::get(Ty, *MaxAddC));
  2263. return Builder.CreateICmp(LHS->getPredicate(), NewAdd,
  2264. ConstantInt::get(Ty, *LHSC));
  2265. }
  2266. }
  2267. }
  2268. }
  2269. // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
  2270. if (predicatesFoldable(PredL, PredR)) {
  2271. if (LHS0 == RHS1 && LHS1 == RHS0)
  2272. LHS->swapOperands();
  2273. if (LHS0 == RHS0 && LHS1 == RHS1) {
  2274. unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
  2275. bool IsSigned = LHS->isSigned() || RHS->isSigned();
  2276. return getNewICmpValue(Code, IsSigned, LHS0, LHS1, Builder);
  2277. }
  2278. }
  2279. // handle (roughly):
  2280. // (icmp ne (A & B), C) | (icmp ne (A & D), E)
  2281. if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
  2282. return V;
  2283. if (LHS->hasOneUse() || RHS->hasOneUse()) {
  2284. // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
  2285. // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
  2286. Value *A = nullptr, *B = nullptr;
  2287. if (PredL == ICmpInst::ICMP_EQ && match(LHS1, m_Zero())) {
  2288. B = LHS0;
  2289. if (PredR == ICmpInst::ICMP_ULT && LHS0 == RHS1)
  2290. A = RHS0;
  2291. else if (PredR == ICmpInst::ICMP_UGT && LHS0 == RHS0)
  2292. A = RHS1;
  2293. }
  2294. // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
  2295. // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
  2296. else if (PredR == ICmpInst::ICMP_EQ && match(RHS1, m_Zero())) {
  2297. B = RHS0;
  2298. if (PredL == ICmpInst::ICMP_ULT && RHS0 == LHS1)
  2299. A = LHS0;
  2300. else if (PredL == ICmpInst::ICMP_UGT && RHS0 == LHS0)
  2301. A = LHS1;
  2302. }
  2303. if (A && B && B->getType()->isIntOrIntVectorTy())
  2304. return Builder.CreateICmp(
  2305. ICmpInst::ICMP_UGE,
  2306. Builder.CreateAdd(B, Constant::getAllOnesValue(B->getType())), A);
  2307. }
  2308. if (Value *V = foldAndOrOfICmpsWithConstEq(LHS, RHS, Or, Builder, Q))
  2309. return V;
  2310. if (Value *V = foldAndOrOfICmpsWithConstEq(RHS, LHS, Or, Builder, Q))
  2311. return V;
  2312. // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
  2313. if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
  2314. return V;
  2315. // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
  2316. if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
  2317. return V;
  2318. if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, false, Builder))
  2319. return V;
  2320. if (Value *V = foldIsPowerOf2(LHS, RHS, false /* JoinedByAnd */, Builder))
  2321. return V;
  2322. if (Value *X =
  2323. foldUnsignedUnderflowCheck(LHS, RHS, /*IsAnd=*/false, Q, Builder))
  2324. return X;
  2325. if (Value *X =
  2326. foldUnsignedUnderflowCheck(RHS, LHS, /*IsAnd=*/false, Q, Builder))
  2327. return X;
  2328. if (Value *X = foldEqOfParts(LHS, RHS, /*IsAnd=*/false))
  2329. return X;
  2330. // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
  2331. // TODO: Remove this when foldLogOpOfMaskedICmps can handle undefs.
  2332. if (PredL == ICmpInst::ICMP_NE && match(LHS1, m_ZeroInt()) &&
  2333. PredR == ICmpInst::ICMP_NE && match(RHS1, m_ZeroInt()) &&
  2334. LHS0->getType() == RHS0->getType()) {
  2335. Value *NewOr = Builder.CreateOr(LHS0, RHS0);
  2336. return Builder.CreateICmp(PredL, NewOr,
  2337. Constant::getNullValue(NewOr->getType()));
  2338. }
  2339. // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
  2340. if (!LHSC || !RHSC)
  2341. return nullptr;
  2342. return foldAndOrOfICmpsUsingRanges(PredL, LHS0, *LHSC, PredR, RHS0, *RHSC,
  2343. Builder, /* IsAnd */ false);
  2344. }
  2345. // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
  2346. // here. We should standardize that construct where it is needed or choose some
  2347. // other way to ensure that commutated variants of patterns are not missed.
  2348. Instruction *InstCombinerImpl::visitOr(BinaryOperator &I) {
  2349. if (Value *V = SimplifyOrInst(I.getOperand(0), I.getOperand(1),
  2350. SQ.getWithInstruction(&I)))
  2351. return replaceInstUsesWith(I, V);
  2352. if (SimplifyAssociativeOrCommutative(I))
  2353. return &I;
  2354. if (Instruction *X = foldVectorBinop(I))
  2355. return X;
  2356. if (Instruction *Phi = foldBinopWithPhiOperands(I))
  2357. return Phi;
  2358. // See if we can simplify any instructions used by the instruction whose sole
  2359. // purpose is to compute bits we don't care about.
  2360. if (SimplifyDemandedInstructionBits(I))
  2361. return &I;
  2362. // Do this before using distributive laws to catch simple and/or/not patterns.
  2363. if (Instruction *Xor = foldOrToXor(I, Builder))
  2364. return Xor;
  2365. if (Instruction *X = foldComplexAndOrPatterns(I, Builder))
  2366. return X;
  2367. // (A&B)|(A&C) -> A&(B|C) etc
  2368. if (Value *V = SimplifyUsingDistributiveLaws(I))
  2369. return replaceInstUsesWith(I, V);
  2370. if (Value *V = SimplifyBSwap(I, Builder))
  2371. return replaceInstUsesWith(I, V);
  2372. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  2373. Type *Ty = I.getType();
  2374. if (Ty->isIntOrIntVectorTy(1)) {
  2375. if (auto *SI0 = dyn_cast<SelectInst>(Op0)) {
  2376. if (auto *I =
  2377. foldAndOrOfSelectUsingImpliedCond(Op1, *SI0, /* IsAnd */ false))
  2378. return I;
  2379. }
  2380. if (auto *SI1 = dyn_cast<SelectInst>(Op1)) {
  2381. if (auto *I =
  2382. foldAndOrOfSelectUsingImpliedCond(Op0, *SI1, /* IsAnd */ false))
  2383. return I;
  2384. }
  2385. }
  2386. if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
  2387. return FoldedLogic;
  2388. if (Instruction *BitOp = matchBSwapOrBitReverse(I, /*MatchBSwaps*/ true,
  2389. /*MatchBitReversals*/ true))
  2390. return BitOp;
  2391. if (Instruction *Funnel = matchFunnelShift(I, *this))
  2392. return Funnel;
  2393. if (Instruction *Concat = matchOrConcat(I, Builder))
  2394. return replaceInstUsesWith(I, Concat);
  2395. Value *X, *Y;
  2396. const APInt *CV;
  2397. if (match(&I, m_c_Or(m_OneUse(m_Xor(m_Value(X), m_APInt(CV))), m_Value(Y))) &&
  2398. !CV->isAllOnes() && MaskedValueIsZero(Y, *CV, 0, &I)) {
  2399. // (X ^ C) | Y -> (X | Y) ^ C iff Y & C == 0
  2400. // The check for a 'not' op is for efficiency (if Y is known zero --> ~X).
  2401. Value *Or = Builder.CreateOr(X, Y);
  2402. return BinaryOperator::CreateXor(Or, ConstantInt::get(Ty, *CV));
  2403. }
  2404. // If the operands have no common bits set:
  2405. // or (mul X, Y), X --> add (mul X, Y), X --> mul X, (Y + 1)
  2406. if (match(&I,
  2407. m_c_Or(m_OneUse(m_Mul(m_Value(X), m_Value(Y))), m_Deferred(X))) &&
  2408. haveNoCommonBitsSet(Op0, Op1, DL)) {
  2409. Value *IncrementY = Builder.CreateAdd(Y, ConstantInt::get(Ty, 1));
  2410. return BinaryOperator::CreateMul(X, IncrementY);
  2411. }
  2412. // (A & C) | (B & D)
  2413. Value *A, *B, *C, *D;
  2414. if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
  2415. match(Op1, m_And(m_Value(B), m_Value(D)))) {
  2416. // (A & C0) | (B & C1)
  2417. const APInt *C0, *C1;
  2418. if (match(C, m_APInt(C0)) && match(D, m_APInt(C1))) {
  2419. Value *X;
  2420. if (*C0 == ~*C1) {
  2421. // ((X | B) & MaskC) | (B & ~MaskC) -> (X & MaskC) | B
  2422. if (match(A, m_c_Or(m_Value(X), m_Specific(B))))
  2423. return BinaryOperator::CreateOr(Builder.CreateAnd(X, *C0), B);
  2424. // (A & MaskC) | ((X | A) & ~MaskC) -> (X & ~MaskC) | A
  2425. if (match(B, m_c_Or(m_Specific(A), m_Value(X))))
  2426. return BinaryOperator::CreateOr(Builder.CreateAnd(X, *C1), A);
  2427. // ((X ^ B) & MaskC) | (B & ~MaskC) -> (X & MaskC) ^ B
  2428. if (match(A, m_c_Xor(m_Value(X), m_Specific(B))))
  2429. return BinaryOperator::CreateXor(Builder.CreateAnd(X, *C0), B);
  2430. // (A & MaskC) | ((X ^ A) & ~MaskC) -> (X & ~MaskC) ^ A
  2431. if (match(B, m_c_Xor(m_Specific(A), m_Value(X))))
  2432. return BinaryOperator::CreateXor(Builder.CreateAnd(X, *C1), A);
  2433. }
  2434. if ((*C0 & *C1).isZero()) {
  2435. // ((X | B) & C0) | (B & C1) --> (X | B) & (C0 | C1)
  2436. // iff (C0 & C1) == 0 and (X & ~C0) == 0
  2437. if (match(A, m_c_Or(m_Value(X), m_Specific(B))) &&
  2438. MaskedValueIsZero(X, ~*C0, 0, &I)) {
  2439. Constant *C01 = ConstantInt::get(Ty, *C0 | *C1);
  2440. return BinaryOperator::CreateAnd(A, C01);
  2441. }
  2442. // (A & C0) | ((X | A) & C1) --> (X | A) & (C0 | C1)
  2443. // iff (C0 & C1) == 0 and (X & ~C1) == 0
  2444. if (match(B, m_c_Or(m_Value(X), m_Specific(A))) &&
  2445. MaskedValueIsZero(X, ~*C1, 0, &I)) {
  2446. Constant *C01 = ConstantInt::get(Ty, *C0 | *C1);
  2447. return BinaryOperator::CreateAnd(B, C01);
  2448. }
  2449. // ((X | C2) & C0) | ((X | C3) & C1) --> (X | C2 | C3) & (C0 | C1)
  2450. // iff (C0 & C1) == 0 and (C2 & ~C0) == 0 and (C3 & ~C1) == 0.
  2451. const APInt *C2, *C3;
  2452. if (match(A, m_Or(m_Value(X), m_APInt(C2))) &&
  2453. match(B, m_Or(m_Specific(X), m_APInt(C3))) &&
  2454. (*C2 & ~*C0).isZero() && (*C3 & ~*C1).isZero()) {
  2455. Value *Or = Builder.CreateOr(X, *C2 | *C3, "bitfield");
  2456. Constant *C01 = ConstantInt::get(Ty, *C0 | *C1);
  2457. return BinaryOperator::CreateAnd(Or, C01);
  2458. }
  2459. }
  2460. }
  2461. // Don't try to form a select if it's unlikely that we'll get rid of at
  2462. // least one of the operands. A select is generally more expensive than the
  2463. // 'or' that it is replacing.
  2464. if (Op0->hasOneUse() || Op1->hasOneUse()) {
  2465. // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
  2466. if (Value *V = matchSelectFromAndOr(A, C, B, D))
  2467. return replaceInstUsesWith(I, V);
  2468. if (Value *V = matchSelectFromAndOr(A, C, D, B))
  2469. return replaceInstUsesWith(I, V);
  2470. if (Value *V = matchSelectFromAndOr(C, A, B, D))
  2471. return replaceInstUsesWith(I, V);
  2472. if (Value *V = matchSelectFromAndOr(C, A, D, B))
  2473. return replaceInstUsesWith(I, V);
  2474. if (Value *V = matchSelectFromAndOr(B, D, A, C))
  2475. return replaceInstUsesWith(I, V);
  2476. if (Value *V = matchSelectFromAndOr(B, D, C, A))
  2477. return replaceInstUsesWith(I, V);
  2478. if (Value *V = matchSelectFromAndOr(D, B, A, C))
  2479. return replaceInstUsesWith(I, V);
  2480. if (Value *V = matchSelectFromAndOr(D, B, C, A))
  2481. return replaceInstUsesWith(I, V);
  2482. }
  2483. }
  2484. // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
  2485. if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
  2486. if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
  2487. return BinaryOperator::CreateOr(Op0, C);
  2488. // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
  2489. if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
  2490. if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
  2491. return BinaryOperator::CreateOr(Op1, C);
  2492. // ((B | C) & A) | B -> B | (A & C)
  2493. if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
  2494. return BinaryOperator::CreateOr(Op1, Builder.CreateAnd(A, C));
  2495. if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
  2496. return DeMorgan;
  2497. // Canonicalize xor to the RHS.
  2498. bool SwappedForXor = false;
  2499. if (match(Op0, m_Xor(m_Value(), m_Value()))) {
  2500. std::swap(Op0, Op1);
  2501. SwappedForXor = true;
  2502. }
  2503. // A | ( A ^ B) -> A | B
  2504. // A | (~A ^ B) -> A | ~B
  2505. // (A & B) | (A ^ B)
  2506. // ~A | (A ^ B) -> ~(A & B)
  2507. // The swap above should always make Op0 the 'not' for the last case.
  2508. if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
  2509. if (Op0 == A || Op0 == B)
  2510. return BinaryOperator::CreateOr(A, B);
  2511. if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
  2512. match(Op0, m_And(m_Specific(B), m_Specific(A))))
  2513. return BinaryOperator::CreateOr(A, B);
  2514. if ((Op0->hasOneUse() || Op1->hasOneUse()) &&
  2515. (match(Op0, m_Not(m_Specific(A))) || match(Op0, m_Not(m_Specific(B)))))
  2516. return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
  2517. if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
  2518. Value *Not = Builder.CreateNot(B, B->getName() + ".not");
  2519. return BinaryOperator::CreateOr(Not, Op0);
  2520. }
  2521. if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
  2522. Value *Not = Builder.CreateNot(A, A->getName() + ".not");
  2523. return BinaryOperator::CreateOr(Not, Op0);
  2524. }
  2525. }
  2526. // A | ~(A | B) -> A | ~B
  2527. // A | ~(A ^ B) -> A | ~B
  2528. if (match(Op1, m_Not(m_Value(A))))
  2529. if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
  2530. if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
  2531. Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
  2532. B->getOpcode() == Instruction::Xor)) {
  2533. Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
  2534. B->getOperand(0);
  2535. Value *Not = Builder.CreateNot(NotOp, NotOp->getName() + ".not");
  2536. return BinaryOperator::CreateOr(Not, Op0);
  2537. }
  2538. if (SwappedForXor)
  2539. std::swap(Op0, Op1);
  2540. {
  2541. ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
  2542. ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
  2543. if (LHS && RHS)
  2544. if (Value *Res = foldOrOfICmps(LHS, RHS, I))
  2545. return replaceInstUsesWith(I, Res);
  2546. // TODO: Make this recursive; it's a little tricky because an arbitrary
  2547. // number of 'or' instructions might have to be created.
  2548. Value *X, *Y;
  2549. if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
  2550. if (auto *Cmp = dyn_cast<ICmpInst>(X))
  2551. if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
  2552. return replaceInstUsesWith(I, Builder.CreateOr(Res, Y));
  2553. if (auto *Cmp = dyn_cast<ICmpInst>(Y))
  2554. if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
  2555. return replaceInstUsesWith(I, Builder.CreateOr(Res, X));
  2556. }
  2557. if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
  2558. if (auto *Cmp = dyn_cast<ICmpInst>(X))
  2559. if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
  2560. return replaceInstUsesWith(I, Builder.CreateOr(Res, Y));
  2561. if (auto *Cmp = dyn_cast<ICmpInst>(Y))
  2562. if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
  2563. return replaceInstUsesWith(I, Builder.CreateOr(Res, X));
  2564. }
  2565. }
  2566. if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
  2567. if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
  2568. if (Value *Res = foldLogicOfFCmps(LHS, RHS, false))
  2569. return replaceInstUsesWith(I, Res);
  2570. if (Instruction *FoldedFCmps = reassociateFCmps(I, Builder))
  2571. return FoldedFCmps;
  2572. if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
  2573. return CastedOr;
  2574. if (Instruction *Sel = foldBinopOfSextBoolToSelect(I))
  2575. return Sel;
  2576. // or(sext(A), B) / or(B, sext(A)) --> A ? -1 : B, where A is i1 or <N x i1>.
  2577. // TODO: Move this into foldBinopOfSextBoolToSelect as a more generalized fold
  2578. // with binop identity constant. But creating a select with non-constant
  2579. // arm may not be reversible due to poison semantics. Is that a good
  2580. // canonicalization?
  2581. if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
  2582. A->getType()->isIntOrIntVectorTy(1))
  2583. return SelectInst::Create(A, ConstantInt::getAllOnesValue(Ty), Op1);
  2584. if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
  2585. A->getType()->isIntOrIntVectorTy(1))
  2586. return SelectInst::Create(A, ConstantInt::getAllOnesValue(Ty), Op0);
  2587. // Note: If we've gotten to the point of visiting the outer OR, then the
  2588. // inner one couldn't be simplified. If it was a constant, then it won't
  2589. // be simplified by a later pass either, so we try swapping the inner/outer
  2590. // ORs in the hopes that we'll be able to simplify it this way.
  2591. // (X|C) | V --> (X|V) | C
  2592. ConstantInt *CI;
  2593. if (Op0->hasOneUse() && !match(Op1, m_ConstantInt()) &&
  2594. match(Op0, m_Or(m_Value(A), m_ConstantInt(CI)))) {
  2595. Value *Inner = Builder.CreateOr(A, Op1);
  2596. Inner->takeName(Op0);
  2597. return BinaryOperator::CreateOr(Inner, CI);
  2598. }
  2599. // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
  2600. // Since this OR statement hasn't been optimized further yet, we hope
  2601. // that this transformation will allow the new ORs to be optimized.
  2602. {
  2603. Value *X = nullptr, *Y = nullptr;
  2604. if (Op0->hasOneUse() && Op1->hasOneUse() &&
  2605. match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
  2606. match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
  2607. Value *orTrue = Builder.CreateOr(A, C);
  2608. Value *orFalse = Builder.CreateOr(B, D);
  2609. return SelectInst::Create(X, orTrue, orFalse);
  2610. }
  2611. }
  2612. // or(ashr(subNSW(Y, X), ScalarSizeInBits(Y) - 1), X) --> X s> Y ? -1 : X.
  2613. {
  2614. Value *X, *Y;
  2615. if (match(&I, m_c_Or(m_OneUse(m_AShr(
  2616. m_NSWSub(m_Value(Y), m_Value(X)),
  2617. m_SpecificInt(Ty->getScalarSizeInBits() - 1))),
  2618. m_Deferred(X)))) {
  2619. Value *NewICmpInst = Builder.CreateICmpSGT(X, Y);
  2620. Value *AllOnes = ConstantInt::getAllOnesValue(Ty);
  2621. return SelectInst::Create(NewICmpInst, AllOnes, X);
  2622. }
  2623. }
  2624. if (Instruction *V =
  2625. canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
  2626. return V;
  2627. CmpInst::Predicate Pred;
  2628. Value *Mul, *Ov, *MulIsNotZero, *UMulWithOv;
  2629. // Check if the OR weakens the overflow condition for umul.with.overflow by
  2630. // treating any non-zero result as overflow. In that case, we overflow if both
  2631. // umul.with.overflow operands are != 0, as in that case the result can only
  2632. // be 0, iff the multiplication overflows.
  2633. if (match(&I,
  2634. m_c_Or(m_CombineAnd(m_ExtractValue<1>(m_Value(UMulWithOv)),
  2635. m_Value(Ov)),
  2636. m_CombineAnd(m_ICmp(Pred,
  2637. m_CombineAnd(m_ExtractValue<0>(
  2638. m_Deferred(UMulWithOv)),
  2639. m_Value(Mul)),
  2640. m_ZeroInt()),
  2641. m_Value(MulIsNotZero)))) &&
  2642. (Ov->hasOneUse() || (MulIsNotZero->hasOneUse() && Mul->hasOneUse())) &&
  2643. Pred == CmpInst::ICMP_NE) {
  2644. Value *A, *B;
  2645. if (match(UMulWithOv, m_Intrinsic<Intrinsic::umul_with_overflow>(
  2646. m_Value(A), m_Value(B)))) {
  2647. Value *NotNullA = Builder.CreateIsNotNull(A);
  2648. Value *NotNullB = Builder.CreateIsNotNull(B);
  2649. return BinaryOperator::CreateAnd(NotNullA, NotNullB);
  2650. }
  2651. }
  2652. // (~x) | y --> ~(x & (~y)) iff that gets rid of inversions
  2653. if (sinkNotIntoOtherHandOfAndOrOr(I))
  2654. return &I;
  2655. // Improve "get low bit mask up to and including bit X" pattern:
  2656. // (1 << X) | ((1 << X) + -1) --> -1 l>> (bitwidth(x) - 1 - X)
  2657. if (match(&I, m_c_Or(m_Add(m_Shl(m_One(), m_Value(X)), m_AllOnes()),
  2658. m_Shl(m_One(), m_Deferred(X)))) &&
  2659. match(&I, m_c_Or(m_OneUse(m_Value()), m_Value()))) {
  2660. Value *Sub = Builder.CreateSub(
  2661. ConstantInt::get(Ty, Ty->getScalarSizeInBits() - 1), X);
  2662. return BinaryOperator::CreateLShr(Constant::getAllOnesValue(Ty), Sub);
  2663. }
  2664. // An or recurrence w/loop invariant step is equivelent to (or start, step)
  2665. PHINode *PN = nullptr;
  2666. Value *Start = nullptr, *Step = nullptr;
  2667. if (matchSimpleRecurrence(&I, PN, Start, Step) && DT.dominates(Step, PN))
  2668. return replaceInstUsesWith(I, Builder.CreateOr(Start, Step));
  2669. return nullptr;
  2670. }
  2671. /// A ^ B can be specified using other logic ops in a variety of patterns. We
  2672. /// can fold these early and efficiently by morphing an existing instruction.
  2673. static Instruction *foldXorToXor(BinaryOperator &I,
  2674. InstCombiner::BuilderTy &Builder) {
  2675. assert(I.getOpcode() == Instruction::Xor);
  2676. Value *Op0 = I.getOperand(0);
  2677. Value *Op1 = I.getOperand(1);
  2678. Value *A, *B;
  2679. // There are 4 commuted variants for each of the basic patterns.
  2680. // (A & B) ^ (A | B) -> A ^ B
  2681. // (A & B) ^ (B | A) -> A ^ B
  2682. // (A | B) ^ (A & B) -> A ^ B
  2683. // (A | B) ^ (B & A) -> A ^ B
  2684. if (match(&I, m_c_Xor(m_And(m_Value(A), m_Value(B)),
  2685. m_c_Or(m_Deferred(A), m_Deferred(B)))))
  2686. return BinaryOperator::CreateXor(A, B);
  2687. // (A | ~B) ^ (~A | B) -> A ^ B
  2688. // (~B | A) ^ (~A | B) -> A ^ B
  2689. // (~A | B) ^ (A | ~B) -> A ^ B
  2690. // (B | ~A) ^ (A | ~B) -> A ^ B
  2691. if (match(&I, m_Xor(m_c_Or(m_Value(A), m_Not(m_Value(B))),
  2692. m_c_Or(m_Not(m_Deferred(A)), m_Deferred(B)))))
  2693. return BinaryOperator::CreateXor(A, B);
  2694. // (A & ~B) ^ (~A & B) -> A ^ B
  2695. // (~B & A) ^ (~A & B) -> A ^ B
  2696. // (~A & B) ^ (A & ~B) -> A ^ B
  2697. // (B & ~A) ^ (A & ~B) -> A ^ B
  2698. if (match(&I, m_Xor(m_c_And(m_Value(A), m_Not(m_Value(B))),
  2699. m_c_And(m_Not(m_Deferred(A)), m_Deferred(B)))))
  2700. return BinaryOperator::CreateXor(A, B);
  2701. // For the remaining cases we need to get rid of one of the operands.
  2702. if (!Op0->hasOneUse() && !Op1->hasOneUse())
  2703. return nullptr;
  2704. // (A | B) ^ ~(A & B) -> ~(A ^ B)
  2705. // (A | B) ^ ~(B & A) -> ~(A ^ B)
  2706. // (A & B) ^ ~(A | B) -> ~(A ^ B)
  2707. // (A & B) ^ ~(B | A) -> ~(A ^ B)
  2708. // Complexity sorting ensures the not will be on the right side.
  2709. if ((match(Op0, m_Or(m_Value(A), m_Value(B))) &&
  2710. match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B))))) ||
  2711. (match(Op0, m_And(m_Value(A), m_Value(B))) &&
  2712. match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))))
  2713. return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
  2714. return nullptr;
  2715. }
  2716. Value *InstCombinerImpl::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS,
  2717. BinaryOperator &I) {
  2718. assert(I.getOpcode() == Instruction::Xor && I.getOperand(0) == LHS &&
  2719. I.getOperand(1) == RHS && "Should be 'xor' with these operands");
  2720. if (predicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
  2721. if (LHS->getOperand(0) == RHS->getOperand(1) &&
  2722. LHS->getOperand(1) == RHS->getOperand(0))
  2723. LHS->swapOperands();
  2724. if (LHS->getOperand(0) == RHS->getOperand(0) &&
  2725. LHS->getOperand(1) == RHS->getOperand(1)) {
  2726. // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
  2727. Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
  2728. unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
  2729. bool IsSigned = LHS->isSigned() || RHS->isSigned();
  2730. return getNewICmpValue(Code, IsSigned, Op0, Op1, Builder);
  2731. }
  2732. }
  2733. // TODO: This can be generalized to compares of non-signbits using
  2734. // decomposeBitTestICmp(). It could be enhanced more by using (something like)
  2735. // foldLogOpOfMaskedICmps().
  2736. ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
  2737. Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
  2738. Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
  2739. if ((LHS->hasOneUse() || RHS->hasOneUse()) &&
  2740. LHS0->getType() == RHS0->getType() &&
  2741. LHS0->getType()->isIntOrIntVectorTy()) {
  2742. // (X > -1) ^ (Y > -1) --> (X ^ Y) < 0
  2743. // (X < 0) ^ (Y < 0) --> (X ^ Y) < 0
  2744. if ((PredL == CmpInst::ICMP_SGT && match(LHS1, m_AllOnes()) &&
  2745. PredR == CmpInst::ICMP_SGT && match(RHS1, m_AllOnes())) ||
  2746. (PredL == CmpInst::ICMP_SLT && match(LHS1, m_Zero()) &&
  2747. PredR == CmpInst::ICMP_SLT && match(RHS1, m_Zero()))) {
  2748. Value *Zero = ConstantInt::getNullValue(LHS0->getType());
  2749. return Builder.CreateICmpSLT(Builder.CreateXor(LHS0, RHS0), Zero);
  2750. }
  2751. // (X > -1) ^ (Y < 0) --> (X ^ Y) > -1
  2752. // (X < 0) ^ (Y > -1) --> (X ^ Y) > -1
  2753. if ((PredL == CmpInst::ICMP_SGT && match(LHS1, m_AllOnes()) &&
  2754. PredR == CmpInst::ICMP_SLT && match(RHS1, m_Zero())) ||
  2755. (PredL == CmpInst::ICMP_SLT && match(LHS1, m_Zero()) &&
  2756. PredR == CmpInst::ICMP_SGT && match(RHS1, m_AllOnes()))) {
  2757. Value *MinusOne = ConstantInt::getAllOnesValue(LHS0->getType());
  2758. return Builder.CreateICmpSGT(Builder.CreateXor(LHS0, RHS0), MinusOne);
  2759. }
  2760. }
  2761. // Instead of trying to imitate the folds for and/or, decompose this 'xor'
  2762. // into those logic ops. That is, try to turn this into an and-of-icmps
  2763. // because we have many folds for that pattern.
  2764. //
  2765. // This is based on a truth table definition of xor:
  2766. // X ^ Y --> (X | Y) & !(X & Y)
  2767. if (Value *OrICmp = SimplifyBinOp(Instruction::Or, LHS, RHS, SQ)) {
  2768. // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
  2769. // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
  2770. if (Value *AndICmp = SimplifyBinOp(Instruction::And, LHS, RHS, SQ)) {
  2771. // TODO: Independently handle cases where the 'and' side is a constant.
  2772. ICmpInst *X = nullptr, *Y = nullptr;
  2773. if (OrICmp == LHS && AndICmp == RHS) {
  2774. // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS --> X & !Y
  2775. X = LHS;
  2776. Y = RHS;
  2777. }
  2778. if (OrICmp == RHS && AndICmp == LHS) {
  2779. // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS --> !Y & X
  2780. X = RHS;
  2781. Y = LHS;
  2782. }
  2783. if (X && Y && (Y->hasOneUse() || canFreelyInvertAllUsersOf(Y, &I))) {
  2784. // Invert the predicate of 'Y', thus inverting its output.
  2785. Y->setPredicate(Y->getInversePredicate());
  2786. // So, are there other uses of Y?
  2787. if (!Y->hasOneUse()) {
  2788. // We need to adapt other uses of Y though. Get a value that matches
  2789. // the original value of Y before inversion. While this increases
  2790. // immediate instruction count, we have just ensured that all the
  2791. // users are freely-invertible, so that 'not' *will* get folded away.
  2792. BuilderTy::InsertPointGuard Guard(Builder);
  2793. // Set insertion point to right after the Y.
  2794. Builder.SetInsertPoint(Y->getParent(), ++(Y->getIterator()));
  2795. Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
  2796. // Replace all uses of Y (excluding the one in NotY!) with NotY.
  2797. Worklist.pushUsersToWorkList(*Y);
  2798. Y->replaceUsesWithIf(NotY,
  2799. [NotY](Use &U) { return U.getUser() != NotY; });
  2800. }
  2801. // All done.
  2802. return Builder.CreateAnd(LHS, RHS);
  2803. }
  2804. }
  2805. }
  2806. return nullptr;
  2807. }
  2808. /// If we have a masked merge, in the canonical form of:
  2809. /// (assuming that A only has one use.)
  2810. /// | A | |B|
  2811. /// ((x ^ y) & M) ^ y
  2812. /// | D |
  2813. /// * If M is inverted:
  2814. /// | D |
  2815. /// ((x ^ y) & ~M) ^ y
  2816. /// We can canonicalize by swapping the final xor operand
  2817. /// to eliminate the 'not' of the mask.
  2818. /// ((x ^ y) & M) ^ x
  2819. /// * If M is a constant, and D has one use, we transform to 'and' / 'or' ops
  2820. /// because that shortens the dependency chain and improves analysis:
  2821. /// (x & M) | (y & ~M)
  2822. static Instruction *visitMaskedMerge(BinaryOperator &I,
  2823. InstCombiner::BuilderTy &Builder) {
  2824. Value *B, *X, *D;
  2825. Value *M;
  2826. if (!match(&I, m_c_Xor(m_Value(B),
  2827. m_OneUse(m_c_And(
  2828. m_CombineAnd(m_c_Xor(m_Deferred(B), m_Value(X)),
  2829. m_Value(D)),
  2830. m_Value(M))))))
  2831. return nullptr;
  2832. Value *NotM;
  2833. if (match(M, m_Not(m_Value(NotM)))) {
  2834. // De-invert the mask and swap the value in B part.
  2835. Value *NewA = Builder.CreateAnd(D, NotM);
  2836. return BinaryOperator::CreateXor(NewA, X);
  2837. }
  2838. Constant *C;
  2839. if (D->hasOneUse() && match(M, m_Constant(C))) {
  2840. // Propagating undef is unsafe. Clamp undef elements to -1.
  2841. Type *EltTy = C->getType()->getScalarType();
  2842. C = Constant::replaceUndefsWith(C, ConstantInt::getAllOnesValue(EltTy));
  2843. // Unfold.
  2844. Value *LHS = Builder.CreateAnd(X, C);
  2845. Value *NotC = Builder.CreateNot(C);
  2846. Value *RHS = Builder.CreateAnd(B, NotC);
  2847. return BinaryOperator::CreateOr(LHS, RHS);
  2848. }
  2849. return nullptr;
  2850. }
  2851. // Transform
  2852. // ~(x ^ y)
  2853. // into:
  2854. // (~x) ^ y
  2855. // or into
  2856. // x ^ (~y)
  2857. static Instruction *sinkNotIntoXor(BinaryOperator &I,
  2858. InstCombiner::BuilderTy &Builder) {
  2859. Value *X, *Y;
  2860. // FIXME: one-use check is not needed in general, but currently we are unable
  2861. // to fold 'not' into 'icmp', if that 'icmp' has multiple uses. (D35182)
  2862. if (!match(&I, m_Not(m_OneUse(m_Xor(m_Value(X), m_Value(Y))))))
  2863. return nullptr;
  2864. // We only want to do the transform if it is free to do.
  2865. if (InstCombiner::isFreeToInvert(X, X->hasOneUse())) {
  2866. // Ok, good.
  2867. } else if (InstCombiner::isFreeToInvert(Y, Y->hasOneUse())) {
  2868. std::swap(X, Y);
  2869. } else
  2870. return nullptr;
  2871. Value *NotX = Builder.CreateNot(X, X->getName() + ".not");
  2872. return BinaryOperator::CreateXor(NotX, Y, I.getName() + ".demorgan");
  2873. }
  2874. /// Canonicalize a shifty way to code absolute value to the more common pattern
  2875. /// that uses negation and select.
  2876. static Instruction *canonicalizeAbs(BinaryOperator &Xor,
  2877. InstCombiner::BuilderTy &Builder) {
  2878. assert(Xor.getOpcode() == Instruction::Xor && "Expected an xor instruction.");
  2879. // There are 4 potential commuted variants. Move the 'ashr' candidate to Op1.
  2880. // We're relying on the fact that we only do this transform when the shift has
  2881. // exactly 2 uses and the add has exactly 1 use (otherwise, we might increase
  2882. // instructions).
  2883. Value *Op0 = Xor.getOperand(0), *Op1 = Xor.getOperand(1);
  2884. if (Op0->hasNUses(2))
  2885. std::swap(Op0, Op1);
  2886. Type *Ty = Xor.getType();
  2887. Value *A;
  2888. const APInt *ShAmt;
  2889. if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
  2890. Op1->hasNUses(2) && *ShAmt == Ty->getScalarSizeInBits() - 1 &&
  2891. match(Op0, m_OneUse(m_c_Add(m_Specific(A), m_Specific(Op1))))) {
  2892. // Op1 = ashr i32 A, 31 ; smear the sign bit
  2893. // xor (add A, Op1), Op1 ; add -1 and flip bits if negative
  2894. // --> (A < 0) ? -A : A
  2895. Value *Cmp = Builder.CreateICmpSLT(A, ConstantInt::getNullValue(Ty));
  2896. // Copy the nuw/nsw flags from the add to the negate.
  2897. auto *Add = cast<BinaryOperator>(Op0);
  2898. Value *Neg = Builder.CreateNeg(A, "", Add->hasNoUnsignedWrap(),
  2899. Add->hasNoSignedWrap());
  2900. return SelectInst::Create(Cmp, Neg, A);
  2901. }
  2902. return nullptr;
  2903. }
  2904. // Transform
  2905. // z = (~x) &/| y
  2906. // into:
  2907. // z = ~(x |/& (~y))
  2908. // iff y is free to invert and all uses of z can be freely updated.
  2909. bool InstCombinerImpl::sinkNotIntoOtherHandOfAndOrOr(BinaryOperator &I) {
  2910. Instruction::BinaryOps NewOpc;
  2911. switch (I.getOpcode()) {
  2912. case Instruction::And:
  2913. NewOpc = Instruction::Or;
  2914. break;
  2915. case Instruction::Or:
  2916. NewOpc = Instruction::And;
  2917. break;
  2918. default:
  2919. return false;
  2920. };
  2921. Value *X, *Y;
  2922. if (!match(&I, m_c_BinOp(m_Not(m_Value(X)), m_Value(Y))))
  2923. return false;
  2924. // Will we be able to fold the `not` into Y eventually?
  2925. if (!InstCombiner::isFreeToInvert(Y, Y->hasOneUse()))
  2926. return false;
  2927. // And can our users be adapted?
  2928. if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
  2929. return false;
  2930. Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
  2931. Value *NewBinOp =
  2932. BinaryOperator::Create(NewOpc, X, NotY, I.getName() + ".not");
  2933. Builder.Insert(NewBinOp);
  2934. replaceInstUsesWith(I, NewBinOp);
  2935. // We can not just create an outer `not`, it will most likely be immediately
  2936. // folded back, reconstructing our initial pattern, and causing an
  2937. // infinite combine loop, so immediately manually fold it away.
  2938. freelyInvertAllUsersOf(NewBinOp);
  2939. return true;
  2940. }
  2941. Instruction *InstCombinerImpl::foldNot(BinaryOperator &I) {
  2942. Value *NotOp;
  2943. if (!match(&I, m_Not(m_Value(NotOp))))
  2944. return nullptr;
  2945. // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
  2946. // We must eliminate the and/or (one-use) for these transforms to not increase
  2947. // the instruction count.
  2948. //
  2949. // ~(~X & Y) --> (X | ~Y)
  2950. // ~(Y & ~X) --> (X | ~Y)
  2951. //
  2952. // Note: The logical matches do not check for the commuted patterns because
  2953. // those are handled via SimplifySelectsFeedingBinaryOp().
  2954. Type *Ty = I.getType();
  2955. Value *X, *Y;
  2956. if (match(NotOp, m_OneUse(m_c_And(m_Not(m_Value(X)), m_Value(Y))))) {
  2957. Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
  2958. return BinaryOperator::CreateOr(X, NotY);
  2959. }
  2960. if (match(NotOp, m_OneUse(m_LogicalAnd(m_Not(m_Value(X)), m_Value(Y))))) {
  2961. Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
  2962. return SelectInst::Create(X, ConstantInt::getTrue(Ty), NotY);
  2963. }
  2964. // ~(~X | Y) --> (X & ~Y)
  2965. // ~(Y | ~X) --> (X & ~Y)
  2966. if (match(NotOp, m_OneUse(m_c_Or(m_Not(m_Value(X)), m_Value(Y))))) {
  2967. Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
  2968. return BinaryOperator::CreateAnd(X, NotY);
  2969. }
  2970. if (match(NotOp, m_OneUse(m_LogicalOr(m_Not(m_Value(X)), m_Value(Y))))) {
  2971. Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
  2972. return SelectInst::Create(X, NotY, ConstantInt::getFalse(Ty));
  2973. }
  2974. // Is this a 'not' (~) fed by a binary operator?
  2975. BinaryOperator *NotVal;
  2976. if (match(NotOp, m_BinOp(NotVal))) {
  2977. if (NotVal->getOpcode() == Instruction::And ||
  2978. NotVal->getOpcode() == Instruction::Or) {
  2979. // Apply DeMorgan's Law when inverts are free:
  2980. // ~(X & Y) --> (~X | ~Y)
  2981. // ~(X | Y) --> (~X & ~Y)
  2982. if (isFreeToInvert(NotVal->getOperand(0),
  2983. NotVal->getOperand(0)->hasOneUse()) &&
  2984. isFreeToInvert(NotVal->getOperand(1),
  2985. NotVal->getOperand(1)->hasOneUse())) {
  2986. Value *NotX = Builder.CreateNot(NotVal->getOperand(0), "notlhs");
  2987. Value *NotY = Builder.CreateNot(NotVal->getOperand(1), "notrhs");
  2988. if (NotVal->getOpcode() == Instruction::And)
  2989. return BinaryOperator::CreateOr(NotX, NotY);
  2990. return BinaryOperator::CreateAnd(NotX, NotY);
  2991. }
  2992. }
  2993. // ~((-X) | Y) --> (X - 1) & (~Y)
  2994. if (match(NotVal,
  2995. m_OneUse(m_c_Or(m_OneUse(m_Neg(m_Value(X))), m_Value(Y))))) {
  2996. Value *DecX = Builder.CreateAdd(X, ConstantInt::getAllOnesValue(Ty));
  2997. Value *NotY = Builder.CreateNot(Y);
  2998. return BinaryOperator::CreateAnd(DecX, NotY);
  2999. }
  3000. // ~(~X >>s Y) --> (X >>s Y)
  3001. if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y))))
  3002. return BinaryOperator::CreateAShr(X, Y);
  3003. // If we are inverting a right-shifted constant, we may be able to eliminate
  3004. // the 'not' by inverting the constant and using the opposite shift type.
  3005. // Canonicalization rules ensure that only a negative constant uses 'ashr',
  3006. // but we must check that in case that transform has not fired yet.
  3007. // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
  3008. Constant *C;
  3009. if (match(NotVal, m_AShr(m_Constant(C), m_Value(Y))) &&
  3010. match(C, m_Negative())) {
  3011. // We matched a negative constant, so propagating undef is unsafe.
  3012. // Clamp undef elements to -1.
  3013. Type *EltTy = Ty->getScalarType();
  3014. C = Constant::replaceUndefsWith(C, ConstantInt::getAllOnesValue(EltTy));
  3015. return BinaryOperator::CreateLShr(ConstantExpr::getNot(C), Y);
  3016. }
  3017. // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
  3018. if (match(NotVal, m_LShr(m_Constant(C), m_Value(Y))) &&
  3019. match(C, m_NonNegative())) {
  3020. // We matched a non-negative constant, so propagating undef is unsafe.
  3021. // Clamp undef elements to 0.
  3022. Type *EltTy = Ty->getScalarType();
  3023. C = Constant::replaceUndefsWith(C, ConstantInt::getNullValue(EltTy));
  3024. return BinaryOperator::CreateAShr(ConstantExpr::getNot(C), Y);
  3025. }
  3026. // ~(X + C) --> ~C - X
  3027. if (match(NotVal, m_c_Add(m_Value(X), m_ImmConstant(C))))
  3028. return BinaryOperator::CreateSub(ConstantExpr::getNot(C), X);
  3029. // ~(X - Y) --> ~X + Y
  3030. // FIXME: is it really beneficial to sink the `not` here?
  3031. if (match(NotVal, m_Sub(m_Value(X), m_Value(Y))))
  3032. if (isa<Constant>(X) || NotVal->hasOneUse())
  3033. return BinaryOperator::CreateAdd(Builder.CreateNot(X), Y);
  3034. // ~(~X + Y) --> X - Y
  3035. if (match(NotVal, m_c_Add(m_Not(m_Value(X)), m_Value(Y))))
  3036. return BinaryOperator::CreateWithCopiedFlags(Instruction::Sub, X, Y,
  3037. NotVal);
  3038. }
  3039. // not (cmp A, B) = !cmp A, B
  3040. CmpInst::Predicate Pred;
  3041. if (match(NotOp, m_OneUse(m_Cmp(Pred, m_Value(), m_Value())))) {
  3042. cast<CmpInst>(NotOp)->setPredicate(CmpInst::getInversePredicate(Pred));
  3043. return replaceInstUsesWith(I, NotOp);
  3044. }
  3045. // Eliminate a bitwise 'not' op of 'not' min/max by inverting the min/max:
  3046. // ~min(~X, ~Y) --> max(X, Y)
  3047. // ~max(~X, Y) --> min(X, ~Y)
  3048. auto *II = dyn_cast<IntrinsicInst>(NotOp);
  3049. if (II && II->hasOneUse()) {
  3050. if (match(NotOp, m_MaxOrMin(m_Value(X), m_Value(Y))) &&
  3051. isFreeToInvert(X, X->hasOneUse()) &&
  3052. isFreeToInvert(Y, Y->hasOneUse())) {
  3053. Intrinsic::ID InvID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
  3054. Value *NotX = Builder.CreateNot(X);
  3055. Value *NotY = Builder.CreateNot(Y);
  3056. Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, NotX, NotY);
  3057. return replaceInstUsesWith(I, InvMaxMin);
  3058. }
  3059. if (match(NotOp, m_c_MaxOrMin(m_Not(m_Value(X)), m_Value(Y)))) {
  3060. Intrinsic::ID InvID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
  3061. Value *NotY = Builder.CreateNot(Y);
  3062. Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, X, NotY);
  3063. return replaceInstUsesWith(I, InvMaxMin);
  3064. }
  3065. }
  3066. // TODO: Remove folds if we canonicalize to intrinsics (see above).
  3067. // Eliminate a bitwise 'not' op of 'not' min/max by inverting the min/max:
  3068. //
  3069. // %notx = xor i32 %x, -1
  3070. // %cmp1 = icmp sgt i32 %notx, %y
  3071. // %smax = select i1 %cmp1, i32 %notx, i32 %y
  3072. // %res = xor i32 %smax, -1
  3073. // =>
  3074. // %noty = xor i32 %y, -1
  3075. // %cmp2 = icmp slt %x, %noty
  3076. // %res = select i1 %cmp2, i32 %x, i32 %noty
  3077. //
  3078. // Same is applicable for smin/umax/umin.
  3079. if (NotOp->hasOneUse()) {
  3080. Value *LHS, *RHS;
  3081. SelectPatternFlavor SPF = matchSelectPattern(NotOp, LHS, RHS).Flavor;
  3082. if (SelectPatternResult::isMinOrMax(SPF)) {
  3083. // It's possible we get here before the not has been simplified, so make
  3084. // sure the input to the not isn't freely invertible.
  3085. if (match(LHS, m_Not(m_Value(X))) && !isFreeToInvert(X, X->hasOneUse())) {
  3086. Value *NotY = Builder.CreateNot(RHS);
  3087. return SelectInst::Create(
  3088. Builder.CreateICmp(getInverseMinMaxPred(SPF), X, NotY), X, NotY);
  3089. }
  3090. // It's possible we get here before the not has been simplified, so make
  3091. // sure the input to the not isn't freely invertible.
  3092. if (match(RHS, m_Not(m_Value(Y))) && !isFreeToInvert(Y, Y->hasOneUse())) {
  3093. Value *NotX = Builder.CreateNot(LHS);
  3094. return SelectInst::Create(
  3095. Builder.CreateICmp(getInverseMinMaxPred(SPF), NotX, Y), NotX, Y);
  3096. }
  3097. // If both sides are freely invertible, then we can get rid of the xor
  3098. // completely.
  3099. if (isFreeToInvert(LHS, !LHS->hasNUsesOrMore(3)) &&
  3100. isFreeToInvert(RHS, !RHS->hasNUsesOrMore(3))) {
  3101. Value *NotLHS = Builder.CreateNot(LHS);
  3102. Value *NotRHS = Builder.CreateNot(RHS);
  3103. return SelectInst::Create(
  3104. Builder.CreateICmp(getInverseMinMaxPred(SPF), NotLHS, NotRHS),
  3105. NotLHS, NotRHS);
  3106. }
  3107. }
  3108. // Pull 'not' into operands of select if both operands are one-use compares
  3109. // or one is one-use compare and the other one is a constant.
  3110. // Inverting the predicates eliminates the 'not' operation.
  3111. // Example:
  3112. // not (select ?, (cmp TPred, ?, ?), (cmp FPred, ?, ?) -->
  3113. // select ?, (cmp InvTPred, ?, ?), (cmp InvFPred, ?, ?)
  3114. // not (select ?, (cmp TPred, ?, ?), true -->
  3115. // select ?, (cmp InvTPred, ?, ?), false
  3116. if (auto *Sel = dyn_cast<SelectInst>(NotOp)) {
  3117. Value *TV = Sel->getTrueValue();
  3118. Value *FV = Sel->getFalseValue();
  3119. auto *CmpT = dyn_cast<CmpInst>(TV);
  3120. auto *CmpF = dyn_cast<CmpInst>(FV);
  3121. bool InvertibleT = (CmpT && CmpT->hasOneUse()) || isa<Constant>(TV);
  3122. bool InvertibleF = (CmpF && CmpF->hasOneUse()) || isa<Constant>(FV);
  3123. if (InvertibleT && InvertibleF) {
  3124. if (CmpT)
  3125. CmpT->setPredicate(CmpT->getInversePredicate());
  3126. else
  3127. Sel->setTrueValue(ConstantExpr::getNot(cast<Constant>(TV)));
  3128. if (CmpF)
  3129. CmpF->setPredicate(CmpF->getInversePredicate());
  3130. else
  3131. Sel->setFalseValue(ConstantExpr::getNot(cast<Constant>(FV)));
  3132. return replaceInstUsesWith(I, Sel);
  3133. }
  3134. }
  3135. }
  3136. if (Instruction *NewXor = sinkNotIntoXor(I, Builder))
  3137. return NewXor;
  3138. return nullptr;
  3139. }
  3140. // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
  3141. // here. We should standardize that construct where it is needed or choose some
  3142. // other way to ensure that commutated variants of patterns are not missed.
  3143. Instruction *InstCombinerImpl::visitXor(BinaryOperator &I) {
  3144. if (Value *V = SimplifyXorInst(I.getOperand(0), I.getOperand(1),
  3145. SQ.getWithInstruction(&I)))
  3146. return replaceInstUsesWith(I, V);
  3147. if (SimplifyAssociativeOrCommutative(I))
  3148. return &I;
  3149. if (Instruction *X = foldVectorBinop(I))
  3150. return X;
  3151. if (Instruction *Phi = foldBinopWithPhiOperands(I))
  3152. return Phi;
  3153. if (Instruction *NewXor = foldXorToXor(I, Builder))
  3154. return NewXor;
  3155. // (A&B)^(A&C) -> A&(B^C) etc
  3156. if (Value *V = SimplifyUsingDistributiveLaws(I))
  3157. return replaceInstUsesWith(I, V);
  3158. // See if we can simplify any instructions used by the instruction whose sole
  3159. // purpose is to compute bits we don't care about.
  3160. if (SimplifyDemandedInstructionBits(I))
  3161. return &I;
  3162. if (Value *V = SimplifyBSwap(I, Builder))
  3163. return replaceInstUsesWith(I, V);
  3164. if (Instruction *R = foldNot(I))
  3165. return R;
  3166. // Fold (X & M) ^ (Y & ~M) -> (X & M) | (Y & ~M)
  3167. // This it a special case in haveNoCommonBitsSet, but the computeKnownBits
  3168. // calls in there are unnecessary as SimplifyDemandedInstructionBits should
  3169. // have already taken care of those cases.
  3170. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  3171. Value *M;
  3172. if (match(&I, m_c_Xor(m_c_And(m_Not(m_Value(M)), m_Value()),
  3173. m_c_And(m_Deferred(M), m_Value()))))
  3174. return BinaryOperator::CreateOr(Op0, Op1);
  3175. if (Instruction *Xor = visitMaskedMerge(I, Builder))
  3176. return Xor;
  3177. Value *X, *Y;
  3178. Constant *C1;
  3179. if (match(Op1, m_Constant(C1))) {
  3180. // Use DeMorgan and reassociation to eliminate a 'not' op.
  3181. Constant *C2;
  3182. if (match(Op0, m_OneUse(m_Or(m_Not(m_Value(X)), m_Constant(C2))))) {
  3183. // (~X | C2) ^ C1 --> ((X & ~C2) ^ -1) ^ C1 --> (X & ~C2) ^ ~C1
  3184. Value *And = Builder.CreateAnd(X, ConstantExpr::getNot(C2));
  3185. return BinaryOperator::CreateXor(And, ConstantExpr::getNot(C1));
  3186. }
  3187. if (match(Op0, m_OneUse(m_And(m_Not(m_Value(X)), m_Constant(C2))))) {
  3188. // (~X & C2) ^ C1 --> ((X | ~C2) ^ -1) ^ C1 --> (X | ~C2) ^ ~C1
  3189. Value *Or = Builder.CreateOr(X, ConstantExpr::getNot(C2));
  3190. return BinaryOperator::CreateXor(Or, ConstantExpr::getNot(C1));
  3191. }
  3192. // Convert xor ([trunc] (ashr X, BW-1)), C =>
  3193. // select(X >s -1, C, ~C)
  3194. // The ashr creates "AllZeroOrAllOne's", which then optionally inverses the
  3195. // constant depending on whether this input is less than 0.
  3196. const APInt *CA;
  3197. if (match(Op0, m_OneUse(m_TruncOrSelf(
  3198. m_AShr(m_Value(X), m_APIntAllowUndef(CA))))) &&
  3199. *CA == X->getType()->getScalarSizeInBits() - 1 &&
  3200. !match(C1, m_AllOnes())) {
  3201. assert(!C1->isZeroValue() && "Unexpected xor with 0");
  3202. Value *ICmp =
  3203. Builder.CreateICmpSGT(X, Constant::getAllOnesValue(X->getType()));
  3204. return SelectInst::Create(ICmp, Op1, Builder.CreateNot(Op1));
  3205. }
  3206. }
  3207. Type *Ty = I.getType();
  3208. {
  3209. const APInt *RHSC;
  3210. if (match(Op1, m_APInt(RHSC))) {
  3211. Value *X;
  3212. const APInt *C;
  3213. // (C - X) ^ signmaskC --> (C + signmaskC) - X
  3214. if (RHSC->isSignMask() && match(Op0, m_Sub(m_APInt(C), m_Value(X))))
  3215. return BinaryOperator::CreateSub(ConstantInt::get(Ty, *C + *RHSC), X);
  3216. // (X + C) ^ signmaskC --> X + (C + signmaskC)
  3217. if (RHSC->isSignMask() && match(Op0, m_Add(m_Value(X), m_APInt(C))))
  3218. return BinaryOperator::CreateAdd(X, ConstantInt::get(Ty, *C + *RHSC));
  3219. // (X | C) ^ RHSC --> X ^ (C ^ RHSC) iff X & C == 0
  3220. if (match(Op0, m_Or(m_Value(X), m_APInt(C))) &&
  3221. MaskedValueIsZero(X, *C, 0, &I))
  3222. return BinaryOperator::CreateXor(X, ConstantInt::get(Ty, *C ^ *RHSC));
  3223. // If RHSC is inverting the remaining bits of shifted X,
  3224. // canonicalize to a 'not' before the shift to help SCEV and codegen:
  3225. // (X << C) ^ RHSC --> ~X << C
  3226. if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_APInt(C)))) &&
  3227. *RHSC == APInt::getAllOnes(Ty->getScalarSizeInBits()).shl(*C)) {
  3228. Value *NotX = Builder.CreateNot(X);
  3229. return BinaryOperator::CreateShl(NotX, ConstantInt::get(Ty, *C));
  3230. }
  3231. // (X >>u C) ^ RHSC --> ~X >>u C
  3232. if (match(Op0, m_OneUse(m_LShr(m_Value(X), m_APInt(C)))) &&
  3233. *RHSC == APInt::getAllOnes(Ty->getScalarSizeInBits()).lshr(*C)) {
  3234. Value *NotX = Builder.CreateNot(X);
  3235. return BinaryOperator::CreateLShr(NotX, ConstantInt::get(Ty, *C));
  3236. }
  3237. // TODO: We could handle 'ashr' here as well. That would be matching
  3238. // a 'not' op and moving it before the shift. Doing that requires
  3239. // preventing the inverse fold in canShiftBinOpWithConstantRHS().
  3240. }
  3241. }
  3242. // FIXME: This should not be limited to scalar (pull into APInt match above).
  3243. {
  3244. Value *X;
  3245. ConstantInt *C1, *C2, *C3;
  3246. // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
  3247. if (match(Op1, m_ConstantInt(C3)) &&
  3248. match(Op0, m_LShr(m_Xor(m_Value(X), m_ConstantInt(C1)),
  3249. m_ConstantInt(C2))) &&
  3250. Op0->hasOneUse()) {
  3251. // fold (C1 >> C2) ^ C3
  3252. APInt FoldConst = C1->getValue().lshr(C2->getValue());
  3253. FoldConst ^= C3->getValue();
  3254. // Prepare the two operands.
  3255. auto *Opnd0 = cast<Instruction>(Builder.CreateLShr(X, C2));
  3256. Opnd0->takeName(cast<Instruction>(Op0));
  3257. Opnd0->setDebugLoc(I.getDebugLoc());
  3258. return BinaryOperator::CreateXor(Opnd0, ConstantInt::get(Ty, FoldConst));
  3259. }
  3260. }
  3261. if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
  3262. return FoldedLogic;
  3263. // Y ^ (X | Y) --> X & ~Y
  3264. // Y ^ (Y | X) --> X & ~Y
  3265. if (match(Op1, m_OneUse(m_c_Or(m_Value(X), m_Specific(Op0)))))
  3266. return BinaryOperator::CreateAnd(X, Builder.CreateNot(Op0));
  3267. // (X | Y) ^ Y --> X & ~Y
  3268. // (Y | X) ^ Y --> X & ~Y
  3269. if (match(Op0, m_OneUse(m_c_Or(m_Value(X), m_Specific(Op1)))))
  3270. return BinaryOperator::CreateAnd(X, Builder.CreateNot(Op1));
  3271. // Y ^ (X & Y) --> ~X & Y
  3272. // Y ^ (Y & X) --> ~X & Y
  3273. if (match(Op1, m_OneUse(m_c_And(m_Value(X), m_Specific(Op0)))))
  3274. return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(X));
  3275. // (X & Y) ^ Y --> ~X & Y
  3276. // (Y & X) ^ Y --> ~X & Y
  3277. // Canonical form is (X & C) ^ C; don't touch that.
  3278. // TODO: A 'not' op is better for analysis and codegen, but demanded bits must
  3279. // be fixed to prefer that (otherwise we get infinite looping).
  3280. if (!match(Op1, m_Constant()) &&
  3281. match(Op0, m_OneUse(m_c_And(m_Value(X), m_Specific(Op1)))))
  3282. return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(X));
  3283. Value *A, *B, *C;
  3284. // (A ^ B) ^ (A | C) --> (~A & C) ^ B -- There are 4 commuted variants.
  3285. if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_Value(A), m_Value(B))),
  3286. m_OneUse(m_c_Or(m_Deferred(A), m_Value(C))))))
  3287. return BinaryOperator::CreateXor(
  3288. Builder.CreateAnd(Builder.CreateNot(A), C), B);
  3289. // (A ^ B) ^ (B | C) --> (~B & C) ^ A -- There are 4 commuted variants.
  3290. if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_Value(A), m_Value(B))),
  3291. m_OneUse(m_c_Or(m_Deferred(B), m_Value(C))))))
  3292. return BinaryOperator::CreateXor(
  3293. Builder.CreateAnd(Builder.CreateNot(B), C), A);
  3294. // (A & B) ^ (A ^ B) -> (A | B)
  3295. if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
  3296. match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
  3297. return BinaryOperator::CreateOr(A, B);
  3298. // (A ^ B) ^ (A & B) -> (A | B)
  3299. if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
  3300. match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
  3301. return BinaryOperator::CreateOr(A, B);
  3302. // (A & ~B) ^ ~A -> ~(A & B)
  3303. // (~B & A) ^ ~A -> ~(A & B)
  3304. if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
  3305. match(Op1, m_Not(m_Specific(A))))
  3306. return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
  3307. // (~A & B) ^ A --> A | B -- There are 4 commuted variants.
  3308. if (match(&I, m_c_Xor(m_c_And(m_Not(m_Value(A)), m_Value(B)), m_Deferred(A))))
  3309. return BinaryOperator::CreateOr(A, B);
  3310. // (~A | B) ^ A --> ~(A & B)
  3311. if (match(Op0, m_OneUse(m_c_Or(m_Not(m_Specific(Op1)), m_Value(B)))))
  3312. return BinaryOperator::CreateNot(Builder.CreateAnd(Op1, B));
  3313. // A ^ (~A | B) --> ~(A & B)
  3314. if (match(Op1, m_OneUse(m_c_Or(m_Not(m_Specific(Op0)), m_Value(B)))))
  3315. return BinaryOperator::CreateNot(Builder.CreateAnd(Op0, B));
  3316. // (A | B) ^ (A | C) --> (B ^ C) & ~A -- There are 4 commuted variants.
  3317. // TODO: Loosen one-use restriction if common operand is a constant.
  3318. Value *D;
  3319. if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B)))) &&
  3320. match(Op1, m_OneUse(m_Or(m_Value(C), m_Value(D))))) {
  3321. if (B == C || B == D)
  3322. std::swap(A, B);
  3323. if (A == C)
  3324. std::swap(C, D);
  3325. if (A == D) {
  3326. Value *NotA = Builder.CreateNot(A);
  3327. return BinaryOperator::CreateAnd(Builder.CreateXor(B, C), NotA);
  3328. }
  3329. }
  3330. if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
  3331. if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
  3332. if (Value *V = foldXorOfICmps(LHS, RHS, I))
  3333. return replaceInstUsesWith(I, V);
  3334. if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
  3335. return CastedXor;
  3336. if (Instruction *Abs = canonicalizeAbs(I, Builder))
  3337. return Abs;
  3338. // Otherwise, if all else failed, try to hoist the xor-by-constant:
  3339. // (X ^ C) ^ Y --> (X ^ Y) ^ C
  3340. // Just like we do in other places, we completely avoid the fold
  3341. // for constantexprs, at least to avoid endless combine loop.
  3342. if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_CombineAnd(m_Value(X),
  3343. m_Unless(m_ConstantExpr())),
  3344. m_ImmConstant(C1))),
  3345. m_Value(Y))))
  3346. return BinaryOperator::CreateXor(Builder.CreateXor(X, Y), C1);
  3347. return nullptr;
  3348. }