Some whitespace fixes
[oota-llvm.git] / 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/Support/PatternMatch.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 using namespace llvm;
18 using namespace PatternMatch;
19
20 /// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
21 /// returning the kind and providing the out parameter results if we
22 /// successfully match.
23 static SelectPatternFlavor
24 MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
25   SelectInst *SI = dyn_cast<SelectInst>(V);
26   if (SI == 0) return SPF_UNKNOWN;
27
28   ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
29   if (ICI == 0) return SPF_UNKNOWN;
30
31   LHS = ICI->getOperand(0);
32   RHS = ICI->getOperand(1);
33
34   // (icmp X, Y) ? X : Y
35   if (SI->getTrueValue() == ICI->getOperand(0) &&
36       SI->getFalseValue() == ICI->getOperand(1)) {
37     switch (ICI->getPredicate()) {
38     default: return SPF_UNKNOWN; // Equality.
39     case ICmpInst::ICMP_UGT:
40     case ICmpInst::ICMP_UGE: return SPF_UMAX;
41     case ICmpInst::ICMP_SGT:
42     case ICmpInst::ICMP_SGE: return SPF_SMAX;
43     case ICmpInst::ICMP_ULT:
44     case ICmpInst::ICMP_ULE: return SPF_UMIN;
45     case ICmpInst::ICMP_SLT:
46     case ICmpInst::ICMP_SLE: return SPF_SMIN;
47     }
48   }
49
50   // (icmp X, Y) ? Y : X
51   if (SI->getTrueValue() == ICI->getOperand(1) &&
52       SI->getFalseValue() == ICI->getOperand(0)) {
53     switch (ICI->getPredicate()) {
54       default: return SPF_UNKNOWN; // Equality.
55       case ICmpInst::ICMP_UGT:
56       case ICmpInst::ICMP_UGE: return SPF_UMIN;
57       case ICmpInst::ICMP_SGT:
58       case ICmpInst::ICMP_SGE: return SPF_SMIN;
59       case ICmpInst::ICMP_ULT:
60       case ICmpInst::ICMP_ULE: return SPF_UMAX;
61       case ICmpInst::ICMP_SLT:
62       case ICmpInst::ICMP_SLE: return SPF_SMAX;
63     }
64   }
65
66   // TODO: (X > 4) ? X : 5   -->  (X >= 5) ? X : 5  -->  MAX(X, 5)
67
68   return SPF_UNKNOWN;
69 }
70
71
72 /// GetSelectFoldableOperands - We want to turn code that looks like this:
73 ///   %C = or %A, %B
74 ///   %D = select %cond, %C, %A
75 /// into:
76 ///   %C = select %cond, %B, 0
77 ///   %D = or %A, %C
78 ///
79 /// Assuming that the specified instruction is an operand to the select, return
80 /// a bitmask indicating which operands of this instruction are foldable if they
81 /// equal the other incoming value of the select.
82 ///
83 static unsigned GetSelectFoldableOperands(Instruction *I) {
84   switch (I->getOpcode()) {
85   case Instruction::Add:
86   case Instruction::Mul:
87   case Instruction::And:
88   case Instruction::Or:
89   case Instruction::Xor:
90     return 3;              // Can fold through either operand.
91   case Instruction::Sub:   // Can only fold on the amount subtracted.
92   case Instruction::Shl:   // Can only fold on the shift amount.
93   case Instruction::LShr:
94   case Instruction::AShr:
95     return 1;
96   default:
97     return 0;              // Cannot fold
98   }
99 }
100
101 /// GetSelectFoldableConstant - For the same transformation as the previous
102 /// function, return the identity constant that goes into the select.
103 static Constant *GetSelectFoldableConstant(Instruction *I) {
104   switch (I->getOpcode()) {
105   default: llvm_unreachable("This cannot happen!");
106   case Instruction::Add:
107   case Instruction::Sub:
108   case Instruction::Or:
109   case Instruction::Xor:
110   case Instruction::Shl:
111   case Instruction::LShr:
112   case Instruction::AShr:
113     return Constant::getNullValue(I->getType());
114   case Instruction::And:
115     return Constant::getAllOnesValue(I->getType());
116   case Instruction::Mul:
117     return ConstantInt::get(I->getType(), 1);
118   }
119 }
120
121 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
122 /// have the same opcode and only one use each.  Try to simplify this.
123 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
124                                           Instruction *FI) {
125   if (TI->getNumOperands() == 1) {
126     // If this is a non-volatile load or a cast from the same type,
127     // merge.
128     if (TI->isCast()) {
129       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
130         return 0;
131     } else {
132       return 0;  // unknown unary op.
133     }
134
135     // Fold this by inserting a select from the input values.
136     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
137                                           FI->getOperand(0), SI.getName()+".v");
138     InsertNewInstBefore(NewSI, SI);
139     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
140                             TI->getType());
141   }
142
143   // Only handle binary operators here.
144   if (!isa<BinaryOperator>(TI))
145     return 0;
146
147   // Figure out if the operations have any operands in common.
148   Value *MatchOp, *OtherOpT, *OtherOpF;
149   bool MatchIsOpZero;
150   if (TI->getOperand(0) == FI->getOperand(0)) {
151     MatchOp  = TI->getOperand(0);
152     OtherOpT = TI->getOperand(1);
153     OtherOpF = FI->getOperand(1);
154     MatchIsOpZero = true;
155   } else if (TI->getOperand(1) == FI->getOperand(1)) {
156     MatchOp  = TI->getOperand(1);
157     OtherOpT = TI->getOperand(0);
158     OtherOpF = FI->getOperand(0);
159     MatchIsOpZero = false;
160   } else if (!TI->isCommutative()) {
161     return 0;
162   } else if (TI->getOperand(0) == FI->getOperand(1)) {
163     MatchOp  = TI->getOperand(0);
164     OtherOpT = TI->getOperand(1);
165     OtherOpF = FI->getOperand(0);
166     MatchIsOpZero = true;
167   } else if (TI->getOperand(1) == FI->getOperand(0)) {
168     MatchOp  = TI->getOperand(1);
169     OtherOpT = TI->getOperand(0);
170     OtherOpF = FI->getOperand(1);
171     MatchIsOpZero = true;
172   } else {
173     return 0;
174   }
175
176   // If we reach here, they do have operations in common.
177   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
178                                          OtherOpF, SI.getName()+".v");
179   InsertNewInstBefore(NewSI, SI);
180
181   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
182     if (MatchIsOpZero)
183       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
184     else
185       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
186   }
187   llvm_unreachable("Shouldn't get here");
188   return 0;
189 }
190
191 static bool isSelect01(Constant *C1, Constant *C2) {
192   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
193   if (!C1I)
194     return false;
195   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
196   if (!C2I)
197     return false;
198   if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
199     return false;
200   return C1I->isOne() || C1I->isAllOnesValue() ||
201          C2I->isOne() || C2I->isAllOnesValue();
202 }
203
204 /// FoldSelectIntoOp - Try fold the select into one of the operands to
205 /// facilitate further optimization.
206 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
207                                             Value *FalseVal) {
208   // See the comment above GetSelectFoldableOperands for a description of the
209   // transformation we are doing here.
210   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
211     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
212         !isa<Constant>(FalseVal)) {
213       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
214         unsigned OpToFold = 0;
215         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
216           OpToFold = 1;
217         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
218           OpToFold = 2;
219         }
220
221         if (OpToFold) {
222           Constant *C = GetSelectFoldableConstant(TVI);
223           Value *OOp = TVI->getOperand(2-OpToFold);
224           // Avoid creating select between 2 constants unless it's selecting
225           // between 0, 1 and -1.
226           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
227             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
228             InsertNewInstBefore(NewSel, SI);
229             NewSel->takeName(TVI);
230             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
231               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
232             llvm_unreachable("Unknown instruction!!");
233           }
234         }
235       }
236     }
237   }
238
239   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
240     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
241         !isa<Constant>(TrueVal)) {
242       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
243         unsigned OpToFold = 0;
244         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
245           OpToFold = 1;
246         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
247           OpToFold = 2;
248         }
249
250         if (OpToFold) {
251           Constant *C = GetSelectFoldableConstant(FVI);
252           Value *OOp = FVI->getOperand(2-OpToFold);
253           // Avoid creating select between 2 constants unless it's selecting
254           // between 0, 1 and -1.
255           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
256             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
257             InsertNewInstBefore(NewSel, SI);
258             NewSel->takeName(FVI);
259             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
260               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
261             llvm_unreachable("Unknown instruction!!");
262           }
263         }
264       }
265     }
266   }
267
268   return 0;
269 }
270
271 /// visitSelectInstWithICmp - Visit a SelectInst that has an
272 /// ICmpInst as its first operand.
273 ///
274 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
275                                                    ICmpInst *ICI) {
276   bool Changed = false;
277   ICmpInst::Predicate Pred = ICI->getPredicate();
278   Value *CmpLHS = ICI->getOperand(0);
279   Value *CmpRHS = ICI->getOperand(1);
280   Value *TrueVal = SI.getTrueValue();
281   Value *FalseVal = SI.getFalseValue();
282
283   // Check cases where the comparison is with a constant that
284   // can be adjusted to fit the min/max idiom. We may edit ICI in
285   // place here, so make sure the select is the only user.
286   if (ICI->hasOneUse())
287     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
288       switch (Pred) {
289       default: break;
290       case ICmpInst::ICMP_ULT:
291       case ICmpInst::ICMP_SLT: {
292         // X < MIN ? T : F  -->  F
293         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
294           return ReplaceInstUsesWith(SI, FalseVal);
295         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
296         Constant *AdjustedRHS =
297           ConstantInt::get(CI->getContext(), CI->getValue()-1);
298         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
299             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
300           Pred = ICmpInst::getSwappedPredicate(Pred);
301           CmpRHS = AdjustedRHS;
302           std::swap(FalseVal, TrueVal);
303           ICI->setPredicate(Pred);
304           ICI->setOperand(1, CmpRHS);
305           SI.setOperand(1, TrueVal);
306           SI.setOperand(2, FalseVal);
307           Changed = true;
308         }
309         break;
310       }
311       case ICmpInst::ICMP_UGT:
312       case ICmpInst::ICMP_SGT: {
313         // X > MAX ? T : F  -->  F
314         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
315           return ReplaceInstUsesWith(SI, FalseVal);
316         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
317         Constant *AdjustedRHS =
318           ConstantInt::get(CI->getContext(), CI->getValue()+1);
319         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
320             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
321           Pred = ICmpInst::getSwappedPredicate(Pred);
322           CmpRHS = AdjustedRHS;
323           std::swap(FalseVal, TrueVal);
324           ICI->setPredicate(Pred);
325           ICI->setOperand(1, CmpRHS);
326           SI.setOperand(1, TrueVal);
327           SI.setOperand(2, FalseVal);
328           Changed = true;
329         }
330         break;
331       }
332       }
333     }
334
335   // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
336   // and       (X <s  0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
337   // FIXME: Type and constness constraints could be lifted, but we have to
338   //        watch code size carefully. We should consider xor instead of
339   //        sub/add when we decide to do that.
340   if (const IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
341     if (TrueVal->getType() == Ty) {
342       if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
343         ConstantInt *C1 = NULL, *C2 = NULL;
344         if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
345           C1 = dyn_cast<ConstantInt>(TrueVal);
346           C2 = dyn_cast<ConstantInt>(FalseVal);
347         } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
348           C1 = dyn_cast<ConstantInt>(FalseVal);
349           C2 = dyn_cast<ConstantInt>(TrueVal);
350         }
351         if (C1 && C2) {
352           // This shift results in either -1 or 0.
353           Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
354
355           // Check if we can express the operation with a single or.
356           if (C2->isAllOnesValue())
357             return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
358
359           Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
360           return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
361         }
362       }
363     }
364   }
365
366   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
367     // Transform (X == Y) ? X : Y  -> Y
368     if (Pred == ICmpInst::ICMP_EQ)
369       return ReplaceInstUsesWith(SI, FalseVal);
370     // Transform (X != Y) ? X : Y  -> X
371     if (Pred == ICmpInst::ICMP_NE)
372       return ReplaceInstUsesWith(SI, TrueVal);
373     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
374
375   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
376     // Transform (X == Y) ? Y : X  -> X
377     if (Pred == ICmpInst::ICMP_EQ)
378       return ReplaceInstUsesWith(SI, FalseVal);
379     // Transform (X != Y) ? Y : X  -> Y
380     if (Pred == ICmpInst::ICMP_NE)
381       return ReplaceInstUsesWith(SI, TrueVal);
382     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
383   }
384   return Changed ? &SI : 0;
385 }
386
387
388 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
389 /// PHI node (but the two may be in different blocks).  See if the true/false
390 /// values (V) are live in all of the predecessor blocks of the PHI.  For
391 /// example, cases like this cannot be mapped:
392 ///
393 ///   X = phi [ C1, BB1], [C2, BB2]
394 ///   Y = add
395 ///   Z = select X, Y, 0
396 ///
397 /// because Y is not live in BB1/BB2.
398 ///
399 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
400                                                    const SelectInst &SI) {
401   // If the value is a non-instruction value like a constant or argument, it
402   // can always be mapped.
403   const Instruction *I = dyn_cast<Instruction>(V);
404   if (I == 0) return true;
405
406   // If V is a PHI node defined in the same block as the condition PHI, we can
407   // map the arguments.
408   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
409
410   if (const PHINode *VP = dyn_cast<PHINode>(I))
411     if (VP->getParent() == CondPHI->getParent())
412       return true;
413
414   // Otherwise, if the PHI and select are defined in the same block and if V is
415   // defined in a different block, then we can transform it.
416   if (SI.getParent() == CondPHI->getParent() &&
417       I->getParent() != CondPHI->getParent())
418     return true;
419
420   // Otherwise we have a 'hard' case and we can't tell without doing more
421   // detailed dominator based analysis, punt.
422   return false;
423 }
424
425 /// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
426 ///   SPF2(SPF1(A, B), C)
427 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
428                                         SelectPatternFlavor SPF1,
429                                         Value *A, Value *B,
430                                         Instruction &Outer,
431                                         SelectPatternFlavor SPF2, Value *C) {
432   if (C == A || C == B) {
433     // MAX(MAX(A, B), B) -> MAX(A, B)
434     // MIN(MIN(a, b), a) -> MIN(a, b)
435     if (SPF1 == SPF2)
436       return ReplaceInstUsesWith(Outer, Inner);
437
438     // MAX(MIN(a, b), a) -> a
439     // MIN(MAX(a, b), a) -> a
440     if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
441         (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
442         (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
443         (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
444       return ReplaceInstUsesWith(Outer, C);
445   }
446
447   // TODO: MIN(MIN(A, 23), 97)
448   return 0;
449 }
450
451
452 /// foldSelectICmpAnd - If one of the constants is zero (we know they can't
453 /// both be) and we have an icmp instruction with zero, and we have an 'and'
454 /// with the non-constant value and a power of two we can turn the select
455 /// into a shift on the result of the 'and'.
456 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
457                                 ConstantInt *FalseVal,
458                                 InstCombiner::BuilderTy *Builder) {
459   const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
460   if (!IC || !IC->isEquality())
461     return 0;
462
463   if (ConstantInt *C = dyn_cast<ConstantInt>(IC->getOperand(1)))
464     if (!C->isZero())
465       return 0;
466
467   ConstantInt *AndRHS;
468   Value *LHS = IC->getOperand(0);
469   if (LHS->getType() != SI.getType() ||
470       !match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
471     return 0;
472
473   // If both select arms are non-zero see if we have a select of the form
474   // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
475   // for 'x ? 2^n : 0' and fix the thing up at the end.
476   ConstantInt *Offset = 0;
477   if (!TrueVal->isZero() && !FalseVal->isZero()) {
478     if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
479       Offset = FalseVal;
480     else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
481       Offset = TrueVal;
482     else
483       return 0;
484
485     // Adjust TrueVal and FalseVal to the offset.
486     TrueVal = ConstantInt::get(Builder->getContext(),
487                                TrueVal->getValue() - Offset->getValue());
488     FalseVal = ConstantInt::get(Builder->getContext(),
489                                 FalseVal->getValue() - Offset->getValue());
490   }
491
492   // Make sure the mask in the 'and' and one of the select arms is a power of 2.
493   if (!AndRHS->getValue().isPowerOf2() ||
494       (!TrueVal->getValue().isPowerOf2() &&
495        !FalseVal->getValue().isPowerOf2()))
496     return 0;
497
498   // Determine which shift is needed to transform result of the 'and' into the
499   // desired result.
500   ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
501   unsigned ValZeros = ValC->getValue().logBase2();
502   unsigned AndZeros = AndRHS->getValue().logBase2();
503
504   Value *V = LHS;
505   if (ValZeros > AndZeros)
506     V = Builder->CreateShl(V, ValZeros - AndZeros);
507   else if (ValZeros < AndZeros)
508     V = Builder->CreateLShr(V, AndZeros - ValZeros);
509
510   // Okay, now we know that everything is set up, we just don't know whether we
511   // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
512   bool ShouldNotVal = !TrueVal->isZero();
513   ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
514   if (ShouldNotVal)
515     V = Builder->CreateXor(V, ValC);
516
517   // Apply an offset if needed.
518   if (Offset)
519     V = Builder->CreateAdd(V, Offset);
520   return V;
521 }
522
523 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
524   Value *CondVal = SI.getCondition();
525   Value *TrueVal = SI.getTrueValue();
526   Value *FalseVal = SI.getFalseValue();
527
528   if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, TD))
529     return ReplaceInstUsesWith(SI, V);
530
531   if (SI.getType()->isIntegerTy(1)) {
532     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
533       if (C->getZExtValue()) {
534         // Change: A = select B, true, C --> A = or B, C
535         return BinaryOperator::CreateOr(CondVal, FalseVal);
536       }
537       // Change: A = select B, false, C --> A = and !B, C
538       Value *NotCond =
539         InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
540                                            "not."+CondVal->getName()), SI);
541       return BinaryOperator::CreateAnd(NotCond, FalseVal);
542     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
543       if (C->getZExtValue() == false) {
544         // Change: A = select B, C, false --> A = and B, C
545         return BinaryOperator::CreateAnd(CondVal, TrueVal);
546       }
547       // Change: A = select B, C, true --> A = or !B, C
548       Value *NotCond =
549         InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
550                                            "not."+CondVal->getName()), SI);
551       return BinaryOperator::CreateOr(NotCond, TrueVal);
552     }
553
554     // select a, b, a  -> a&b
555     // select a, a, b  -> a|b
556     if (CondVal == TrueVal)
557       return BinaryOperator::CreateOr(CondVal, FalseVal);
558     else if (CondVal == FalseVal)
559       return BinaryOperator::CreateAnd(CondVal, TrueVal);
560   }
561
562   // Selecting between two integer constants?
563   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
564     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
565       // select C, 1, 0 -> zext C to int
566       if (FalseValC->isZero() && TrueValC->getValue() == 1)
567         return new ZExtInst(CondVal, SI.getType());
568
569       // select C, -1, 0 -> sext C to int
570       if (FalseValC->isZero() && TrueValC->isAllOnesValue())
571         return new SExtInst(CondVal, SI.getType());
572
573       // select C, 0, 1 -> zext !C to int
574       if (TrueValC->isZero() && FalseValC->getValue() == 1) {
575         Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
576         return new ZExtInst(NotCond, SI.getType());
577       }
578
579       // select C, 0, -1 -> sext !C to int
580       if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
581         Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
582         return new SExtInst(NotCond, SI.getType());
583       }
584
585       if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
586         return ReplaceInstUsesWith(SI, V);
587     }
588
589   // See if we are selecting two values based on a comparison of the two values.
590   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
591     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
592       // Transform (X == Y) ? X : Y  -> Y
593       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
594         // This is not safe in general for floating point:
595         // consider X== -0, Y== +0.
596         // It becomes safe if either operand is a nonzero constant.
597         ConstantFP *CFPt, *CFPf;
598         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
599               !CFPt->getValueAPF().isZero()) ||
600             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
601              !CFPf->getValueAPF().isZero()))
602         return ReplaceInstUsesWith(SI, FalseVal);
603       }
604       // Transform (X une Y) ? X : Y  -> X
605       if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
606         // This is not safe in general for floating point:
607         // consider X== -0, Y== +0.
608         // It becomes safe if either operand is a nonzero constant.
609         ConstantFP *CFPt, *CFPf;
610         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
611               !CFPt->getValueAPF().isZero()) ||
612             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
613              !CFPf->getValueAPF().isZero()))
614         return ReplaceInstUsesWith(SI, TrueVal);
615       }
616       // NOTE: if we wanted to, this is where to detect MIN/MAX
617
618     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
619       // Transform (X == Y) ? Y : X  -> X
620       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
621         // This is not safe in general for floating point:
622         // consider X== -0, Y== +0.
623         // It becomes safe if either operand is a nonzero constant.
624         ConstantFP *CFPt, *CFPf;
625         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
626               !CFPt->getValueAPF().isZero()) ||
627             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
628              !CFPf->getValueAPF().isZero()))
629           return ReplaceInstUsesWith(SI, FalseVal);
630       }
631       // Transform (X une Y) ? Y : X  -> Y
632       if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
633         // This is not safe in general for floating point:
634         // consider X== -0, Y== +0.
635         // It becomes safe if either operand is a nonzero constant.
636         ConstantFP *CFPt, *CFPf;
637         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
638               !CFPt->getValueAPF().isZero()) ||
639             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
640              !CFPf->getValueAPF().isZero()))
641           return ReplaceInstUsesWith(SI, TrueVal);
642       }
643       // NOTE: if we wanted to, this is where to detect MIN/MAX
644     }
645     // NOTE: if we wanted to, this is where to detect ABS
646   }
647
648   // See if we are selecting two values based on a comparison of the two values.
649   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
650     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
651       return Result;
652
653   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
654     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
655       if (TI->hasOneUse() && FI->hasOneUse()) {
656         Instruction *AddOp = 0, *SubOp = 0;
657
658         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
659         if (TI->getOpcode() == FI->getOpcode())
660           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
661             return IV;
662
663         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
664         // even legal for FP.
665         if ((TI->getOpcode() == Instruction::Sub &&
666              FI->getOpcode() == Instruction::Add) ||
667             (TI->getOpcode() == Instruction::FSub &&
668              FI->getOpcode() == Instruction::FAdd)) {
669           AddOp = FI; SubOp = TI;
670         } else if ((FI->getOpcode() == Instruction::Sub &&
671                     TI->getOpcode() == Instruction::Add) ||
672                    (FI->getOpcode() == Instruction::FSub &&
673                     TI->getOpcode() == Instruction::FAdd)) {
674           AddOp = TI; SubOp = FI;
675         }
676
677         if (AddOp) {
678           Value *OtherAddOp = 0;
679           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
680             OtherAddOp = AddOp->getOperand(1);
681           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
682             OtherAddOp = AddOp->getOperand(0);
683           }
684
685           if (OtherAddOp) {
686             // So at this point we know we have (Y -> OtherAddOp):
687             //        select C, (add X, Y), (sub X, Z)
688             Value *NegVal;  // Compute -Z
689             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
690               NegVal = ConstantExpr::getNeg(C);
691             } else if (SI.getType()->isFloatingPointTy()) {
692               NegVal = InsertNewInstBefore(
693                     BinaryOperator::CreateFNeg(SubOp->getOperand(1),
694                                               "tmp"), SI);
695             } else {
696               NegVal = InsertNewInstBefore(
697                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
698                                               "tmp"), SI);
699             }
700
701             Value *NewTrueOp = OtherAddOp;
702             Value *NewFalseOp = NegVal;
703             if (AddOp != TI)
704               std::swap(NewTrueOp, NewFalseOp);
705             Instruction *NewSel =
706               SelectInst::Create(CondVal, NewTrueOp,
707                                  NewFalseOp, SI.getName() + ".p");
708
709             NewSel = InsertNewInstBefore(NewSel, SI);
710             if (SI.getType()->isFloatingPointTy())
711               return BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
712             else
713               return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
714           }
715         }
716       }
717
718   // See if we can fold the select into one of our operands.
719   if (SI.getType()->isIntegerTy()) {
720     if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
721       return FoldI;
722
723     // MAX(MAX(a, b), a) -> MAX(a, b)
724     // MIN(MIN(a, b), a) -> MIN(a, b)
725     // MAX(MIN(a, b), a) -> a
726     // MIN(MAX(a, b), a) -> a
727     Value *LHS, *RHS, *LHS2, *RHS2;
728     if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
729       if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
730         if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2, 
731                                           SI, SPF, RHS))
732           return R;
733       if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
734         if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
735                                           SI, SPF, LHS))
736           return R;
737     }
738
739     // TODO.
740     // ABS(-X) -> ABS(X)
741     // ABS(ABS(X)) -> ABS(X)
742   }
743
744   // See if we can fold the select into a phi node if the condition is a select.
745   if (isa<PHINode>(SI.getCondition()))
746     // The true/false values have to be live in the PHI predecessor's blocks.
747     if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
748         CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
749       if (Instruction *NV = FoldOpIntoPhi(SI))
750         return NV;
751
752   if (BinaryOperator::isNot(CondVal)) {
753     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
754     SI.setOperand(1, FalseVal);
755     SI.setOperand(2, TrueVal);
756     return &SI;
757   }
758
759   return 0;
760 }