split call handling out to InstCombineCalls.cpp
[oota-llvm.git] / lib / Transforms / InstCombine / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
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 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG.  This pass is where
12 // algebraic simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "InstCombine.h"
39 #include "llvm/IntrinsicInst.h"
40 #include "llvm/LLVMContext.h"
41 #include "llvm/DerivedTypes.h"
42 #include "llvm/GlobalVariable.h"
43 #include "llvm/Operator.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Analysis/InstructionSimplify.h"
46 #include "llvm/Analysis/MemoryBuiltins.h"
47 #include "llvm/Target/TargetData.h"
48 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
49 #include "llvm/Transforms/Utils/Local.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/GetElementPtrTypeIterator.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/PatternMatch.h"
55 #include "llvm/ADT/SmallPtrSet.h"
56 #include "llvm/ADT/Statistic.h"
57 #include "llvm/ADT/STLExtras.h"
58 #include <algorithm>
59 #include <climits>
60 using namespace llvm;
61 using namespace llvm::PatternMatch;
62
63 STATISTIC(NumCombined , "Number of insts combined");
64 STATISTIC(NumConstProp, "Number of constant folds");
65 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
66 STATISTIC(NumSunkInst , "Number of instructions sunk");
67
68
69 char InstCombiner::ID = 0;
70 static RegisterPass<InstCombiner>
71 X("instcombine", "Combine redundant instructions");
72
73 void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
74   AU.addPreservedID(LCSSAID);
75   AU.setPreservesCFG();
76 }
77
78
79 /// ShouldChangeType - Return true if it is desirable to convert a computation
80 /// from 'From' to 'To'.  We don't want to convert from a legal to an illegal
81 /// type for example, or from a smaller to a larger illegal type.
82 bool InstCombiner::ShouldChangeType(const Type *From, const Type *To) const {
83   assert(isa<IntegerType>(From) && isa<IntegerType>(To));
84   
85   // If we don't have TD, we don't know if the source/dest are legal.
86   if (!TD) return false;
87   
88   unsigned FromWidth = From->getPrimitiveSizeInBits();
89   unsigned ToWidth = To->getPrimitiveSizeInBits();
90   bool FromLegal = TD->isLegalInteger(FromWidth);
91   bool ToLegal = TD->isLegalInteger(ToWidth);
92   
93   // If this is a legal integer from type, and the result would be an illegal
94   // type, don't do the transformation.
95   if (FromLegal && !ToLegal)
96     return false;
97   
98   // Otherwise, if both are illegal, do not increase the size of the result. We
99   // do allow things like i160 -> i64, but not i64 -> i160.
100   if (!FromLegal && !ToLegal && ToWidth > FromWidth)
101     return false;
102   
103   return true;
104 }
105
106 /// getBitCastOperand - If the specified operand is a CastInst, a constant
107 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
108 /// operand value, otherwise return null.
109
110 // FIXME: Value::stripPointerCasts
111 static Value *getBitCastOperand(Value *V) {
112   if (Operator *O = dyn_cast<Operator>(V)) {
113     if (O->getOpcode() == Instruction::BitCast)
114       return O->getOperand(0);
115     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
116       if (GEP->hasAllZeroIndices())
117         return GEP->getPointerOperand();
118   }
119   return 0;
120 }
121
122
123
124 // SimplifyCommutative - This performs a few simplifications for commutative
125 // operators:
126 //
127 //  1. Order operands such that they are listed from right (least complex) to
128 //     left (most complex).  This puts constants before unary operators before
129 //     binary operators.
130 //
131 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
132 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
133 //
134 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
135   bool Changed = false;
136   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
137     Changed = !I.swapOperands();
138
139   if (!I.isAssociative()) return Changed;
140   
141   Instruction::BinaryOps Opcode = I.getOpcode();
142   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
143     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
144       if (isa<Constant>(I.getOperand(1))) {
145         Constant *Folded = ConstantExpr::get(I.getOpcode(),
146                                              cast<Constant>(I.getOperand(1)),
147                                              cast<Constant>(Op->getOperand(1)));
148         I.setOperand(0, Op->getOperand(0));
149         I.setOperand(1, Folded);
150         return true;
151       }
152       
153       if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1)))
154         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
155             Op->hasOneUse() && Op1->hasOneUse()) {
156           Constant *C1 = cast<Constant>(Op->getOperand(1));
157           Constant *C2 = cast<Constant>(Op1->getOperand(1));
158
159           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
160           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
161           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
162                                                     Op1->getOperand(0),
163                                                     Op1->getName(), &I);
164           Worklist.Add(New);
165           I.setOperand(0, New);
166           I.setOperand(1, Folded);
167           return true;
168         }
169     }
170   return Changed;
171 }
172
173 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
174 // if the LHS is a constant zero (which is the 'negate' form).
175 //
176 Value *InstCombiner::dyn_castNegVal(Value *V) const {
177   if (BinaryOperator::isNeg(V))
178     return BinaryOperator::getNegArgument(V);
179
180   // Constants can be considered to be negated values if they can be folded.
181   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
182     return ConstantExpr::getNeg(C);
183
184   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
185     if (C->getType()->getElementType()->isInteger())
186       return ConstantExpr::getNeg(C);
187
188   return 0;
189 }
190
191 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
192 // instruction if the LHS is a constant negative zero (which is the 'negate'
193 // form).
194 //
195 Value *InstCombiner::dyn_castFNegVal(Value *V) const {
196   if (BinaryOperator::isFNeg(V))
197     return BinaryOperator::getFNegArgument(V);
198
199   // Constants can be considered to be negated values if they can be folded.
200   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
201     return ConstantExpr::getFNeg(C);
202
203   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
204     if (C->getType()->getElementType()->isFloatingPoint())
205       return ConstantExpr::getFNeg(C);
206
207   return 0;
208 }
209
210 /// isFreeToInvert - Return true if the specified value is free to invert (apply
211 /// ~ to).  This happens in cases where the ~ can be eliminated.
212 static inline bool isFreeToInvert(Value *V) {
213   // ~(~(X)) -> X.
214   if (BinaryOperator::isNot(V))
215     return true;
216   
217   // Constants can be considered to be not'ed values.
218   if (isa<ConstantInt>(V))
219     return true;
220   
221   // Compares can be inverted if they have a single use.
222   if (CmpInst *CI = dyn_cast<CmpInst>(V))
223     return CI->hasOneUse();
224   
225   return false;
226 }
227
228 static inline Value *dyn_castNotVal(Value *V) {
229   // If this is not(not(x)) don't return that this is a not: we want the two
230   // not's to be folded first.
231   if (BinaryOperator::isNot(V)) {
232     Value *Operand = BinaryOperator::getNotArgument(V);
233     if (!isFreeToInvert(Operand))
234       return Operand;
235   }
236
237   // Constants can be considered to be not'ed values...
238   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
239     return ConstantInt::get(C->getType(), ~C->getValue());
240   return 0;
241 }
242
243
244
245 /// AddOne - Add one to a ConstantInt.
246 static Constant *AddOne(Constant *C) {
247   return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
248 }
249 /// SubOne - Subtract one from a ConstantInt.
250 static Constant *SubOne(ConstantInt *C) {
251   return ConstantInt::get(C->getContext(), C->getValue()-1);
252 }
253
254
255 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
256                                              InstCombiner *IC) {
257   if (CastInst *CI = dyn_cast<CastInst>(&I))
258     return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
259
260   // Figure out if the constant is the left or the right argument.
261   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
262   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
263
264   if (Constant *SOC = dyn_cast<Constant>(SO)) {
265     if (ConstIsRHS)
266       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
267     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
268   }
269
270   Value *Op0 = SO, *Op1 = ConstOperand;
271   if (!ConstIsRHS)
272     std::swap(Op0, Op1);
273   
274   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
275     return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
276                                     SO->getName()+".op");
277   if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
278     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
279                                    SO->getName()+".cmp");
280   if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
281     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
282                                    SO->getName()+".cmp");
283   llvm_unreachable("Unknown binary instruction type!");
284 }
285
286 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
287 // constant as the other operand, try to fold the binary operator into the
288 // select arguments.  This also works for Cast instructions, which obviously do
289 // not have a second operand.
290 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
291   // Don't modify shared select instructions
292   if (!SI->hasOneUse()) return 0;
293   Value *TV = SI->getOperand(1);
294   Value *FV = SI->getOperand(2);
295
296   if (isa<Constant>(TV) || isa<Constant>(FV)) {
297     // Bool selects with constant operands can be folded to logical ops.
298     if (SI->getType() == Type::getInt1Ty(SI->getContext())) return 0;
299
300     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
301     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
302
303     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
304                               SelectFalseVal);
305   }
306   return 0;
307 }
308
309
310 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
311 /// has a PHI node as operand #0, see if we can fold the instruction into the
312 /// PHI (which is only possible if all operands to the PHI are constants).
313 ///
314 /// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
315 /// that would normally be unprofitable because they strongly encourage jump
316 /// threading.
317 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
318                                          bool AllowAggressive) {
319   AllowAggressive = false;
320   PHINode *PN = cast<PHINode>(I.getOperand(0));
321   unsigned NumPHIValues = PN->getNumIncomingValues();
322   if (NumPHIValues == 0 ||
323       // We normally only transform phis with a single use, unless we're trying
324       // hard to make jump threading happen.
325       (!PN->hasOneUse() && !AllowAggressive))
326     return 0;
327   
328   
329   // Check to see if all of the operands of the PHI are simple constants
330   // (constantint/constantfp/undef).  If there is one non-constant value,
331   // remember the BB it is in.  If there is more than one or if *it* is a PHI,
332   // bail out.  We don't do arbitrary constant expressions here because moving
333   // their computation can be expensive without a cost model.
334   BasicBlock *NonConstBB = 0;
335   for (unsigned i = 0; i != NumPHIValues; ++i)
336     if (!isa<Constant>(PN->getIncomingValue(i)) ||
337         isa<ConstantExpr>(PN->getIncomingValue(i))) {
338       if (NonConstBB) return 0;  // More than one non-const value.
339       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
340       NonConstBB = PN->getIncomingBlock(i);
341       
342       // If the incoming non-constant value is in I's block, we have an infinite
343       // loop.
344       if (NonConstBB == I.getParent())
345         return 0;
346     }
347   
348   // If there is exactly one non-constant value, we can insert a copy of the
349   // operation in that block.  However, if this is a critical edge, we would be
350   // inserting the computation one some other paths (e.g. inside a loop).  Only
351   // do this if the pred block is unconditionally branching into the phi block.
352   if (NonConstBB != 0 && !AllowAggressive) {
353     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
354     if (!BI || !BI->isUnconditional()) return 0;
355   }
356
357   // Okay, we can do the transformation: create the new PHI node.
358   PHINode *NewPN = PHINode::Create(I.getType(), "");
359   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
360   InsertNewInstBefore(NewPN, *PN);
361   NewPN->takeName(PN);
362
363   // Next, add all of the operands to the PHI.
364   if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
365     // We only currently try to fold the condition of a select when it is a phi,
366     // not the true/false values.
367     Value *TrueV = SI->getTrueValue();
368     Value *FalseV = SI->getFalseValue();
369     BasicBlock *PhiTransBB = PN->getParent();
370     for (unsigned i = 0; i != NumPHIValues; ++i) {
371       BasicBlock *ThisBB = PN->getIncomingBlock(i);
372       Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
373       Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
374       Value *InV = 0;
375       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
376         InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
377       } else {
378         assert(PN->getIncomingBlock(i) == NonConstBB);
379         InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
380                                  FalseVInPred,
381                                  "phitmp", NonConstBB->getTerminator());
382         Worklist.Add(cast<Instruction>(InV));
383       }
384       NewPN->addIncoming(InV, ThisBB);
385     }
386   } else if (I.getNumOperands() == 2) {
387     Constant *C = cast<Constant>(I.getOperand(1));
388     for (unsigned i = 0; i != NumPHIValues; ++i) {
389       Value *InV = 0;
390       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
391         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
392           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
393         else
394           InV = ConstantExpr::get(I.getOpcode(), InC, C);
395       } else {
396         assert(PN->getIncomingBlock(i) == NonConstBB);
397         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
398           InV = BinaryOperator::Create(BO->getOpcode(),
399                                        PN->getIncomingValue(i), C, "phitmp",
400                                        NonConstBB->getTerminator());
401         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
402           InV = CmpInst::Create(CI->getOpcode(),
403                                 CI->getPredicate(),
404                                 PN->getIncomingValue(i), C, "phitmp",
405                                 NonConstBB->getTerminator());
406         else
407           llvm_unreachable("Unknown binop!");
408         
409         Worklist.Add(cast<Instruction>(InV));
410       }
411       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
412     }
413   } else { 
414     CastInst *CI = cast<CastInst>(&I);
415     const Type *RetTy = CI->getType();
416     for (unsigned i = 0; i != NumPHIValues; ++i) {
417       Value *InV;
418       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
419         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
420       } else {
421         assert(PN->getIncomingBlock(i) == NonConstBB);
422         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
423                                I.getType(), "phitmp", 
424                                NonConstBB->getTerminator());
425         Worklist.Add(cast<Instruction>(InV));
426       }
427       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
428     }
429   }
430   return ReplaceInstUsesWith(I, NewPN);
431 }
432
433
434 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
435 /// are carefully arranged to allow folding of expressions such as:
436 ///
437 ///      (A < B) | (A > B) --> (A != B)
438 ///
439 /// Note that this is only valid if the first and second predicates have the
440 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
441 ///
442 /// Three bits are used to represent the condition, as follows:
443 ///   0  A > B
444 ///   1  A == B
445 ///   2  A < B
446 ///
447 /// <=>  Value  Definition
448 /// 000     0   Always false
449 /// 001     1   A >  B
450 /// 010     2   A == B
451 /// 011     3   A >= B
452 /// 100     4   A <  B
453 /// 101     5   A != B
454 /// 110     6   A <= B
455 /// 111     7   Always true
456 ///  
457 static unsigned getICmpCode(const ICmpInst *ICI) {
458   switch (ICI->getPredicate()) {
459     // False -> 0
460   case ICmpInst::ICMP_UGT: return 1;  // 001
461   case ICmpInst::ICMP_SGT: return 1;  // 001
462   case ICmpInst::ICMP_EQ:  return 2;  // 010
463   case ICmpInst::ICMP_UGE: return 3;  // 011
464   case ICmpInst::ICMP_SGE: return 3;  // 011
465   case ICmpInst::ICMP_ULT: return 4;  // 100
466   case ICmpInst::ICMP_SLT: return 4;  // 100
467   case ICmpInst::ICMP_NE:  return 5;  // 101
468   case ICmpInst::ICMP_ULE: return 6;  // 110
469   case ICmpInst::ICMP_SLE: return 6;  // 110
470     // True -> 7
471   default:
472     llvm_unreachable("Invalid ICmp predicate!");
473     return 0;
474   }
475 }
476
477 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
478 /// predicate into a three bit mask. It also returns whether it is an ordered
479 /// predicate by reference.
480 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
481   isOrdered = false;
482   switch (CC) {
483   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
484   case FCmpInst::FCMP_UNO:                   return 0;  // 000
485   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
486   case FCmpInst::FCMP_UGT:                   return 1;  // 001
487   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
488   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
489   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
490   case FCmpInst::FCMP_UGE:                   return 3;  // 011
491   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
492   case FCmpInst::FCMP_ULT:                   return 4;  // 100
493   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
494   case FCmpInst::FCMP_UNE:                   return 5;  // 101
495   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
496   case FCmpInst::FCMP_ULE:                   return 6;  // 110
497     // True -> 7
498   default:
499     // Not expecting FCMP_FALSE and FCMP_TRUE;
500     llvm_unreachable("Unexpected FCmp predicate!");
501     return 0;
502   }
503 }
504
505 /// getICmpValue - This is the complement of getICmpCode, which turns an
506 /// opcode and two operands into either a constant true or false, or a brand 
507 /// new ICmp instruction. The sign is passed in to determine which kind
508 /// of predicate to use in the new icmp instruction.
509 static Value *getICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS) {
510   switch (Code) {
511   default: assert(0 && "Illegal ICmp code!");
512   case 0:
513     return ConstantInt::getFalse(LHS->getContext());
514   case 1: 
515     if (Sign)
516       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
517     return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
518   case 2:
519     return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
520   case 3: 
521     if (Sign)
522       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
523     return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
524   case 4: 
525     if (Sign)
526       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
527     return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
528   case 5:
529     return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
530   case 6: 
531     if (Sign)
532       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
533     return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
534   case 7:
535     return ConstantInt::getTrue(LHS->getContext());
536   }
537 }
538
539 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
540 /// opcode and two operands into either a FCmp instruction. isordered is passed
541 /// in to determine which kind of predicate to use in the new fcmp instruction.
542 static Value *getFCmpValue(bool isordered, unsigned code,
543                            Value *LHS, Value *RHS) {
544   switch (code) {
545   default: llvm_unreachable("Illegal FCmp code!");
546   case  0:
547     if (isordered)
548       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
549     else
550       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
551   case  1: 
552     if (isordered)
553       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
554     else
555       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
556   case  2: 
557     if (isordered)
558       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
559     else
560       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
561   case  3: 
562     if (isordered)
563       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
564     else
565       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
566   case  4: 
567     if (isordered)
568       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
569     else
570       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
571   case  5: 
572     if (isordered)
573       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
574     else
575       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
576   case  6: 
577     if (isordered)
578       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
579     else
580       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
581   case  7: return ConstantInt::getTrue(LHS->getContext());
582   }
583 }
584
585 /// PredicatesFoldable - Return true if both predicates match sign or if at
586 /// least one of them is an equality comparison (which is signless).
587 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
588   return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
589          (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
590          (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
591 }
592
593 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
594 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
595 // guaranteed to be a binary operator.
596 Instruction *InstCombiner::OptAndOp(Instruction *Op,
597                                     ConstantInt *OpRHS,
598                                     ConstantInt *AndRHS,
599                                     BinaryOperator &TheAnd) {
600   Value *X = Op->getOperand(0);
601   Constant *Together = 0;
602   if (!Op->isShift())
603     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
604
605   switch (Op->getOpcode()) {
606   case Instruction::Xor:
607     if (Op->hasOneUse()) {
608       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
609       Value *And = Builder->CreateAnd(X, AndRHS);
610       And->takeName(Op);
611       return BinaryOperator::CreateXor(And, Together);
612     }
613     break;
614   case Instruction::Or:
615     if (Together == AndRHS) // (X | C) & C --> C
616       return ReplaceInstUsesWith(TheAnd, AndRHS);
617
618     if (Op->hasOneUse() && Together != OpRHS) {
619       // (X | C1) & C2 --> (X | (C1&C2)) & C2
620       Value *Or = Builder->CreateOr(X, Together);
621       Or->takeName(Op);
622       return BinaryOperator::CreateAnd(Or, AndRHS);
623     }
624     break;
625   case Instruction::Add:
626     if (Op->hasOneUse()) {
627       // Adding a one to a single bit bit-field should be turned into an XOR
628       // of the bit.  First thing to check is to see if this AND is with a
629       // single bit constant.
630       const APInt &AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
631
632       // If there is only one bit set.
633       if (AndRHSV.isPowerOf2()) {
634         // Ok, at this point, we know that we are masking the result of the
635         // ADD down to exactly one bit.  If the constant we are adding has
636         // no bits set below this bit, then we can eliminate the ADD.
637         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
638
639         // Check to see if any bits below the one bit set in AndRHSV are set.
640         if ((AddRHS & (AndRHSV-1)) == 0) {
641           // If not, the only thing that can effect the output of the AND is
642           // the bit specified by AndRHSV.  If that bit is set, the effect of
643           // the XOR is to toggle the bit.  If it is clear, then the ADD has
644           // no effect.
645           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
646             TheAnd.setOperand(0, X);
647             return &TheAnd;
648           } else {
649             // Pull the XOR out of the AND.
650             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
651             NewAnd->takeName(Op);
652             return BinaryOperator::CreateXor(NewAnd, AndRHS);
653           }
654         }
655       }
656     }
657     break;
658
659   case Instruction::Shl: {
660     // We know that the AND will not produce any of the bits shifted in, so if
661     // the anded constant includes them, clear them now!
662     //
663     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
664     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
665     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
666     ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
667                                        AndRHS->getValue() & ShlMask);
668
669     if (CI->getValue() == ShlMask) { 
670     // Masking out bits that the shift already masks
671       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
672     } else if (CI != AndRHS) {                  // Reducing bits set in and.
673       TheAnd.setOperand(1, CI);
674       return &TheAnd;
675     }
676     break;
677   }
678   case Instruction::LShr: {
679     // We know that the AND will not produce any of the bits shifted in, so if
680     // the anded constant includes them, clear them now!  This only applies to
681     // unsigned shifts, because a signed shr may bring in set bits!
682     //
683     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
684     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
685     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
686     ConstantInt *CI = ConstantInt::get(Op->getContext(),
687                                        AndRHS->getValue() & ShrMask);
688
689     if (CI->getValue() == ShrMask) {   
690     // Masking out bits that the shift already masks.
691       return ReplaceInstUsesWith(TheAnd, Op);
692     } else if (CI != AndRHS) {
693       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
694       return &TheAnd;
695     }
696     break;
697   }
698   case Instruction::AShr:
699     // Signed shr.
700     // See if this is shifting in some sign extension, then masking it out
701     // with an and.
702     if (Op->hasOneUse()) {
703       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
704       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
705       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
706       Constant *C = ConstantInt::get(Op->getContext(),
707                                      AndRHS->getValue() & ShrMask);
708       if (C == AndRHS) {          // Masking out bits shifted in.
709         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
710         // Make the argument unsigned.
711         Value *ShVal = Op->getOperand(0);
712         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
713         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
714       }
715     }
716     break;
717   }
718   return 0;
719 }
720
721
722 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
723 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
724 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
725 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
726 /// insert new instructions.
727 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
728                                            bool isSigned, bool Inside, 
729                                            Instruction &IB) {
730   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
731             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
732          "Lo is not <= Hi in range emission code!");
733     
734   if (Inside) {
735     if (Lo == Hi)  // Trivially false.
736       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
737
738     // V >= Min && V < Hi --> V < Hi
739     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
740       ICmpInst::Predicate pred = (isSigned ? 
741         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
742       return new ICmpInst(pred, V, Hi);
743     }
744
745     // Emit V-Lo <u Hi-Lo
746     Constant *NegLo = ConstantExpr::getNeg(Lo);
747     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
748     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
749     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
750   }
751
752   if (Lo == Hi)  // Trivially true.
753     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
754
755   // V < Min || V >= Hi -> V > Hi-1
756   Hi = SubOne(cast<ConstantInt>(Hi));
757   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
758     ICmpInst::Predicate pred = (isSigned ? 
759         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
760     return new ICmpInst(pred, V, Hi);
761   }
762
763   // Emit V-Lo >u Hi-1-Lo
764   // Note that Hi has already had one subtracted from it, above.
765   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
766   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
767   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
768   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
769 }
770
771 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
772 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
773 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
774 // not, since all 1s are not contiguous.
775 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
776   const APInt& V = Val->getValue();
777   uint32_t BitWidth = Val->getType()->getBitWidth();
778   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
779
780   // look for the first zero bit after the run of ones
781   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
782   // look for the first non-zero bit
783   ME = V.getActiveBits(); 
784   return true;
785 }
786
787 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
788 /// where isSub determines whether the operator is a sub.  If we can fold one of
789 /// the following xforms:
790 /// 
791 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
792 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
793 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
794 ///
795 /// return (A +/- B).
796 ///
797 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
798                                         ConstantInt *Mask, bool isSub,
799                                         Instruction &I) {
800   Instruction *LHSI = dyn_cast<Instruction>(LHS);
801   if (!LHSI || LHSI->getNumOperands() != 2 ||
802       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
803
804   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
805
806   switch (LHSI->getOpcode()) {
807   default: return 0;
808   case Instruction::And:
809     if (ConstantExpr::getAnd(N, Mask) == Mask) {
810       // If the AndRHS is a power of two minus one (0+1+), this is simple.
811       if ((Mask->getValue().countLeadingZeros() + 
812            Mask->getValue().countPopulation()) == 
813           Mask->getValue().getBitWidth())
814         break;
815
816       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
817       // part, we don't need any explicit masks to take them out of A.  If that
818       // is all N is, ignore it.
819       uint32_t MB = 0, ME = 0;
820       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
821         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
822         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
823         if (MaskedValueIsZero(RHS, Mask))
824           break;
825       }
826     }
827     return 0;
828   case Instruction::Or:
829   case Instruction::Xor:
830     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
831     if ((Mask->getValue().countLeadingZeros() + 
832          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
833         && ConstantExpr::getAnd(N, Mask)->isNullValue())
834       break;
835     return 0;
836   }
837   
838   if (isSub)
839     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
840   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
841 }
842
843 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
844 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
845                                           ICmpInst *LHS, ICmpInst *RHS) {
846   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
847
848   // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
849   if (PredicatesFoldable(LHSCC, RHSCC)) {
850     if (LHS->getOperand(0) == RHS->getOperand(1) &&
851         LHS->getOperand(1) == RHS->getOperand(0))
852       LHS->swapOperands();
853     if (LHS->getOperand(0) == RHS->getOperand(0) &&
854         LHS->getOperand(1) == RHS->getOperand(1)) {
855       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
856       unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
857       bool isSigned = LHS->isSigned() || RHS->isSigned();
858       Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
859       if (Instruction *I = dyn_cast<Instruction>(RV))
860         return I;
861       // Otherwise, it's a constant boolean value.
862       return ReplaceInstUsesWith(I, RV);
863     }
864   }
865   
866   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
867   Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
868   ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
869   ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
870   if (LHSCst == 0 || RHSCst == 0) return 0;
871   
872   if (LHSCst == RHSCst && LHSCC == RHSCC) {
873     // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
874     // where C is a power of 2
875     if (LHSCC == ICmpInst::ICMP_ULT &&
876         LHSCst->getValue().isPowerOf2()) {
877       Value *NewOr = Builder->CreateOr(Val, Val2);
878       return new ICmpInst(LHSCC, NewOr, LHSCst);
879     }
880     
881     // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
882     if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
883       Value *NewOr = Builder->CreateOr(Val, Val2);
884       return new ICmpInst(LHSCC, NewOr, LHSCst);
885     }
886   }
887   
888   // From here on, we only handle:
889   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
890   if (Val != Val2) return 0;
891   
892   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
893   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
894       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
895       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
896       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
897     return 0;
898   
899   // We can't fold (ugt x, C) & (sgt x, C2).
900   if (!PredicatesFoldable(LHSCC, RHSCC))
901     return 0;
902     
903   // Ensure that the larger constant is on the RHS.
904   bool ShouldSwap;
905   if (CmpInst::isSigned(LHSCC) ||
906       (ICmpInst::isEquality(LHSCC) && 
907        CmpInst::isSigned(RHSCC)))
908     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
909   else
910     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
911     
912   if (ShouldSwap) {
913     std::swap(LHS, RHS);
914     std::swap(LHSCst, RHSCst);
915     std::swap(LHSCC, RHSCC);
916   }
917
918   // At this point, we know we have have two icmp instructions
919   // comparing a value against two constants and and'ing the result
920   // together.  Because of the above check, we know that we only have
921   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
922   // (from the icmp folding check above), that the two constants 
923   // are not equal and that the larger constant is on the RHS
924   assert(LHSCst != RHSCst && "Compares not folded above?");
925
926   switch (LHSCC) {
927   default: llvm_unreachable("Unknown integer condition code!");
928   case ICmpInst::ICMP_EQ:
929     switch (RHSCC) {
930     default: llvm_unreachable("Unknown integer condition code!");
931     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
932     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
933     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
934       return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
935     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
936     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
937     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
938       return ReplaceInstUsesWith(I, LHS);
939     }
940   case ICmpInst::ICMP_NE:
941     switch (RHSCC) {
942     default: llvm_unreachable("Unknown integer condition code!");
943     case ICmpInst::ICMP_ULT:
944       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
945         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
946       break;                        // (X != 13 & X u< 15) -> no change
947     case ICmpInst::ICMP_SLT:
948       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
949         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
950       break;                        // (X != 13 & X s< 15) -> no change
951     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
952     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
953     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
954       return ReplaceInstUsesWith(I, RHS);
955     case ICmpInst::ICMP_NE:
956       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
957         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
958         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
959         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
960                             ConstantInt::get(Add->getType(), 1));
961       }
962       break;                        // (X != 13 & X != 15) -> no change
963     }
964     break;
965   case ICmpInst::ICMP_ULT:
966     switch (RHSCC) {
967     default: llvm_unreachable("Unknown integer condition code!");
968     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
969     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
970       return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
971     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
972       break;
973     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
974     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
975       return ReplaceInstUsesWith(I, LHS);
976     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
977       break;
978     }
979     break;
980   case ICmpInst::ICMP_SLT:
981     switch (RHSCC) {
982     default: llvm_unreachable("Unknown integer condition code!");
983     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
984     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
985       return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
986     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
987       break;
988     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
989     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
990       return ReplaceInstUsesWith(I, LHS);
991     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
992       break;
993     }
994     break;
995   case ICmpInst::ICMP_UGT:
996     switch (RHSCC) {
997     default: llvm_unreachable("Unknown integer condition code!");
998     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
999     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
1000       return ReplaceInstUsesWith(I, RHS);
1001     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
1002       break;
1003     case ICmpInst::ICMP_NE:
1004       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
1005         return new ICmpInst(LHSCC, Val, RHSCst);
1006       break;                        // (X u> 13 & X != 15) -> no change
1007     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
1008       return InsertRangeTest(Val, AddOne(LHSCst),
1009                              RHSCst, false, true, I);
1010     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
1011       break;
1012     }
1013     break;
1014   case ICmpInst::ICMP_SGT:
1015     switch (RHSCC) {
1016     default: llvm_unreachable("Unknown integer condition code!");
1017     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
1018     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
1019       return ReplaceInstUsesWith(I, RHS);
1020     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
1021       break;
1022     case ICmpInst::ICMP_NE:
1023       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
1024         return new ICmpInst(LHSCC, Val, RHSCst);
1025       break;                        // (X s> 13 & X != 15) -> no change
1026     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
1027       return InsertRangeTest(Val, AddOne(LHSCst),
1028                              RHSCst, true, true, I);
1029     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
1030       break;
1031     }
1032     break;
1033   }
1034  
1035   return 0;
1036 }
1037
1038 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
1039                                           FCmpInst *RHS) {
1040   
1041   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1042       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
1043     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
1044     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1045       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1046         // If either of the constants are nans, then the whole thing returns
1047         // false.
1048         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1049           return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
1050         return new FCmpInst(FCmpInst::FCMP_ORD,
1051                             LHS->getOperand(0), RHS->getOperand(0));
1052       }
1053     
1054     // Handle vector zeros.  This occurs because the canonical form of
1055     // "fcmp ord x,x" is "fcmp ord x, 0".
1056     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1057         isa<ConstantAggregateZero>(RHS->getOperand(1)))
1058       return new FCmpInst(FCmpInst::FCMP_ORD,
1059                           LHS->getOperand(0), RHS->getOperand(0));
1060     return 0;
1061   }
1062   
1063   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1064   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1065   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1066   
1067   
1068   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1069     // Swap RHS operands to match LHS.
1070     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1071     std::swap(Op1LHS, Op1RHS);
1072   }
1073   
1074   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1075     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1076     if (Op0CC == Op1CC)
1077       return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
1078     
1079     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
1080       return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
1081     if (Op0CC == FCmpInst::FCMP_TRUE)
1082       return ReplaceInstUsesWith(I, RHS);
1083     if (Op1CC == FCmpInst::FCMP_TRUE)
1084       return ReplaceInstUsesWith(I, LHS);
1085     
1086     bool Op0Ordered;
1087     bool Op1Ordered;
1088     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1089     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1090     if (Op1Pred == 0) {
1091       std::swap(LHS, RHS);
1092       std::swap(Op0Pred, Op1Pred);
1093       std::swap(Op0Ordered, Op1Ordered);
1094     }
1095     if (Op0Pred == 0) {
1096       // uno && ueq -> uno && (uno || eq) -> ueq
1097       // ord && olt -> ord && (ord && lt) -> olt
1098       if (Op0Ordered == Op1Ordered)
1099         return ReplaceInstUsesWith(I, RHS);
1100       
1101       // uno && oeq -> uno && (ord && eq) -> false
1102       // uno && ord -> false
1103       if (!Op0Ordered)
1104         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
1105       // ord && ueq -> ord && (uno || eq) -> oeq
1106       return cast<Instruction>(getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS));
1107     }
1108   }
1109
1110   return 0;
1111 }
1112
1113
1114 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1115   bool Changed = SimplifyCommutative(I);
1116   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1117
1118   if (Value *V = SimplifyAndInst(Op0, Op1, TD))
1119     return ReplaceInstUsesWith(I, V);
1120
1121   // See if we can simplify any instructions used by the instruction whose sole 
1122   // purpose is to compute bits we don't care about.
1123   if (SimplifyDemandedInstructionBits(I))
1124     return &I;  
1125
1126   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1127     const APInt &AndRHSMask = AndRHS->getValue();
1128     APInt NotAndRHS(~AndRHSMask);
1129
1130     // Optimize a variety of ((val OP C1) & C2) combinations...
1131     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1132       Value *Op0LHS = Op0I->getOperand(0);
1133       Value *Op0RHS = Op0I->getOperand(1);
1134       switch (Op0I->getOpcode()) {
1135       default: break;
1136       case Instruction::Xor:
1137       case Instruction::Or:
1138         // If the mask is only needed on one incoming arm, push it up.
1139         if (!Op0I->hasOneUse()) break;
1140           
1141         if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1142           // Not masking anything out for the LHS, move to RHS.
1143           Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1144                                              Op0RHS->getName()+".masked");
1145           return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1146         }
1147         if (!isa<Constant>(Op0RHS) &&
1148             MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1149           // Not masking anything out for the RHS, move to LHS.
1150           Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1151                                              Op0LHS->getName()+".masked");
1152           return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1153         }
1154
1155         break;
1156       case Instruction::Add:
1157         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1158         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1159         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1160         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1161           return BinaryOperator::CreateAnd(V, AndRHS);
1162         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1163           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
1164         break;
1165
1166       case Instruction::Sub:
1167         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1168         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1169         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1170         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1171           return BinaryOperator::CreateAnd(V, AndRHS);
1172
1173         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
1174         // has 1's for all bits that the subtraction with A might affect.
1175         if (Op0I->hasOneUse()) {
1176           uint32_t BitWidth = AndRHSMask.getBitWidth();
1177           uint32_t Zeros = AndRHSMask.countLeadingZeros();
1178           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1179
1180           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
1181           if (!(A && A->isZero()) &&               // avoid infinite recursion.
1182               MaskedValueIsZero(Op0LHS, Mask)) {
1183             Value *NewNeg = Builder->CreateNeg(Op0RHS);
1184             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1185           }
1186         }
1187         break;
1188
1189       case Instruction::Shl:
1190       case Instruction::LShr:
1191         // (1 << x) & 1 --> zext(x == 0)
1192         // (1 >> x) & 1 --> zext(x == 0)
1193         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1194           Value *NewICmp =
1195             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1196           return new ZExtInst(NewICmp, I.getType());
1197         }
1198         break;
1199       }
1200
1201       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1202         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1203           return Res;
1204     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1205       // If this is an integer truncation or change from signed-to-unsigned, and
1206       // if the source is an and/or with immediate, transform it.  This
1207       // frequently occurs for bitfield accesses.
1208       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
1209         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
1210             CastOp->getNumOperands() == 2)
1211           if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
1212             if (CastOp->getOpcode() == Instruction::And) {
1213               // Change: and (cast (and X, C1) to T), C2
1214               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
1215               // This will fold the two constants together, which may allow 
1216               // other simplifications.
1217               Value *NewCast = Builder->CreateTruncOrBitCast(
1218                 CastOp->getOperand(0), I.getType(), 
1219                 CastOp->getName()+".shrunk");
1220               // trunc_or_bitcast(C1)&C2
1221               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
1222               C3 = ConstantExpr::getAnd(C3, AndRHS);
1223               return BinaryOperator::CreateAnd(NewCast, C3);
1224             } else if (CastOp->getOpcode() == Instruction::Or) {
1225               // Change: and (cast (or X, C1) to T), C2
1226               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
1227               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
1228               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
1229                 // trunc(C1)&C2
1230                 return ReplaceInstUsesWith(I, AndRHS);
1231             }
1232           }
1233       }
1234     }
1235
1236     // Try to fold constant and into select arguments.
1237     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1238       if (Instruction *R = FoldOpIntoSelect(I, SI))
1239         return R;
1240     if (isa<PHINode>(Op0))
1241       if (Instruction *NV = FoldOpIntoPhi(I))
1242         return NV;
1243   }
1244
1245
1246   // (~A & ~B) == (~(A | B)) - De Morgan's Law
1247   if (Value *Op0NotVal = dyn_castNotVal(Op0))
1248     if (Value *Op1NotVal = dyn_castNotVal(Op1))
1249       if (Op0->hasOneUse() && Op1->hasOneUse()) {
1250         Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1251                                       I.getName()+".demorgan");
1252         return BinaryOperator::CreateNot(Or);
1253       }
1254
1255   {
1256     Value *A = 0, *B = 0, *C = 0, *D = 0;
1257     // (A|B) & ~(A&B) -> A^B
1258     if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1259         match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1260         ((A == C && B == D) || (A == D && B == C)))
1261       return BinaryOperator::CreateXor(A, B);
1262     
1263     // ~(A&B) & (A|B) -> A^B
1264     if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1265         match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1266         ((A == C && B == D) || (A == D && B == C)))
1267       return BinaryOperator::CreateXor(A, B);
1268     
1269     if (Op0->hasOneUse() &&
1270         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
1271       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
1272         I.swapOperands();     // Simplify below
1273         std::swap(Op0, Op1);
1274       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
1275         cast<BinaryOperator>(Op0)->swapOperands();
1276         I.swapOperands();     // Simplify below
1277         std::swap(Op0, Op1);
1278       }
1279     }
1280
1281     if (Op1->hasOneUse() &&
1282         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
1283       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
1284         cast<BinaryOperator>(Op1)->swapOperands();
1285         std::swap(A, B);
1286       }
1287       if (A == Op0)                                // A&(A^B) -> A & ~B
1288         return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
1289     }
1290
1291     // (A&((~A)|B)) -> A&B
1292     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1293         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1294       return BinaryOperator::CreateAnd(A, Op1);
1295     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1296         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1297       return BinaryOperator::CreateAnd(A, Op0);
1298   }
1299   
1300   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
1301     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
1302       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
1303         return Res;
1304
1305   // fold (and (cast A), (cast B)) -> (cast (and A, B))
1306   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
1307     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
1308       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
1309         const Type *SrcTy = Op0C->getOperand(0)->getType();
1310         if (SrcTy == Op1C->getOperand(0)->getType() &&
1311             SrcTy->isIntOrIntVector() &&
1312             // Only do this if the casts both really cause code to be generated.
1313             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
1314                               I.getType()) &&
1315             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
1316                               I.getType())) {
1317           Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
1318                                             Op1C->getOperand(0), I.getName());
1319           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1320         }
1321       }
1322     
1323   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
1324   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1325     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1326       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
1327           SI0->getOperand(1) == SI1->getOperand(1) &&
1328           (SI0->hasOneUse() || SI1->hasOneUse())) {
1329         Value *NewOp =
1330           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
1331                              SI0->getName());
1332         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
1333                                       SI1->getOperand(1));
1334       }
1335   }
1336
1337   // If and'ing two fcmp, try combine them into one.
1338   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
1339     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1340       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
1341         return Res;
1342   }
1343
1344   return Changed ? &I : 0;
1345 }
1346
1347 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
1348 /// capable of providing pieces of a bswap.  The subexpression provides pieces
1349 /// of a bswap if it is proven that each of the non-zero bytes in the output of
1350 /// the expression came from the corresponding "byte swapped" byte in some other
1351 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
1352 /// we know that the expression deposits the low byte of %X into the high byte
1353 /// of the bswap result and that all other bytes are zero.  This expression is
1354 /// accepted, the high byte of ByteValues is set to X to indicate a correct
1355 /// match.
1356 ///
1357 /// This function returns true if the match was unsuccessful and false if so.
1358 /// On entry to the function the "OverallLeftShift" is a signed integer value
1359 /// indicating the number of bytes that the subexpression is later shifted.  For
1360 /// example, if the expression is later right shifted by 16 bits, the
1361 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
1362 /// byte of ByteValues is actually being set.
1363 ///
1364 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1365 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
1366 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
1367 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
1368 /// always in the local (OverallLeftShift) coordinate space.
1369 ///
1370 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
1371                               SmallVector<Value*, 8> &ByteValues) {
1372   if (Instruction *I = dyn_cast<Instruction>(V)) {
1373     // If this is an or instruction, it may be an inner node of the bswap.
1374     if (I->getOpcode() == Instruction::Or) {
1375       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1376                                ByteValues) ||
1377              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1378                                ByteValues);
1379     }
1380   
1381     // If this is a logical shift by a constant multiple of 8, recurse with
1382     // OverallLeftShift and ByteMask adjusted.
1383     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1384       unsigned ShAmt = 
1385         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1386       // Ensure the shift amount is defined and of a byte value.
1387       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1388         return true;
1389
1390       unsigned ByteShift = ShAmt >> 3;
1391       if (I->getOpcode() == Instruction::Shl) {
1392         // X << 2 -> collect(X, +2)
1393         OverallLeftShift += ByteShift;
1394         ByteMask >>= ByteShift;
1395       } else {
1396         // X >>u 2 -> collect(X, -2)
1397         OverallLeftShift -= ByteShift;
1398         ByteMask <<= ByteShift;
1399         ByteMask &= (~0U >> (32-ByteValues.size()));
1400       }
1401
1402       if (OverallLeftShift >= (int)ByteValues.size()) return true;
1403       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1404
1405       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
1406                                ByteValues);
1407     }
1408
1409     // If this is a logical 'and' with a mask that clears bytes, clear the
1410     // corresponding bytes in ByteMask.
1411     if (I->getOpcode() == Instruction::And &&
1412         isa<ConstantInt>(I->getOperand(1))) {
1413       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1414       unsigned NumBytes = ByteValues.size();
1415       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1416       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1417       
1418       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1419         // If this byte is masked out by a later operation, we don't care what
1420         // the and mask is.
1421         if ((ByteMask & (1 << i)) == 0)
1422           continue;
1423         
1424         // If the AndMask is all zeros for this byte, clear the bit.
1425         APInt MaskB = AndMask & Byte;
1426         if (MaskB == 0) {
1427           ByteMask &= ~(1U << i);
1428           continue;
1429         }
1430         
1431         // If the AndMask is not all ones for this byte, it's not a bytezap.
1432         if (MaskB != Byte)
1433           return true;
1434
1435         // Otherwise, this byte is kept.
1436       }
1437
1438       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
1439                                ByteValues);
1440     }
1441   }
1442   
1443   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
1444   // the input value to the bswap.  Some observations: 1) if more than one byte
1445   // is demanded from this input, then it could not be successfully assembled
1446   // into a byteswap.  At least one of the two bytes would not be aligned with
1447   // their ultimate destination.
1448   if (!isPowerOf2_32(ByteMask)) return true;
1449   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
1450   
1451   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1452   // is demanded, it needs to go into byte 0 of the result.  This means that the
1453   // byte needs to be shifted until it lands in the right byte bucket.  The
1454   // shift amount depends on the position: if the byte is coming from the high
1455   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
1456   // low part, it must be shifted left.
1457   unsigned DestByteNo = InputByteNo + OverallLeftShift;
1458   if (InputByteNo < ByteValues.size()/2) {
1459     if (ByteValues.size()-1-DestByteNo != InputByteNo)
1460       return true;
1461   } else {
1462     if (ByteValues.size()-1-DestByteNo != InputByteNo)
1463       return true;
1464   }
1465   
1466   // If the destination byte value is already defined, the values are or'd
1467   // together, which isn't a bswap (unless it's an or of the same bits).
1468   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1469     return true;
1470   ByteValues[DestByteNo] = V;
1471   return false;
1472 }
1473
1474 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1475 /// If so, insert the new bswap intrinsic and return it.
1476 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1477   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
1478   if (!ITy || ITy->getBitWidth() % 16 || 
1479       // ByteMask only allows up to 32-byte values.
1480       ITy->getBitWidth() > 32*8) 
1481     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
1482   
1483   /// ByteValues - For each byte of the result, we keep track of which value
1484   /// defines each byte.
1485   SmallVector<Value*, 8> ByteValues;
1486   ByteValues.resize(ITy->getBitWidth()/8);
1487     
1488   // Try to find all the pieces corresponding to the bswap.
1489   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1490   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1491     return 0;
1492   
1493   // Check to see if all of the bytes come from the same value.
1494   Value *V = ByteValues[0];
1495   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
1496   
1497   // Check to make sure that all of the bytes come from the same value.
1498   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1499     if (ByteValues[i] != V)
1500       return 0;
1501   const Type *Tys[] = { ITy };
1502   Module *M = I.getParent()->getParent()->getParent();
1503   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
1504   return CallInst::Create(F, V);
1505 }
1506
1507 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
1508 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1509 /// we can simplify this expression to "cond ? C : D or B".
1510 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1511                                          Value *C, Value *D) {
1512   // If A is not a select of -1/0, this cannot match.
1513   Value *Cond = 0;
1514   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
1515     return 0;
1516
1517   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
1518   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
1519     return SelectInst::Create(Cond, C, B);
1520   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
1521     return SelectInst::Create(Cond, C, B);
1522   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
1523   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
1524     return SelectInst::Create(Cond, C, D);
1525   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
1526     return SelectInst::Create(Cond, C, D);
1527   return 0;
1528 }
1529
1530 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1531 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
1532                                          ICmpInst *LHS, ICmpInst *RHS) {
1533   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1534
1535   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1536   if (PredicatesFoldable(LHSCC, RHSCC)) {
1537     if (LHS->getOperand(0) == RHS->getOperand(1) &&
1538         LHS->getOperand(1) == RHS->getOperand(0))
1539       LHS->swapOperands();
1540     if (LHS->getOperand(0) == RHS->getOperand(0) &&
1541         LHS->getOperand(1) == RHS->getOperand(1)) {
1542       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1543       unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1544       bool isSigned = LHS->isSigned() || RHS->isSigned();
1545       Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
1546       if (Instruction *I = dyn_cast<Instruction>(RV))
1547         return I;
1548       // Otherwise, it's a constant boolean value.
1549       return ReplaceInstUsesWith(I, RV);
1550     }
1551   }
1552   
1553   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1554   Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1555   ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1556   ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1557   if (LHSCst == 0 || RHSCst == 0) return 0;
1558
1559   // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1560   if (LHSCst == RHSCst && LHSCC == RHSCC &&
1561       LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1562     Value *NewOr = Builder->CreateOr(Val, Val2);
1563     return new ICmpInst(LHSCC, NewOr, LHSCst);
1564   }
1565   
1566   // From here on, we only handle:
1567   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1568   if (Val != Val2) return 0;
1569   
1570   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1571   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1572       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1573       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1574       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1575     return 0;
1576   
1577   // We can't fold (ugt x, C) | (sgt x, C2).
1578   if (!PredicatesFoldable(LHSCC, RHSCC))
1579     return 0;
1580   
1581   // Ensure that the larger constant is on the RHS.
1582   bool ShouldSwap;
1583   if (CmpInst::isSigned(LHSCC) ||
1584       (ICmpInst::isEquality(LHSCC) && 
1585        CmpInst::isSigned(RHSCC)))
1586     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1587   else
1588     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1589   
1590   if (ShouldSwap) {
1591     std::swap(LHS, RHS);
1592     std::swap(LHSCst, RHSCst);
1593     std::swap(LHSCC, RHSCC);
1594   }
1595   
1596   // At this point, we know we have have two icmp instructions
1597   // comparing a value against two constants and or'ing the result
1598   // together.  Because of the above check, we know that we only have
1599   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1600   // icmp folding check above), that the two constants are not
1601   // equal.
1602   assert(LHSCst != RHSCst && "Compares not folded above?");
1603
1604   switch (LHSCC) {
1605   default: llvm_unreachable("Unknown integer condition code!");
1606   case ICmpInst::ICMP_EQ:
1607     switch (RHSCC) {
1608     default: llvm_unreachable("Unknown integer condition code!");
1609     case ICmpInst::ICMP_EQ:
1610       if (LHSCst == SubOne(RHSCst)) {
1611         // (X == 13 | X == 14) -> X-13 <u 2
1612         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1613         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1614         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1615         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
1616       }
1617       break;                         // (X == 13 | X == 15) -> no change
1618     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
1619     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
1620       break;
1621     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
1622     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
1623     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
1624       return ReplaceInstUsesWith(I, RHS);
1625     }
1626     break;
1627   case ICmpInst::ICMP_NE:
1628     switch (RHSCC) {
1629     default: llvm_unreachable("Unknown integer condition code!");
1630     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
1631     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
1632     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
1633       return ReplaceInstUsesWith(I, LHS);
1634     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
1635     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
1636     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
1637       return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1638     }
1639     break;
1640   case ICmpInst::ICMP_ULT:
1641     switch (RHSCC) {
1642     default: llvm_unreachable("Unknown integer condition code!");
1643     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
1644       break;
1645     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
1646       // If RHSCst is [us]MAXINT, it is always false.  Not handling
1647       // this can cause overflow.
1648       if (RHSCst->isMaxValue(false))
1649         return ReplaceInstUsesWith(I, LHS);
1650       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
1651                              false, false, I);
1652     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
1653       break;
1654     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
1655     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
1656       return ReplaceInstUsesWith(I, RHS);
1657     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
1658       break;
1659     }
1660     break;
1661   case ICmpInst::ICMP_SLT:
1662     switch (RHSCC) {
1663     default: llvm_unreachable("Unknown integer condition code!");
1664     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
1665       break;
1666     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
1667       // If RHSCst is [us]MAXINT, it is always false.  Not handling
1668       // this can cause overflow.
1669       if (RHSCst->isMaxValue(true))
1670         return ReplaceInstUsesWith(I, LHS);
1671       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
1672                              true, false, I);
1673     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
1674       break;
1675     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
1676     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
1677       return ReplaceInstUsesWith(I, RHS);
1678     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
1679       break;
1680     }
1681     break;
1682   case ICmpInst::ICMP_UGT:
1683     switch (RHSCC) {
1684     default: llvm_unreachable("Unknown integer condition code!");
1685     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
1686     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
1687       return ReplaceInstUsesWith(I, LHS);
1688     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
1689       break;
1690     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
1691     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
1692       return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1693     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
1694       break;
1695     }
1696     break;
1697   case ICmpInst::ICMP_SGT:
1698     switch (RHSCC) {
1699     default: llvm_unreachable("Unknown integer condition code!");
1700     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
1701     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
1702       return ReplaceInstUsesWith(I, LHS);
1703     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
1704       break;
1705     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
1706     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
1707       return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1708     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
1709       break;
1710     }
1711     break;
1712   }
1713   return 0;
1714 }
1715
1716 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
1717                                          FCmpInst *RHS) {
1718   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1719       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
1720       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1721     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1722       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1723         // If either of the constants are nans, then the whole thing returns
1724         // true.
1725         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1726           return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1727         
1728         // Otherwise, no need to compare the two constants, compare the
1729         // rest.
1730         return new FCmpInst(FCmpInst::FCMP_UNO,
1731                             LHS->getOperand(0), RHS->getOperand(0));
1732       }
1733     
1734     // Handle vector zeros.  This occurs because the canonical form of
1735     // "fcmp uno x,x" is "fcmp uno x, 0".
1736     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1737         isa<ConstantAggregateZero>(RHS->getOperand(1)))
1738       return new FCmpInst(FCmpInst::FCMP_UNO,
1739                           LHS->getOperand(0), RHS->getOperand(0));
1740     
1741     return 0;
1742   }
1743   
1744   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1745   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1746   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1747   
1748   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1749     // Swap RHS operands to match LHS.
1750     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1751     std::swap(Op1LHS, Op1RHS);
1752   }
1753   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1754     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1755     if (Op0CC == Op1CC)
1756       return new FCmpInst((FCmpInst::Predicate)Op0CC,
1757                           Op0LHS, Op0RHS);
1758     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
1759       return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1760     if (Op0CC == FCmpInst::FCMP_FALSE)
1761       return ReplaceInstUsesWith(I, RHS);
1762     if (Op1CC == FCmpInst::FCMP_FALSE)
1763       return ReplaceInstUsesWith(I, LHS);
1764     bool Op0Ordered;
1765     bool Op1Ordered;
1766     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1767     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1768     if (Op0Ordered == Op1Ordered) {
1769       // If both are ordered or unordered, return a new fcmp with
1770       // or'ed predicates.
1771       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS);
1772       if (Instruction *I = dyn_cast<Instruction>(RV))
1773         return I;
1774       // Otherwise, it's a constant boolean value...
1775       return ReplaceInstUsesWith(I, RV);
1776     }
1777   }
1778   return 0;
1779 }
1780
1781 /// FoldOrWithConstants - This helper function folds:
1782 ///
1783 ///     ((A | B) & C1) | (B & C2)
1784 ///
1785 /// into:
1786 /// 
1787 ///     (A & C1) | B
1788 ///
1789 /// when the XOR of the two constants is "all ones" (-1).
1790 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1791                                                Value *A, Value *B, Value *C) {
1792   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1793   if (!CI1) return 0;
1794
1795   Value *V1 = 0;
1796   ConstantInt *CI2 = 0;
1797   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
1798
1799   APInt Xor = CI1->getValue() ^ CI2->getValue();
1800   if (!Xor.isAllOnesValue()) return 0;
1801
1802   if (V1 == A || V1 == B) {
1803     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1804     return BinaryOperator::CreateOr(NewOp, V1);
1805   }
1806
1807   return 0;
1808 }
1809
1810 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1811   bool Changed = SimplifyCommutative(I);
1812   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1813
1814   if (Value *V = SimplifyOrInst(Op0, Op1, TD))
1815     return ReplaceInstUsesWith(I, V);
1816   
1817   
1818   // See if we can simplify any instructions used by the instruction whose sole 
1819   // purpose is to compute bits we don't care about.
1820   if (SimplifyDemandedInstructionBits(I))
1821     return &I;
1822
1823   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1824     ConstantInt *C1 = 0; Value *X = 0;
1825     // (X & C1) | C2 --> (X | C2) & (C1|C2)
1826     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
1827         Op0->hasOneUse()) {
1828       Value *Or = Builder->CreateOr(X, RHS);
1829       Or->takeName(Op0);
1830       return BinaryOperator::CreateAnd(Or, 
1831                          ConstantInt::get(I.getContext(),
1832                                           RHS->getValue() | C1->getValue()));
1833     }
1834
1835     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1836     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1837         Op0->hasOneUse()) {
1838       Value *Or = Builder->CreateOr(X, RHS);
1839       Or->takeName(Op0);
1840       return BinaryOperator::CreateXor(Or,
1841                  ConstantInt::get(I.getContext(),
1842                                   C1->getValue() & ~RHS->getValue()));
1843     }
1844
1845     // Try to fold constant and into select arguments.
1846     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1847       if (Instruction *R = FoldOpIntoSelect(I, SI))
1848         return R;
1849     if (isa<PHINode>(Op0))
1850       if (Instruction *NV = FoldOpIntoPhi(I))
1851         return NV;
1852   }
1853
1854   Value *A = 0, *B = 0;
1855   ConstantInt *C1 = 0, *C2 = 0;
1856
1857   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
1858   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
1859   if (match(Op0, m_Or(m_Value(), m_Value())) ||
1860       match(Op1, m_Or(m_Value(), m_Value())) ||
1861       (match(Op0, m_Shift(m_Value(), m_Value())) &&
1862        match(Op1, m_Shift(m_Value(), m_Value())))) {
1863     if (Instruction *BSwap = MatchBSwap(I))
1864       return BSwap;
1865   }
1866   
1867   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1868   if (Op0->hasOneUse() &&
1869       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1870       MaskedValueIsZero(Op1, C1->getValue())) {
1871     Value *NOr = Builder->CreateOr(A, Op1);
1872     NOr->takeName(Op0);
1873     return BinaryOperator::CreateXor(NOr, C1);
1874   }
1875
1876   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1877   if (Op1->hasOneUse() &&
1878       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1879       MaskedValueIsZero(Op0, C1->getValue())) {
1880     Value *NOr = Builder->CreateOr(A, Op0);
1881     NOr->takeName(Op0);
1882     return BinaryOperator::CreateXor(NOr, C1);
1883   }
1884
1885   // (A & C)|(B & D)
1886   Value *C = 0, *D = 0;
1887   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1888       match(Op1, m_And(m_Value(B), m_Value(D)))) {
1889     Value *V1 = 0, *V2 = 0, *V3 = 0;
1890     C1 = dyn_cast<ConstantInt>(C);
1891     C2 = dyn_cast<ConstantInt>(D);
1892     if (C1 && C2) {  // (A & C1)|(B & C2)
1893       // If we have: ((V + N) & C1) | (V & C2)
1894       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1895       // replace with V+N.
1896       if (C1->getValue() == ~C2->getValue()) {
1897         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1898             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1899           // Add commutes, try both ways.
1900           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1901             return ReplaceInstUsesWith(I, A);
1902           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1903             return ReplaceInstUsesWith(I, A);
1904         }
1905         // Or commutes, try both ways.
1906         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
1907             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1908           // Add commutes, try both ways.
1909           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
1910             return ReplaceInstUsesWith(I, B);
1911           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
1912             return ReplaceInstUsesWith(I, B);
1913         }
1914       }
1915       
1916       // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
1917       // iff (C1&C2) == 0 and (N&~C1) == 0
1918       if ((C1->getValue() & C2->getValue()) == 0) {
1919         if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
1920             ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) ||  // (V|N)
1921              (V2 == B && MaskedValueIsZero(V1, ~C1->getValue()))))   // (N|V)
1922           return BinaryOperator::CreateAnd(A,
1923                                ConstantInt::get(A->getContext(),
1924                                                 C1->getValue()|C2->getValue()));
1925         // Or commutes, try both ways.
1926         if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
1927             ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) ||  // (V|N)
1928              (V2 == A && MaskedValueIsZero(V1, ~C2->getValue()))))   // (N|V)
1929           return BinaryOperator::CreateAnd(B,
1930                                ConstantInt::get(B->getContext(),
1931                                                 C1->getValue()|C2->getValue()));
1932       }
1933     }
1934     
1935     // Check to see if we have any common things being and'ed.  If so, find the
1936     // terms for V1 & (V2|V3).
1937     if (Op0->hasOneUse() || Op1->hasOneUse()) {
1938       V1 = 0;
1939       if (A == B)      // (A & C)|(A & D) == A & (C|D)
1940         V1 = A, V2 = C, V3 = D;
1941       else if (A == D) // (A & C)|(B & A) == A & (B|C)
1942         V1 = A, V2 = B, V3 = C;
1943       else if (C == B) // (A & C)|(C & D) == C & (A|D)
1944         V1 = C, V2 = A, V3 = D;
1945       else if (C == D) // (A & C)|(B & C) == C & (A|B)
1946         V1 = C, V2 = A, V3 = B;
1947       
1948       if (V1) {
1949         Value *Or = Builder->CreateOr(V2, V3, "tmp");
1950         return BinaryOperator::CreateAnd(V1, Or);
1951       }
1952     }
1953
1954     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
1955     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
1956       return Match;
1957     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
1958       return Match;
1959     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
1960       return Match;
1961     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
1962       return Match;
1963
1964     // ((A&~B)|(~A&B)) -> A^B
1965     if ((match(C, m_Not(m_Specific(D))) &&
1966          match(B, m_Not(m_Specific(A)))))
1967       return BinaryOperator::CreateXor(A, D);
1968     // ((~B&A)|(~A&B)) -> A^B
1969     if ((match(A, m_Not(m_Specific(D))) &&
1970          match(B, m_Not(m_Specific(C)))))
1971       return BinaryOperator::CreateXor(C, D);
1972     // ((A&~B)|(B&~A)) -> A^B
1973     if ((match(C, m_Not(m_Specific(B))) &&
1974          match(D, m_Not(m_Specific(A)))))
1975       return BinaryOperator::CreateXor(A, B);
1976     // ((~B&A)|(B&~A)) -> A^B
1977     if ((match(A, m_Not(m_Specific(B))) &&
1978          match(D, m_Not(m_Specific(C)))))
1979       return BinaryOperator::CreateXor(C, B);
1980   }
1981   
1982   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
1983   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1984     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1985       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
1986           SI0->getOperand(1) == SI1->getOperand(1) &&
1987           (SI0->hasOneUse() || SI1->hasOneUse())) {
1988         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
1989                                          SI0->getName());
1990         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
1991                                       SI1->getOperand(1));
1992       }
1993   }
1994
1995   // ((A|B)&1)|(B&-2) -> (A&1) | B
1996   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
1997       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
1998     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
1999     if (Ret) return Ret;
2000   }
2001   // (B&-2)|((A|B)&1) -> (A&1) | B
2002   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
2003       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
2004     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
2005     if (Ret) return Ret;
2006   }
2007
2008   // (~A | ~B) == (~(A & B)) - De Morgan's Law
2009   if (Value *Op0NotVal = dyn_castNotVal(Op0))
2010     if (Value *Op1NotVal = dyn_castNotVal(Op1))
2011       if (Op0->hasOneUse() && Op1->hasOneUse()) {
2012         Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
2013                                         I.getName()+".demorgan");
2014         return BinaryOperator::CreateNot(And);
2015       }
2016
2017   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2018     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2019       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
2020         return Res;
2021     
2022   // fold (or (cast A), (cast B)) -> (cast (or A, B))
2023   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2024     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2025       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
2026         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
2027             !isa<ICmpInst>(Op1C->getOperand(0))) {
2028           const Type *SrcTy = Op0C->getOperand(0)->getType();
2029           if (SrcTy == Op1C->getOperand(0)->getType() &&
2030               SrcTy->isIntOrIntVector() &&
2031               // Only do this if the casts both really cause code to be
2032               // generated.
2033               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
2034                                 I.getType()) &&
2035               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
2036                                 I.getType())) {
2037             Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
2038                                              Op1C->getOperand(0), I.getName());
2039             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2040           }
2041         }
2042       }
2043   }
2044   
2045     
2046   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
2047   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
2048     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2049       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
2050         return Res;
2051   }
2052
2053   return Changed ? &I : 0;
2054 }
2055
2056 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2057   bool Changed = SimplifyCommutative(I);
2058   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2059
2060   if (isa<UndefValue>(Op1)) {
2061     if (isa<UndefValue>(Op0))
2062       // Handle undef ^ undef -> 0 special case. This is a common
2063       // idiom (misuse).
2064       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2065     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
2066   }
2067
2068   // xor X, X = 0
2069   if (Op0 == Op1)
2070     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2071   
2072   // See if we can simplify any instructions used by the instruction whose sole 
2073   // purpose is to compute bits we don't care about.
2074   if (SimplifyDemandedInstructionBits(I))
2075     return &I;
2076   if (isa<VectorType>(I.getType()))
2077     if (isa<ConstantAggregateZero>(Op1))
2078       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
2079
2080   // Is this a ~ operation?
2081   if (Value *NotOp = dyn_castNotVal(&I)) {
2082     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
2083       if (Op0I->getOpcode() == Instruction::And || 
2084           Op0I->getOpcode() == Instruction::Or) {
2085         // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2086         // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2087         if (dyn_castNotVal(Op0I->getOperand(1)))
2088           Op0I->swapOperands();
2089         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2090           Value *NotY =
2091             Builder->CreateNot(Op0I->getOperand(1),
2092                                Op0I->getOperand(1)->getName()+".not");
2093           if (Op0I->getOpcode() == Instruction::And)
2094             return BinaryOperator::CreateOr(Op0NotVal, NotY);
2095           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2096         }
2097         
2098         // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2099         // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2100         if (isFreeToInvert(Op0I->getOperand(0)) && 
2101             isFreeToInvert(Op0I->getOperand(1))) {
2102           Value *NotX =
2103             Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2104           Value *NotY =
2105             Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2106           if (Op0I->getOpcode() == Instruction::And)
2107             return BinaryOperator::CreateOr(NotX, NotY);
2108           return BinaryOperator::CreateAnd(NotX, NotY);
2109         }
2110       }
2111     }
2112   }
2113   
2114   
2115   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2116     if (RHS->isOne() && Op0->hasOneUse()) {
2117       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
2118       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
2119         return new ICmpInst(ICI->getInversePredicate(),
2120                             ICI->getOperand(0), ICI->getOperand(1));
2121
2122       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
2123         return new FCmpInst(FCI->getInversePredicate(),
2124                             FCI->getOperand(0), FCI->getOperand(1));
2125     }
2126
2127     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2128     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2129       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2130         if (CI->hasOneUse() && Op0C->hasOneUse()) {
2131           Instruction::CastOps Opcode = Op0C->getOpcode();
2132           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2133               (RHS == ConstantExpr::getCast(Opcode, 
2134                                            ConstantInt::getTrue(I.getContext()),
2135                                             Op0C->getDestTy()))) {
2136             CI->setPredicate(CI->getInversePredicate());
2137             return CastInst::Create(Opcode, CI, Op0C->getType());
2138           }
2139         }
2140       }
2141     }
2142
2143     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2144       // ~(c-X) == X-c-1 == X+(-c-1)
2145       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2146         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2147           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2148           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2149                                       ConstantInt::get(I.getType(), 1));
2150           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2151         }
2152           
2153       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2154         if (Op0I->getOpcode() == Instruction::Add) {
2155           // ~(X-c) --> (-c-1)-X
2156           if (RHS->isAllOnesValue()) {
2157             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2158             return BinaryOperator::CreateSub(
2159                            ConstantExpr::getSub(NegOp0CI,
2160                                       ConstantInt::get(I.getType(), 1)),
2161                                       Op0I->getOperand(0));
2162           } else if (RHS->getValue().isSignBit()) {
2163             // (X + C) ^ signbit -> (X + C + signbit)
2164             Constant *C = ConstantInt::get(I.getContext(),
2165                                            RHS->getValue() + Op0CI->getValue());
2166             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2167
2168           }
2169         } else if (Op0I->getOpcode() == Instruction::Or) {
2170           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2171           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
2172             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2173             // Anything in both C1 and C2 is known to be zero, remove it from
2174             // NewRHS.
2175             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2176             NewRHS = ConstantExpr::getAnd(NewRHS, 
2177                                        ConstantExpr::getNot(CommonBits));
2178             Worklist.Add(Op0I);
2179             I.setOperand(0, Op0I->getOperand(0));
2180             I.setOperand(1, NewRHS);
2181             return &I;
2182           }
2183         }
2184       }
2185     }
2186
2187     // Try to fold constant and into select arguments.
2188     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2189       if (Instruction *R = FoldOpIntoSelect(I, SI))
2190         return R;
2191     if (isa<PHINode>(Op0))
2192       if (Instruction *NV = FoldOpIntoPhi(I))
2193         return NV;
2194   }
2195
2196   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
2197     if (X == Op1)
2198       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2199
2200   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
2201     if (X == Op0)
2202       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2203
2204   
2205   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2206   if (Op1I) {
2207     Value *A, *B;
2208     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2209       if (A == Op0) {              // B^(B|A) == (A|B)^B
2210         Op1I->swapOperands();
2211         I.swapOperands();
2212         std::swap(Op0, Op1);
2213       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
2214         I.swapOperands();     // Simplified below.
2215         std::swap(Op0, Op1);
2216       }
2217     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
2218       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
2219     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
2220       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
2221     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
2222                Op1I->hasOneUse()){
2223       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
2224         Op1I->swapOperands();
2225         std::swap(A, B);
2226       }
2227       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
2228         I.swapOperands();     // Simplified below.
2229         std::swap(Op0, Op1);
2230       }
2231     }
2232   }
2233   
2234   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2235   if (Op0I) {
2236     Value *A, *B;
2237     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2238         Op0I->hasOneUse()) {
2239       if (A == Op1)                                  // (B|A)^B == (A|B)^B
2240         std::swap(A, B);
2241       if (B == Op1)                                  // (A|B)^B == A & ~B
2242         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
2243     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
2244       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
2245     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
2246       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
2247     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
2248                Op0I->hasOneUse()){
2249       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
2250         std::swap(A, B);
2251       if (B == Op1 &&                                      // (B&A)^A == ~B & A
2252           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
2253         return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
2254       }
2255     }
2256   }
2257   
2258   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
2259   if (Op0I && Op1I && Op0I->isShift() && 
2260       Op0I->getOpcode() == Op1I->getOpcode() && 
2261       Op0I->getOperand(1) == Op1I->getOperand(1) &&
2262       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
2263     Value *NewOp =
2264       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2265                          Op0I->getName());
2266     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
2267                                   Op1I->getOperand(1));
2268   }
2269     
2270   if (Op0I && Op1I) {
2271     Value *A, *B, *C, *D;
2272     // (A & B)^(A | B) -> A ^ B
2273     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2274         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
2275       if ((A == C && B == D) || (A == D && B == C)) 
2276         return BinaryOperator::CreateXor(A, B);
2277     }
2278     // (A | B)^(A & B) -> A ^ B
2279     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2280         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
2281       if ((A == C && B == D) || (A == D && B == C)) 
2282         return BinaryOperator::CreateXor(A, B);
2283     }
2284     
2285     // (A & B)^(C & D)
2286     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
2287         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2288         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
2289       // (X & Y)^(X & Y) -> (Y^Z) & X
2290       Value *X = 0, *Y = 0, *Z = 0;
2291       if (A == C)
2292         X = A, Y = B, Z = D;
2293       else if (A == D)
2294         X = A, Y = B, Z = C;
2295       else if (B == C)
2296         X = B, Y = A, Z = D;
2297       else if (B == D)
2298         X = B, Y = A, Z = C;
2299       
2300       if (X) {
2301         Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
2302         return BinaryOperator::CreateAnd(NewOp, X);
2303       }
2304     }
2305   }
2306     
2307   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2308   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2309     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2310       if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2311         if (LHS->getOperand(0) == RHS->getOperand(1) &&
2312             LHS->getOperand(1) == RHS->getOperand(0))
2313           LHS->swapOperands();
2314         if (LHS->getOperand(0) == RHS->getOperand(0) &&
2315             LHS->getOperand(1) == RHS->getOperand(1)) {
2316           Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2317           unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2318           bool isSigned = LHS->isSigned() || RHS->isSigned();
2319           Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
2320           if (Instruction *I = dyn_cast<Instruction>(RV))
2321             return I;
2322           // Otherwise, it's a constant boolean value.
2323           return ReplaceInstUsesWith(I, RV);
2324         }
2325       }
2326
2327   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2328   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2329     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2330       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
2331         const Type *SrcTy = Op0C->getOperand(0)->getType();
2332         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
2333             // Only do this if the casts both really cause code to be generated.
2334             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
2335                               I.getType()) &&
2336             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
2337                               I.getType())) {
2338           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2339                                             Op1C->getOperand(0), I.getName());
2340           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2341         }
2342       }
2343   }
2344
2345   return Changed ? &I : 0;
2346 }
2347
2348
2349 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
2350   return commonShiftTransforms(I);
2351 }
2352
2353 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
2354   return commonShiftTransforms(I);
2355 }
2356
2357 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
2358   if (Instruction *R = commonShiftTransforms(I))
2359     return R;
2360   
2361   Value *Op0 = I.getOperand(0);
2362   
2363   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
2364   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2365     if (CSI->isAllOnesValue())
2366       return ReplaceInstUsesWith(I, CSI);
2367
2368   // See if we can turn a signed shr into an unsigned shr.
2369   if (MaskedValueIsZero(Op0,
2370                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
2371     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
2372
2373   // Arithmetic shifting an all-sign-bit value is a no-op.
2374   unsigned NumSignBits = ComputeNumSignBits(Op0);
2375   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
2376     return ReplaceInstUsesWith(I, Op0);
2377
2378   return 0;
2379 }
2380
2381 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
2382   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
2383   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2384
2385   // shl X, 0 == X and shr X, 0 == X
2386   // shl 0, X == 0 and shr 0, X == 0
2387   if (Op1 == Constant::getNullValue(Op1->getType()) ||
2388       Op0 == Constant::getNullValue(Op0->getType()))
2389     return ReplaceInstUsesWith(I, Op0);
2390   
2391   if (isa<UndefValue>(Op0)) {            
2392     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
2393       return ReplaceInstUsesWith(I, Op0);
2394     else                                    // undef << X -> 0, undef >>u X -> 0
2395       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2396   }
2397   if (isa<UndefValue>(Op1)) {
2398     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
2399       return ReplaceInstUsesWith(I, Op0);          
2400     else                                     // X << undef, X >>u undef -> 0
2401       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2402   }
2403
2404   // See if we can fold away this shift.
2405   if (SimplifyDemandedInstructionBits(I))
2406     return &I;
2407
2408   // Try to fold constant and into select arguments.
2409   if (isa<Constant>(Op0))
2410     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2411       if (Instruction *R = FoldOpIntoSelect(I, SI))
2412         return R;
2413
2414   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
2415     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
2416       return Res;
2417   return 0;
2418 }
2419
2420 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
2421                                                BinaryOperator &I) {
2422   bool isLeftShift = I.getOpcode() == Instruction::Shl;
2423
2424   // See if we can simplify any instructions used by the instruction whose sole 
2425   // purpose is to compute bits we don't care about.
2426   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
2427   
2428   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
2429   // a signed shift.
2430   //
2431   if (Op1->uge(TypeBits)) {
2432     if (I.getOpcode() != Instruction::AShr)
2433       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2434     else {
2435       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
2436       return &I;
2437     }
2438   }
2439   
2440   // ((X*C1) << C2) == (X * (C1 << C2))
2441   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2442     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2443       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
2444         return BinaryOperator::CreateMul(BO->getOperand(0),
2445                                         ConstantExpr::getShl(BOOp, Op1));
2446   
2447   // Try to fold constant and into select arguments.
2448   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2449     if (Instruction *R = FoldOpIntoSelect(I, SI))
2450       return R;
2451   if (isa<PHINode>(Op0))
2452     if (Instruction *NV = FoldOpIntoPhi(I))
2453       return NV;
2454   
2455   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
2456   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
2457     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
2458     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
2459     // place.  Don't try to do this transformation in this case.  Also, we
2460     // require that the input operand is a shift-by-constant so that we have
2461     // confidence that the shifts will get folded together.  We could do this
2462     // xform in more cases, but it is unlikely to be profitable.
2463     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
2464         isa<ConstantInt>(TrOp->getOperand(1))) {
2465       // Okay, we'll do this xform.  Make the shift of shift.
2466       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
2467       // (shift2 (shift1 & 0x00FF), c2)
2468       Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
2469
2470       // For logical shifts, the truncation has the effect of making the high
2471       // part of the register be zeros.  Emulate this by inserting an AND to
2472       // clear the top bits as needed.  This 'and' will usually be zapped by
2473       // other xforms later if dead.
2474       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
2475       unsigned DstSize = TI->getType()->getScalarSizeInBits();
2476       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
2477       
2478       // The mask we constructed says what the trunc would do if occurring
2479       // between the shifts.  We want to know the effect *after* the second
2480       // shift.  We know that it is a logical shift by a constant, so adjust the
2481       // mask as appropriate.
2482       if (I.getOpcode() == Instruction::Shl)
2483         MaskV <<= Op1->getZExtValue();
2484       else {
2485         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
2486         MaskV = MaskV.lshr(Op1->getZExtValue());
2487       }
2488
2489       // shift1 & 0x00FF
2490       Value *And = Builder->CreateAnd(NSh,
2491                                       ConstantInt::get(I.getContext(), MaskV),
2492                                       TI->getName());
2493
2494       // Return the value truncated to the interesting size.
2495       return new TruncInst(And, I.getType());
2496     }
2497   }
2498   
2499   if (Op0->hasOneUse()) {
2500     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
2501       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
2502       Value *V1, *V2;
2503       ConstantInt *CC;
2504       switch (Op0BO->getOpcode()) {
2505         default: break;
2506         case Instruction::Add:
2507         case Instruction::And:
2508         case Instruction::Or:
2509         case Instruction::Xor: {
2510           // These operators commute.
2511           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
2512           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
2513               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
2514                     m_Specific(Op1)))) {
2515             Value *YS =         // (Y << C)
2516               Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
2517             // (X + (Y << C))
2518             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
2519                                             Op0BO->getOperand(1)->getName());
2520             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
2521             return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
2522                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
2523           }
2524           
2525           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
2526           Value *Op0BOOp1 = Op0BO->getOperand(1);
2527           if (isLeftShift && Op0BOOp1->hasOneUse() &&
2528               match(Op0BOOp1, 
2529                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
2530                           m_ConstantInt(CC))) &&
2531               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
2532             Value *YS =   // (Y << C)
2533               Builder->CreateShl(Op0BO->getOperand(0), Op1,
2534                                            Op0BO->getName());
2535             // X & (CC << C)
2536             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
2537                                            V1->getName()+".mask");
2538             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
2539           }
2540         }
2541           
2542         // FALL THROUGH.
2543         case Instruction::Sub: {
2544           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
2545           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
2546               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
2547                     m_Specific(Op1)))) {
2548             Value *YS =  // (Y << C)
2549               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
2550             // (X + (Y << C))
2551             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
2552                                             Op0BO->getOperand(0)->getName());
2553             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
2554             return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
2555                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
2556           }
2557           
2558           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
2559           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
2560               match(Op0BO->getOperand(0),
2561                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
2562                           m_ConstantInt(CC))) && V2 == Op1 &&
2563               cast<BinaryOperator>(Op0BO->getOperand(0))
2564                   ->getOperand(0)->hasOneUse()) {
2565             Value *YS = // (Y << C)
2566               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
2567             // X & (CC << C)
2568             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
2569                                            V1->getName()+".mask");
2570             
2571             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
2572           }
2573           
2574           break;
2575         }
2576       }
2577       
2578       
2579       // If the operand is an bitwise operator with a constant RHS, and the
2580       // shift is the only use, we can pull it out of the shift.
2581       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2582         bool isValid = true;     // Valid only for And, Or, Xor
2583         bool highBitSet = false; // Transform if high bit of constant set?
2584         
2585         switch (Op0BO->getOpcode()) {
2586           default: isValid = false; break;   // Do not perform transform!
2587           case Instruction::Add:
2588             isValid = isLeftShift;
2589             break;
2590           case Instruction::Or:
2591           case Instruction::Xor:
2592             highBitSet = false;
2593             break;
2594           case Instruction::And:
2595             highBitSet = true;
2596             break;
2597         }
2598         
2599         // If this is a signed shift right, and the high bit is modified
2600         // by the logical operation, do not perform the transformation.
2601         // The highBitSet boolean indicates the value of the high bit of
2602         // the constant which would cause it to be modified for this
2603         // operation.
2604         //
2605         if (isValid && I.getOpcode() == Instruction::AShr)
2606           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
2607         
2608         if (isValid) {
2609           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
2610           
2611           Value *NewShift =
2612             Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
2613           NewShift->takeName(Op0BO);
2614           
2615           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
2616                                         NewRHS);
2617         }
2618       }
2619     }
2620   }
2621   
2622   // Find out if this is a shift of a shift by a constant.
2623   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
2624   if (ShiftOp && !ShiftOp->isShift())
2625     ShiftOp = 0;
2626   
2627   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
2628     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
2629     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
2630     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
2631     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
2632     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
2633     Value *X = ShiftOp->getOperand(0);
2634     
2635     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
2636     
2637     const IntegerType *Ty = cast<IntegerType>(I.getType());
2638     
2639     // Check for (X << c1) << c2  and  (X >> c1) >> c2
2640     if (I.getOpcode() == ShiftOp->getOpcode()) {
2641       // If this is oversized composite shift, then unsigned shifts get 0, ashr
2642       // saturates.
2643       if (AmtSum >= TypeBits) {
2644         if (I.getOpcode() != Instruction::AShr)
2645           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2646         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
2647       }
2648       
2649       return BinaryOperator::Create(I.getOpcode(), X,
2650                                     ConstantInt::get(Ty, AmtSum));
2651     }
2652     
2653     if (ShiftOp->getOpcode() == Instruction::LShr &&
2654         I.getOpcode() == Instruction::AShr) {
2655       if (AmtSum >= TypeBits)
2656         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2657       
2658       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
2659       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
2660     }
2661     
2662     if (ShiftOp->getOpcode() == Instruction::AShr &&
2663         I.getOpcode() == Instruction::LShr) {
2664       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
2665       if (AmtSum >= TypeBits)
2666         AmtSum = TypeBits-1;
2667       
2668       Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
2669
2670       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
2671       return BinaryOperator::CreateAnd(Shift,
2672                                        ConstantInt::get(I.getContext(), Mask));
2673     }
2674     
2675     // Okay, if we get here, one shift must be left, and the other shift must be
2676     // right.  See if the amounts are equal.
2677     if (ShiftAmt1 == ShiftAmt2) {
2678       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
2679       if (I.getOpcode() == Instruction::Shl) {
2680         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
2681         return BinaryOperator::CreateAnd(X,
2682                                          ConstantInt::get(I.getContext(),Mask));
2683       }
2684       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
2685       if (I.getOpcode() == Instruction::LShr) {
2686         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
2687         return BinaryOperator::CreateAnd(X,
2688                                         ConstantInt::get(I.getContext(), Mask));
2689       }
2690       // We can simplify ((X << C) >>s C) into a trunc + sext.
2691       // NOTE: we could do this for any C, but that would make 'unusual' integer
2692       // types.  For now, just stick to ones well-supported by the code
2693       // generators.
2694       const Type *SExtType = 0;
2695       switch (Ty->getBitWidth() - ShiftAmt1) {
2696       case 1  :
2697       case 8  :
2698       case 16 :
2699       case 32 :
2700       case 64 :
2701       case 128:
2702         SExtType = IntegerType::get(I.getContext(),
2703                                     Ty->getBitWidth() - ShiftAmt1);
2704         break;
2705       default: break;
2706       }
2707       if (SExtType)
2708         return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
2709       // Otherwise, we can't handle it yet.
2710     } else if (ShiftAmt1 < ShiftAmt2) {
2711       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
2712       
2713       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
2714       if (I.getOpcode() == Instruction::Shl) {
2715         assert(ShiftOp->getOpcode() == Instruction::LShr ||
2716                ShiftOp->getOpcode() == Instruction::AShr);
2717         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
2718         
2719         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
2720         return BinaryOperator::CreateAnd(Shift,
2721                                          ConstantInt::get(I.getContext(),Mask));
2722       }
2723       
2724       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
2725       if (I.getOpcode() == Instruction::LShr) {
2726         assert(ShiftOp->getOpcode() == Instruction::Shl);
2727         Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
2728         
2729         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
2730         return BinaryOperator::CreateAnd(Shift,
2731                                          ConstantInt::get(I.getContext(),Mask));
2732       }
2733       
2734       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
2735     } else {
2736       assert(ShiftAmt2 < ShiftAmt1);
2737       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
2738
2739       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
2740       if (I.getOpcode() == Instruction::Shl) {
2741         assert(ShiftOp->getOpcode() == Instruction::LShr ||
2742                ShiftOp->getOpcode() == Instruction::AShr);
2743         Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
2744                                             ConstantInt::get(Ty, ShiftDiff));
2745         
2746         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
2747         return BinaryOperator::CreateAnd(Shift,
2748                                          ConstantInt::get(I.getContext(),Mask));
2749       }
2750       
2751       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
2752       if (I.getOpcode() == Instruction::LShr) {
2753         assert(ShiftOp->getOpcode() == Instruction::Shl);
2754         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
2755         
2756         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
2757         return BinaryOperator::CreateAnd(Shift,
2758                                          ConstantInt::get(I.getContext(),Mask));
2759       }
2760       
2761       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
2762     }
2763   }
2764   return 0;
2765 }
2766
2767
2768
2769 /// FindElementAtOffset - Given a type and a constant offset, determine whether
2770 /// or not there is a sequence of GEP indices into the type that will land us at
2771 /// the specified offset.  If so, fill them into NewIndices and return the
2772 /// resultant element type, otherwise return null.
2773 const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset, 
2774                                           SmallVectorImpl<Value*> &NewIndices) {
2775   if (!TD) return 0;
2776   if (!Ty->isSized()) return 0;
2777   
2778   // Start with the index over the outer type.  Note that the type size
2779   // might be zero (even if the offset isn't zero) if the indexed type
2780   // is something like [0 x {int, int}]
2781   const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
2782   int64_t FirstIdx = 0;
2783   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
2784     FirstIdx = Offset/TySize;
2785     Offset -= FirstIdx*TySize;
2786     
2787     // Handle hosts where % returns negative instead of values [0..TySize).
2788     if (Offset < 0) {
2789       --FirstIdx;
2790       Offset += TySize;
2791       assert(Offset >= 0);
2792     }
2793     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
2794   }
2795   
2796   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
2797     
2798   // Index into the types.  If we fail, set OrigBase to null.
2799   while (Offset) {
2800     // Indexing into tail padding between struct/array elements.
2801     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
2802       return 0;
2803     
2804     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
2805       const StructLayout *SL = TD->getStructLayout(STy);
2806       assert(Offset < (int64_t)SL->getSizeInBytes() &&
2807              "Offset must stay within the indexed type");
2808       
2809       unsigned Elt = SL->getElementContainingOffset(Offset);
2810       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
2811                                             Elt));
2812       
2813       Offset -= SL->getElementOffset(Elt);
2814       Ty = STy->getElementType(Elt);
2815     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
2816       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
2817       assert(EltSize && "Cannot index into a zero-sized array");
2818       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
2819       Offset %= EltSize;
2820       Ty = AT->getElementType();
2821     } else {
2822       // Otherwise, we can't index into the middle of this atomic type, bail.
2823       return 0;
2824     }
2825   }
2826   
2827   return Ty;
2828 }
2829
2830
2831
2832 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
2833   SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
2834
2835   if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
2836     return ReplaceInstUsesWith(GEP, V);
2837
2838   Value *PtrOp = GEP.getOperand(0);
2839
2840   if (isa<UndefValue>(GEP.getOperand(0)))
2841     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
2842
2843   // Eliminate unneeded casts for indices.
2844   if (TD) {
2845     bool MadeChange = false;
2846     unsigned PtrSize = TD->getPointerSizeInBits();
2847     
2848     gep_type_iterator GTI = gep_type_begin(GEP);
2849     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
2850          I != E; ++I, ++GTI) {
2851       if (!isa<SequentialType>(*GTI)) continue;
2852       
2853       // If we are using a wider index than needed for this platform, shrink it
2854       // to what we need.  If narrower, sign-extend it to what we need.  This
2855       // explicit cast can make subsequent optimizations more obvious.
2856       unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
2857       if (OpBits == PtrSize)
2858         continue;
2859       
2860       *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
2861       MadeChange = true;
2862     }
2863     if (MadeChange) return &GEP;
2864   }
2865
2866   // Combine Indices - If the source pointer to this getelementptr instruction
2867   // is a getelementptr instruction, combine the indices of the two
2868   // getelementptr instructions into a single instruction.
2869   //
2870   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
2871     // Note that if our source is a gep chain itself that we wait for that
2872     // chain to be resolved before we perform this transformation.  This
2873     // avoids us creating a TON of code in some cases.
2874     //
2875     if (GetElementPtrInst *SrcGEP =
2876           dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
2877       if (SrcGEP->getNumOperands() == 2)
2878         return 0;   // Wait until our source is folded to completion.
2879
2880     SmallVector<Value*, 8> Indices;
2881
2882     // Find out whether the last index in the source GEP is a sequential idx.
2883     bool EndsWithSequential = false;
2884     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
2885          I != E; ++I)
2886       EndsWithSequential = !isa<StructType>(*I);
2887
2888     // Can we combine the two pointer arithmetics offsets?
2889     if (EndsWithSequential) {
2890       // Replace: gep (gep %P, long B), long A, ...
2891       // With:    T = long A+B; gep %P, T, ...
2892       //
2893       Value *Sum;
2894       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
2895       Value *GO1 = GEP.getOperand(1);
2896       if (SO1 == Constant::getNullValue(SO1->getType())) {
2897         Sum = GO1;
2898       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
2899         Sum = SO1;
2900       } else {
2901         // If they aren't the same type, then the input hasn't been processed
2902         // by the loop above yet (which canonicalizes sequential index types to
2903         // intptr_t).  Just avoid transforming this until the input has been
2904         // normalized.
2905         if (SO1->getType() != GO1->getType())
2906           return 0;
2907         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
2908       }
2909
2910       // Update the GEP in place if possible.
2911       if (Src->getNumOperands() == 2) {
2912         GEP.setOperand(0, Src->getOperand(0));
2913         GEP.setOperand(1, Sum);
2914         return &GEP;
2915       }
2916       Indices.append(Src->op_begin()+1, Src->op_end()-1);
2917       Indices.push_back(Sum);
2918       Indices.append(GEP.op_begin()+2, GEP.op_end());
2919     } else if (isa<Constant>(*GEP.idx_begin()) &&
2920                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
2921                Src->getNumOperands() != 1) {
2922       // Otherwise we can do the fold if the first index of the GEP is a zero
2923       Indices.append(Src->op_begin()+1, Src->op_end());
2924       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
2925     }
2926
2927     if (!Indices.empty())
2928       return (cast<GEPOperator>(&GEP)->isInBounds() &&
2929               Src->isInBounds()) ?
2930         GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
2931                                           Indices.end(), GEP.getName()) :
2932         GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
2933                                   Indices.end(), GEP.getName());
2934   }
2935   
2936   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
2937   if (Value *X = getBitCastOperand(PtrOp)) {
2938     assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
2939
2940     // If the input bitcast is actually "bitcast(bitcast(x))", then we don't 
2941     // want to change the gep until the bitcasts are eliminated.
2942     if (getBitCastOperand(X)) {
2943       Worklist.AddValue(PtrOp);
2944       return 0;
2945     }
2946     
2947     bool HasZeroPointerIndex = false;
2948     if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
2949       HasZeroPointerIndex = C->isZero();
2950     
2951     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
2952     // into     : GEP [10 x i8]* X, i32 0, ...
2953     //
2954     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
2955     //           into     : GEP i8* X, ...
2956     // 
2957     // This occurs when the program declares an array extern like "int X[];"
2958     if (HasZeroPointerIndex) {
2959       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
2960       const PointerType *XTy = cast<PointerType>(X->getType());
2961       if (const ArrayType *CATy =
2962           dyn_cast<ArrayType>(CPTy->getElementType())) {
2963         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
2964         if (CATy->getElementType() == XTy->getElementType()) {
2965           // -> GEP i8* X, ...
2966           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
2967           return cast<GEPOperator>(&GEP)->isInBounds() ?
2968             GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
2969                                               GEP.getName()) :
2970             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
2971                                       GEP.getName());
2972         }
2973         
2974         if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
2975           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
2976           if (CATy->getElementType() == XATy->getElementType()) {
2977             // -> GEP [10 x i8]* X, i32 0, ...
2978             // At this point, we know that the cast source type is a pointer
2979             // to an array of the same type as the destination pointer
2980             // array.  Because the array type is never stepped over (there
2981             // is a leading zero) we can fold the cast into this GEP.
2982             GEP.setOperand(0, X);
2983             return &GEP;
2984           }
2985         }
2986       }
2987     } else if (GEP.getNumOperands() == 2) {
2988       // Transform things like:
2989       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
2990       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
2991       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
2992       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
2993       if (TD && isa<ArrayType>(SrcElTy) &&
2994           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
2995           TD->getTypeAllocSize(ResElTy)) {
2996         Value *Idx[2];
2997         Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
2998         Idx[1] = GEP.getOperand(1);
2999         Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
3000           Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
3001           Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
3002         // V and GEP are both pointer types --> BitCast
3003         return new BitCastInst(NewGEP, GEP.getType());
3004       }
3005       
3006       // Transform things like:
3007       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
3008       //   (where tmp = 8*tmp2) into:
3009       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
3010       
3011       if (TD && isa<ArrayType>(SrcElTy) &&
3012           ResElTy == Type::getInt8Ty(GEP.getContext())) {
3013         uint64_t ArrayEltSize =
3014             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
3015         
3016         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
3017         // allow either a mul, shift, or constant here.
3018         Value *NewIdx = 0;
3019         ConstantInt *Scale = 0;
3020         if (ArrayEltSize == 1) {
3021           NewIdx = GEP.getOperand(1);
3022           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
3023         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
3024           NewIdx = ConstantInt::get(CI->getType(), 1);
3025           Scale = CI;
3026         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
3027           if (Inst->getOpcode() == Instruction::Shl &&
3028               isa<ConstantInt>(Inst->getOperand(1))) {
3029             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
3030             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
3031             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
3032                                      1ULL << ShAmtVal);
3033             NewIdx = Inst->getOperand(0);
3034           } else if (Inst->getOpcode() == Instruction::Mul &&
3035                      isa<ConstantInt>(Inst->getOperand(1))) {
3036             Scale = cast<ConstantInt>(Inst->getOperand(1));
3037             NewIdx = Inst->getOperand(0);
3038           }
3039         }
3040         
3041         // If the index will be to exactly the right offset with the scale taken
3042         // out, perform the transformation. Note, we don't know whether Scale is
3043         // signed or not. We'll use unsigned version of division/modulo
3044         // operation after making sure Scale doesn't have the sign bit set.
3045         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
3046             Scale->getZExtValue() % ArrayEltSize == 0) {
3047           Scale = ConstantInt::get(Scale->getType(),
3048                                    Scale->getZExtValue() / ArrayEltSize);
3049           if (Scale->getZExtValue() != 1) {
3050             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
3051                                                        false /*ZExt*/);
3052             NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
3053           }
3054
3055           // Insert the new GEP instruction.
3056           Value *Idx[2];
3057           Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
3058           Idx[1] = NewIdx;
3059           Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
3060             Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
3061             Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
3062           // The NewGEP must be pointer typed, so must the old one -> BitCast
3063           return new BitCastInst(NewGEP, GEP.getType());
3064         }
3065       }
3066     }
3067   }
3068   
3069   /// See if we can simplify:
3070   ///   X = bitcast A* to B*
3071   ///   Y = gep X, <...constant indices...>
3072   /// into a gep of the original struct.  This is important for SROA and alias
3073   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
3074   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
3075     if (TD &&
3076         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
3077       // Determine how much the GEP moves the pointer.  We are guaranteed to get
3078       // a constant back from EmitGEPOffset.
3079       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
3080       int64_t Offset = OffsetV->getSExtValue();
3081       
3082       // If this GEP instruction doesn't move the pointer, just replace the GEP
3083       // with a bitcast of the real input to the dest type.
3084       if (Offset == 0) {
3085         // If the bitcast is of an allocation, and the allocation will be
3086         // converted to match the type of the cast, don't touch this.
3087         if (isa<AllocaInst>(BCI->getOperand(0)) ||
3088             isMalloc(BCI->getOperand(0))) {
3089           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
3090           if (Instruction *I = visitBitCast(*BCI)) {
3091             if (I != BCI) {
3092               I->takeName(BCI);
3093               BCI->getParent()->getInstList().insert(BCI, I);
3094               ReplaceInstUsesWith(*BCI, I);
3095             }
3096             return &GEP;
3097           }
3098         }
3099         return new BitCastInst(BCI->getOperand(0), GEP.getType());
3100       }
3101       
3102       // Otherwise, if the offset is non-zero, we need to find out if there is a
3103       // field at Offset in 'A's type.  If so, we can pull the cast through the
3104       // GEP.
3105       SmallVector<Value*, 8> NewIndices;
3106       const Type *InTy =
3107         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
3108       if (FindElementAtOffset(InTy, Offset, NewIndices)) {
3109         Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
3110           Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
3111                                      NewIndices.end()) :
3112           Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
3113                              NewIndices.end());
3114         
3115         if (NGEP->getType() == GEP.getType())
3116           return ReplaceInstUsesWith(GEP, NGEP);
3117         NGEP->takeName(&GEP);
3118         return new BitCastInst(NGEP, GEP.getType());
3119       }
3120     }
3121   }    
3122     
3123   return 0;
3124 }
3125
3126 Instruction *InstCombiner::visitFree(Instruction &FI) {
3127   Value *Op = FI.getOperand(1);
3128
3129   // free undef -> unreachable.
3130   if (isa<UndefValue>(Op)) {
3131     // Insert a new store to null because we cannot modify the CFG here.
3132     new StoreInst(ConstantInt::getTrue(FI.getContext()),
3133            UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
3134     return EraseInstFromFunction(FI);
3135   }
3136   
3137   // If we have 'free null' delete the instruction.  This can happen in stl code
3138   // when lots of inlining happens.
3139   if (isa<ConstantPointerNull>(Op))
3140     return EraseInstFromFunction(FI);
3141
3142   // If we have a malloc call whose only use is a free call, delete both.
3143   if (isMalloc(Op)) {
3144     if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
3145       if (Op->hasOneUse() && CI->hasOneUse()) {
3146         EraseInstFromFunction(FI);
3147         EraseInstFromFunction(*CI);
3148         return EraseInstFromFunction(*cast<Instruction>(Op));
3149       }
3150     } else {
3151       // Op is a call to malloc
3152       if (Op->hasOneUse()) {
3153         EraseInstFromFunction(FI);
3154         return EraseInstFromFunction(*cast<Instruction>(Op));
3155       }
3156     }
3157   }
3158
3159   return 0;
3160 }
3161
3162
3163
3164 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3165   // Change br (not X), label True, label False to: br X, label False, True
3166   Value *X = 0;
3167   BasicBlock *TrueDest;
3168   BasicBlock *FalseDest;
3169   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
3170       !isa<Constant>(X)) {
3171     // Swap Destinations and condition...
3172     BI.setCondition(X);
3173     BI.setSuccessor(0, FalseDest);
3174     BI.setSuccessor(1, TrueDest);
3175     return &BI;
3176   }
3177
3178   // Cannonicalize fcmp_one -> fcmp_oeq
3179   FCmpInst::Predicate FPred; Value *Y;
3180   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
3181                              TrueDest, FalseDest)) &&
3182       BI.getCondition()->hasOneUse())
3183     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
3184         FPred == FCmpInst::FCMP_OGE) {
3185       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
3186       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
3187       
3188       // Swap Destinations and condition.
3189       BI.setSuccessor(0, FalseDest);
3190       BI.setSuccessor(1, TrueDest);
3191       Worklist.Add(Cond);
3192       return &BI;
3193     }
3194
3195   // Cannonicalize icmp_ne -> icmp_eq
3196   ICmpInst::Predicate IPred;
3197   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
3198                       TrueDest, FalseDest)) &&
3199       BI.getCondition()->hasOneUse())
3200     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
3201         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
3202         IPred == ICmpInst::ICMP_SGE) {
3203       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
3204       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
3205       // Swap Destinations and condition.
3206       BI.setSuccessor(0, FalseDest);
3207       BI.setSuccessor(1, TrueDest);
3208       Worklist.Add(Cond);
3209       return &BI;
3210     }
3211
3212   return 0;
3213 }
3214
3215 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
3216   Value *Cond = SI.getCondition();
3217   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
3218     if (I->getOpcode() == Instruction::Add)
3219       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3220         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
3221         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
3222           SI.setOperand(i,
3223                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
3224                                                 AddRHS));
3225         SI.setOperand(0, I->getOperand(0));
3226         Worklist.Add(I);
3227         return &SI;
3228       }
3229   }
3230   return 0;
3231 }
3232
3233 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
3234   Value *Agg = EV.getAggregateOperand();
3235
3236   if (!EV.hasIndices())
3237     return ReplaceInstUsesWith(EV, Agg);
3238
3239   if (Constant *C = dyn_cast<Constant>(Agg)) {
3240     if (isa<UndefValue>(C))
3241       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
3242       
3243     if (isa<ConstantAggregateZero>(C))
3244       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
3245
3246     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
3247       // Extract the element indexed by the first index out of the constant
3248       Value *V = C->getOperand(*EV.idx_begin());
3249       if (EV.getNumIndices() > 1)
3250         // Extract the remaining indices out of the constant indexed by the
3251         // first index
3252         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
3253       else
3254         return ReplaceInstUsesWith(EV, V);
3255     }
3256     return 0; // Can't handle other constants
3257   } 
3258   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
3259     // We're extracting from an insertvalue instruction, compare the indices
3260     const unsigned *exti, *exte, *insi, *inse;
3261     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
3262          exte = EV.idx_end(), inse = IV->idx_end();
3263          exti != exte && insi != inse;
3264          ++exti, ++insi) {
3265       if (*insi != *exti)
3266         // The insert and extract both reference distinctly different elements.
3267         // This means the extract is not influenced by the insert, and we can
3268         // replace the aggregate operand of the extract with the aggregate
3269         // operand of the insert. i.e., replace
3270         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
3271         // %E = extractvalue { i32, { i32 } } %I, 0
3272         // with
3273         // %E = extractvalue { i32, { i32 } } %A, 0
3274         return ExtractValueInst::Create(IV->getAggregateOperand(),
3275                                         EV.idx_begin(), EV.idx_end());
3276     }
3277     if (exti == exte && insi == inse)
3278       // Both iterators are at the end: Index lists are identical. Replace
3279       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
3280       // %C = extractvalue { i32, { i32 } } %B, 1, 0
3281       // with "i32 42"
3282       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
3283     if (exti == exte) {
3284       // The extract list is a prefix of the insert list. i.e. replace
3285       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
3286       // %E = extractvalue { i32, { i32 } } %I, 1
3287       // with
3288       // %X = extractvalue { i32, { i32 } } %A, 1
3289       // %E = insertvalue { i32 } %X, i32 42, 0
3290       // by switching the order of the insert and extract (though the
3291       // insertvalue should be left in, since it may have other uses).
3292       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
3293                                                  EV.idx_begin(), EV.idx_end());
3294       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
3295                                      insi, inse);
3296     }
3297     if (insi == inse)
3298       // The insert list is a prefix of the extract list
3299       // We can simply remove the common indices from the extract and make it
3300       // operate on the inserted value instead of the insertvalue result.
3301       // i.e., replace
3302       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
3303       // %E = extractvalue { i32, { i32 } } %I, 1, 0
3304       // with
3305       // %E extractvalue { i32 } { i32 42 }, 0
3306       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
3307                                       exti, exte);
3308   }
3309   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
3310     // We're extracting from an intrinsic, see if we're the only user, which
3311     // allows us to simplify multiple result intrinsics to simpler things that
3312     // just get one value..
3313     if (II->hasOneUse()) {
3314       // Check if we're grabbing the overflow bit or the result of a 'with
3315       // overflow' intrinsic.  If it's the latter we can remove the intrinsic
3316       // and replace it with a traditional binary instruction.
3317       switch (II->getIntrinsicID()) {
3318       case Intrinsic::uadd_with_overflow:
3319       case Intrinsic::sadd_with_overflow:
3320         if (*EV.idx_begin() == 0) {  // Normal result.
3321           Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
3322           II->replaceAllUsesWith(UndefValue::get(II->getType()));
3323           EraseInstFromFunction(*II);
3324           return BinaryOperator::CreateAdd(LHS, RHS);
3325         }
3326         break;
3327       case Intrinsic::usub_with_overflow:
3328       case Intrinsic::ssub_with_overflow:
3329         if (*EV.idx_begin() == 0) {  // Normal result.
3330           Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
3331           II->replaceAllUsesWith(UndefValue::get(II->getType()));
3332           EraseInstFromFunction(*II);
3333           return BinaryOperator::CreateSub(LHS, RHS);
3334         }
3335         break;
3336       case Intrinsic::umul_with_overflow:
3337       case Intrinsic::smul_with_overflow:
3338         if (*EV.idx_begin() == 0) {  // Normal result.
3339           Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
3340           II->replaceAllUsesWith(UndefValue::get(II->getType()));
3341           EraseInstFromFunction(*II);
3342           return BinaryOperator::CreateMul(LHS, RHS);
3343         }
3344         break;
3345       default:
3346         break;
3347       }
3348     }
3349   }
3350   // Can't simplify extracts from other values. Note that nested extracts are
3351   // already simplified implicitely by the above (extract ( extract (insert) )
3352   // will be translated into extract ( insert ( extract ) ) first and then just
3353   // the value inserted, if appropriate).
3354   return 0;
3355 }
3356
3357
3358
3359
3360 /// TryToSinkInstruction - Try to move the specified instruction from its
3361 /// current block into the beginning of DestBlock, which can only happen if it's
3362 /// safe to move the instruction past all of the instructions between it and the
3363 /// end of its block.
3364 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
3365   assert(I->hasOneUse() && "Invariants didn't hold!");
3366
3367   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
3368   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
3369     return false;
3370
3371   // Do not sink alloca instructions out of the entry block.
3372   if (isa<AllocaInst>(I) && I->getParent() ==
3373         &DestBlock->getParent()->getEntryBlock())
3374     return false;
3375
3376   // We can only sink load instructions if there is nothing between the load and
3377   // the end of block that could change the value.
3378   if (I->mayReadFromMemory()) {
3379     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
3380          Scan != E; ++Scan)
3381       if (Scan->mayWriteToMemory())
3382         return false;
3383   }
3384
3385   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
3386
3387   I->moveBefore(InsertPos);
3388   ++NumSunkInst;
3389   return true;
3390 }
3391
3392
3393 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
3394 /// all reachable code to the worklist.
3395 ///
3396 /// This has a couple of tricks to make the code faster and more powerful.  In
3397 /// particular, we constant fold and DCE instructions as we go, to avoid adding
3398 /// them to the worklist (this significantly speeds up instcombine on code where
3399 /// many instructions are dead or constant).  Additionally, if we find a branch
3400 /// whose condition is a known constant, we only visit the reachable successors.
3401 ///
3402 static bool AddReachableCodeToWorklist(BasicBlock *BB, 
3403                                        SmallPtrSet<BasicBlock*, 64> &Visited,
3404                                        InstCombiner &IC,
3405                                        const TargetData *TD) {
3406   bool MadeIRChange = false;
3407   SmallVector<BasicBlock*, 256> Worklist;
3408   Worklist.push_back(BB);
3409   
3410   std::vector<Instruction*> InstrsForInstCombineWorklist;
3411   InstrsForInstCombineWorklist.reserve(128);
3412
3413   SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
3414   
3415   while (!Worklist.empty()) {
3416     BB = Worklist.back();
3417     Worklist.pop_back();
3418     
3419     // We have now visited this block!  If we've already been here, ignore it.
3420     if (!Visited.insert(BB)) continue;
3421
3422     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
3423       Instruction *Inst = BBI++;
3424       
3425       // DCE instruction if trivially dead.
3426       if (isInstructionTriviallyDead(Inst)) {
3427         ++NumDeadInst;
3428         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
3429         Inst->eraseFromParent();
3430         continue;
3431       }
3432       
3433       // ConstantProp instruction if trivially constant.
3434       if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
3435         if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
3436           DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
3437                        << *Inst << '\n');
3438           Inst->replaceAllUsesWith(C);
3439           ++NumConstProp;
3440           Inst->eraseFromParent();
3441           continue;
3442         }
3443       
3444       
3445       
3446       if (TD) {
3447         // See if we can constant fold its operands.
3448         for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
3449              i != e; ++i) {
3450           ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
3451           if (CE == 0) continue;
3452           
3453           // If we already folded this constant, don't try again.
3454           if (!FoldedConstants.insert(CE))
3455             continue;
3456           
3457           Constant *NewC = ConstantFoldConstantExpression(CE, TD);
3458           if (NewC && NewC != CE) {
3459             *i = NewC;
3460             MadeIRChange = true;
3461           }
3462         }
3463       }
3464       
3465
3466       InstrsForInstCombineWorklist.push_back(Inst);
3467     }
3468
3469     // Recursively visit successors.  If this is a branch or switch on a
3470     // constant, only visit the reachable successor.
3471     TerminatorInst *TI = BB->getTerminator();
3472     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3473       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
3474         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
3475         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
3476         Worklist.push_back(ReachableBB);
3477         continue;
3478       }
3479     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3480       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
3481         // See if this is an explicit destination.
3482         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
3483           if (SI->getCaseValue(i) == Cond) {
3484             BasicBlock *ReachableBB = SI->getSuccessor(i);
3485             Worklist.push_back(ReachableBB);
3486             continue;
3487           }
3488         
3489         // Otherwise it is the default destination.
3490         Worklist.push_back(SI->getSuccessor(0));
3491         continue;
3492       }
3493     }
3494     
3495     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
3496       Worklist.push_back(TI->getSuccessor(i));
3497   }
3498   
3499   // Once we've found all of the instructions to add to instcombine's worklist,
3500   // add them in reverse order.  This way instcombine will visit from the top
3501   // of the function down.  This jives well with the way that it adds all uses
3502   // of instructions to the worklist after doing a transformation, thus avoiding
3503   // some N^2 behavior in pathological cases.
3504   IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
3505                               InstrsForInstCombineWorklist.size());
3506   
3507   return MadeIRChange;
3508 }
3509
3510 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
3511   MadeIRChange = false;
3512   
3513   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
3514         << F.getNameStr() << "\n");
3515
3516   {
3517     // Do a depth-first traversal of the function, populate the worklist with
3518     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
3519     // track of which blocks we visit.
3520     SmallPtrSet<BasicBlock*, 64> Visited;
3521     MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
3522
3523     // Do a quick scan over the function.  If we find any blocks that are
3524     // unreachable, remove any instructions inside of them.  This prevents
3525     // the instcombine code from having to deal with some bad special cases.
3526     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
3527       if (!Visited.count(BB)) {
3528         Instruction *Term = BB->getTerminator();
3529         while (Term != BB->begin()) {   // Remove instrs bottom-up
3530           BasicBlock::iterator I = Term; --I;
3531
3532           DEBUG(errs() << "IC: DCE: " << *I << '\n');
3533           // A debug intrinsic shouldn't force another iteration if we weren't
3534           // going to do one without it.
3535           if (!isa<DbgInfoIntrinsic>(I)) {
3536             ++NumDeadInst;
3537             MadeIRChange = true;
3538           }
3539
3540           // If I is not void type then replaceAllUsesWith undef.
3541           // This allows ValueHandlers and custom metadata to adjust itself.
3542           if (!I->getType()->isVoidTy())
3543             I->replaceAllUsesWith(UndefValue::get(I->getType()));
3544           I->eraseFromParent();
3545         }
3546       }
3547   }
3548
3549   while (!Worklist.isEmpty()) {
3550     Instruction *I = Worklist.RemoveOne();
3551     if (I == 0) continue;  // skip null values.
3552
3553     // Check to see if we can DCE the instruction.
3554     if (isInstructionTriviallyDead(I)) {
3555       DEBUG(errs() << "IC: DCE: " << *I << '\n');
3556       EraseInstFromFunction(*I);
3557       ++NumDeadInst;
3558       MadeIRChange = true;
3559       continue;
3560     }
3561
3562     // Instruction isn't dead, see if we can constant propagate it.
3563     if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
3564       if (Constant *C = ConstantFoldInstruction(I, TD)) {
3565         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
3566
3567         // Add operands to the worklist.
3568         ReplaceInstUsesWith(*I, C);
3569         ++NumConstProp;
3570         EraseInstFromFunction(*I);
3571         MadeIRChange = true;
3572         continue;
3573       }
3574
3575     // See if we can trivially sink this instruction to a successor basic block.
3576     if (I->hasOneUse()) {
3577       BasicBlock *BB = I->getParent();
3578       Instruction *UserInst = cast<Instruction>(I->use_back());
3579       BasicBlock *UserParent;
3580       
3581       // Get the block the use occurs in.
3582       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
3583         UserParent = PN->getIncomingBlock(I->use_begin().getUse());
3584       else
3585         UserParent = UserInst->getParent();
3586       
3587       if (UserParent != BB) {
3588         bool UserIsSuccessor = false;
3589         // See if the user is one of our successors.
3590         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
3591           if (*SI == UserParent) {
3592             UserIsSuccessor = true;
3593             break;
3594           }
3595
3596         // If the user is one of our immediate successors, and if that successor
3597         // only has us as a predecessors (we'd have to split the critical edge
3598         // otherwise), we can keep going.
3599         if (UserIsSuccessor && UserParent->getSinglePredecessor())
3600           // Okay, the CFG is simple enough, try to sink this instruction.
3601           MadeIRChange |= TryToSinkInstruction(I, UserParent);
3602       }
3603     }
3604
3605     // Now that we have an instruction, try combining it to simplify it.
3606     Builder->SetInsertPoint(I->getParent(), I);
3607     
3608 #ifndef NDEBUG
3609     std::string OrigI;
3610 #endif
3611     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
3612     DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
3613
3614     if (Instruction *Result = visit(*I)) {
3615       ++NumCombined;
3616       // Should we replace the old instruction with a new one?
3617       if (Result != I) {
3618         DEBUG(errs() << "IC: Old = " << *I << '\n'
3619                      << "    New = " << *Result << '\n');
3620
3621         // Everything uses the new instruction now.
3622         I->replaceAllUsesWith(Result);
3623
3624         // Push the new instruction and any users onto the worklist.
3625         Worklist.Add(Result);
3626         Worklist.AddUsersToWorkList(*Result);
3627
3628         // Move the name to the new instruction first.
3629         Result->takeName(I);
3630
3631         // Insert the new instruction into the basic block...
3632         BasicBlock *InstParent = I->getParent();
3633         BasicBlock::iterator InsertPos = I;
3634
3635         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
3636           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
3637             ++InsertPos;
3638
3639         InstParent->getInstList().insert(InsertPos, Result);
3640
3641         EraseInstFromFunction(*I);
3642       } else {
3643 #ifndef NDEBUG
3644         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
3645                      << "    New = " << *I << '\n');
3646 #endif
3647
3648         // If the instruction was modified, it's possible that it is now dead.
3649         // if so, remove it.
3650         if (isInstructionTriviallyDead(I)) {
3651           EraseInstFromFunction(*I);
3652         } else {
3653           Worklist.Add(I);
3654           Worklist.AddUsersToWorkList(*I);
3655         }
3656       }
3657       MadeIRChange = true;
3658     }
3659   }
3660
3661   Worklist.Zap();
3662   return MadeIRChange;
3663 }
3664
3665
3666 bool InstCombiner::runOnFunction(Function &F) {
3667   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
3668   TD = getAnalysisIfAvailable<TargetData>();
3669
3670   
3671   /// Builder - This is an IRBuilder that automatically inserts new
3672   /// instructions into the worklist when they are created.
3673   IRBuilder<true, TargetFolder, InstCombineIRInserter> 
3674     TheBuilder(F.getContext(), TargetFolder(TD),
3675                InstCombineIRInserter(Worklist));
3676   Builder = &TheBuilder;
3677   
3678   bool EverMadeChange = false;
3679
3680   // Iterate while there is work to do.
3681   unsigned Iteration = 0;
3682   while (DoOneIteration(F, Iteration++))
3683     EverMadeChange = true;
3684   
3685   Builder = 0;
3686   return EverMadeChange;
3687 }
3688
3689 FunctionPass *llvm::createInstructionCombiningPass() {
3690   return new InstCombiner();
3691 }