InstCombineSelect.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192
  1. //===- InstCombineSelect.cpp ----------------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the visitSelect function.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "InstCombineInternal.h"
  14. #include "llvm/Analysis/ConstantFolding.h"
  15. #include "llvm/Analysis/InstructionSimplify.h"
  16. #include "llvm/Analysis/ValueTracking.h"
  17. #include "llvm/IR/PatternMatch.h"
  18. using namespace llvm;
  19. using namespace PatternMatch;
  20. #define DEBUG_TYPE "instcombine"
  21. static SelectPatternFlavor
  22. getInverseMinMaxSelectPattern(SelectPatternFlavor SPF) {
  23. switch (SPF) {
  24. default:
  25. llvm_unreachable("unhandled!");
  26. case SPF_SMIN:
  27. return SPF_SMAX;
  28. case SPF_UMIN:
  29. return SPF_UMAX;
  30. case SPF_SMAX:
  31. return SPF_SMIN;
  32. case SPF_UMAX:
  33. return SPF_UMIN;
  34. }
  35. }
  36. static CmpInst::Predicate getICmpPredicateForMinMax(SelectPatternFlavor SPF) {
  37. switch (SPF) {
  38. default:
  39. llvm_unreachable("unhandled!");
  40. case SPF_SMIN:
  41. return ICmpInst::ICMP_SLT;
  42. case SPF_UMIN:
  43. return ICmpInst::ICMP_ULT;
  44. case SPF_SMAX:
  45. return ICmpInst::ICMP_SGT;
  46. case SPF_UMAX:
  47. return ICmpInst::ICMP_UGT;
  48. }
  49. }
  50. static Value *generateMinMaxSelectPattern(InstCombiner::BuilderTy *Builder,
  51. SelectPatternFlavor SPF, Value *A,
  52. Value *B) {
  53. CmpInst::Predicate Pred = getICmpPredicateForMinMax(SPF);
  54. return Builder->CreateSelect(Builder->CreateICmp(Pred, A, B), A, B);
  55. }
  56. /// GetSelectFoldableOperands - We want to turn code that looks like this:
  57. /// %C = or %A, %B
  58. /// %D = select %cond, %C, %A
  59. /// into:
  60. /// %C = select %cond, %B, 0
  61. /// %D = or %A, %C
  62. ///
  63. /// Assuming that the specified instruction is an operand to the select, return
  64. /// a bitmask indicating which operands of this instruction are foldable if they
  65. /// equal the other incoming value of the select.
  66. ///
  67. static unsigned GetSelectFoldableOperands(Instruction *I) {
  68. switch (I->getOpcode()) {
  69. case Instruction::Add:
  70. case Instruction::Mul:
  71. case Instruction::And:
  72. case Instruction::Or:
  73. case Instruction::Xor:
  74. return 3; // Can fold through either operand.
  75. case Instruction::Sub: // Can only fold on the amount subtracted.
  76. case Instruction::Shl: // Can only fold on the shift amount.
  77. case Instruction::LShr:
  78. case Instruction::AShr:
  79. return 1;
  80. default:
  81. return 0; // Cannot fold
  82. }
  83. }
  84. /// GetSelectFoldableConstant - For the same transformation as the previous
  85. /// function, return the identity constant that goes into the select.
  86. static Constant *GetSelectFoldableConstant(Instruction *I) {
  87. switch (I->getOpcode()) {
  88. default: llvm_unreachable("This cannot happen!");
  89. case Instruction::Add:
  90. case Instruction::Sub:
  91. case Instruction::Or:
  92. case Instruction::Xor:
  93. case Instruction::Shl:
  94. case Instruction::LShr:
  95. case Instruction::AShr:
  96. return Constant::getNullValue(I->getType());
  97. case Instruction::And:
  98. return Constant::getAllOnesValue(I->getType());
  99. case Instruction::Mul:
  100. return ConstantInt::get(I->getType(), 1);
  101. }
  102. }
  103. /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
  104. /// have the same opcode and only one use each. Try to simplify this.
  105. Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
  106. Instruction *FI) {
  107. if (TI->getNumOperands() == 1) {
  108. // If this is a non-volatile load or a cast from the same type,
  109. // merge.
  110. if (TI->isCast()) {
  111. Type *FIOpndTy = FI->getOperand(0)->getType();
  112. if (TI->getOperand(0)->getType() != FIOpndTy)
  113. return nullptr;
  114. // The select condition may be a vector. We may only change the operand
  115. // type if the vector width remains the same (and matches the condition).
  116. Type *CondTy = SI.getCondition()->getType();
  117. if (CondTy->isVectorTy() && (!FIOpndTy->isVectorTy() ||
  118. CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements()))
  119. return nullptr;
  120. } else {
  121. return nullptr; // unknown unary op.
  122. }
  123. // Fold this by inserting a select from the input values.
  124. Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
  125. FI->getOperand(0), SI.getName()+".v");
  126. return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
  127. TI->getType());
  128. }
  129. // Only handle binary operators here.
  130. if (!isa<BinaryOperator>(TI))
  131. return nullptr;
  132. // Figure out if the operations have any operands in common.
  133. Value *MatchOp, *OtherOpT, *OtherOpF;
  134. bool MatchIsOpZero;
  135. if (TI->getOperand(0) == FI->getOperand(0)) {
  136. MatchOp = TI->getOperand(0);
  137. OtherOpT = TI->getOperand(1);
  138. OtherOpF = FI->getOperand(1);
  139. MatchIsOpZero = true;
  140. } else if (TI->getOperand(1) == FI->getOperand(1)) {
  141. MatchOp = TI->getOperand(1);
  142. OtherOpT = TI->getOperand(0);
  143. OtherOpF = FI->getOperand(0);
  144. MatchIsOpZero = false;
  145. } else if (!TI->isCommutative()) {
  146. return nullptr;
  147. } else if (TI->getOperand(0) == FI->getOperand(1)) {
  148. MatchOp = TI->getOperand(0);
  149. OtherOpT = TI->getOperand(1);
  150. OtherOpF = FI->getOperand(0);
  151. MatchIsOpZero = true;
  152. } else if (TI->getOperand(1) == FI->getOperand(0)) {
  153. MatchOp = TI->getOperand(1);
  154. OtherOpT = TI->getOperand(0);
  155. OtherOpF = FI->getOperand(1);
  156. MatchIsOpZero = true;
  157. } else {
  158. return nullptr;
  159. }
  160. // If we reach here, they do have operations in common.
  161. Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT,
  162. OtherOpF, SI.getName()+".v");
  163. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
  164. if (MatchIsOpZero)
  165. return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
  166. else
  167. return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
  168. }
  169. llvm_unreachable("Shouldn't get here");
  170. }
  171. static bool isSelect01(Constant *C1, Constant *C2) {
  172. ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
  173. if (!C1I)
  174. return false;
  175. ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
  176. if (!C2I)
  177. return false;
  178. if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
  179. return false;
  180. return C1I->isOne() || C1I->isAllOnesValue() ||
  181. C2I->isOne() || C2I->isAllOnesValue();
  182. }
  183. /// FoldSelectIntoOp - Try fold the select into one of the operands to
  184. /// facilitate further optimization.
  185. Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
  186. Value *FalseVal) {
  187. // See the comment above GetSelectFoldableOperands for a description of the
  188. // transformation we are doing here.
  189. if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
  190. if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
  191. !isa<Constant>(FalseVal)) {
  192. if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
  193. unsigned OpToFold = 0;
  194. if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
  195. OpToFold = 1;
  196. } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
  197. OpToFold = 2;
  198. }
  199. if (OpToFold) {
  200. Constant *C = GetSelectFoldableConstant(TVI);
  201. Value *OOp = TVI->getOperand(2-OpToFold);
  202. // Avoid creating select between 2 constants unless it's selecting
  203. // between 0, 1 and -1.
  204. if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
  205. Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
  206. NewSel->takeName(TVI);
  207. BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
  208. BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
  209. FalseVal, NewSel);
  210. if (isa<PossiblyExactOperator>(BO))
  211. BO->setIsExact(TVI_BO->isExact());
  212. if (isa<OverflowingBinaryOperator>(BO)) {
  213. BO->setHasNoUnsignedWrap(TVI_BO->hasNoUnsignedWrap());
  214. BO->setHasNoSignedWrap(TVI_BO->hasNoSignedWrap());
  215. }
  216. return BO;
  217. }
  218. }
  219. }
  220. }
  221. }
  222. if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
  223. if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
  224. !isa<Constant>(TrueVal)) {
  225. if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
  226. unsigned OpToFold = 0;
  227. if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
  228. OpToFold = 1;
  229. } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
  230. OpToFold = 2;
  231. }
  232. if (OpToFold) {
  233. Constant *C = GetSelectFoldableConstant(FVI);
  234. Value *OOp = FVI->getOperand(2-OpToFold);
  235. // Avoid creating select between 2 constants unless it's selecting
  236. // between 0, 1 and -1.
  237. if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
  238. Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
  239. NewSel->takeName(FVI);
  240. BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
  241. BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
  242. TrueVal, NewSel);
  243. if (isa<PossiblyExactOperator>(BO))
  244. BO->setIsExact(FVI_BO->isExact());
  245. if (isa<OverflowingBinaryOperator>(BO)) {
  246. BO->setHasNoUnsignedWrap(FVI_BO->hasNoUnsignedWrap());
  247. BO->setHasNoSignedWrap(FVI_BO->hasNoSignedWrap());
  248. }
  249. return BO;
  250. }
  251. }
  252. }
  253. }
  254. }
  255. return nullptr;
  256. }
  257. /// foldSelectICmpAndOr - We want to turn:
  258. /// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
  259. /// into:
  260. /// (or (shl (and X, C1), C3), y)
  261. /// iff:
  262. /// C1 and C2 are both powers of 2
  263. /// where:
  264. /// C3 = Log(C2) - Log(C1)
  265. ///
  266. /// This transform handles cases where:
  267. /// 1. The icmp predicate is inverted
  268. /// 2. The select operands are reversed
  269. /// 3. The magnitude of C2 and C1 are flipped
  270. static Value *foldSelectICmpAndOr(const SelectInst &SI, Value *TrueVal,
  271. Value *FalseVal,
  272. InstCombiner::BuilderTy *Builder) {
  273. const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
  274. if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
  275. return nullptr;
  276. Value *CmpLHS = IC->getOperand(0);
  277. Value *CmpRHS = IC->getOperand(1);
  278. if (!match(CmpRHS, m_Zero()))
  279. return nullptr;
  280. Value *X;
  281. const APInt *C1;
  282. if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1))))
  283. return nullptr;
  284. const APInt *C2;
  285. bool OrOnTrueVal = false;
  286. bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
  287. if (!OrOnFalseVal)
  288. OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
  289. if (!OrOnFalseVal && !OrOnTrueVal)
  290. return nullptr;
  291. Value *V = CmpLHS;
  292. Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
  293. unsigned C1Log = C1->logBase2();
  294. unsigned C2Log = C2->logBase2();
  295. if (C2Log > C1Log) {
  296. V = Builder->CreateZExtOrTrunc(V, Y->getType());
  297. V = Builder->CreateShl(V, C2Log - C1Log);
  298. } else if (C1Log > C2Log) {
  299. V = Builder->CreateLShr(V, C1Log - C2Log);
  300. V = Builder->CreateZExtOrTrunc(V, Y->getType());
  301. } else
  302. V = Builder->CreateZExtOrTrunc(V, Y->getType());
  303. ICmpInst::Predicate Pred = IC->getPredicate();
  304. if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) ||
  305. (Pred == ICmpInst::ICMP_EQ && OrOnTrueVal))
  306. V = Builder->CreateXor(V, *C2);
  307. return Builder->CreateOr(V, Y);
  308. }
  309. /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
  310. /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
  311. ///
  312. /// For example, we can fold the following code sequence:
  313. /// \code
  314. /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
  315. /// %1 = icmp ne i32 %x, 0
  316. /// %2 = select i1 %1, i32 %0, i32 32
  317. /// \code
  318. ///
  319. /// into:
  320. /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
  321. static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
  322. InstCombiner::BuilderTy *Builder) {
  323. ICmpInst::Predicate Pred = ICI->getPredicate();
  324. Value *CmpLHS = ICI->getOperand(0);
  325. Value *CmpRHS = ICI->getOperand(1);
  326. // Check if the condition value compares a value for equality against zero.
  327. if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
  328. return nullptr;
  329. Value *Count = FalseVal;
  330. Value *ValueOnZero = TrueVal;
  331. if (Pred == ICmpInst::ICMP_NE)
  332. std::swap(Count, ValueOnZero);
  333. // Skip zero extend/truncate.
  334. Value *V = nullptr;
  335. if (match(Count, m_ZExt(m_Value(V))) ||
  336. match(Count, m_Trunc(m_Value(V))))
  337. Count = V;
  338. // Check if the value propagated on zero is a constant number equal to the
  339. // sizeof in bits of 'Count'.
  340. unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
  341. if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
  342. return nullptr;
  343. // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
  344. // input to the cttz/ctlz is used as LHS for the compare instruction.
  345. if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
  346. match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
  347. IntrinsicInst *II = cast<IntrinsicInst>(Count);
  348. IRBuilder<> Builder(II);
  349. // Explicitly clear the 'undef_on_zero' flag.
  350. IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
  351. Type *Ty = NewI->getArgOperand(1)->getType();
  352. NewI->setArgOperand(1, Constant::getNullValue(Ty));
  353. Builder.Insert(NewI);
  354. return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
  355. }
  356. return nullptr;
  357. }
  358. /// visitSelectInstWithICmp - Visit a SelectInst that has an
  359. /// ICmpInst as its first operand.
  360. ///
  361. Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
  362. ICmpInst *ICI) {
  363. bool Changed = false;
  364. ICmpInst::Predicate Pred = ICI->getPredicate();
  365. Value *CmpLHS = ICI->getOperand(0);
  366. Value *CmpRHS = ICI->getOperand(1);
  367. Value *TrueVal = SI.getTrueValue();
  368. Value *FalseVal = SI.getFalseValue();
  369. // Check cases where the comparison is with a constant that
  370. // can be adjusted to fit the min/max idiom. We may move or edit ICI
  371. // here, so make sure the select is the only user.
  372. if (ICI->hasOneUse())
  373. if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
  374. switch (Pred) {
  375. default: break;
  376. case ICmpInst::ICMP_ULT:
  377. case ICmpInst::ICMP_SLT:
  378. case ICmpInst::ICMP_UGT:
  379. case ICmpInst::ICMP_SGT: {
  380. // These transformations only work for selects over integers.
  381. IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
  382. if (!SelectTy)
  383. break;
  384. Constant *AdjustedRHS;
  385. if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
  386. AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
  387. else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
  388. AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
  389. // X > C ? X : C+1 --> X < C+1 ? C+1 : X
  390. // X < C ? X : C-1 --> X > C-1 ? C-1 : X
  391. if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
  392. (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
  393. ; // Nothing to do here. Values match without any sign/zero extension.
  394. // Types do not match. Instead of calculating this with mixed types
  395. // promote all to the larger type. This enables scalar evolution to
  396. // analyze this expression.
  397. else if (CmpRHS->getType()->getScalarSizeInBits()
  398. < SelectTy->getBitWidth()) {
  399. Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
  400. // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
  401. // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
  402. // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
  403. // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
  404. if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
  405. sextRHS == FalseVal) {
  406. CmpLHS = TrueVal;
  407. AdjustedRHS = sextRHS;
  408. } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
  409. sextRHS == TrueVal) {
  410. CmpLHS = FalseVal;
  411. AdjustedRHS = sextRHS;
  412. } else if (ICI->isUnsigned()) {
  413. Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
  414. // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
  415. // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
  416. // zext + signed compare cannot be changed:
  417. // 0xff <s 0x00, but 0x00ff >s 0x0000
  418. if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
  419. zextRHS == FalseVal) {
  420. CmpLHS = TrueVal;
  421. AdjustedRHS = zextRHS;
  422. } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
  423. zextRHS == TrueVal) {
  424. CmpLHS = FalseVal;
  425. AdjustedRHS = zextRHS;
  426. } else
  427. break;
  428. } else
  429. break;
  430. } else
  431. break;
  432. Pred = ICmpInst::getSwappedPredicate(Pred);
  433. CmpRHS = AdjustedRHS;
  434. std::swap(FalseVal, TrueVal);
  435. ICI->setPredicate(Pred);
  436. ICI->setOperand(0, CmpLHS);
  437. ICI->setOperand(1, CmpRHS);
  438. SI.setOperand(1, TrueVal);
  439. SI.setOperand(2, FalseVal);
  440. // Move ICI instruction right before the select instruction. Otherwise
  441. // the sext/zext value may be defined after the ICI instruction uses it.
  442. ICI->moveBefore(&SI);
  443. Changed = true;
  444. break;
  445. }
  446. }
  447. }
  448. // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
  449. // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
  450. // FIXME: Type and constness constraints could be lifted, but we have to
  451. // watch code size carefully. We should consider xor instead of
  452. // sub/add when we decide to do that.
  453. if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
  454. if (TrueVal->getType() == Ty) {
  455. if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
  456. ConstantInt *C1 = nullptr, *C2 = nullptr;
  457. if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
  458. C1 = dyn_cast<ConstantInt>(TrueVal);
  459. C2 = dyn_cast<ConstantInt>(FalseVal);
  460. } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
  461. C1 = dyn_cast<ConstantInt>(FalseVal);
  462. C2 = dyn_cast<ConstantInt>(TrueVal);
  463. }
  464. if (C1 && C2) {
  465. // This shift results in either -1 or 0.
  466. Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
  467. // Check if we can express the operation with a single or.
  468. if (C2->isAllOnesValue())
  469. return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
  470. Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
  471. return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
  472. }
  473. }
  474. }
  475. }
  476. // NOTE: if we wanted to, this is where to detect integer MIN/MAX
  477. if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
  478. if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
  479. // Transform (X == C) ? X : Y -> (X == C) ? C : Y
  480. SI.setOperand(1, CmpRHS);
  481. Changed = true;
  482. } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
  483. // Transform (X != C) ? Y : X -> (X != C) ? Y : C
  484. SI.setOperand(2, CmpRHS);
  485. Changed = true;
  486. }
  487. }
  488. {
  489. unsigned BitWidth = DL.getTypeSizeInBits(TrueVal->getType());
  490. APInt MinSignedValue = APInt::getSignBit(BitWidth);
  491. Value *X;
  492. const APInt *Y, *C;
  493. bool TrueWhenUnset;
  494. bool IsBitTest = false;
  495. if (ICmpInst::isEquality(Pred) &&
  496. match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
  497. match(CmpRHS, m_Zero())) {
  498. IsBitTest = true;
  499. TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
  500. } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
  501. X = CmpLHS;
  502. Y = &MinSignedValue;
  503. IsBitTest = true;
  504. TrueWhenUnset = false;
  505. } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
  506. X = CmpLHS;
  507. Y = &MinSignedValue;
  508. IsBitTest = true;
  509. TrueWhenUnset = true;
  510. }
  511. if (IsBitTest) {
  512. Value *V = nullptr;
  513. // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
  514. if (TrueWhenUnset && TrueVal == X &&
  515. match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
  516. V = Builder->CreateAnd(X, ~(*Y));
  517. // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
  518. else if (!TrueWhenUnset && FalseVal == X &&
  519. match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
  520. V = Builder->CreateAnd(X, ~(*Y));
  521. // (X & Y) == 0 ? X ^ Y : X --> X | Y
  522. else if (TrueWhenUnset && FalseVal == X &&
  523. match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
  524. V = Builder->CreateOr(X, *Y);
  525. // (X & Y) != 0 ? X : X ^ Y --> X | Y
  526. else if (!TrueWhenUnset && TrueVal == X &&
  527. match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
  528. V = Builder->CreateOr(X, *Y);
  529. if (V)
  530. return ReplaceInstUsesWith(SI, V);
  531. }
  532. }
  533. if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
  534. return ReplaceInstUsesWith(SI, V);
  535. if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
  536. return ReplaceInstUsesWith(SI, V);
  537. return Changed ? &SI : nullptr;
  538. }
  539. /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
  540. /// PHI node (but the two may be in different blocks). See if the true/false
  541. /// values (V) are live in all of the predecessor blocks of the PHI. For
  542. /// example, cases like this cannot be mapped:
  543. ///
  544. /// X = phi [ C1, BB1], [C2, BB2]
  545. /// Y = add
  546. /// Z = select X, Y, 0
  547. ///
  548. /// because Y is not live in BB1/BB2.
  549. ///
  550. static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
  551. const SelectInst &SI) {
  552. // If the value is a non-instruction value like a constant or argument, it
  553. // can always be mapped.
  554. const Instruction *I = dyn_cast<Instruction>(V);
  555. if (!I) return true;
  556. // If V is a PHI node defined in the same block as the condition PHI, we can
  557. // map the arguments.
  558. const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
  559. if (const PHINode *VP = dyn_cast<PHINode>(I))
  560. if (VP->getParent() == CondPHI->getParent())
  561. return true;
  562. // Otherwise, if the PHI and select are defined in the same block and if V is
  563. // defined in a different block, then we can transform it.
  564. if (SI.getParent() == CondPHI->getParent() &&
  565. I->getParent() != CondPHI->getParent())
  566. return true;
  567. // Otherwise we have a 'hard' case and we can't tell without doing more
  568. // detailed dominator based analysis, punt.
  569. return false;
  570. }
  571. /// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
  572. /// SPF2(SPF1(A, B), C)
  573. Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
  574. SelectPatternFlavor SPF1,
  575. Value *A, Value *B,
  576. Instruction &Outer,
  577. SelectPatternFlavor SPF2, Value *C) {
  578. if (C == A || C == B) {
  579. // MAX(MAX(A, B), B) -> MAX(A, B)
  580. // MIN(MIN(a, b), a) -> MIN(a, b)
  581. if (SPF1 == SPF2)
  582. return ReplaceInstUsesWith(Outer, Inner);
  583. // MAX(MIN(a, b), a) -> a
  584. // MIN(MAX(a, b), a) -> a
  585. if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
  586. (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
  587. (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
  588. (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
  589. return ReplaceInstUsesWith(Outer, C);
  590. }
  591. if (SPF1 == SPF2) {
  592. if (ConstantInt *CB = dyn_cast<ConstantInt>(B)) {
  593. if (ConstantInt *CC = dyn_cast<ConstantInt>(C)) {
  594. APInt ACB = CB->getValue();
  595. APInt ACC = CC->getValue();
  596. // MIN(MIN(A, 23), 97) -> MIN(A, 23)
  597. // MAX(MAX(A, 97), 23) -> MAX(A, 97)
  598. if ((SPF1 == SPF_UMIN && ACB.ule(ACC)) ||
  599. (SPF1 == SPF_SMIN && ACB.sle(ACC)) ||
  600. (SPF1 == SPF_UMAX && ACB.uge(ACC)) ||
  601. (SPF1 == SPF_SMAX && ACB.sge(ACC)))
  602. return ReplaceInstUsesWith(Outer, Inner);
  603. // MIN(MIN(A, 97), 23) -> MIN(A, 23)
  604. // MAX(MAX(A, 23), 97) -> MAX(A, 97)
  605. if ((SPF1 == SPF_UMIN && ACB.ugt(ACC)) ||
  606. (SPF1 == SPF_SMIN && ACB.sgt(ACC)) ||
  607. (SPF1 == SPF_UMAX && ACB.ult(ACC)) ||
  608. (SPF1 == SPF_SMAX && ACB.slt(ACC))) {
  609. Outer.replaceUsesOfWith(Inner, A);
  610. return &Outer;
  611. }
  612. }
  613. }
  614. }
  615. // ABS(ABS(X)) -> ABS(X)
  616. // NABS(NABS(X)) -> NABS(X)
  617. if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
  618. return ReplaceInstUsesWith(Outer, Inner);
  619. }
  620. // ABS(NABS(X)) -> ABS(X)
  621. // NABS(ABS(X)) -> NABS(X)
  622. if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
  623. (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
  624. SelectInst *SI = cast<SelectInst>(Inner);
  625. Value *NewSI = Builder->CreateSelect(
  626. SI->getCondition(), SI->getFalseValue(), SI->getTrueValue());
  627. return ReplaceInstUsesWith(Outer, NewSI);
  628. }
  629. auto IsFreeOrProfitableToInvert =
  630. [&](Value *V, Value *&NotV, bool &ElidesXor) {
  631. if (match(V, m_Not(m_Value(NotV)))) {
  632. // If V has at most 2 uses then we can get rid of the xor operation
  633. // entirely.
  634. ElidesXor |= !V->hasNUsesOrMore(3);
  635. return true;
  636. }
  637. if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
  638. NotV = nullptr;
  639. return true;
  640. }
  641. return false;
  642. };
  643. Value *NotA, *NotB, *NotC;
  644. bool ElidesXor = false;
  645. // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
  646. // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
  647. // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
  648. // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
  649. //
  650. // This transform is performance neutral if we can elide at least one xor from
  651. // the set of three operands, since we'll be tacking on an xor at the very
  652. // end.
  653. if (IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
  654. IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
  655. IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
  656. if (!NotA)
  657. NotA = Builder->CreateNot(A);
  658. if (!NotB)
  659. NotB = Builder->CreateNot(B);
  660. if (!NotC)
  661. NotC = Builder->CreateNot(C);
  662. Value *NewInner = generateMinMaxSelectPattern(
  663. Builder, getInverseMinMaxSelectPattern(SPF1), NotA, NotB);
  664. Value *NewOuter = Builder->CreateNot(generateMinMaxSelectPattern(
  665. Builder, getInverseMinMaxSelectPattern(SPF2), NewInner, NotC));
  666. return ReplaceInstUsesWith(Outer, NewOuter);
  667. }
  668. return nullptr;
  669. }
  670. /// foldSelectICmpAnd - If one of the constants is zero (we know they can't
  671. /// both be) and we have an icmp instruction with zero, and we have an 'and'
  672. /// with the non-constant value and a power of two we can turn the select
  673. /// into a shift on the result of the 'and'.
  674. static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
  675. ConstantInt *FalseVal,
  676. InstCombiner::BuilderTy *Builder) {
  677. const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
  678. if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
  679. return nullptr;
  680. if (!match(IC->getOperand(1), m_Zero()))
  681. return nullptr;
  682. ConstantInt *AndRHS;
  683. Value *LHS = IC->getOperand(0);
  684. if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
  685. return nullptr;
  686. // If both select arms are non-zero see if we have a select of the form
  687. // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
  688. // for 'x ? 2^n : 0' and fix the thing up at the end.
  689. ConstantInt *Offset = nullptr;
  690. if (!TrueVal->isZero() && !FalseVal->isZero()) {
  691. if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
  692. Offset = FalseVal;
  693. else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
  694. Offset = TrueVal;
  695. else
  696. return nullptr;
  697. // Adjust TrueVal and FalseVal to the offset.
  698. TrueVal = ConstantInt::get(Builder->getContext(),
  699. TrueVal->getValue() - Offset->getValue());
  700. FalseVal = ConstantInt::get(Builder->getContext(),
  701. FalseVal->getValue() - Offset->getValue());
  702. }
  703. // Make sure the mask in the 'and' and one of the select arms is a power of 2.
  704. if (!AndRHS->getValue().isPowerOf2() ||
  705. (!TrueVal->getValue().isPowerOf2() &&
  706. !FalseVal->getValue().isPowerOf2()))
  707. return nullptr;
  708. // Determine which shift is needed to transform result of the 'and' into the
  709. // desired result.
  710. ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
  711. unsigned ValZeros = ValC->getValue().logBase2();
  712. unsigned AndZeros = AndRHS->getValue().logBase2();
  713. // If types don't match we can still convert the select by introducing a zext
  714. // or a trunc of the 'and'. The trunc case requires that all of the truncated
  715. // bits are zero, we can figure that out by looking at the 'and' mask.
  716. if (AndZeros >= ValC->getBitWidth())
  717. return nullptr;
  718. Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType());
  719. if (ValZeros > AndZeros)
  720. V = Builder->CreateShl(V, ValZeros - AndZeros);
  721. else if (ValZeros < AndZeros)
  722. V = Builder->CreateLShr(V, AndZeros - ValZeros);
  723. // Okay, now we know that everything is set up, we just don't know whether we
  724. // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
  725. bool ShouldNotVal = !TrueVal->isZero();
  726. ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
  727. if (ShouldNotVal)
  728. V = Builder->CreateXor(V, ValC);
  729. // Apply an offset if needed.
  730. if (Offset)
  731. V = Builder->CreateAdd(V, Offset);
  732. return V;
  733. }
  734. Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
  735. Value *CondVal = SI.getCondition();
  736. Value *TrueVal = SI.getTrueValue();
  737. Value *FalseVal = SI.getFalseValue();
  738. if (Value *V =
  739. SimplifySelectInst(CondVal, TrueVal, FalseVal, DL, TLI, DT, AC))
  740. return ReplaceInstUsesWith(SI, V);
  741. if (SI.getType()->isIntegerTy(1)) {
  742. if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
  743. if (C->getZExtValue()) {
  744. // Change: A = select B, true, C --> A = or B, C
  745. return BinaryOperator::CreateOr(CondVal, FalseVal);
  746. }
  747. // Change: A = select B, false, C --> A = and !B, C
  748. Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
  749. return BinaryOperator::CreateAnd(NotCond, FalseVal);
  750. }
  751. if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
  752. if (!C->getZExtValue()) {
  753. // Change: A = select B, C, false --> A = and B, C
  754. return BinaryOperator::CreateAnd(CondVal, TrueVal);
  755. }
  756. // Change: A = select B, C, true --> A = or !B, C
  757. Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
  758. return BinaryOperator::CreateOr(NotCond, TrueVal);
  759. }
  760. // select a, b, a -> a&b
  761. // select a, a, b -> a|b
  762. if (CondVal == TrueVal)
  763. return BinaryOperator::CreateOr(CondVal, FalseVal);
  764. if (CondVal == FalseVal)
  765. return BinaryOperator::CreateAnd(CondVal, TrueVal);
  766. // select a, ~a, b -> (~a)&b
  767. // select a, b, ~a -> (~a)|b
  768. if (match(TrueVal, m_Not(m_Specific(CondVal))))
  769. return BinaryOperator::CreateAnd(TrueVal, FalseVal);
  770. if (match(FalseVal, m_Not(m_Specific(CondVal))))
  771. return BinaryOperator::CreateOr(TrueVal, FalseVal);
  772. }
  773. // Selecting between two integer constants?
  774. if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
  775. if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
  776. // select C, 1, 0 -> zext C to int
  777. if (FalseValC->isZero() && TrueValC->getValue() == 1)
  778. return new ZExtInst(CondVal, SI.getType());
  779. // select C, -1, 0 -> sext C to int
  780. if (FalseValC->isZero() && TrueValC->isAllOnesValue())
  781. return new SExtInst(CondVal, SI.getType());
  782. // select C, 0, 1 -> zext !C to int
  783. if (TrueValC->isZero() && FalseValC->getValue() == 1) {
  784. Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
  785. return new ZExtInst(NotCond, SI.getType());
  786. }
  787. // select C, 0, -1 -> sext !C to int
  788. if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
  789. Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
  790. return new SExtInst(NotCond, SI.getType());
  791. }
  792. if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
  793. return ReplaceInstUsesWith(SI, V);
  794. }
  795. // See if we are selecting two values based on a comparison of the two values.
  796. if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
  797. if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
  798. // Transform (X == Y) ? X : Y -> Y
  799. if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
  800. // This is not safe in general for floating point:
  801. // consider X== -0, Y== +0.
  802. // It becomes safe if either operand is a nonzero constant.
  803. ConstantFP *CFPt, *CFPf;
  804. if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
  805. !CFPt->getValueAPF().isZero()) ||
  806. ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
  807. !CFPf->getValueAPF().isZero()))
  808. return ReplaceInstUsesWith(SI, FalseVal);
  809. }
  810. // Transform (X une Y) ? X : Y -> X
  811. if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
  812. // This is not safe in general for floating point:
  813. // consider X== -0, Y== +0.
  814. // It becomes safe if either operand is a nonzero constant.
  815. ConstantFP *CFPt, *CFPf;
  816. if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
  817. !CFPt->getValueAPF().isZero()) ||
  818. ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
  819. !CFPf->getValueAPF().isZero()))
  820. return ReplaceInstUsesWith(SI, TrueVal);
  821. }
  822. // Canonicalize to use ordered comparisons by swapping the select
  823. // operands.
  824. //
  825. // e.g.
  826. // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
  827. if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
  828. FCmpInst::Predicate InvPred = FCI->getInversePredicate();
  829. Value *NewCond = Builder->CreateFCmp(InvPred, TrueVal, FalseVal,
  830. FCI->getName() + ".inv");
  831. return SelectInst::Create(NewCond, FalseVal, TrueVal,
  832. SI.getName() + ".p");
  833. }
  834. // NOTE: if we wanted to, this is where to detect MIN/MAX
  835. } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
  836. // Transform (X == Y) ? Y : X -> X
  837. if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
  838. // This is not safe in general for floating point:
  839. // consider X== -0, Y== +0.
  840. // It becomes safe if either operand is a nonzero constant.
  841. ConstantFP *CFPt, *CFPf;
  842. if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
  843. !CFPt->getValueAPF().isZero()) ||
  844. ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
  845. !CFPf->getValueAPF().isZero()))
  846. return ReplaceInstUsesWith(SI, FalseVal);
  847. }
  848. // Transform (X une Y) ? Y : X -> Y
  849. if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
  850. // This is not safe in general for floating point:
  851. // consider X== -0, Y== +0.
  852. // It becomes safe if either operand is a nonzero constant.
  853. ConstantFP *CFPt, *CFPf;
  854. if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
  855. !CFPt->getValueAPF().isZero()) ||
  856. ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
  857. !CFPf->getValueAPF().isZero()))
  858. return ReplaceInstUsesWith(SI, TrueVal);
  859. }
  860. // Canonicalize to use ordered comparisons by swapping the select
  861. // operands.
  862. //
  863. // e.g.
  864. // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
  865. if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
  866. FCmpInst::Predicate InvPred = FCI->getInversePredicate();
  867. Value *NewCond = Builder->CreateFCmp(InvPred, FalseVal, TrueVal,
  868. FCI->getName() + ".inv");
  869. return SelectInst::Create(NewCond, FalseVal, TrueVal,
  870. SI.getName() + ".p");
  871. }
  872. // NOTE: if we wanted to, this is where to detect MIN/MAX
  873. }
  874. // NOTE: if we wanted to, this is where to detect ABS
  875. }
  876. // See if we are selecting two values based on a comparison of the two values.
  877. if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
  878. if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
  879. return Result;
  880. if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
  881. if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
  882. if (TI->hasOneUse() && FI->hasOneUse()) {
  883. Instruction *AddOp = nullptr, *SubOp = nullptr;
  884. // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
  885. if (TI->getOpcode() == FI->getOpcode())
  886. if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
  887. return IV;
  888. // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
  889. // even legal for FP.
  890. if ((TI->getOpcode() == Instruction::Sub &&
  891. FI->getOpcode() == Instruction::Add) ||
  892. (TI->getOpcode() == Instruction::FSub &&
  893. FI->getOpcode() == Instruction::FAdd)) {
  894. AddOp = FI; SubOp = TI;
  895. } else if ((FI->getOpcode() == Instruction::Sub &&
  896. TI->getOpcode() == Instruction::Add) ||
  897. (FI->getOpcode() == Instruction::FSub &&
  898. TI->getOpcode() == Instruction::FAdd)) {
  899. AddOp = TI; SubOp = FI;
  900. }
  901. if (AddOp) {
  902. Value *OtherAddOp = nullptr;
  903. if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
  904. OtherAddOp = AddOp->getOperand(1);
  905. } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
  906. OtherAddOp = AddOp->getOperand(0);
  907. }
  908. if (OtherAddOp) {
  909. // So at this point we know we have (Y -> OtherAddOp):
  910. // select C, (add X, Y), (sub X, Z)
  911. Value *NegVal; // Compute -Z
  912. if (SI.getType()->isFPOrFPVectorTy()) {
  913. NegVal = Builder->CreateFNeg(SubOp->getOperand(1));
  914. if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
  915. FastMathFlags Flags = AddOp->getFastMathFlags();
  916. Flags &= SubOp->getFastMathFlags();
  917. NegInst->setFastMathFlags(Flags);
  918. }
  919. } else {
  920. NegVal = Builder->CreateNeg(SubOp->getOperand(1));
  921. }
  922. Value *NewTrueOp = OtherAddOp;
  923. Value *NewFalseOp = NegVal;
  924. if (AddOp != TI)
  925. std::swap(NewTrueOp, NewFalseOp);
  926. Value *NewSel =
  927. Builder->CreateSelect(CondVal, NewTrueOp,
  928. NewFalseOp, SI.getName() + ".p");
  929. if (SI.getType()->isFPOrFPVectorTy()) {
  930. Instruction *RI =
  931. BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
  932. FastMathFlags Flags = AddOp->getFastMathFlags();
  933. Flags &= SubOp->getFastMathFlags();
  934. RI->setFastMathFlags(Flags);
  935. return RI;
  936. } else
  937. return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
  938. }
  939. }
  940. }
  941. // See if we can fold the select into one of our operands.
  942. if (SI.getType()->isIntOrIntVectorTy()) {
  943. if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
  944. return FoldI;
  945. Value *LHS, *RHS, *LHS2, *RHS2;
  946. Instruction::CastOps CastOp;
  947. SelectPatternFlavor SPF = matchSelectPattern(&SI, LHS, RHS, &CastOp);
  948. if (SPF) {
  949. // Canonicalize so that type casts are outside select patterns.
  950. if (LHS->getType()->getPrimitiveSizeInBits() !=
  951. SI.getType()->getPrimitiveSizeInBits()) {
  952. CmpInst::Predicate Pred = getICmpPredicateForMinMax(SPF);
  953. Value *Cmp = Builder->CreateICmp(Pred, LHS, RHS);
  954. Value *NewSI = Builder->CreateCast(CastOp,
  955. Builder->CreateSelect(Cmp, LHS, RHS),
  956. SI.getType());
  957. return ReplaceInstUsesWith(SI, NewSI);
  958. }
  959. // MAX(MAX(a, b), a) -> MAX(a, b)
  960. // MIN(MIN(a, b), a) -> MIN(a, b)
  961. // MAX(MIN(a, b), a) -> a
  962. // MIN(MAX(a, b), a) -> a
  963. if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2))
  964. if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
  965. SI, SPF, RHS))
  966. return R;
  967. if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2))
  968. if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
  969. SI, SPF, LHS))
  970. return R;
  971. }
  972. // MAX(~a, ~b) -> ~MIN(a, b)
  973. if (SPF == SPF_SMAX || SPF == SPF_UMAX) {
  974. if (IsFreeToInvert(LHS, LHS->hasNUses(2)) &&
  975. IsFreeToInvert(RHS, RHS->hasNUses(2))) {
  976. // This transform adds a xor operation and that extra cost needs to be
  977. // justified. We look for simplifications that will result from
  978. // applying this rule:
  979. bool Profitable =
  980. (LHS->hasNUses(2) && match(LHS, m_Not(m_Value()))) ||
  981. (RHS->hasNUses(2) && match(RHS, m_Not(m_Value()))) ||
  982. (SI.hasOneUse() && match(*SI.user_begin(), m_Not(m_Value())));
  983. if (Profitable) {
  984. Value *NewLHS = Builder->CreateNot(LHS);
  985. Value *NewRHS = Builder->CreateNot(RHS);
  986. Value *NewCmp = SPF == SPF_SMAX
  987. ? Builder->CreateICmpSLT(NewLHS, NewRHS)
  988. : Builder->CreateICmpULT(NewLHS, NewRHS);
  989. Value *NewSI =
  990. Builder->CreateNot(Builder->CreateSelect(NewCmp, NewLHS, NewRHS));
  991. return ReplaceInstUsesWith(SI, NewSI);
  992. }
  993. }
  994. }
  995. // TODO.
  996. // ABS(-X) -> ABS(X)
  997. }
  998. // See if we can fold the select into a phi node if the condition is a select.
  999. if (isa<PHINode>(SI.getCondition()))
  1000. // The true/false values have to be live in the PHI predecessor's blocks.
  1001. if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
  1002. CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
  1003. if (Instruction *NV = FoldOpIntoPhi(SI))
  1004. return NV;
  1005. if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
  1006. if (TrueSI->getCondition()->getType() == CondVal->getType()) {
  1007. // select(C, select(C, a, b), c) -> select(C, a, c)
  1008. if (TrueSI->getCondition() == CondVal) {
  1009. if (SI.getTrueValue() == TrueSI->getTrueValue())
  1010. return nullptr;
  1011. SI.setOperand(1, TrueSI->getTrueValue());
  1012. return &SI;
  1013. }
  1014. // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
  1015. // We choose this as normal form to enable folding on the And and shortening
  1016. // paths for the values (this helps GetUnderlyingObjects() for example).
  1017. if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
  1018. Value *And = Builder->CreateAnd(CondVal, TrueSI->getCondition());
  1019. SI.setOperand(0, And);
  1020. SI.setOperand(1, TrueSI->getTrueValue());
  1021. return &SI;
  1022. }
  1023. }
  1024. }
  1025. if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
  1026. if (FalseSI->getCondition()->getType() == CondVal->getType()) {
  1027. // select(C, a, select(C, b, c)) -> select(C, a, c)
  1028. if (FalseSI->getCondition() == CondVal) {
  1029. if (SI.getFalseValue() == FalseSI->getFalseValue())
  1030. return nullptr;
  1031. SI.setOperand(2, FalseSI->getFalseValue());
  1032. return &SI;
  1033. }
  1034. // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
  1035. if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
  1036. Value *Or = Builder->CreateOr(CondVal, FalseSI->getCondition());
  1037. SI.setOperand(0, Or);
  1038. SI.setOperand(2, FalseSI->getFalseValue());
  1039. return &SI;
  1040. }
  1041. }
  1042. }
  1043. if (BinaryOperator::isNot(CondVal)) {
  1044. SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
  1045. SI.setOperand(1, FalseVal);
  1046. SI.setOperand(2, TrueVal);
  1047. return &SI;
  1048. }
  1049. if (VectorType* VecTy = dyn_cast<VectorType>(SI.getType())) {
  1050. unsigned VWidth = VecTy->getNumElements();
  1051. APInt UndefElts(VWidth, 0);
  1052. APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
  1053. if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
  1054. if (V != &SI)
  1055. return ReplaceInstUsesWith(SI, V);
  1056. return &SI;
  1057. }
  1058. if (isa<ConstantAggregateZero>(CondVal)) {
  1059. return ReplaceInstUsesWith(SI, FalseVal);
  1060. }
  1061. }
  1062. return nullptr;
  1063. }