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