InstCombineSelect.cpp 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559
  1. //===- InstCombineSelect.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 visitSelect function.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "InstCombineInternal.h"
  13. #include "llvm/ADT/APInt.h"
  14. #include "llvm/ADT/Optional.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/Analysis/AssumptionCache.h"
  18. #include "llvm/Analysis/CmpInstAnalysis.h"
  19. #include "llvm/Analysis/InstructionSimplify.h"
  20. #include "llvm/Analysis/ValueTracking.h"
  21. #include "llvm/IR/BasicBlock.h"
  22. #include "llvm/IR/Constant.h"
  23. #include "llvm/IR/Constants.h"
  24. #include "llvm/IR/DerivedTypes.h"
  25. #include "llvm/IR/IRBuilder.h"
  26. #include "llvm/IR/InstrTypes.h"
  27. #include "llvm/IR/Instruction.h"
  28. #include "llvm/IR/Instructions.h"
  29. #include "llvm/IR/IntrinsicInst.h"
  30. #include "llvm/IR/Intrinsics.h"
  31. #include "llvm/IR/Operator.h"
  32. #include "llvm/IR/PatternMatch.h"
  33. #include "llvm/IR/Type.h"
  34. #include "llvm/IR/User.h"
  35. #include "llvm/IR/Value.h"
  36. #include "llvm/Support/Casting.h"
  37. #include "llvm/Support/ErrorHandling.h"
  38. #include "llvm/Support/KnownBits.h"
  39. #include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
  40. #include <cassert>
  41. #include <utility>
  42. using namespace llvm;
  43. using namespace PatternMatch;
  44. #define DEBUG_TYPE "instcombine"
  45. static Value *createMinMax(InstCombiner::BuilderTy &Builder,
  46. SelectPatternFlavor SPF, Value *A, Value *B) {
  47. CmpInst::Predicate Pred = getMinMaxPred(SPF);
  48. assert(CmpInst::isIntPredicate(Pred) && "Expected integer predicate");
  49. return Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
  50. }
  51. /// Replace a select operand based on an equality comparison with the identity
  52. /// constant of a binop.
  53. static Instruction *foldSelectBinOpIdentity(SelectInst &Sel,
  54. const TargetLibraryInfo &TLI) {
  55. // The select condition must be an equality compare with a constant operand.
  56. Value *X;
  57. Constant *C;
  58. CmpInst::Predicate Pred;
  59. if (!match(Sel.getCondition(), m_Cmp(Pred, m_Value(X), m_Constant(C))))
  60. return nullptr;
  61. bool IsEq;
  62. if (ICmpInst::isEquality(Pred))
  63. IsEq = Pred == ICmpInst::ICMP_EQ;
  64. else if (Pred == FCmpInst::FCMP_OEQ)
  65. IsEq = true;
  66. else if (Pred == FCmpInst::FCMP_UNE)
  67. IsEq = false;
  68. else
  69. return nullptr;
  70. // A select operand must be a binop.
  71. BinaryOperator *BO;
  72. if (!match(Sel.getOperand(IsEq ? 1 : 2), m_BinOp(BO)))
  73. return nullptr;
  74. // The compare constant must be the identity constant for that binop.
  75. // If this a floating-point compare with 0.0, any zero constant will do.
  76. Type *Ty = BO->getType();
  77. Constant *IdC = ConstantExpr::getBinOpIdentity(BO->getOpcode(), Ty, true);
  78. if (IdC != C) {
  79. if (!IdC || !CmpInst::isFPPredicate(Pred))
  80. return nullptr;
  81. if (!match(IdC, m_AnyZeroFP()) || !match(C, m_AnyZeroFP()))
  82. return nullptr;
  83. }
  84. // Last, match the compare variable operand with a binop operand.
  85. Value *Y;
  86. if (!BO->isCommutative() && !match(BO, m_BinOp(m_Value(Y), m_Specific(X))))
  87. return nullptr;
  88. if (!match(BO, m_c_BinOp(m_Value(Y), m_Specific(X))))
  89. return nullptr;
  90. // +0.0 compares equal to -0.0, and so it does not behave as required for this
  91. // transform. Bail out if we can not exclude that possibility.
  92. if (isa<FPMathOperator>(BO))
  93. if (!BO->hasNoSignedZeros() && !CannotBeNegativeZero(Y, &TLI))
  94. return nullptr;
  95. // BO = binop Y, X
  96. // S = { select (cmp eq X, C), BO, ? } or { select (cmp ne X, C), ?, BO }
  97. // =>
  98. // S = { select (cmp eq X, C), Y, ? } or { select (cmp ne X, C), ?, Y }
  99. Sel.setOperand(IsEq ? 1 : 2, Y);
  100. return &Sel;
  101. }
  102. /// This folds:
  103. /// select (icmp eq (and X, C1)), TC, FC
  104. /// iff C1 is a power 2 and the difference between TC and FC is a power-of-2.
  105. /// To something like:
  106. /// (shr (and (X, C1)), (log2(C1) - log2(TC-FC))) + FC
  107. /// Or:
  108. /// (shl (and (X, C1)), (log2(TC-FC) - log2(C1))) + FC
  109. /// With some variations depending if FC is larger than TC, or the shift
  110. /// isn't needed, or the bit widths don't match.
  111. static Value *foldSelectICmpAnd(SelectInst &Sel, ICmpInst *Cmp,
  112. InstCombiner::BuilderTy &Builder) {
  113. const APInt *SelTC, *SelFC;
  114. if (!match(Sel.getTrueValue(), m_APInt(SelTC)) ||
  115. !match(Sel.getFalseValue(), m_APInt(SelFC)))
  116. return nullptr;
  117. // If this is a vector select, we need a vector compare.
  118. Type *SelType = Sel.getType();
  119. if (SelType->isVectorTy() != Cmp->getType()->isVectorTy())
  120. return nullptr;
  121. Value *V;
  122. APInt AndMask;
  123. bool CreateAnd = false;
  124. ICmpInst::Predicate Pred = Cmp->getPredicate();
  125. if (ICmpInst::isEquality(Pred)) {
  126. if (!match(Cmp->getOperand(1), m_Zero()))
  127. return nullptr;
  128. V = Cmp->getOperand(0);
  129. const APInt *AndRHS;
  130. if (!match(V, m_And(m_Value(), m_Power2(AndRHS))))
  131. return nullptr;
  132. AndMask = *AndRHS;
  133. } else if (decomposeBitTestICmp(Cmp->getOperand(0), Cmp->getOperand(1),
  134. Pred, V, AndMask)) {
  135. assert(ICmpInst::isEquality(Pred) && "Not equality test?");
  136. if (!AndMask.isPowerOf2())
  137. return nullptr;
  138. CreateAnd = true;
  139. } else {
  140. return nullptr;
  141. }
  142. // In general, when both constants are non-zero, we would need an offset to
  143. // replace the select. This would require more instructions than we started
  144. // with. But there's one special-case that we handle here because it can
  145. // simplify/reduce the instructions.
  146. APInt TC = *SelTC;
  147. APInt FC = *SelFC;
  148. if (!TC.isNullValue() && !FC.isNullValue()) {
  149. // If the select constants differ by exactly one bit and that's the same
  150. // bit that is masked and checked by the select condition, the select can
  151. // be replaced by bitwise logic to set/clear one bit of the constant result.
  152. if (TC.getBitWidth() != AndMask.getBitWidth() || (TC ^ FC) != AndMask)
  153. return nullptr;
  154. if (CreateAnd) {
  155. // If we have to create an 'and', then we must kill the cmp to not
  156. // increase the instruction count.
  157. if (!Cmp->hasOneUse())
  158. return nullptr;
  159. V = Builder.CreateAnd(V, ConstantInt::get(SelType, AndMask));
  160. }
  161. bool ExtraBitInTC = TC.ugt(FC);
  162. if (Pred == ICmpInst::ICMP_EQ) {
  163. // If the masked bit in V is clear, clear or set the bit in the result:
  164. // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) ^ TC
  165. // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) | TC
  166. Constant *C = ConstantInt::get(SelType, TC);
  167. return ExtraBitInTC ? Builder.CreateXor(V, C) : Builder.CreateOr(V, C);
  168. }
  169. if (Pred == ICmpInst::ICMP_NE) {
  170. // If the masked bit in V is set, set or clear the bit in the result:
  171. // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) | FC
  172. // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) ^ FC
  173. Constant *C = ConstantInt::get(SelType, FC);
  174. return ExtraBitInTC ? Builder.CreateOr(V, C) : Builder.CreateXor(V, C);
  175. }
  176. llvm_unreachable("Only expecting equality predicates");
  177. }
  178. // Make sure one of the select arms is a power-of-2.
  179. if (!TC.isPowerOf2() && !FC.isPowerOf2())
  180. return nullptr;
  181. // Determine which shift is needed to transform result of the 'and' into the
  182. // desired result.
  183. const APInt &ValC = !TC.isNullValue() ? TC : FC;
  184. unsigned ValZeros = ValC.logBase2();
  185. unsigned AndZeros = AndMask.logBase2();
  186. // Insert the 'and' instruction on the input to the truncate.
  187. if (CreateAnd)
  188. V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask));
  189. // If types don't match, we can still convert the select by introducing a zext
  190. // or a trunc of the 'and'.
  191. if (ValZeros > AndZeros) {
  192. V = Builder.CreateZExtOrTrunc(V, SelType);
  193. V = Builder.CreateShl(V, ValZeros - AndZeros);
  194. } else if (ValZeros < AndZeros) {
  195. V = Builder.CreateLShr(V, AndZeros - ValZeros);
  196. V = Builder.CreateZExtOrTrunc(V, SelType);
  197. } else {
  198. V = Builder.CreateZExtOrTrunc(V, SelType);
  199. }
  200. // Okay, now we know that everything is set up, we just don't know whether we
  201. // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
  202. bool ShouldNotVal = !TC.isNullValue();
  203. ShouldNotVal ^= Pred == ICmpInst::ICMP_NE;
  204. if (ShouldNotVal)
  205. V = Builder.CreateXor(V, ValC);
  206. return V;
  207. }
  208. /// We want to turn code that looks like this:
  209. /// %C = or %A, %B
  210. /// %D = select %cond, %C, %A
  211. /// into:
  212. /// %C = select %cond, %B, 0
  213. /// %D = or %A, %C
  214. ///
  215. /// Assuming that the specified instruction is an operand to the select, return
  216. /// a bitmask indicating which operands of this instruction are foldable if they
  217. /// equal the other incoming value of the select.
  218. static unsigned getSelectFoldableOperands(BinaryOperator *I) {
  219. switch (I->getOpcode()) {
  220. case Instruction::Add:
  221. case Instruction::Mul:
  222. case Instruction::And:
  223. case Instruction::Or:
  224. case Instruction::Xor:
  225. return 3; // Can fold through either operand.
  226. case Instruction::Sub: // Can only fold on the amount subtracted.
  227. case Instruction::Shl: // Can only fold on the shift amount.
  228. case Instruction::LShr:
  229. case Instruction::AShr:
  230. return 1;
  231. default:
  232. return 0; // Cannot fold
  233. }
  234. }
  235. /// For the same transformation as the previous function, return the identity
  236. /// constant that goes into the select.
  237. static APInt getSelectFoldableConstant(BinaryOperator *I) {
  238. switch (I->getOpcode()) {
  239. default: llvm_unreachable("This cannot happen!");
  240. case Instruction::Add:
  241. case Instruction::Sub:
  242. case Instruction::Or:
  243. case Instruction::Xor:
  244. case Instruction::Shl:
  245. case Instruction::LShr:
  246. case Instruction::AShr:
  247. return APInt::getNullValue(I->getType()->getScalarSizeInBits());
  248. case Instruction::And:
  249. return APInt::getAllOnesValue(I->getType()->getScalarSizeInBits());
  250. case Instruction::Mul:
  251. return APInt(I->getType()->getScalarSizeInBits(), 1);
  252. }
  253. }
  254. /// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
  255. Instruction *InstCombiner::foldSelectOpOp(SelectInst &SI, Instruction *TI,
  256. Instruction *FI) {
  257. // Don't break up min/max patterns. The hasOneUse checks below prevent that
  258. // for most cases, but vector min/max with bitcasts can be transformed. If the
  259. // one-use restrictions are eased for other patterns, we still don't want to
  260. // obfuscate min/max.
  261. if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
  262. match(&SI, m_SMax(m_Value(), m_Value())) ||
  263. match(&SI, m_UMin(m_Value(), m_Value())) ||
  264. match(&SI, m_UMax(m_Value(), m_Value()))))
  265. return nullptr;
  266. // If this is a cast from the same type, merge.
  267. Value *Cond = SI.getCondition();
  268. Type *CondTy = Cond->getType();
  269. if (TI->getNumOperands() == 1 && TI->isCast()) {
  270. Type *FIOpndTy = FI->getOperand(0)->getType();
  271. if (TI->getOperand(0)->getType() != FIOpndTy)
  272. return nullptr;
  273. // The select condition may be a vector. We may only change the operand
  274. // type if the vector width remains the same (and matches the condition).
  275. if (CondTy->isVectorTy()) {
  276. if (!FIOpndTy->isVectorTy())
  277. return nullptr;
  278. if (CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements())
  279. return nullptr;
  280. // TODO: If the backend knew how to deal with casts better, we could
  281. // remove this limitation. For now, there's too much potential to create
  282. // worse codegen by promoting the select ahead of size-altering casts
  283. // (PR28160).
  284. //
  285. // Note that ValueTracking's matchSelectPattern() looks through casts
  286. // without checking 'hasOneUse' when it matches min/max patterns, so this
  287. // transform may end up happening anyway.
  288. if (TI->getOpcode() != Instruction::BitCast &&
  289. (!TI->hasOneUse() || !FI->hasOneUse()))
  290. return nullptr;
  291. } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
  292. // TODO: The one-use restrictions for a scalar select could be eased if
  293. // the fold of a select in visitLoadInst() was enhanced to match a pattern
  294. // that includes a cast.
  295. return nullptr;
  296. }
  297. // Fold this by inserting a select from the input values.
  298. Value *NewSI =
  299. Builder.CreateSelect(Cond, TI->getOperand(0), FI->getOperand(0),
  300. SI.getName() + ".v", &SI);
  301. return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
  302. TI->getType());
  303. }
  304. // Cond ? -X : -Y --> -(Cond ? X : Y)
  305. Value *X, *Y;
  306. if (match(TI, m_FNeg(m_Value(X))) && match(FI, m_FNeg(m_Value(Y))) &&
  307. (TI->hasOneUse() || FI->hasOneUse())) {
  308. Value *NewSel = Builder.CreateSelect(Cond, X, Y, SI.getName() + ".v", &SI);
  309. // TODO: Remove the hack for the binop form when the unary op is optimized
  310. // properly with all IR passes.
  311. if (TI->getOpcode() != Instruction::FNeg)
  312. return BinaryOperator::CreateFNegFMF(NewSel, cast<BinaryOperator>(TI));
  313. return UnaryOperator::CreateFNeg(NewSel);
  314. }
  315. // Only handle binary operators (including two-operand getelementptr) with
  316. // one-use here. As with the cast case above, it may be possible to relax the
  317. // one-use constraint, but that needs be examined carefully since it may not
  318. // reduce the total number of instructions.
  319. if (TI->getNumOperands() != 2 || FI->getNumOperands() != 2 ||
  320. (!isa<BinaryOperator>(TI) && !isa<GetElementPtrInst>(TI)) ||
  321. !TI->hasOneUse() || !FI->hasOneUse())
  322. return nullptr;
  323. // Figure out if the operations have any operands in common.
  324. Value *MatchOp, *OtherOpT, *OtherOpF;
  325. bool MatchIsOpZero;
  326. if (TI->getOperand(0) == FI->getOperand(0)) {
  327. MatchOp = TI->getOperand(0);
  328. OtherOpT = TI->getOperand(1);
  329. OtherOpF = FI->getOperand(1);
  330. MatchIsOpZero = true;
  331. } else if (TI->getOperand(1) == FI->getOperand(1)) {
  332. MatchOp = TI->getOperand(1);
  333. OtherOpT = TI->getOperand(0);
  334. OtherOpF = FI->getOperand(0);
  335. MatchIsOpZero = false;
  336. } else if (!TI->isCommutative()) {
  337. return nullptr;
  338. } else if (TI->getOperand(0) == FI->getOperand(1)) {
  339. MatchOp = TI->getOperand(0);
  340. OtherOpT = TI->getOperand(1);
  341. OtherOpF = FI->getOperand(0);
  342. MatchIsOpZero = true;
  343. } else if (TI->getOperand(1) == FI->getOperand(0)) {
  344. MatchOp = TI->getOperand(1);
  345. OtherOpT = TI->getOperand(0);
  346. OtherOpF = FI->getOperand(1);
  347. MatchIsOpZero = true;
  348. } else {
  349. return nullptr;
  350. }
  351. // If the select condition is a vector, the operands of the original select's
  352. // operands also must be vectors. This may not be the case for getelementptr
  353. // for example.
  354. if (CondTy->isVectorTy() && (!OtherOpT->getType()->isVectorTy() ||
  355. !OtherOpF->getType()->isVectorTy()))
  356. return nullptr;
  357. // If we reach here, they do have operations in common.
  358. Value *NewSI = Builder.CreateSelect(Cond, OtherOpT, OtherOpF,
  359. SI.getName() + ".v", &SI);
  360. Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
  361. Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
  362. if (auto *BO = dyn_cast<BinaryOperator>(TI)) {
  363. BinaryOperator *NewBO = BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
  364. NewBO->copyIRFlags(TI);
  365. NewBO->andIRFlags(FI);
  366. return NewBO;
  367. }
  368. if (auto *TGEP = dyn_cast<GetElementPtrInst>(TI)) {
  369. auto *FGEP = cast<GetElementPtrInst>(FI);
  370. Type *ElementType = TGEP->getResultElementType();
  371. return TGEP->isInBounds() && FGEP->isInBounds()
  372. ? GetElementPtrInst::CreateInBounds(ElementType, Op0, {Op1})
  373. : GetElementPtrInst::Create(ElementType, Op0, {Op1});
  374. }
  375. llvm_unreachable("Expected BinaryOperator or GEP");
  376. return nullptr;
  377. }
  378. static bool isSelect01(const APInt &C1I, const APInt &C2I) {
  379. if (!C1I.isNullValue() && !C2I.isNullValue()) // One side must be zero.
  380. return false;
  381. return C1I.isOneValue() || C1I.isAllOnesValue() ||
  382. C2I.isOneValue() || C2I.isAllOnesValue();
  383. }
  384. /// Try to fold the select into one of the operands to allow further
  385. /// optimization.
  386. Instruction *InstCombiner::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
  387. Value *FalseVal) {
  388. // See the comment above GetSelectFoldableOperands for a description of the
  389. // transformation we are doing here.
  390. if (auto *TVI = dyn_cast<BinaryOperator>(TrueVal)) {
  391. if (TVI->hasOneUse() && !isa<Constant>(FalseVal)) {
  392. if (unsigned SFO = getSelectFoldableOperands(TVI)) {
  393. unsigned OpToFold = 0;
  394. if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
  395. OpToFold = 1;
  396. } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
  397. OpToFold = 2;
  398. }
  399. if (OpToFold) {
  400. APInt CI = getSelectFoldableConstant(TVI);
  401. Value *OOp = TVI->getOperand(2-OpToFold);
  402. // Avoid creating select between 2 constants unless it's selecting
  403. // between 0, 1 and -1.
  404. const APInt *OOpC;
  405. bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
  406. if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
  407. Value *C = ConstantInt::get(OOp->getType(), CI);
  408. Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C);
  409. NewSel->takeName(TVI);
  410. BinaryOperator *BO = BinaryOperator::Create(TVI->getOpcode(),
  411. FalseVal, NewSel);
  412. BO->copyIRFlags(TVI);
  413. return BO;
  414. }
  415. }
  416. }
  417. }
  418. }
  419. if (auto *FVI = dyn_cast<BinaryOperator>(FalseVal)) {
  420. if (FVI->hasOneUse() && !isa<Constant>(TrueVal)) {
  421. if (unsigned SFO = getSelectFoldableOperands(FVI)) {
  422. unsigned OpToFold = 0;
  423. if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
  424. OpToFold = 1;
  425. } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
  426. OpToFold = 2;
  427. }
  428. if (OpToFold) {
  429. APInt CI = getSelectFoldableConstant(FVI);
  430. Value *OOp = FVI->getOperand(2-OpToFold);
  431. // Avoid creating select between 2 constants unless it's selecting
  432. // between 0, 1 and -1.
  433. const APInt *OOpC;
  434. bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
  435. if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
  436. Value *C = ConstantInt::get(OOp->getType(), CI);
  437. Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp);
  438. NewSel->takeName(FVI);
  439. BinaryOperator *BO = BinaryOperator::Create(FVI->getOpcode(),
  440. TrueVal, NewSel);
  441. BO->copyIRFlags(FVI);
  442. return BO;
  443. }
  444. }
  445. }
  446. }
  447. }
  448. return nullptr;
  449. }
  450. /// We want to turn:
  451. /// (select (icmp eq (and X, Y), 0), (and (lshr X, Z), 1), 1)
  452. /// into:
  453. /// zext (icmp ne i32 (and X, (or Y, (shl 1, Z))), 0)
  454. /// Note:
  455. /// Z may be 0 if lshr is missing.
  456. /// Worst-case scenario is that we will replace 5 instructions with 5 different
  457. /// instructions, but we got rid of select.
  458. static Instruction *foldSelectICmpAndAnd(Type *SelType, const ICmpInst *Cmp,
  459. Value *TVal, Value *FVal,
  460. InstCombiner::BuilderTy &Builder) {
  461. if (!(Cmp->hasOneUse() && Cmp->getOperand(0)->hasOneUse() &&
  462. Cmp->getPredicate() == ICmpInst::ICMP_EQ &&
  463. match(Cmp->getOperand(1), m_Zero()) && match(FVal, m_One())))
  464. return nullptr;
  465. // The TrueVal has general form of: and %B, 1
  466. Value *B;
  467. if (!match(TVal, m_OneUse(m_And(m_Value(B), m_One()))))
  468. return nullptr;
  469. // Where %B may be optionally shifted: lshr %X, %Z.
  470. Value *X, *Z;
  471. const bool HasShift = match(B, m_OneUse(m_LShr(m_Value(X), m_Value(Z))));
  472. if (!HasShift)
  473. X = B;
  474. Value *Y;
  475. if (!match(Cmp->getOperand(0), m_c_And(m_Specific(X), m_Value(Y))))
  476. return nullptr;
  477. // ((X & Y) == 0) ? ((X >> Z) & 1) : 1 --> (X & (Y | (1 << Z))) != 0
  478. // ((X & Y) == 0) ? (X & 1) : 1 --> (X & (Y | 1)) != 0
  479. Constant *One = ConstantInt::get(SelType, 1);
  480. Value *MaskB = HasShift ? Builder.CreateShl(One, Z) : One;
  481. Value *FullMask = Builder.CreateOr(Y, MaskB);
  482. Value *MaskedX = Builder.CreateAnd(X, FullMask);
  483. Value *ICmpNeZero = Builder.CreateIsNotNull(MaskedX);
  484. return new ZExtInst(ICmpNeZero, SelType);
  485. }
  486. /// We want to turn:
  487. /// (select (icmp sgt x, C), lshr (X, Y), ashr (X, Y)); iff C s>= -1
  488. /// (select (icmp slt x, C), ashr (X, Y), lshr (X, Y)); iff C s>= 0
  489. /// into:
  490. /// ashr (X, Y)
  491. static Value *foldSelectICmpLshrAshr(const ICmpInst *IC, Value *TrueVal,
  492. Value *FalseVal,
  493. InstCombiner::BuilderTy &Builder) {
  494. ICmpInst::Predicate Pred = IC->getPredicate();
  495. Value *CmpLHS = IC->getOperand(0);
  496. Value *CmpRHS = IC->getOperand(1);
  497. if (!CmpRHS->getType()->isIntOrIntVectorTy())
  498. return nullptr;
  499. Value *X, *Y;
  500. unsigned Bitwidth = CmpRHS->getType()->getScalarSizeInBits();
  501. if ((Pred != ICmpInst::ICMP_SGT ||
  502. !match(CmpRHS,
  503. m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, -1)))) &&
  504. (Pred != ICmpInst::ICMP_SLT ||
  505. !match(CmpRHS,
  506. m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, 0)))))
  507. return nullptr;
  508. // Canonicalize so that ashr is in FalseVal.
  509. if (Pred == ICmpInst::ICMP_SLT)
  510. std::swap(TrueVal, FalseVal);
  511. if (match(TrueVal, m_LShr(m_Value(X), m_Value(Y))) &&
  512. match(FalseVal, m_AShr(m_Specific(X), m_Specific(Y))) &&
  513. match(CmpLHS, m_Specific(X))) {
  514. const auto *Ashr = cast<Instruction>(FalseVal);
  515. // if lshr is not exact and ashr is, this new ashr must not be exact.
  516. bool IsExact = Ashr->isExact() && cast<Instruction>(TrueVal)->isExact();
  517. return Builder.CreateAShr(X, Y, IC->getName(), IsExact);
  518. }
  519. return nullptr;
  520. }
  521. /// We want to turn:
  522. /// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
  523. /// into:
  524. /// (or (shl (and X, C1), C3), Y)
  525. /// iff:
  526. /// C1 and C2 are both powers of 2
  527. /// where:
  528. /// C3 = Log(C2) - Log(C1)
  529. ///
  530. /// This transform handles cases where:
  531. /// 1. The icmp predicate is inverted
  532. /// 2. The select operands are reversed
  533. /// 3. The magnitude of C2 and C1 are flipped
  534. static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal,
  535. Value *FalseVal,
  536. InstCombiner::BuilderTy &Builder) {
  537. // Only handle integer compares. Also, if this is a vector select, we need a
  538. // vector compare.
  539. if (!TrueVal->getType()->isIntOrIntVectorTy() ||
  540. TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy())
  541. return nullptr;
  542. Value *CmpLHS = IC->getOperand(0);
  543. Value *CmpRHS = IC->getOperand(1);
  544. Value *V;
  545. unsigned C1Log;
  546. bool IsEqualZero;
  547. bool NeedAnd = false;
  548. if (IC->isEquality()) {
  549. if (!match(CmpRHS, m_Zero()))
  550. return nullptr;
  551. const APInt *C1;
  552. if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
  553. return nullptr;
  554. V = CmpLHS;
  555. C1Log = C1->logBase2();
  556. IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ;
  557. } else if (IC->getPredicate() == ICmpInst::ICMP_SLT ||
  558. IC->getPredicate() == ICmpInst::ICMP_SGT) {
  559. // We also need to recognize (icmp slt (trunc (X)), 0) and
  560. // (icmp sgt (trunc (X)), -1).
  561. IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT;
  562. if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) ||
  563. (!IsEqualZero && !match(CmpRHS, m_Zero())))
  564. return nullptr;
  565. if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V)))))
  566. return nullptr;
  567. C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1;
  568. NeedAnd = true;
  569. } else {
  570. return nullptr;
  571. }
  572. const APInt *C2;
  573. bool OrOnTrueVal = false;
  574. bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
  575. if (!OrOnFalseVal)
  576. OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
  577. if (!OrOnFalseVal && !OrOnTrueVal)
  578. return nullptr;
  579. Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
  580. unsigned C2Log = C2->logBase2();
  581. bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal);
  582. bool NeedShift = C1Log != C2Log;
  583. bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() !=
  584. V->getType()->getScalarSizeInBits();
  585. // Make sure we don't create more instructions than we save.
  586. Value *Or = OrOnFalseVal ? FalseVal : TrueVal;
  587. if ((NeedShift + NeedXor + NeedZExtTrunc) >
  588. (IC->hasOneUse() + Or->hasOneUse()))
  589. return nullptr;
  590. if (NeedAnd) {
  591. // Insert the AND instruction on the input to the truncate.
  592. APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log);
  593. V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1));
  594. }
  595. if (C2Log > C1Log) {
  596. V = Builder.CreateZExtOrTrunc(V, Y->getType());
  597. V = Builder.CreateShl(V, C2Log - C1Log);
  598. } else if (C1Log > C2Log) {
  599. V = Builder.CreateLShr(V, C1Log - C2Log);
  600. V = Builder.CreateZExtOrTrunc(V, Y->getType());
  601. } else
  602. V = Builder.CreateZExtOrTrunc(V, Y->getType());
  603. if (NeedXor)
  604. V = Builder.CreateXor(V, *C2);
  605. return Builder.CreateOr(V, Y);
  606. }
  607. /// Transform patterns such as (a > b) ? a - b : 0 into usub.sat(a, b).
  608. /// There are 8 commuted/swapped variants of this pattern.
  609. /// TODO: Also support a - UMIN(a,b) patterns.
  610. static Value *canonicalizeSaturatedSubtract(const ICmpInst *ICI,
  611. const Value *TrueVal,
  612. const Value *FalseVal,
  613. InstCombiner::BuilderTy &Builder) {
  614. ICmpInst::Predicate Pred = ICI->getPredicate();
  615. if (!ICmpInst::isUnsigned(Pred))
  616. return nullptr;
  617. // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0
  618. if (match(TrueVal, m_Zero())) {
  619. Pred = ICmpInst::getInversePredicate(Pred);
  620. std::swap(TrueVal, FalseVal);
  621. }
  622. if (!match(FalseVal, m_Zero()))
  623. return nullptr;
  624. Value *A = ICI->getOperand(0);
  625. Value *B = ICI->getOperand(1);
  626. if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) {
  627. // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0
  628. std::swap(A, B);
  629. Pred = ICmpInst::getSwappedPredicate(Pred);
  630. }
  631. assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
  632. "Unexpected isUnsigned predicate!");
  633. // Account for swapped form of subtraction: ((a > b) ? b - a : 0).
  634. bool IsNegative = false;
  635. if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A))))
  636. IsNegative = true;
  637. else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B))))
  638. return nullptr;
  639. // If sub is used anywhere else, we wouldn't be able to eliminate it
  640. // afterwards.
  641. if (!TrueVal->hasOneUse())
  642. return nullptr;
  643. // (a > b) ? a - b : 0 -> usub.sat(a, b)
  644. // (a > b) ? b - a : 0 -> -usub.sat(a, b)
  645. Value *Result = Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, A, B);
  646. if (IsNegative)
  647. Result = Builder.CreateNeg(Result);
  648. return Result;
  649. }
  650. static Value *canonicalizeSaturatedAdd(ICmpInst *Cmp, Value *TVal, Value *FVal,
  651. InstCombiner::BuilderTy &Builder) {
  652. if (!Cmp->hasOneUse())
  653. return nullptr;
  654. // Match unsigned saturated add with constant.
  655. Value *Cmp0 = Cmp->getOperand(0);
  656. Value *Cmp1 = Cmp->getOperand(1);
  657. ICmpInst::Predicate Pred = Cmp->getPredicate();
  658. Value *X;
  659. const APInt *C, *CmpC;
  660. if (Pred == ICmpInst::ICMP_ULT &&
  661. match(TVal, m_Add(m_Value(X), m_APInt(C))) && X == Cmp0 &&
  662. match(FVal, m_AllOnes()) && match(Cmp1, m_APInt(CmpC)) && *CmpC == ~*C) {
  663. // (X u< ~C) ? (X + C) : -1 --> uadd.sat(X, C)
  664. return Builder.CreateBinaryIntrinsic(
  665. Intrinsic::uadd_sat, X, ConstantInt::get(X->getType(), *C));
  666. }
  667. // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
  668. // There are 8 commuted variants.
  669. // Canonicalize -1 (saturated result) to true value of the select. Just
  670. // swapping the compare operands is legal, because the selected value is the
  671. // same in case of equality, so we can interchange u< and u<=.
  672. if (match(FVal, m_AllOnes())) {
  673. std::swap(TVal, FVal);
  674. std::swap(Cmp0, Cmp1);
  675. }
  676. if (!match(TVal, m_AllOnes()))
  677. return nullptr;
  678. // Canonicalize predicate to 'ULT'.
  679. if (Pred == ICmpInst::ICMP_UGT) {
  680. Pred = ICmpInst::ICMP_ULT;
  681. std::swap(Cmp0, Cmp1);
  682. }
  683. if (Pred != ICmpInst::ICMP_ULT)
  684. return nullptr;
  685. // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
  686. Value *Y;
  687. if (match(Cmp0, m_Not(m_Value(X))) &&
  688. match(FVal, m_c_Add(m_Specific(X), m_Value(Y))) && Y == Cmp1) {
  689. // (~X u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
  690. // (~X u< Y) ? -1 : (Y + X) --> uadd.sat(X, Y)
  691. return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, X, Y);
  692. }
  693. // The 'not' op may be included in the sum but not the compare.
  694. X = Cmp0;
  695. Y = Cmp1;
  696. if (match(FVal, m_c_Add(m_Not(m_Specific(X)), m_Specific(Y)))) {
  697. // (X u< Y) ? -1 : (~X + Y) --> uadd.sat(~X, Y)
  698. // (X u< Y) ? -1 : (Y + ~X) --> uadd.sat(Y, ~X)
  699. BinaryOperator *BO = cast<BinaryOperator>(FVal);
  700. return Builder.CreateBinaryIntrinsic(
  701. Intrinsic::uadd_sat, BO->getOperand(0), BO->getOperand(1));
  702. }
  703. return nullptr;
  704. }
  705. /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
  706. /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
  707. ///
  708. /// For example, we can fold the following code sequence:
  709. /// \code
  710. /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
  711. /// %1 = icmp ne i32 %x, 0
  712. /// %2 = select i1 %1, i32 %0, i32 32
  713. /// \code
  714. ///
  715. /// into:
  716. /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
  717. static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
  718. InstCombiner::BuilderTy &Builder) {
  719. ICmpInst::Predicate Pred = ICI->getPredicate();
  720. Value *CmpLHS = ICI->getOperand(0);
  721. Value *CmpRHS = ICI->getOperand(1);
  722. // Check if the condition value compares a value for equality against zero.
  723. if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
  724. return nullptr;
  725. Value *Count = FalseVal;
  726. Value *ValueOnZero = TrueVal;
  727. if (Pred == ICmpInst::ICMP_NE)
  728. std::swap(Count, ValueOnZero);
  729. // Skip zero extend/truncate.
  730. Value *V = nullptr;
  731. if (match(Count, m_ZExt(m_Value(V))) ||
  732. match(Count, m_Trunc(m_Value(V))))
  733. Count = V;
  734. // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
  735. // input to the cttz/ctlz is used as LHS for the compare instruction.
  736. if (!match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) &&
  737. !match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS))))
  738. return nullptr;
  739. IntrinsicInst *II = cast<IntrinsicInst>(Count);
  740. // Check if the value propagated on zero is a constant number equal to the
  741. // sizeof in bits of 'Count'.
  742. unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
  743. if (match(ValueOnZero, m_SpecificInt(SizeOfInBits))) {
  744. // Explicitly clear the 'undef_on_zero' flag.
  745. IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
  746. NewI->setArgOperand(1, ConstantInt::getFalse(NewI->getContext()));
  747. Builder.Insert(NewI);
  748. return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
  749. }
  750. // If the ValueOnZero is not the bitwidth, we can at least make use of the
  751. // fact that the cttz/ctlz result will not be used if the input is zero, so
  752. // it's okay to relax it to undef for that case.
  753. if (II->hasOneUse() && !match(II->getArgOperand(1), m_One()))
  754. II->setArgOperand(1, ConstantInt::getTrue(II->getContext()));
  755. return nullptr;
  756. }
  757. /// Return true if we find and adjust an icmp+select pattern where the compare
  758. /// is with a constant that can be incremented or decremented to match the
  759. /// minimum or maximum idiom.
  760. static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
  761. ICmpInst::Predicate Pred = Cmp.getPredicate();
  762. Value *CmpLHS = Cmp.getOperand(0);
  763. Value *CmpRHS = Cmp.getOperand(1);
  764. Value *TrueVal = Sel.getTrueValue();
  765. Value *FalseVal = Sel.getFalseValue();
  766. // We may move or edit the compare, so make sure the select is the only user.
  767. const APInt *CmpC;
  768. if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
  769. return false;
  770. // These transforms only work for selects of integers or vector selects of
  771. // integer vectors.
  772. Type *SelTy = Sel.getType();
  773. auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
  774. if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
  775. return false;
  776. Constant *AdjustedRHS;
  777. if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
  778. AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
  779. else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
  780. AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
  781. else
  782. return false;
  783. // X > C ? X : C+1 --> X < C+1 ? C+1 : X
  784. // X < C ? X : C-1 --> X > C-1 ? C-1 : X
  785. if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
  786. (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
  787. ; // Nothing to do here. Values match without any sign/zero extension.
  788. }
  789. // Types do not match. Instead of calculating this with mixed types, promote
  790. // all to the larger type. This enables scalar evolution to analyze this
  791. // expression.
  792. else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
  793. Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
  794. // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
  795. // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
  796. // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
  797. // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
  798. if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
  799. CmpLHS = TrueVal;
  800. AdjustedRHS = SextRHS;
  801. } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
  802. SextRHS == TrueVal) {
  803. CmpLHS = FalseVal;
  804. AdjustedRHS = SextRHS;
  805. } else if (Cmp.isUnsigned()) {
  806. Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
  807. // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
  808. // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
  809. // zext + signed compare cannot be changed:
  810. // 0xff <s 0x00, but 0x00ff >s 0x0000
  811. if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
  812. CmpLHS = TrueVal;
  813. AdjustedRHS = ZextRHS;
  814. } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
  815. ZextRHS == TrueVal) {
  816. CmpLHS = FalseVal;
  817. AdjustedRHS = ZextRHS;
  818. } else {
  819. return false;
  820. }
  821. } else {
  822. return false;
  823. }
  824. } else {
  825. return false;
  826. }
  827. Pred = ICmpInst::getSwappedPredicate(Pred);
  828. CmpRHS = AdjustedRHS;
  829. std::swap(FalseVal, TrueVal);
  830. Cmp.setPredicate(Pred);
  831. Cmp.setOperand(0, CmpLHS);
  832. Cmp.setOperand(1, CmpRHS);
  833. Sel.setOperand(1, TrueVal);
  834. Sel.setOperand(2, FalseVal);
  835. Sel.swapProfMetadata();
  836. // Move the compare instruction right before the select instruction. Otherwise
  837. // the sext/zext value may be defined after the compare instruction uses it.
  838. Cmp.moveBefore(&Sel);
  839. return true;
  840. }
  841. /// If this is an integer min/max (icmp + select) with a constant operand,
  842. /// create the canonical icmp for the min/max operation and canonicalize the
  843. /// constant to the 'false' operand of the select:
  844. /// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2
  845. /// Note: if C1 != C2, this will change the icmp constant to the existing
  846. /// constant operand of the select.
  847. static Instruction *
  848. canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp,
  849. InstCombiner::BuilderTy &Builder) {
  850. if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
  851. return nullptr;
  852. // Canonicalize the compare predicate based on whether we have min or max.
  853. Value *LHS, *RHS;
  854. SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
  855. if (!SelectPatternResult::isMinOrMax(SPR.Flavor))
  856. return nullptr;
  857. // Is this already canonical?
  858. ICmpInst::Predicate CanonicalPred = getMinMaxPred(SPR.Flavor);
  859. if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS &&
  860. Cmp.getPredicate() == CanonicalPred)
  861. return nullptr;
  862. // Create the canonical compare and plug it into the select.
  863. Sel.setCondition(Builder.CreateICmp(CanonicalPred, LHS, RHS));
  864. // If the select operands did not change, we're done.
  865. if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS)
  866. return &Sel;
  867. // If we are swapping the select operands, swap the metadata too.
  868. assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS &&
  869. "Unexpected results from matchSelectPattern");
  870. Sel.swapValues();
  871. Sel.swapProfMetadata();
  872. return &Sel;
  873. }
  874. /// There are many select variants for each of ABS/NABS.
  875. /// In matchSelectPattern(), there are different compare constants, compare
  876. /// predicates/operands and select operands.
  877. /// In isKnownNegation(), there are different formats of negated operands.
  878. /// Canonicalize all these variants to 1 pattern.
  879. /// This makes CSE more likely.
  880. static Instruction *canonicalizeAbsNabs(SelectInst &Sel, ICmpInst &Cmp,
  881. InstCombiner::BuilderTy &Builder) {
  882. if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
  883. return nullptr;
  884. // Choose a sign-bit check for the compare (likely simpler for codegen).
  885. // ABS: (X <s 0) ? -X : X
  886. // NABS: (X <s 0) ? X : -X
  887. Value *LHS, *RHS;
  888. SelectPatternFlavor SPF = matchSelectPattern(&Sel, LHS, RHS).Flavor;
  889. if (SPF != SelectPatternFlavor::SPF_ABS &&
  890. SPF != SelectPatternFlavor::SPF_NABS)
  891. return nullptr;
  892. Value *TVal = Sel.getTrueValue();
  893. Value *FVal = Sel.getFalseValue();
  894. assert(isKnownNegation(TVal, FVal) &&
  895. "Unexpected result from matchSelectPattern");
  896. // The compare may use the negated abs()/nabs() operand, or it may use
  897. // negation in non-canonical form such as: sub A, B.
  898. bool CmpUsesNegatedOp = match(Cmp.getOperand(0), m_Neg(m_Specific(TVal))) ||
  899. match(Cmp.getOperand(0), m_Neg(m_Specific(FVal)));
  900. bool CmpCanonicalized = !CmpUsesNegatedOp &&
  901. match(Cmp.getOperand(1), m_ZeroInt()) &&
  902. Cmp.getPredicate() == ICmpInst::ICMP_SLT;
  903. bool RHSCanonicalized = match(RHS, m_Neg(m_Specific(LHS)));
  904. // Is this already canonical?
  905. if (CmpCanonicalized && RHSCanonicalized)
  906. return nullptr;
  907. // If RHS is used by other instructions except compare and select, don't
  908. // canonicalize it to not increase the instruction count.
  909. if (!(RHS->hasOneUse() || (RHS->hasNUses(2) && CmpUsesNegatedOp)))
  910. return nullptr;
  911. // Create the canonical compare: icmp slt LHS 0.
  912. if (!CmpCanonicalized) {
  913. Cmp.setPredicate(ICmpInst::ICMP_SLT);
  914. Cmp.setOperand(1, ConstantInt::getNullValue(Cmp.getOperand(0)->getType()));
  915. if (CmpUsesNegatedOp)
  916. Cmp.setOperand(0, LHS);
  917. }
  918. // Create the canonical RHS: RHS = sub (0, LHS).
  919. if (!RHSCanonicalized) {
  920. assert(RHS->hasOneUse() && "RHS use number is not right");
  921. RHS = Builder.CreateNeg(LHS);
  922. if (TVal == LHS) {
  923. Sel.setFalseValue(RHS);
  924. FVal = RHS;
  925. } else {
  926. Sel.setTrueValue(RHS);
  927. TVal = RHS;
  928. }
  929. }
  930. // If the select operands do not change, we're done.
  931. if (SPF == SelectPatternFlavor::SPF_NABS) {
  932. if (TVal == LHS)
  933. return &Sel;
  934. assert(FVal == LHS && "Unexpected results from matchSelectPattern");
  935. } else {
  936. if (FVal == LHS)
  937. return &Sel;
  938. assert(TVal == LHS && "Unexpected results from matchSelectPattern");
  939. }
  940. // We are swapping the select operands, so swap the metadata too.
  941. Sel.swapValues();
  942. Sel.swapProfMetadata();
  943. return &Sel;
  944. }
  945. static Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *ReplaceOp,
  946. const SimplifyQuery &Q) {
  947. // If this is a binary operator, try to simplify it with the replaced op
  948. // because we know Op and ReplaceOp are equivalant.
  949. // For example: V = X + 1, Op = X, ReplaceOp = 42
  950. // Simplifies as: add(42, 1) --> 43
  951. if (auto *BO = dyn_cast<BinaryOperator>(V)) {
  952. if (BO->getOperand(0) == Op)
  953. return SimplifyBinOp(BO->getOpcode(), ReplaceOp, BO->getOperand(1), Q);
  954. if (BO->getOperand(1) == Op)
  955. return SimplifyBinOp(BO->getOpcode(), BO->getOperand(0), ReplaceOp, Q);
  956. }
  957. return nullptr;
  958. }
  959. /// If we have a select with an equality comparison, then we know the value in
  960. /// one of the arms of the select. See if substituting this value into an arm
  961. /// and simplifying the result yields the same value as the other arm.
  962. ///
  963. /// To make this transform safe, we must drop poison-generating flags
  964. /// (nsw, etc) if we simplified to a binop because the select may be guarding
  965. /// that poison from propagating. If the existing binop already had no
  966. /// poison-generating flags, then this transform can be done by instsimplify.
  967. ///
  968. /// Consider:
  969. /// %cmp = icmp eq i32 %x, 2147483647
  970. /// %add = add nsw i32 %x, 1
  971. /// %sel = select i1 %cmp, i32 -2147483648, i32 %add
  972. ///
  973. /// We can't replace %sel with %add unless we strip away the flags.
  974. static Value *foldSelectValueEquivalence(SelectInst &Sel, ICmpInst &Cmp,
  975. const SimplifyQuery &Q) {
  976. if (!Cmp.isEquality())
  977. return nullptr;
  978. // Canonicalize the pattern to ICMP_EQ by swapping the select operands.
  979. Value *TrueVal = Sel.getTrueValue(), *FalseVal = Sel.getFalseValue();
  980. if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
  981. std::swap(TrueVal, FalseVal);
  982. // Try each equivalence substitution possibility.
  983. // We have an 'EQ' comparison, so the select's false value will propagate.
  984. // Example:
  985. // (X == 42) ? 43 : (X + 1) --> (X == 42) ? (X + 1) : (X + 1) --> X + 1
  986. // (X == 42) ? (X + 1) : 43 --> (X == 42) ? (42 + 1) : 43 --> 43
  987. Value *CmpLHS = Cmp.getOperand(0), *CmpRHS = Cmp.getOperand(1);
  988. if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q) == TrueVal ||
  989. simplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q) == TrueVal ||
  990. simplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q) == FalseVal ||
  991. simplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q) == FalseVal) {
  992. if (auto *FalseInst = dyn_cast<Instruction>(FalseVal))
  993. FalseInst->dropPoisonGeneratingFlags();
  994. return FalseVal;
  995. }
  996. return nullptr;
  997. }
  998. // See if this is a pattern like:
  999. // %old_cmp1 = icmp slt i32 %x, C2
  1000. // %old_replacement = select i1 %old_cmp1, i32 %target_low, i32 %target_high
  1001. // %old_x_offseted = add i32 %x, C1
  1002. // %old_cmp0 = icmp ult i32 %old_x_offseted, C0
  1003. // %r = select i1 %old_cmp0, i32 %x, i32 %old_replacement
  1004. // This can be rewritten as more canonical pattern:
  1005. // %new_cmp1 = icmp slt i32 %x, -C1
  1006. // %new_cmp2 = icmp sge i32 %x, C0-C1
  1007. // %new_clamped_low = select i1 %new_cmp1, i32 %target_low, i32 %x
  1008. // %r = select i1 %new_cmp2, i32 %target_high, i32 %new_clamped_low
  1009. // Iff -C1 s<= C2 s<= C0-C1
  1010. // Also ULT predicate can also be UGT iff C0 != -1 (+invert result)
  1011. // SLT predicate can also be SGT iff C2 != INT_MAX (+invert res.)
  1012. static Instruction *canonicalizeClampLike(SelectInst &Sel0, ICmpInst &Cmp0,
  1013. InstCombiner::BuilderTy &Builder) {
  1014. Value *X = Sel0.getTrueValue();
  1015. Value *Sel1 = Sel0.getFalseValue();
  1016. // First match the condition of the outermost select.
  1017. // Said condition must be one-use.
  1018. if (!Cmp0.hasOneUse())
  1019. return nullptr;
  1020. Value *Cmp00 = Cmp0.getOperand(0);
  1021. Constant *C0;
  1022. if (!match(Cmp0.getOperand(1),
  1023. m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0))))
  1024. return nullptr;
  1025. // Canonicalize Cmp0 into the form we expect.
  1026. // FIXME: we shouldn't care about lanes that are 'undef' in the end?
  1027. switch (Cmp0.getPredicate()) {
  1028. case ICmpInst::Predicate::ICMP_ULT:
  1029. break; // Great!
  1030. case ICmpInst::Predicate::ICMP_ULE:
  1031. // We'd have to increment C0 by one, and for that it must not have all-ones
  1032. // element, but then it would have been canonicalized to 'ult' before
  1033. // we get here. So we can't do anything useful with 'ule'.
  1034. return nullptr;
  1035. case ICmpInst::Predicate::ICMP_UGT:
  1036. // We want to canonicalize it to 'ult', so we'll need to increment C0,
  1037. // which again means it must not have any all-ones elements.
  1038. if (!match(C0,
  1039. m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_NE,
  1040. APInt::getAllOnesValue(
  1041. C0->getType()->getScalarSizeInBits()))))
  1042. return nullptr; // Can't do, have all-ones element[s].
  1043. C0 = AddOne(C0);
  1044. std::swap(X, Sel1);
  1045. break;
  1046. case ICmpInst::Predicate::ICMP_UGE:
  1047. // The only way we'd get this predicate if this `icmp` has extra uses,
  1048. // but then we won't be able to do this fold.
  1049. return nullptr;
  1050. default:
  1051. return nullptr; // Unknown predicate.
  1052. }
  1053. // Now that we've canonicalized the ICmp, we know the X we expect;
  1054. // the select in other hand should be one-use.
  1055. if (!Sel1->hasOneUse())
  1056. return nullptr;
  1057. // We now can finish matching the condition of the outermost select:
  1058. // it should either be the X itself, or an addition of some constant to X.
  1059. Constant *C1;
  1060. if (Cmp00 == X)
  1061. C1 = ConstantInt::getNullValue(Sel0.getType());
  1062. else if (!match(Cmp00,
  1063. m_Add(m_Specific(X),
  1064. m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C1)))))
  1065. return nullptr;
  1066. Value *Cmp1;
  1067. ICmpInst::Predicate Pred1;
  1068. Constant *C2;
  1069. Value *ReplacementLow, *ReplacementHigh;
  1070. if (!match(Sel1, m_Select(m_Value(Cmp1), m_Value(ReplacementLow),
  1071. m_Value(ReplacementHigh))) ||
  1072. !match(Cmp1,
  1073. m_ICmp(Pred1, m_Specific(X),
  1074. m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C2)))))
  1075. return nullptr;
  1076. if (!Cmp1->hasOneUse() && (Cmp00 == X || !Cmp00->hasOneUse()))
  1077. return nullptr; // Not enough one-use instructions for the fold.
  1078. // FIXME: this restriction could be relaxed if Cmp1 can be reused as one of
  1079. // two comparisons we'll need to build.
  1080. // Canonicalize Cmp1 into the form we expect.
  1081. // FIXME: we shouldn't care about lanes that are 'undef' in the end?
  1082. switch (Pred1) {
  1083. case ICmpInst::Predicate::ICMP_SLT:
  1084. break;
  1085. case ICmpInst::Predicate::ICMP_SLE:
  1086. // We'd have to increment C2 by one, and for that it must not have signed
  1087. // max element, but then it would have been canonicalized to 'slt' before
  1088. // we get here. So we can't do anything useful with 'sle'.
  1089. return nullptr;
  1090. case ICmpInst::Predicate::ICMP_SGT:
  1091. // We want to canonicalize it to 'slt', so we'll need to increment C2,
  1092. // which again means it must not have any signed max elements.
  1093. if (!match(C2,
  1094. m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_NE,
  1095. APInt::getSignedMaxValue(
  1096. C2->getType()->getScalarSizeInBits()))))
  1097. return nullptr; // Can't do, have signed max element[s].
  1098. C2 = AddOne(C2);
  1099. LLVM_FALLTHROUGH;
  1100. case ICmpInst::Predicate::ICMP_SGE:
  1101. // Also non-canonical, but here we don't need to change C2,
  1102. // so we don't have any restrictions on C2, so we can just handle it.
  1103. std::swap(ReplacementLow, ReplacementHigh);
  1104. break;
  1105. default:
  1106. return nullptr; // Unknown predicate.
  1107. }
  1108. // The thresholds of this clamp-like pattern.
  1109. auto *ThresholdLowIncl = ConstantExpr::getNeg(C1);
  1110. auto *ThresholdHighExcl = ConstantExpr::getSub(C0, C1);
  1111. // The fold has a precondition 1: C2 s>= ThresholdLow
  1112. auto *Precond1 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SGE, C2,
  1113. ThresholdLowIncl);
  1114. if (!match(Precond1, m_One()))
  1115. return nullptr;
  1116. // The fold has a precondition 2: C2 s<= ThresholdHigh
  1117. auto *Precond2 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SLE, C2,
  1118. ThresholdHighExcl);
  1119. if (!match(Precond2, m_One()))
  1120. return nullptr;
  1121. // All good, finally emit the new pattern.
  1122. Value *ShouldReplaceLow = Builder.CreateICmpSLT(X, ThresholdLowIncl);
  1123. Value *ShouldReplaceHigh = Builder.CreateICmpSGE(X, ThresholdHighExcl);
  1124. Value *MaybeReplacedLow =
  1125. Builder.CreateSelect(ShouldReplaceLow, ReplacementLow, X);
  1126. Instruction *MaybeReplacedHigh =
  1127. SelectInst::Create(ShouldReplaceHigh, ReplacementHigh, MaybeReplacedLow);
  1128. return MaybeReplacedHigh;
  1129. }
  1130. // If we have
  1131. // %cmp = icmp [canonical predicate] i32 %x, C0
  1132. // %r = select i1 %cmp, i32 %y, i32 C1
  1133. // Where C0 != C1 and %x may be different from %y, see if the constant that we
  1134. // will have if we flip the strictness of the predicate (i.e. without changing
  1135. // the result) is identical to the C1 in select. If it matches we can change
  1136. // original comparison to one with swapped predicate, reuse the constant,
  1137. // and swap the hands of select.
  1138. static Instruction *
  1139. tryToReuseConstantFromSelectInComparison(SelectInst &Sel, ICmpInst &Cmp,
  1140. InstCombiner::BuilderTy &Builder) {
  1141. ICmpInst::Predicate Pred;
  1142. Value *X;
  1143. Constant *C0;
  1144. if (!match(&Cmp, m_OneUse(m_ICmp(
  1145. Pred, m_Value(X),
  1146. m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0))))))
  1147. return nullptr;
  1148. // If comparison predicate is non-relational, we won't be able to do anything.
  1149. if (ICmpInst::isEquality(Pred))
  1150. return nullptr;
  1151. // If comparison predicate is non-canonical, then we certainly won't be able
  1152. // to make it canonical; canonicalizeCmpWithConstant() already tried.
  1153. if (!isCanonicalPredicate(Pred))
  1154. return nullptr;
  1155. // If the [input] type of comparison and select type are different, lets abort
  1156. // for now. We could try to compare constants with trunc/[zs]ext though.
  1157. if (C0->getType() != Sel.getType())
  1158. return nullptr;
  1159. // FIXME: are there any magic icmp predicate+constant pairs we must not touch?
  1160. Value *SelVal0, *SelVal1; // We do not care which one is from where.
  1161. match(&Sel, m_Select(m_Value(), m_Value(SelVal0), m_Value(SelVal1)));
  1162. // At least one of these values we are selecting between must be a constant
  1163. // else we'll never succeed.
  1164. if (!match(SelVal0, m_AnyIntegralConstant()) &&
  1165. !match(SelVal1, m_AnyIntegralConstant()))
  1166. return nullptr;
  1167. // Does this constant C match any of the `select` values?
  1168. auto MatchesSelectValue = [SelVal0, SelVal1](Constant *C) {
  1169. return C->isElementWiseEqual(SelVal0) || C->isElementWiseEqual(SelVal1);
  1170. };
  1171. // If C0 *already* matches true/false value of select, we are done.
  1172. if (MatchesSelectValue(C0))
  1173. return nullptr;
  1174. // Check the constant we'd have with flipped-strictness predicate.
  1175. auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, C0);
  1176. if (!FlippedStrictness)
  1177. return nullptr;
  1178. // If said constant doesn't match either, then there is no hope,
  1179. if (!MatchesSelectValue(FlippedStrictness->second))
  1180. return nullptr;
  1181. // It matched! Lets insert the new comparison just before select.
  1182. InstCombiner::BuilderTy::InsertPointGuard Guard(Builder);
  1183. Builder.SetInsertPoint(&Sel);
  1184. Pred = ICmpInst::getSwappedPredicate(Pred); // Yes, swapped.
  1185. Value *NewCmp = Builder.CreateICmp(Pred, X, FlippedStrictness->second,
  1186. Cmp.getName() + ".inv");
  1187. Sel.setCondition(NewCmp);
  1188. Sel.swapValues();
  1189. Sel.swapProfMetadata();
  1190. return &Sel;
  1191. }
  1192. /// Visit a SelectInst that has an ICmpInst as its first operand.
  1193. Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI,
  1194. ICmpInst *ICI) {
  1195. if (Value *V = foldSelectValueEquivalence(SI, *ICI, SQ))
  1196. return replaceInstUsesWith(SI, V);
  1197. if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, Builder))
  1198. return NewSel;
  1199. if (Instruction *NewAbs = canonicalizeAbsNabs(SI, *ICI, Builder))
  1200. return NewAbs;
  1201. if (Instruction *NewAbs = canonicalizeClampLike(SI, *ICI, Builder))
  1202. return NewAbs;
  1203. if (Instruction *NewSel =
  1204. tryToReuseConstantFromSelectInComparison(SI, *ICI, Builder))
  1205. return NewSel;
  1206. bool Changed = adjustMinMax(SI, *ICI);
  1207. if (Value *V = foldSelectICmpAnd(SI, ICI, Builder))
  1208. return replaceInstUsesWith(SI, V);
  1209. // NOTE: if we wanted to, this is where to detect integer MIN/MAX
  1210. Value *TrueVal = SI.getTrueValue();
  1211. Value *FalseVal = SI.getFalseValue();
  1212. ICmpInst::Predicate Pred = ICI->getPredicate();
  1213. Value *CmpLHS = ICI->getOperand(0);
  1214. Value *CmpRHS = ICI->getOperand(1);
  1215. if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
  1216. if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
  1217. // Transform (X == C) ? X : Y -> (X == C) ? C : Y
  1218. SI.setOperand(1, CmpRHS);
  1219. Changed = true;
  1220. } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
  1221. // Transform (X != C) ? Y : X -> (X != C) ? Y : C
  1222. SI.setOperand(2, CmpRHS);
  1223. Changed = true;
  1224. }
  1225. }
  1226. // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
  1227. // decomposeBitTestICmp() might help.
  1228. {
  1229. unsigned BitWidth =
  1230. DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
  1231. APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
  1232. Value *X;
  1233. const APInt *Y, *C;
  1234. bool TrueWhenUnset;
  1235. bool IsBitTest = false;
  1236. if (ICmpInst::isEquality(Pred) &&
  1237. match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
  1238. match(CmpRHS, m_Zero())) {
  1239. IsBitTest = true;
  1240. TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
  1241. } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
  1242. X = CmpLHS;
  1243. Y = &MinSignedValue;
  1244. IsBitTest = true;
  1245. TrueWhenUnset = false;
  1246. } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
  1247. X = CmpLHS;
  1248. Y = &MinSignedValue;
  1249. IsBitTest = true;
  1250. TrueWhenUnset = true;
  1251. }
  1252. if (IsBitTest) {
  1253. Value *V = nullptr;
  1254. // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
  1255. if (TrueWhenUnset && TrueVal == X &&
  1256. match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
  1257. V = Builder.CreateAnd(X, ~(*Y));
  1258. // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
  1259. else if (!TrueWhenUnset && FalseVal == X &&
  1260. match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
  1261. V = Builder.CreateAnd(X, ~(*Y));
  1262. // (X & Y) == 0 ? X ^ Y : X --> X | Y
  1263. else if (TrueWhenUnset && FalseVal == X &&
  1264. match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
  1265. V = Builder.CreateOr(X, *Y);
  1266. // (X & Y) != 0 ? X : X ^ Y --> X | Y
  1267. else if (!TrueWhenUnset && TrueVal == X &&
  1268. match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
  1269. V = Builder.CreateOr(X, *Y);
  1270. if (V)
  1271. return replaceInstUsesWith(SI, V);
  1272. }
  1273. }
  1274. if (Instruction *V =
  1275. foldSelectICmpAndAnd(SI.getType(), ICI, TrueVal, FalseVal, Builder))
  1276. return V;
  1277. if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder))
  1278. return replaceInstUsesWith(SI, V);
  1279. if (Value *V = foldSelectICmpLshrAshr(ICI, TrueVal, FalseVal, Builder))
  1280. return replaceInstUsesWith(SI, V);
  1281. if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
  1282. return replaceInstUsesWith(SI, V);
  1283. if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder))
  1284. return replaceInstUsesWith(SI, V);
  1285. if (Value *V = canonicalizeSaturatedAdd(ICI, TrueVal, FalseVal, Builder))
  1286. return replaceInstUsesWith(SI, V);
  1287. return Changed ? &SI : nullptr;
  1288. }
  1289. /// SI is a select whose condition is a PHI node (but the two may be in
  1290. /// different blocks). See if the true/false values (V) are live in all of the
  1291. /// predecessor blocks of the PHI. For example, cases like this can't be mapped:
  1292. ///
  1293. /// X = phi [ C1, BB1], [C2, BB2]
  1294. /// Y = add
  1295. /// Z = select X, Y, 0
  1296. ///
  1297. /// because Y is not live in BB1/BB2.
  1298. static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
  1299. const SelectInst &SI) {
  1300. // If the value is a non-instruction value like a constant or argument, it
  1301. // can always be mapped.
  1302. const Instruction *I = dyn_cast<Instruction>(V);
  1303. if (!I) return true;
  1304. // If V is a PHI node defined in the same block as the condition PHI, we can
  1305. // map the arguments.
  1306. const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
  1307. if (const PHINode *VP = dyn_cast<PHINode>(I))
  1308. if (VP->getParent() == CondPHI->getParent())
  1309. return true;
  1310. // Otherwise, if the PHI and select are defined in the same block and if V is
  1311. // defined in a different block, then we can transform it.
  1312. if (SI.getParent() == CondPHI->getParent() &&
  1313. I->getParent() != CondPHI->getParent())
  1314. return true;
  1315. // Otherwise we have a 'hard' case and we can't tell without doing more
  1316. // detailed dominator based analysis, punt.
  1317. return false;
  1318. }
  1319. /// We have an SPF (e.g. a min or max) of an SPF of the form:
  1320. /// SPF2(SPF1(A, B), C)
  1321. Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner,
  1322. SelectPatternFlavor SPF1,
  1323. Value *A, Value *B,
  1324. Instruction &Outer,
  1325. SelectPatternFlavor SPF2, Value *C) {
  1326. if (Outer.getType() != Inner->getType())
  1327. return nullptr;
  1328. if (C == A || C == B) {
  1329. // MAX(MAX(A, B), B) -> MAX(A, B)
  1330. // MIN(MIN(a, b), a) -> MIN(a, b)
  1331. // TODO: This could be done in instsimplify.
  1332. if (SPF1 == SPF2 && SelectPatternResult::isMinOrMax(SPF1))
  1333. return replaceInstUsesWith(Outer, Inner);
  1334. // MAX(MIN(a, b), a) -> a
  1335. // MIN(MAX(a, b), a) -> a
  1336. // TODO: This could be done in instsimplify.
  1337. if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
  1338. (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
  1339. (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
  1340. (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
  1341. return replaceInstUsesWith(Outer, C);
  1342. }
  1343. if (SPF1 == SPF2) {
  1344. const APInt *CB, *CC;
  1345. if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
  1346. // MIN(MIN(A, 23), 97) -> MIN(A, 23)
  1347. // MAX(MAX(A, 97), 23) -> MAX(A, 97)
  1348. // TODO: This could be done in instsimplify.
  1349. if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
  1350. (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
  1351. (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
  1352. (SPF1 == SPF_SMAX && CB->sge(*CC)))
  1353. return replaceInstUsesWith(Outer, Inner);
  1354. // MIN(MIN(A, 97), 23) -> MIN(A, 23)
  1355. // MAX(MAX(A, 23), 97) -> MAX(A, 97)
  1356. if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
  1357. (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
  1358. (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
  1359. (SPF1 == SPF_SMAX && CB->slt(*CC))) {
  1360. Outer.replaceUsesOfWith(Inner, A);
  1361. return &Outer;
  1362. }
  1363. }
  1364. }
  1365. // max(max(A, B), min(A, B)) --> max(A, B)
  1366. // min(min(A, B), max(A, B)) --> min(A, B)
  1367. // TODO: This could be done in instsimplify.
  1368. if (SPF1 == SPF2 &&
  1369. ((SPF1 == SPF_UMIN && match(C, m_c_UMax(m_Specific(A), m_Specific(B)))) ||
  1370. (SPF1 == SPF_SMIN && match(C, m_c_SMax(m_Specific(A), m_Specific(B)))) ||
  1371. (SPF1 == SPF_UMAX && match(C, m_c_UMin(m_Specific(A), m_Specific(B)))) ||
  1372. (SPF1 == SPF_SMAX && match(C, m_c_SMin(m_Specific(A), m_Specific(B))))))
  1373. return replaceInstUsesWith(Outer, Inner);
  1374. // ABS(ABS(X)) -> ABS(X)
  1375. // NABS(NABS(X)) -> NABS(X)
  1376. // TODO: This could be done in instsimplify.
  1377. if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
  1378. return replaceInstUsesWith(Outer, Inner);
  1379. }
  1380. // ABS(NABS(X)) -> ABS(X)
  1381. // NABS(ABS(X)) -> NABS(X)
  1382. if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
  1383. (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
  1384. SelectInst *SI = cast<SelectInst>(Inner);
  1385. Value *NewSI =
  1386. Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(),
  1387. SI->getTrueValue(), SI->getName(), SI);
  1388. return replaceInstUsesWith(Outer, NewSI);
  1389. }
  1390. auto IsFreeOrProfitableToInvert =
  1391. [&](Value *V, Value *&NotV, bool &ElidesXor) {
  1392. if (match(V, m_Not(m_Value(NotV)))) {
  1393. // If V has at most 2 uses then we can get rid of the xor operation
  1394. // entirely.
  1395. ElidesXor |= !V->hasNUsesOrMore(3);
  1396. return true;
  1397. }
  1398. if (isFreeToInvert(V, !V->hasNUsesOrMore(3))) {
  1399. NotV = nullptr;
  1400. return true;
  1401. }
  1402. return false;
  1403. };
  1404. Value *NotA, *NotB, *NotC;
  1405. bool ElidesXor = false;
  1406. // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
  1407. // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
  1408. // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
  1409. // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
  1410. //
  1411. // This transform is performance neutral if we can elide at least one xor from
  1412. // the set of three operands, since we'll be tacking on an xor at the very
  1413. // end.
  1414. if (SelectPatternResult::isMinOrMax(SPF1) &&
  1415. SelectPatternResult::isMinOrMax(SPF2) &&
  1416. IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
  1417. IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
  1418. IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
  1419. if (!NotA)
  1420. NotA = Builder.CreateNot(A);
  1421. if (!NotB)
  1422. NotB = Builder.CreateNot(B);
  1423. if (!NotC)
  1424. NotC = Builder.CreateNot(C);
  1425. Value *NewInner = createMinMax(Builder, getInverseMinMaxFlavor(SPF1), NotA,
  1426. NotB);
  1427. Value *NewOuter = Builder.CreateNot(
  1428. createMinMax(Builder, getInverseMinMaxFlavor(SPF2), NewInner, NotC));
  1429. return replaceInstUsesWith(Outer, NewOuter);
  1430. }
  1431. return nullptr;
  1432. }
  1433. /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
  1434. /// This is even legal for FP.
  1435. static Instruction *foldAddSubSelect(SelectInst &SI,
  1436. InstCombiner::BuilderTy &Builder) {
  1437. Value *CondVal = SI.getCondition();
  1438. Value *TrueVal = SI.getTrueValue();
  1439. Value *FalseVal = SI.getFalseValue();
  1440. auto *TI = dyn_cast<Instruction>(TrueVal);
  1441. auto *FI = dyn_cast<Instruction>(FalseVal);
  1442. if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
  1443. return nullptr;
  1444. Instruction *AddOp = nullptr, *SubOp = nullptr;
  1445. if ((TI->getOpcode() == Instruction::Sub &&
  1446. FI->getOpcode() == Instruction::Add) ||
  1447. (TI->getOpcode() == Instruction::FSub &&
  1448. FI->getOpcode() == Instruction::FAdd)) {
  1449. AddOp = FI;
  1450. SubOp = TI;
  1451. } else if ((FI->getOpcode() == Instruction::Sub &&
  1452. TI->getOpcode() == Instruction::Add) ||
  1453. (FI->getOpcode() == Instruction::FSub &&
  1454. TI->getOpcode() == Instruction::FAdd)) {
  1455. AddOp = TI;
  1456. SubOp = FI;
  1457. }
  1458. if (AddOp) {
  1459. Value *OtherAddOp = nullptr;
  1460. if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
  1461. OtherAddOp = AddOp->getOperand(1);
  1462. } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
  1463. OtherAddOp = AddOp->getOperand(0);
  1464. }
  1465. if (OtherAddOp) {
  1466. // So at this point we know we have (Y -> OtherAddOp):
  1467. // select C, (add X, Y), (sub X, Z)
  1468. Value *NegVal; // Compute -Z
  1469. if (SI.getType()->isFPOrFPVectorTy()) {
  1470. NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
  1471. if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
  1472. FastMathFlags Flags = AddOp->getFastMathFlags();
  1473. Flags &= SubOp->getFastMathFlags();
  1474. NegInst->setFastMathFlags(Flags);
  1475. }
  1476. } else {
  1477. NegVal = Builder.CreateNeg(SubOp->getOperand(1));
  1478. }
  1479. Value *NewTrueOp = OtherAddOp;
  1480. Value *NewFalseOp = NegVal;
  1481. if (AddOp != TI)
  1482. std::swap(NewTrueOp, NewFalseOp);
  1483. Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
  1484. SI.getName() + ".p", &SI);
  1485. if (SI.getType()->isFPOrFPVectorTy()) {
  1486. Instruction *RI =
  1487. BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
  1488. FastMathFlags Flags = AddOp->getFastMathFlags();
  1489. Flags &= SubOp->getFastMathFlags();
  1490. RI->setFastMathFlags(Flags);
  1491. return RI;
  1492. } else
  1493. return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
  1494. }
  1495. }
  1496. return nullptr;
  1497. }
  1498. Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) {
  1499. Constant *C;
  1500. if (!match(Sel.getTrueValue(), m_Constant(C)) &&
  1501. !match(Sel.getFalseValue(), m_Constant(C)))
  1502. return nullptr;
  1503. Instruction *ExtInst;
  1504. if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
  1505. !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
  1506. return nullptr;
  1507. auto ExtOpcode = ExtInst->getOpcode();
  1508. if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
  1509. return nullptr;
  1510. // If we are extending from a boolean type or if we can create a select that
  1511. // has the same size operands as its condition, try to narrow the select.
  1512. Value *X = ExtInst->getOperand(0);
  1513. Type *SmallType = X->getType();
  1514. Value *Cond = Sel.getCondition();
  1515. auto *Cmp = dyn_cast<CmpInst>(Cond);
  1516. if (!SmallType->isIntOrIntVectorTy(1) &&
  1517. (!Cmp || Cmp->getOperand(0)->getType() != SmallType))
  1518. return nullptr;
  1519. // If the constant is the same after truncation to the smaller type and
  1520. // extension to the original type, we can narrow the select.
  1521. Type *SelType = Sel.getType();
  1522. Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
  1523. Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
  1524. if (ExtC == C) {
  1525. Value *TruncCVal = cast<Value>(TruncC);
  1526. if (ExtInst == Sel.getFalseValue())
  1527. std::swap(X, TruncCVal);
  1528. // select Cond, (ext X), C --> ext(select Cond, X, C')
  1529. // select Cond, C, (ext X) --> ext(select Cond, C', X)
  1530. Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
  1531. return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
  1532. }
  1533. // If one arm of the select is the extend of the condition, replace that arm
  1534. // with the extension of the appropriate known bool value.
  1535. if (Cond == X) {
  1536. if (ExtInst == Sel.getTrueValue()) {
  1537. // select X, (sext X), C --> select X, -1, C
  1538. // select X, (zext X), C --> select X, 1, C
  1539. Constant *One = ConstantInt::getTrue(SmallType);
  1540. Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
  1541. return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
  1542. } else {
  1543. // select X, C, (sext X) --> select X, C, 0
  1544. // select X, C, (zext X) --> select X, C, 0
  1545. Constant *Zero = ConstantInt::getNullValue(SelType);
  1546. return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
  1547. }
  1548. }
  1549. return nullptr;
  1550. }
  1551. /// Try to transform a vector select with a constant condition vector into a
  1552. /// shuffle for easier combining with other shuffles and insert/extract.
  1553. static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
  1554. Value *CondVal = SI.getCondition();
  1555. Constant *CondC;
  1556. if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
  1557. return nullptr;
  1558. unsigned NumElts = CondVal->getType()->getVectorNumElements();
  1559. SmallVector<Constant *, 16> Mask;
  1560. Mask.reserve(NumElts);
  1561. Type *Int32Ty = Type::getInt32Ty(CondVal->getContext());
  1562. for (unsigned i = 0; i != NumElts; ++i) {
  1563. Constant *Elt = CondC->getAggregateElement(i);
  1564. if (!Elt)
  1565. return nullptr;
  1566. if (Elt->isOneValue()) {
  1567. // If the select condition element is true, choose from the 1st vector.
  1568. Mask.push_back(ConstantInt::get(Int32Ty, i));
  1569. } else if (Elt->isNullValue()) {
  1570. // If the select condition element is false, choose from the 2nd vector.
  1571. Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts));
  1572. } else if (isa<UndefValue>(Elt)) {
  1573. // Undef in a select condition (choose one of the operands) does not mean
  1574. // the same thing as undef in a shuffle mask (any value is acceptable), so
  1575. // give up.
  1576. return nullptr;
  1577. } else {
  1578. // Bail out on a constant expression.
  1579. return nullptr;
  1580. }
  1581. }
  1582. return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(),
  1583. ConstantVector::get(Mask));
  1584. }
  1585. /// If we have a select of vectors with a scalar condition, try to convert that
  1586. /// to a vector select by splatting the condition. A splat may get folded with
  1587. /// other operations in IR and having all operands of a select be vector types
  1588. /// is likely better for vector codegen.
  1589. static Instruction *canonicalizeScalarSelectOfVecs(
  1590. SelectInst &Sel, InstCombiner::BuilderTy &Builder) {
  1591. Type *Ty = Sel.getType();
  1592. if (!Ty->isVectorTy())
  1593. return nullptr;
  1594. // We can replace a single-use extract with constant index.
  1595. Value *Cond = Sel.getCondition();
  1596. if (!match(Cond, m_OneUse(m_ExtractElement(m_Value(), m_ConstantInt()))))
  1597. return nullptr;
  1598. // select (extelt V, Index), T, F --> select (splat V, Index), T, F
  1599. // Splatting the extracted condition reduces code (we could directly create a
  1600. // splat shuffle of the source vector to eliminate the intermediate step).
  1601. unsigned NumElts = Ty->getVectorNumElements();
  1602. Value *SplatCond = Builder.CreateVectorSplat(NumElts, Cond);
  1603. Sel.setCondition(SplatCond);
  1604. return &Sel;
  1605. }
  1606. /// Reuse bitcasted operands between a compare and select:
  1607. /// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
  1608. /// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
  1609. static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
  1610. InstCombiner::BuilderTy &Builder) {
  1611. Value *Cond = Sel.getCondition();
  1612. Value *TVal = Sel.getTrueValue();
  1613. Value *FVal = Sel.getFalseValue();
  1614. CmpInst::Predicate Pred;
  1615. Value *A, *B;
  1616. if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
  1617. return nullptr;
  1618. // The select condition is a compare instruction. If the select's true/false
  1619. // values are already the same as the compare operands, there's nothing to do.
  1620. if (TVal == A || TVal == B || FVal == A || FVal == B)
  1621. return nullptr;
  1622. Value *C, *D;
  1623. if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
  1624. return nullptr;
  1625. // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
  1626. Value *TSrc, *FSrc;
  1627. if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
  1628. !match(FVal, m_BitCast(m_Value(FSrc))))
  1629. return nullptr;
  1630. // If the select true/false values are *different bitcasts* of the same source
  1631. // operands, make the select operands the same as the compare operands and
  1632. // cast the result. This is the canonical select form for min/max.
  1633. Value *NewSel;
  1634. if (TSrc == C && FSrc == D) {
  1635. // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
  1636. // bitcast (select (cmp A, B), A, B)
  1637. NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
  1638. } else if (TSrc == D && FSrc == C) {
  1639. // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
  1640. // bitcast (select (cmp A, B), B, A)
  1641. NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
  1642. } else {
  1643. return nullptr;
  1644. }
  1645. return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
  1646. }
  1647. /// Try to eliminate select instructions that test the returned flag of cmpxchg
  1648. /// instructions.
  1649. ///
  1650. /// If a select instruction tests the returned flag of a cmpxchg instruction and
  1651. /// selects between the returned value of the cmpxchg instruction its compare
  1652. /// operand, the result of the select will always be equal to its false value.
  1653. /// For example:
  1654. ///
  1655. /// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
  1656. /// %1 = extractvalue { i64, i1 } %0, 1
  1657. /// %2 = extractvalue { i64, i1 } %0, 0
  1658. /// %3 = select i1 %1, i64 %compare, i64 %2
  1659. /// ret i64 %3
  1660. ///
  1661. /// The returned value of the cmpxchg instruction (%2) is the original value
  1662. /// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2
  1663. /// must have been equal to %compare. Thus, the result of the select is always
  1664. /// equal to %2, and the code can be simplified to:
  1665. ///
  1666. /// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
  1667. /// %1 = extractvalue { i64, i1 } %0, 0
  1668. /// ret i64 %1
  1669. ///
  1670. static Instruction *foldSelectCmpXchg(SelectInst &SI) {
  1671. // A helper that determines if V is an extractvalue instruction whose
  1672. // aggregate operand is a cmpxchg instruction and whose single index is equal
  1673. // to I. If such conditions are true, the helper returns the cmpxchg
  1674. // instruction; otherwise, a nullptr is returned.
  1675. auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * {
  1676. auto *Extract = dyn_cast<ExtractValueInst>(V);
  1677. if (!Extract)
  1678. return nullptr;
  1679. if (Extract->getIndices()[0] != I)
  1680. return nullptr;
  1681. return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand());
  1682. };
  1683. // If the select has a single user, and this user is a select instruction that
  1684. // we can simplify, skip the cmpxchg simplification for now.
  1685. if (SI.hasOneUse())
  1686. if (auto *Select = dyn_cast<SelectInst>(SI.user_back()))
  1687. if (Select->getCondition() == SI.getCondition())
  1688. if (Select->getFalseValue() == SI.getTrueValue() ||
  1689. Select->getTrueValue() == SI.getFalseValue())
  1690. return nullptr;
  1691. // Ensure the select condition is the returned flag of a cmpxchg instruction.
  1692. auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1);
  1693. if (!CmpXchg)
  1694. return nullptr;
  1695. // Check the true value case: The true value of the select is the returned
  1696. // value of the same cmpxchg used by the condition, and the false value is the
  1697. // cmpxchg instruction's compare operand.
  1698. if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0))
  1699. if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue()) {
  1700. SI.setTrueValue(SI.getFalseValue());
  1701. return &SI;
  1702. }
  1703. // Check the false value case: The false value of the select is the returned
  1704. // value of the same cmpxchg used by the condition, and the true value is the
  1705. // cmpxchg instruction's compare operand.
  1706. if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0))
  1707. if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue()) {
  1708. SI.setTrueValue(SI.getFalseValue());
  1709. return &SI;
  1710. }
  1711. return nullptr;
  1712. }
  1713. static Instruction *moveAddAfterMinMax(SelectPatternFlavor SPF, Value *X,
  1714. Value *Y,
  1715. InstCombiner::BuilderTy &Builder) {
  1716. assert(SelectPatternResult::isMinOrMax(SPF) && "Expected min/max pattern");
  1717. bool IsUnsigned = SPF == SelectPatternFlavor::SPF_UMIN ||
  1718. SPF == SelectPatternFlavor::SPF_UMAX;
  1719. // TODO: If InstSimplify could fold all cases where C2 <= C1, we could change
  1720. // the constant value check to an assert.
  1721. Value *A;
  1722. const APInt *C1, *C2;
  1723. if (IsUnsigned && match(X, m_NUWAdd(m_Value(A), m_APInt(C1))) &&
  1724. match(Y, m_APInt(C2)) && C2->uge(*C1) && X->hasNUses(2)) {
  1725. // umin (add nuw A, C1), C2 --> add nuw (umin A, C2 - C1), C1
  1726. // umax (add nuw A, C1), C2 --> add nuw (umax A, C2 - C1), C1
  1727. Value *NewMinMax = createMinMax(Builder, SPF, A,
  1728. ConstantInt::get(X->getType(), *C2 - *C1));
  1729. return BinaryOperator::CreateNUW(BinaryOperator::Add, NewMinMax,
  1730. ConstantInt::get(X->getType(), *C1));
  1731. }
  1732. if (!IsUnsigned && match(X, m_NSWAdd(m_Value(A), m_APInt(C1))) &&
  1733. match(Y, m_APInt(C2)) && X->hasNUses(2)) {
  1734. bool Overflow;
  1735. APInt Diff = C2->ssub_ov(*C1, Overflow);
  1736. if (!Overflow) {
  1737. // smin (add nsw A, C1), C2 --> add nsw (smin A, C2 - C1), C1
  1738. // smax (add nsw A, C1), C2 --> add nsw (smax A, C2 - C1), C1
  1739. Value *NewMinMax = createMinMax(Builder, SPF, A,
  1740. ConstantInt::get(X->getType(), Diff));
  1741. return BinaryOperator::CreateNSW(BinaryOperator::Add, NewMinMax,
  1742. ConstantInt::get(X->getType(), *C1));
  1743. }
  1744. }
  1745. return nullptr;
  1746. }
  1747. /// Reduce a sequence of min/max with a common operand.
  1748. static Instruction *factorizeMinMaxTree(SelectPatternFlavor SPF, Value *LHS,
  1749. Value *RHS,
  1750. InstCombiner::BuilderTy &Builder) {
  1751. assert(SelectPatternResult::isMinOrMax(SPF) && "Expected a min/max");
  1752. // TODO: Allow FP min/max with nnan/nsz.
  1753. if (!LHS->getType()->isIntOrIntVectorTy())
  1754. return nullptr;
  1755. // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
  1756. Value *A, *B, *C, *D;
  1757. SelectPatternResult L = matchSelectPattern(LHS, A, B);
  1758. SelectPatternResult R = matchSelectPattern(RHS, C, D);
  1759. if (SPF != L.Flavor || L.Flavor != R.Flavor)
  1760. return nullptr;
  1761. // Look for a common operand. The use checks are different than usual because
  1762. // a min/max pattern typically has 2 uses of each op: 1 by the cmp and 1 by
  1763. // the select.
  1764. Value *MinMaxOp = nullptr;
  1765. Value *ThirdOp = nullptr;
  1766. if (!LHS->hasNUsesOrMore(3) && RHS->hasNUsesOrMore(3)) {
  1767. // If the LHS is only used in this chain and the RHS is used outside of it,
  1768. // reuse the RHS min/max because that will eliminate the LHS.
  1769. if (D == A || C == A) {
  1770. // min(min(a, b), min(c, a)) --> min(min(c, a), b)
  1771. // min(min(a, b), min(a, d)) --> min(min(a, d), b)
  1772. MinMaxOp = RHS;
  1773. ThirdOp = B;
  1774. } else if (D == B || C == B) {
  1775. // min(min(a, b), min(c, b)) --> min(min(c, b), a)
  1776. // min(min(a, b), min(b, d)) --> min(min(b, d), a)
  1777. MinMaxOp = RHS;
  1778. ThirdOp = A;
  1779. }
  1780. } else if (!RHS->hasNUsesOrMore(3)) {
  1781. // Reuse the LHS. This will eliminate the RHS.
  1782. if (D == A || D == B) {
  1783. // min(min(a, b), min(c, a)) --> min(min(a, b), c)
  1784. // min(min(a, b), min(c, b)) --> min(min(a, b), c)
  1785. MinMaxOp = LHS;
  1786. ThirdOp = C;
  1787. } else if (C == A || C == B) {
  1788. // min(min(a, b), min(b, d)) --> min(min(a, b), d)
  1789. // min(min(a, b), min(c, b)) --> min(min(a, b), d)
  1790. MinMaxOp = LHS;
  1791. ThirdOp = D;
  1792. }
  1793. }
  1794. if (!MinMaxOp || !ThirdOp)
  1795. return nullptr;
  1796. CmpInst::Predicate P = getMinMaxPred(SPF);
  1797. Value *CmpABC = Builder.CreateICmp(P, MinMaxOp, ThirdOp);
  1798. return SelectInst::Create(CmpABC, MinMaxOp, ThirdOp);
  1799. }
  1800. /// Try to reduce a rotate pattern that includes a compare and select into a
  1801. /// funnel shift intrinsic. Example:
  1802. /// rotl32(a, b) --> (b == 0 ? a : ((a >> (32 - b)) | (a << b)))
  1803. /// --> call llvm.fshl.i32(a, a, b)
  1804. static Instruction *foldSelectRotate(SelectInst &Sel) {
  1805. // The false value of the select must be a rotate of the true value.
  1806. Value *Or0, *Or1;
  1807. if (!match(Sel.getFalseValue(), m_OneUse(m_Or(m_Value(Or0), m_Value(Or1)))))
  1808. return nullptr;
  1809. Value *TVal = Sel.getTrueValue();
  1810. Value *SA0, *SA1;
  1811. if (!match(Or0, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA0)))) ||
  1812. !match(Or1, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA1)))))
  1813. return nullptr;
  1814. auto ShiftOpcode0 = cast<BinaryOperator>(Or0)->getOpcode();
  1815. auto ShiftOpcode1 = cast<BinaryOperator>(Or1)->getOpcode();
  1816. if (ShiftOpcode0 == ShiftOpcode1)
  1817. return nullptr;
  1818. // We have one of these patterns so far:
  1819. // select ?, TVal, (or (lshr TVal, SA0), (shl TVal, SA1))
  1820. // select ?, TVal, (or (shl TVal, SA0), (lshr TVal, SA1))
  1821. // This must be a power-of-2 rotate for a bitmasking transform to be valid.
  1822. unsigned Width = Sel.getType()->getScalarSizeInBits();
  1823. if (!isPowerOf2_32(Width))
  1824. return nullptr;
  1825. // Check the shift amounts to see if they are an opposite pair.
  1826. Value *ShAmt;
  1827. if (match(SA1, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA0)))))
  1828. ShAmt = SA0;
  1829. else if (match(SA0, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA1)))))
  1830. ShAmt = SA1;
  1831. else
  1832. return nullptr;
  1833. // Finally, see if the select is filtering out a shift-by-zero.
  1834. Value *Cond = Sel.getCondition();
  1835. ICmpInst::Predicate Pred;
  1836. if (!match(Cond, m_OneUse(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()))) ||
  1837. Pred != ICmpInst::ICMP_EQ)
  1838. return nullptr;
  1839. // This is a rotate that avoids shift-by-bitwidth UB in a suboptimal way.
  1840. // Convert to funnel shift intrinsic.
  1841. bool IsFshl = (ShAmt == SA0 && ShiftOpcode0 == BinaryOperator::Shl) ||
  1842. (ShAmt == SA1 && ShiftOpcode1 == BinaryOperator::Shl);
  1843. Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
  1844. Function *F = Intrinsic::getDeclaration(Sel.getModule(), IID, Sel.getType());
  1845. return IntrinsicInst::Create(F, { TVal, TVal, ShAmt });
  1846. }
  1847. Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
  1848. Value *CondVal = SI.getCondition();
  1849. Value *TrueVal = SI.getTrueValue();
  1850. Value *FalseVal = SI.getFalseValue();
  1851. Type *SelType = SI.getType();
  1852. // FIXME: Remove this workaround when freeze related patches are done.
  1853. // For select with undef operand which feeds into an equality comparison,
  1854. // don't simplify it so loop unswitch can know the equality comparison
  1855. // may have an undef operand. This is a workaround for PR31652 caused by
  1856. // descrepancy about branch on undef between LoopUnswitch and GVN.
  1857. if (isa<UndefValue>(TrueVal) || isa<UndefValue>(FalseVal)) {
  1858. if (llvm::any_of(SI.users(), [&](User *U) {
  1859. ICmpInst *CI = dyn_cast<ICmpInst>(U);
  1860. if (CI && CI->isEquality())
  1861. return true;
  1862. return false;
  1863. })) {
  1864. return nullptr;
  1865. }
  1866. }
  1867. if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal,
  1868. SQ.getWithInstruction(&SI)))
  1869. return replaceInstUsesWith(SI, V);
  1870. if (Instruction *I = canonicalizeSelectToShuffle(SI))
  1871. return I;
  1872. if (Instruction *I = canonicalizeScalarSelectOfVecs(SI, Builder))
  1873. return I;
  1874. // Canonicalize a one-use integer compare with a non-canonical predicate by
  1875. // inverting the predicate and swapping the select operands. This matches a
  1876. // compare canonicalization for conditional branches.
  1877. // TODO: Should we do the same for FP compares?
  1878. CmpInst::Predicate Pred;
  1879. if (match(CondVal, m_OneUse(m_ICmp(Pred, m_Value(), m_Value()))) &&
  1880. !isCanonicalPredicate(Pred)) {
  1881. // Swap true/false values and condition.
  1882. CmpInst *Cond = cast<CmpInst>(CondVal);
  1883. Cond->setPredicate(CmpInst::getInversePredicate(Pred));
  1884. SI.setOperand(1, FalseVal);
  1885. SI.setOperand(2, TrueVal);
  1886. SI.swapProfMetadata();
  1887. Worklist.Add(Cond);
  1888. return &SI;
  1889. }
  1890. if (SelType->isIntOrIntVectorTy(1) &&
  1891. TrueVal->getType() == CondVal->getType()) {
  1892. if (match(TrueVal, m_One())) {
  1893. // Change: A = select B, true, C --> A = or B, C
  1894. return BinaryOperator::CreateOr(CondVal, FalseVal);
  1895. }
  1896. if (match(TrueVal, m_Zero())) {
  1897. // Change: A = select B, false, C --> A = and !B, C
  1898. Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
  1899. return BinaryOperator::CreateAnd(NotCond, FalseVal);
  1900. }
  1901. if (match(FalseVal, m_Zero())) {
  1902. // Change: A = select B, C, false --> A = and B, C
  1903. return BinaryOperator::CreateAnd(CondVal, TrueVal);
  1904. }
  1905. if (match(FalseVal, m_One())) {
  1906. // Change: A = select B, C, true --> A = or !B, C
  1907. Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
  1908. return BinaryOperator::CreateOr(NotCond, TrueVal);
  1909. }
  1910. // select a, a, b -> a | b
  1911. // select a, b, a -> a & b
  1912. if (CondVal == TrueVal)
  1913. return BinaryOperator::CreateOr(CondVal, FalseVal);
  1914. if (CondVal == FalseVal)
  1915. return BinaryOperator::CreateAnd(CondVal, TrueVal);
  1916. // select a, ~a, b -> (~a) & b
  1917. // select a, b, ~a -> (~a) | b
  1918. if (match(TrueVal, m_Not(m_Specific(CondVal))))
  1919. return BinaryOperator::CreateAnd(TrueVal, FalseVal);
  1920. if (match(FalseVal, m_Not(m_Specific(CondVal))))
  1921. return BinaryOperator::CreateOr(TrueVal, FalseVal);
  1922. }
  1923. // Selecting between two integer or vector splat integer constants?
  1924. //
  1925. // Note that we don't handle a scalar select of vectors:
  1926. // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
  1927. // because that may need 3 instructions to splat the condition value:
  1928. // extend, insertelement, shufflevector.
  1929. if (SelType->isIntOrIntVectorTy() &&
  1930. CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
  1931. // select C, 1, 0 -> zext C to int
  1932. if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
  1933. return new ZExtInst(CondVal, SelType);
  1934. // select C, -1, 0 -> sext C to int
  1935. if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
  1936. return new SExtInst(CondVal, SelType);
  1937. // select C, 0, 1 -> zext !C to int
  1938. if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
  1939. Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
  1940. return new ZExtInst(NotCond, SelType);
  1941. }
  1942. // select C, 0, -1 -> sext !C to int
  1943. if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
  1944. Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
  1945. return new SExtInst(NotCond, SelType);
  1946. }
  1947. }
  1948. // See if we are selecting two values based on a comparison of the two values.
  1949. if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
  1950. if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
  1951. // Canonicalize to use ordered comparisons by swapping the select
  1952. // operands.
  1953. //
  1954. // e.g.
  1955. // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
  1956. if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
  1957. FCmpInst::Predicate InvPred = FCI->getInversePredicate();
  1958. IRBuilder<>::FastMathFlagGuard FMFG(Builder);
  1959. Builder.setFastMathFlags(FCI->getFastMathFlags());
  1960. Value *NewCond = Builder.CreateFCmp(InvPred, TrueVal, FalseVal,
  1961. FCI->getName() + ".inv");
  1962. return SelectInst::Create(NewCond, FalseVal, TrueVal,
  1963. SI.getName() + ".p");
  1964. }
  1965. // NOTE: if we wanted to, this is where to detect MIN/MAX
  1966. } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
  1967. // Canonicalize to use ordered comparisons by swapping the select
  1968. // operands.
  1969. //
  1970. // e.g.
  1971. // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
  1972. if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
  1973. FCmpInst::Predicate InvPred = FCI->getInversePredicate();
  1974. IRBuilder<>::FastMathFlagGuard FMFG(Builder);
  1975. Builder.setFastMathFlags(FCI->getFastMathFlags());
  1976. Value *NewCond = Builder.CreateFCmp(InvPred, FalseVal, TrueVal,
  1977. FCI->getName() + ".inv");
  1978. return SelectInst::Create(NewCond, FalseVal, TrueVal,
  1979. SI.getName() + ".p");
  1980. }
  1981. // NOTE: if we wanted to, this is where to detect MIN/MAX
  1982. }
  1983. }
  1984. // Canonicalize select with fcmp to fabs(). -0.0 makes this tricky. We need
  1985. // fast-math-flags (nsz) or fsub with +0.0 (not fneg) for this to work. We
  1986. // also require nnan because we do not want to unintentionally change the
  1987. // sign of a NaN value.
  1988. // FIXME: These folds should test/propagate FMF from the select, not the
  1989. // fsub or fneg.
  1990. // (X <= +/-0.0) ? (0.0 - X) : X --> fabs(X)
  1991. Instruction *FSub;
  1992. if (match(CondVal, m_FCmp(Pred, m_Specific(FalseVal), m_AnyZeroFP())) &&
  1993. match(TrueVal, m_FSub(m_PosZeroFP(), m_Specific(FalseVal))) &&
  1994. match(TrueVal, m_Instruction(FSub)) && FSub->hasNoNaNs() &&
  1995. (Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)) {
  1996. Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FalseVal, FSub);
  1997. return replaceInstUsesWith(SI, Fabs);
  1998. }
  1999. // (X > +/-0.0) ? X : (0.0 - X) --> fabs(X)
  2000. if (match(CondVal, m_FCmp(Pred, m_Specific(TrueVal), m_AnyZeroFP())) &&
  2001. match(FalseVal, m_FSub(m_PosZeroFP(), m_Specific(TrueVal))) &&
  2002. match(FalseVal, m_Instruction(FSub)) && FSub->hasNoNaNs() &&
  2003. (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT)) {
  2004. Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, TrueVal, FSub);
  2005. return replaceInstUsesWith(SI, Fabs);
  2006. }
  2007. // With nnan and nsz:
  2008. // (X < +/-0.0) ? -X : X --> fabs(X)
  2009. // (X <= +/-0.0) ? -X : X --> fabs(X)
  2010. Instruction *FNeg;
  2011. if (match(CondVal, m_FCmp(Pred, m_Specific(FalseVal), m_AnyZeroFP())) &&
  2012. match(TrueVal, m_FNeg(m_Specific(FalseVal))) &&
  2013. match(TrueVal, m_Instruction(FNeg)) &&
  2014. FNeg->hasNoNaNs() && FNeg->hasNoSignedZeros() &&
  2015. (Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
  2016. Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE)) {
  2017. Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FalseVal, FNeg);
  2018. return replaceInstUsesWith(SI, Fabs);
  2019. }
  2020. // With nnan and nsz:
  2021. // (X > +/-0.0) ? X : -X --> fabs(X)
  2022. // (X >= +/-0.0) ? X : -X --> fabs(X)
  2023. if (match(CondVal, m_FCmp(Pred, m_Specific(TrueVal), m_AnyZeroFP())) &&
  2024. match(FalseVal, m_FNeg(m_Specific(TrueVal))) &&
  2025. match(FalseVal, m_Instruction(FNeg)) &&
  2026. FNeg->hasNoNaNs() && FNeg->hasNoSignedZeros() &&
  2027. (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_OGE ||
  2028. Pred == FCmpInst::FCMP_UGT || Pred == FCmpInst::FCMP_UGE)) {
  2029. Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, TrueVal, FNeg);
  2030. return replaceInstUsesWith(SI, Fabs);
  2031. }
  2032. // See if we are selecting two values based on a comparison of the two values.
  2033. if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
  2034. if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
  2035. return Result;
  2036. if (Instruction *Add = foldAddSubSelect(SI, Builder))
  2037. return Add;
  2038. // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
  2039. auto *TI = dyn_cast<Instruction>(TrueVal);
  2040. auto *FI = dyn_cast<Instruction>(FalseVal);
  2041. if (TI && FI && TI->getOpcode() == FI->getOpcode())
  2042. if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
  2043. return IV;
  2044. if (Instruction *I = foldSelectExtConst(SI))
  2045. return I;
  2046. // See if we can fold the select into one of our operands.
  2047. if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
  2048. if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
  2049. return FoldI;
  2050. Value *LHS, *RHS;
  2051. Instruction::CastOps CastOp;
  2052. SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
  2053. auto SPF = SPR.Flavor;
  2054. if (SPF) {
  2055. Value *LHS2, *RHS2;
  2056. if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
  2057. if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS), SPF2, LHS2,
  2058. RHS2, SI, SPF, RHS))
  2059. return R;
  2060. if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
  2061. if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS), SPF2, LHS2,
  2062. RHS2, SI, SPF, LHS))
  2063. return R;
  2064. // TODO.
  2065. // ABS(-X) -> ABS(X)
  2066. }
  2067. if (SelectPatternResult::isMinOrMax(SPF)) {
  2068. // Canonicalize so that
  2069. // - type casts are outside select patterns.
  2070. // - float clamp is transformed to min/max pattern
  2071. bool IsCastNeeded = LHS->getType() != SelType;
  2072. Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
  2073. Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
  2074. if (IsCastNeeded ||
  2075. (LHS->getType()->isFPOrFPVectorTy() &&
  2076. ((CmpLHS != LHS && CmpLHS != RHS) ||
  2077. (CmpRHS != LHS && CmpRHS != RHS)))) {
  2078. CmpInst::Predicate Pred = getMinMaxPred(SPF, SPR.Ordered);
  2079. Value *Cmp;
  2080. if (CmpInst::isIntPredicate(Pred)) {
  2081. Cmp = Builder.CreateICmp(Pred, LHS, RHS);
  2082. } else {
  2083. IRBuilder<>::FastMathFlagGuard FMFG(Builder);
  2084. auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
  2085. Builder.setFastMathFlags(FMF);
  2086. Cmp = Builder.CreateFCmp(Pred, LHS, RHS);
  2087. }
  2088. Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
  2089. if (!IsCastNeeded)
  2090. return replaceInstUsesWith(SI, NewSI);
  2091. Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
  2092. return replaceInstUsesWith(SI, NewCast);
  2093. }
  2094. // MAX(~a, ~b) -> ~MIN(a, b)
  2095. // MAX(~a, C) -> ~MIN(a, ~C)
  2096. // MIN(~a, ~b) -> ~MAX(a, b)
  2097. // MIN(~a, C) -> ~MAX(a, ~C)
  2098. auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * {
  2099. Value *A;
  2100. if (match(X, m_Not(m_Value(A))) && !X->hasNUsesOrMore(3) &&
  2101. !isFreeToInvert(A, A->hasOneUse()) &&
  2102. // Passing false to only consider m_Not and constants.
  2103. isFreeToInvert(Y, false)) {
  2104. Value *B = Builder.CreateNot(Y);
  2105. Value *NewMinMax = createMinMax(Builder, getInverseMinMaxFlavor(SPF),
  2106. A, B);
  2107. // Copy the profile metadata.
  2108. if (MDNode *MD = SI.getMetadata(LLVMContext::MD_prof)) {
  2109. cast<SelectInst>(NewMinMax)->setMetadata(LLVMContext::MD_prof, MD);
  2110. // Swap the metadata if the operands are swapped.
  2111. if (X == SI.getFalseValue() && Y == SI.getTrueValue())
  2112. cast<SelectInst>(NewMinMax)->swapProfMetadata();
  2113. }
  2114. return BinaryOperator::CreateNot(NewMinMax);
  2115. }
  2116. return nullptr;
  2117. };
  2118. if (Instruction *I = moveNotAfterMinMax(LHS, RHS))
  2119. return I;
  2120. if (Instruction *I = moveNotAfterMinMax(RHS, LHS))
  2121. return I;
  2122. if (Instruction *I = moveAddAfterMinMax(SPF, LHS, RHS, Builder))
  2123. return I;
  2124. if (Instruction *I = factorizeMinMaxTree(SPF, LHS, RHS, Builder))
  2125. return I;
  2126. }
  2127. }
  2128. // Canonicalize select of FP values where NaN and -0.0 are not valid as
  2129. // minnum/maxnum intrinsics.
  2130. if (isa<FPMathOperator>(SI) && SI.hasNoNaNs() && SI.hasNoSignedZeros()) {
  2131. Value *X, *Y;
  2132. if (match(&SI, m_OrdFMax(m_Value(X), m_Value(Y))))
  2133. return replaceInstUsesWith(
  2134. SI, Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, X, Y, &SI));
  2135. if (match(&SI, m_OrdFMin(m_Value(X), m_Value(Y))))
  2136. return replaceInstUsesWith(
  2137. SI, Builder.CreateBinaryIntrinsic(Intrinsic::minnum, X, Y, &SI));
  2138. }
  2139. // See if we can fold the select into a phi node if the condition is a select.
  2140. if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
  2141. // The true/false values have to be live in the PHI predecessor's blocks.
  2142. if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
  2143. canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
  2144. if (Instruction *NV = foldOpIntoPhi(SI, PN))
  2145. return NV;
  2146. if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
  2147. if (TrueSI->getCondition()->getType() == CondVal->getType()) {
  2148. // select(C, select(C, a, b), c) -> select(C, a, c)
  2149. if (TrueSI->getCondition() == CondVal) {
  2150. if (SI.getTrueValue() == TrueSI->getTrueValue())
  2151. return nullptr;
  2152. SI.setOperand(1, TrueSI->getTrueValue());
  2153. return &SI;
  2154. }
  2155. // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
  2156. // We choose this as normal form to enable folding on the And and shortening
  2157. // paths for the values (this helps GetUnderlyingObjects() for example).
  2158. if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
  2159. Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition());
  2160. SI.setOperand(0, And);
  2161. SI.setOperand(1, TrueSI->getTrueValue());
  2162. return &SI;
  2163. }
  2164. }
  2165. }
  2166. if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
  2167. if (FalseSI->getCondition()->getType() == CondVal->getType()) {
  2168. // select(C, a, select(C, b, c)) -> select(C, a, c)
  2169. if (FalseSI->getCondition() == CondVal) {
  2170. if (SI.getFalseValue() == FalseSI->getFalseValue())
  2171. return nullptr;
  2172. SI.setOperand(2, FalseSI->getFalseValue());
  2173. return &SI;
  2174. }
  2175. // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
  2176. if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
  2177. Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition());
  2178. SI.setOperand(0, Or);
  2179. SI.setOperand(2, FalseSI->getFalseValue());
  2180. return &SI;
  2181. }
  2182. }
  2183. }
  2184. auto canMergeSelectThroughBinop = [](BinaryOperator *BO) {
  2185. // The select might be preventing a division by 0.
  2186. switch (BO->getOpcode()) {
  2187. default:
  2188. return true;
  2189. case Instruction::SRem:
  2190. case Instruction::URem:
  2191. case Instruction::SDiv:
  2192. case Instruction::UDiv:
  2193. return false;
  2194. }
  2195. };
  2196. // Try to simplify a binop sandwiched between 2 selects with the same
  2197. // condition.
  2198. // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z)
  2199. BinaryOperator *TrueBO;
  2200. if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) &&
  2201. canMergeSelectThroughBinop(TrueBO)) {
  2202. if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) {
  2203. if (TrueBOSI->getCondition() == CondVal) {
  2204. TrueBO->setOperand(0, TrueBOSI->getTrueValue());
  2205. Worklist.Add(TrueBO);
  2206. return &SI;
  2207. }
  2208. }
  2209. if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) {
  2210. if (TrueBOSI->getCondition() == CondVal) {
  2211. TrueBO->setOperand(1, TrueBOSI->getTrueValue());
  2212. Worklist.Add(TrueBO);
  2213. return &SI;
  2214. }
  2215. }
  2216. }
  2217. // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W))
  2218. BinaryOperator *FalseBO;
  2219. if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) &&
  2220. canMergeSelectThroughBinop(FalseBO)) {
  2221. if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) {
  2222. if (FalseBOSI->getCondition() == CondVal) {
  2223. FalseBO->setOperand(0, FalseBOSI->getFalseValue());
  2224. Worklist.Add(FalseBO);
  2225. return &SI;
  2226. }
  2227. }
  2228. if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) {
  2229. if (FalseBOSI->getCondition() == CondVal) {
  2230. FalseBO->setOperand(1, FalseBOSI->getFalseValue());
  2231. Worklist.Add(FalseBO);
  2232. return &SI;
  2233. }
  2234. }
  2235. }
  2236. Value *NotCond;
  2237. if (match(CondVal, m_Not(m_Value(NotCond)))) {
  2238. SI.setOperand(0, NotCond);
  2239. SI.setOperand(1, FalseVal);
  2240. SI.setOperand(2, TrueVal);
  2241. SI.swapProfMetadata();
  2242. return &SI;
  2243. }
  2244. if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) {
  2245. unsigned VWidth = VecTy->getNumElements();
  2246. APInt UndefElts(VWidth, 0);
  2247. APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
  2248. if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
  2249. if (V != &SI)
  2250. return replaceInstUsesWith(SI, V);
  2251. return &SI;
  2252. }
  2253. }
  2254. // If we can compute the condition, there's no need for a select.
  2255. // Like the above fold, we are attempting to reduce compile-time cost by
  2256. // putting this fold here with limitations rather than in InstSimplify.
  2257. // The motivation for this call into value tracking is to take advantage of
  2258. // the assumption cache, so make sure that is populated.
  2259. if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
  2260. KnownBits Known(1);
  2261. computeKnownBits(CondVal, Known, 0, &SI);
  2262. if (Known.One.isOneValue())
  2263. return replaceInstUsesWith(SI, TrueVal);
  2264. if (Known.Zero.isOneValue())
  2265. return replaceInstUsesWith(SI, FalseVal);
  2266. }
  2267. if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
  2268. return BitCastSel;
  2269. // Simplify selects that test the returned flag of cmpxchg instructions.
  2270. if (Instruction *Select = foldSelectCmpXchg(SI))
  2271. return Select;
  2272. if (Instruction *Select = foldSelectBinOpIdentity(SI, TLI))
  2273. return Select;
  2274. if (Instruction *Rot = foldSelectRotate(SI))
  2275. return Rot;
  2276. return nullptr;
  2277. }