For PR950:
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 algebraic
12 // simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add int %X, 1
16 //    %Z = add int %Y, 1
17 // into:
18 //    %Z = add int %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. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All SetCC 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 "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "llvm/Support/CallSite.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/GetElementPtrTypeIterator.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/PatternMatch.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include <algorithm>
55 #include <iostream>
56 using namespace llvm;
57 using namespace llvm::PatternMatch;
58
59 namespace {
60   Statistic<> NumCombined ("instcombine", "Number of insts combined");
61   Statistic<> NumConstProp("instcombine", "Number of constant folds");
62   Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
63   Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
64   Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
65
66   class VISIBILITY_HIDDEN InstCombiner
67     : public FunctionPass,
68       public InstVisitor<InstCombiner, Instruction*> {
69     // Worklist of all of the instructions that need to be simplified.
70     std::vector<Instruction*> WorkList;
71     TargetData *TD;
72
73     /// AddUsersToWorkList - When an instruction is simplified, add all users of
74     /// the instruction to the work lists because they might get more simplified
75     /// now.
76     ///
77     void AddUsersToWorkList(Value &I) {
78       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
79            UI != UE; ++UI)
80         WorkList.push_back(cast<Instruction>(*UI));
81     }
82
83     /// AddUsesToWorkList - When an instruction is simplified, add operands to
84     /// the work lists because they might get more simplified now.
85     ///
86     void AddUsesToWorkList(Instruction &I) {
87       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
88         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
89           WorkList.push_back(Op);
90     }
91     
92     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
93     /// dead.  Add all of its operands to the worklist, turning them into
94     /// undef's to reduce the number of uses of those instructions.
95     ///
96     /// Return the specified operand before it is turned into an undef.
97     ///
98     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
99       Value *R = I.getOperand(op);
100       
101       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
102         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
103           WorkList.push_back(Op);
104           // Set the operand to undef to drop the use.
105           I.setOperand(i, UndefValue::get(Op->getType()));
106         }
107       
108       return R;
109     }
110
111     // removeFromWorkList - remove all instances of I from the worklist.
112     void removeFromWorkList(Instruction *I);
113   public:
114     virtual bool runOnFunction(Function &F);
115
116     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
117       AU.addRequired<TargetData>();
118       AU.addPreservedID(LCSSAID);
119       AU.setPreservesCFG();
120     }
121
122     TargetData &getTargetData() const { return *TD; }
123
124     // Visitation implementation - Implement instruction combining for different
125     // instruction types.  The semantics are as follows:
126     // Return Value:
127     //    null        - No change was made
128     //     I          - Change was made, I is still valid, I may be dead though
129     //   otherwise    - Change was made, replace I with returned instruction
130     //
131     Instruction *visitAdd(BinaryOperator &I);
132     Instruction *visitSub(BinaryOperator &I);
133     Instruction *visitMul(BinaryOperator &I);
134     Instruction *visitDiv(BinaryOperator &I);
135     Instruction *visitRem(BinaryOperator &I);
136     Instruction *visitAnd(BinaryOperator &I);
137     Instruction *visitOr (BinaryOperator &I);
138     Instruction *visitXor(BinaryOperator &I);
139     Instruction *visitSetCondInst(SetCondInst &I);
140     Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
141
142     Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
143                               Instruction::BinaryOps Cond, Instruction &I);
144     Instruction *visitShiftInst(ShiftInst &I);
145     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
146                                      ShiftInst &I);
147     Instruction *visitCastInst(CastInst &CI);
148     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
149                                 Instruction *FI);
150     Instruction *visitSelectInst(SelectInst &CI);
151     Instruction *visitCallInst(CallInst &CI);
152     Instruction *visitInvokeInst(InvokeInst &II);
153     Instruction *visitPHINode(PHINode &PN);
154     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
155     Instruction *visitAllocationInst(AllocationInst &AI);
156     Instruction *visitFreeInst(FreeInst &FI);
157     Instruction *visitLoadInst(LoadInst &LI);
158     Instruction *visitStoreInst(StoreInst &SI);
159     Instruction *visitBranchInst(BranchInst &BI);
160     Instruction *visitSwitchInst(SwitchInst &SI);
161     Instruction *visitInsertElementInst(InsertElementInst &IE);
162     Instruction *visitExtractElementInst(ExtractElementInst &EI);
163     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
164
165     // visitInstruction - Specify what to return for unhandled instructions...
166     Instruction *visitInstruction(Instruction &I) { return 0; }
167
168   private:
169     Instruction *visitCallSite(CallSite CS);
170     bool transformConstExprCastCall(CallSite CS);
171
172   public:
173     // InsertNewInstBefore - insert an instruction New before instruction Old
174     // in the program.  Add the new instruction to the worklist.
175     //
176     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
177       assert(New && New->getParent() == 0 &&
178              "New instruction already inserted into a basic block!");
179       BasicBlock *BB = Old.getParent();
180       BB->getInstList().insert(&Old, New);  // Insert inst
181       WorkList.push_back(New);              // Add to worklist
182       return New;
183     }
184
185     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
186     /// This also adds the cast to the worklist.  Finally, this returns the
187     /// cast.
188     Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
189       if (V->getType() == Ty) return V;
190
191       if (Constant *CV = dyn_cast<Constant>(V))
192         return ConstantExpr::getCast(CV, Ty);
193       
194       Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
195       WorkList.push_back(C);
196       return C;
197     }
198
199     // ReplaceInstUsesWith - This method is to be used when an instruction is
200     // found to be dead, replacable with another preexisting expression.  Here
201     // we add all uses of I to the worklist, replace all uses of I with the new
202     // value, then return I, so that the inst combiner will know that I was
203     // modified.
204     //
205     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
206       AddUsersToWorkList(I);         // Add all modified instrs to worklist
207       if (&I != V) {
208         I.replaceAllUsesWith(V);
209         return &I;
210       } else {
211         // If we are replacing the instruction with itself, this must be in a
212         // segment of unreachable code, so just clobber the instruction.
213         I.replaceAllUsesWith(UndefValue::get(I.getType()));
214         return &I;
215       }
216     }
217
218     // UpdateValueUsesWith - This method is to be used when an value is
219     // found to be replacable with another preexisting expression or was
220     // updated.  Here we add all uses of I to the worklist, replace all uses of
221     // I with the new value (unless the instruction was just updated), then
222     // return true, so that the inst combiner will know that I was modified.
223     //
224     bool UpdateValueUsesWith(Value *Old, Value *New) {
225       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
226       if (Old != New)
227         Old->replaceAllUsesWith(New);
228       if (Instruction *I = dyn_cast<Instruction>(Old))
229         WorkList.push_back(I);
230       if (Instruction *I = dyn_cast<Instruction>(New))
231         WorkList.push_back(I);
232       return true;
233     }
234     
235     // EraseInstFromFunction - When dealing with an instruction that has side
236     // effects or produces a void value, we can't rely on DCE to delete the
237     // instruction.  Instead, visit methods should return the value returned by
238     // this function.
239     Instruction *EraseInstFromFunction(Instruction &I) {
240       assert(I.use_empty() && "Cannot erase instruction that is used!");
241       AddUsesToWorkList(I);
242       removeFromWorkList(&I);
243       I.eraseFromParent();
244       return 0;  // Don't do anything with FI
245     }
246
247   private:
248     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
249     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
250     /// casts that are known to not do anything...
251     ///
252     Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
253                                    Instruction *InsertBefore);
254
255     // SimplifyCommutative - This performs a few simplifications for commutative
256     // operators.
257     bool SimplifyCommutative(BinaryOperator &I);
258
259     bool SimplifyDemandedBits(Value *V, uint64_t Mask, 
260                               uint64_t &KnownZero, uint64_t &KnownOne,
261                               unsigned Depth = 0);
262
263     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
264                                       uint64_t &UndefElts, unsigned Depth = 0);
265       
266     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
267     // PHI node as operand #0, see if we can fold the instruction into the PHI
268     // (which is only possible if all operands to the PHI are constants).
269     Instruction *FoldOpIntoPhi(Instruction &I);
270
271     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
272     // operator and they all are only used by the PHI, PHI together their
273     // inputs, and do the operation once, to the result of the PHI.
274     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
275
276     Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
277                           ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
278     
279     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
280                               bool isSub, Instruction &I);
281     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
282                                  bool Inside, Instruction &IB);
283     Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
284     Instruction *MatchBSwap(BinaryOperator &I);
285
286     Value *EvaluateInDifferentType(Value *V, const Type *Ty);
287   };
288
289   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
290 }
291
292 // getComplexity:  Assign a complexity or rank value to LLVM Values...
293 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
294 static unsigned getComplexity(Value *V) {
295   if (isa<Instruction>(V)) {
296     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
297       return 3;
298     return 4;
299   }
300   if (isa<Argument>(V)) return 3;
301   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
302 }
303
304 // isOnlyUse - Return true if this instruction will be deleted if we stop using
305 // it.
306 static bool isOnlyUse(Value *V) {
307   return V->hasOneUse() || isa<Constant>(V);
308 }
309
310 // getPromotedType - Return the specified type promoted as it would be to pass
311 // though a va_arg area...
312 static const Type *getPromotedType(const Type *Ty) {
313   switch (Ty->getTypeID()) {
314   case Type::SByteTyID:
315   case Type::ShortTyID:  return Type::IntTy;
316   case Type::UByteTyID:
317   case Type::UShortTyID: return Type::UIntTy;
318   case Type::FloatTyID:  return Type::DoubleTy;
319   default:               return Ty;
320   }
321 }
322
323 /// isCast - If the specified operand is a CastInst or a constant expr cast,
324 /// return the operand value, otherwise return null.
325 static Value *isCast(Value *V) {
326   if (CastInst *I = dyn_cast<CastInst>(V))
327     return I->getOperand(0);
328   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
329     if (CE->getOpcode() == Instruction::Cast)
330       return CE->getOperand(0);
331   return 0;
332 }
333
334 enum CastType {
335   Noop     = 0,
336   Truncate = 1,
337   Signext  = 2,
338   Zeroext  = 3
339 };
340
341 /// getCastType - In the future, we will split the cast instruction into these
342 /// various types.  Until then, we have to do the analysis here.
343 static CastType getCastType(const Type *Src, const Type *Dest) {
344   assert(Src->isIntegral() && Dest->isIntegral() &&
345          "Only works on integral types!");
346   unsigned SrcSize = Src->getPrimitiveSizeInBits();
347   unsigned DestSize = Dest->getPrimitiveSizeInBits();
348   
349   if (SrcSize == DestSize) return Noop;
350   if (SrcSize > DestSize)  return Truncate;
351   if (Src->isSigned()) return Signext;
352   return Zeroext;
353 }
354
355
356 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
357 // instruction.
358 //
359 static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
360                                    const Type *DstTy, TargetData *TD) {
361   
362   // It is legal to eliminate the instruction if casting A->B->A if the sizes
363   // are identical and the bits don't get reinterpreted (for example
364   // int->float->int would not be allowed).
365   if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
366     return true;
367   
368   // If we are casting between pointer and integer types, treat pointers as
369   // integers of the appropriate size for the code below.
370   if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
371   if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
372   if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
373   
374   // Allow free casting and conversion of sizes as long as the sign doesn't
375   // change...
376   if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
377     CastType FirstCast = getCastType(SrcTy, MidTy);
378     CastType SecondCast = getCastType(MidTy, DstTy);
379     
380     // Capture the effect of these two casts.  If the result is a legal cast,
381     // the CastType is stored here, otherwise a special code is used.
382     static const unsigned CastResult[] = {
383       // First cast is noop
384       0, 1, 2, 3,
385       // First cast is a truncate
386       1, 1, 4, 4,         // trunc->extend is not safe to eliminate
387                           // First cast is a sign ext
388       2, 5, 2, 4,         // signext->zeroext never ok
389                           // First cast is a zero ext
390       3, 5, 3, 3,
391     };
392     
393     unsigned Result = CastResult[FirstCast*4+SecondCast];
394     switch (Result) {
395     default: assert(0 && "Illegal table value!");
396     case 0:
397     case 1:
398     case 2:
399     case 3:
400       // FIXME: in the future, when LLVM has explicit sign/zeroextends and
401       // truncates, we could eliminate more casts.
402       return (unsigned)getCastType(SrcTy, DstTy) == Result;
403     case 4:
404       return false;  // Not possible to eliminate this here.
405     case 5:
406       // Sign or zero extend followed by truncate is always ok if the result
407       // is a truncate or noop.
408       CastType ResultCast = getCastType(SrcTy, DstTy);
409       if (ResultCast == Noop || ResultCast == Truncate)
410         return true;
411         // Otherwise we are still growing the value, we are only safe if the
412         // result will match the sign/zeroextendness of the result.
413         return ResultCast == FirstCast;
414     }
415   }
416   
417   // If this is a cast from 'float -> double -> integer', cast from
418   // 'float -> integer' directly, as the value isn't changed by the 
419   // float->double conversion.
420   if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
421       DstTy->isIntegral() && 
422       SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
423     return true;
424   
425   // Packed type conversions don't modify bits.
426   if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
427     return true;
428   
429   return false;
430 }
431
432 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
433 /// in any code being generated.  It does not require codegen if V is simple
434 /// enough or if the cast can be folded into other casts.
435 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
436   if (V->getType() == Ty || isa<Constant>(V)) return false;
437   
438   // If this is a noop cast, it isn't real codegen.
439   if (V->getType()->isLosslesslyConvertibleTo(Ty))
440     return false;
441
442   // If this is another cast that can be eliminated, it isn't codegen either.
443   if (const CastInst *CI = dyn_cast<CastInst>(V))
444     if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
445                                TD))
446       return false;
447   return true;
448 }
449
450 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
451 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
452 /// casts that are known to not do anything...
453 ///
454 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
455                                              Instruction *InsertBefore) {
456   if (V->getType() == DestTy) return V;
457   if (Constant *C = dyn_cast<Constant>(V))
458     return ConstantExpr::getCast(C, DestTy);
459   
460   CastInst *CI = new CastInst(V, DestTy, V->getName());
461   InsertNewInstBefore(CI, *InsertBefore);
462   return CI;
463 }
464
465 // SimplifyCommutative - This performs a few simplifications for commutative
466 // operators:
467 //
468 //  1. Order operands such that they are listed from right (least complex) to
469 //     left (most complex).  This puts constants before unary operators before
470 //     binary operators.
471 //
472 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
473 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
474 //
475 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
476   bool Changed = false;
477   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
478     Changed = !I.swapOperands();
479
480   if (!I.isAssociative()) return Changed;
481   Instruction::BinaryOps Opcode = I.getOpcode();
482   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
483     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
484       if (isa<Constant>(I.getOperand(1))) {
485         Constant *Folded = ConstantExpr::get(I.getOpcode(),
486                                              cast<Constant>(I.getOperand(1)),
487                                              cast<Constant>(Op->getOperand(1)));
488         I.setOperand(0, Op->getOperand(0));
489         I.setOperand(1, Folded);
490         return true;
491       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
492         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
493             isOnlyUse(Op) && isOnlyUse(Op1)) {
494           Constant *C1 = cast<Constant>(Op->getOperand(1));
495           Constant *C2 = cast<Constant>(Op1->getOperand(1));
496
497           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
498           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
499           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
500                                                     Op1->getOperand(0),
501                                                     Op1->getName(), &I);
502           WorkList.push_back(New);
503           I.setOperand(0, New);
504           I.setOperand(1, Folded);
505           return true;
506         }
507     }
508   return Changed;
509 }
510
511 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
512 // if the LHS is a constant zero (which is the 'negate' form).
513 //
514 static inline Value *dyn_castNegVal(Value *V) {
515   if (BinaryOperator::isNeg(V))
516     return BinaryOperator::getNegArgument(V);
517
518   // Constants can be considered to be negated values if they can be folded.
519   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
520     return ConstantExpr::getNeg(C);
521   return 0;
522 }
523
524 static inline Value *dyn_castNotVal(Value *V) {
525   if (BinaryOperator::isNot(V))
526     return BinaryOperator::getNotArgument(V);
527
528   // Constants can be considered to be not'ed values...
529   if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
530     return ConstantExpr::getNot(C);
531   return 0;
532 }
533
534 // dyn_castFoldableMul - If this value is a multiply that can be folded into
535 // other computations (because it has a constant operand), return the
536 // non-constant operand of the multiply, and set CST to point to the multiplier.
537 // Otherwise, return null.
538 //
539 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
540   if (V->hasOneUse() && V->getType()->isInteger())
541     if (Instruction *I = dyn_cast<Instruction>(V)) {
542       if (I->getOpcode() == Instruction::Mul)
543         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
544           return I->getOperand(0);
545       if (I->getOpcode() == Instruction::Shl)
546         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
547           // The multiplier is really 1 << CST.
548           Constant *One = ConstantInt::get(V->getType(), 1);
549           CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
550           return I->getOperand(0);
551         }
552     }
553   return 0;
554 }
555
556 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
557 /// expression, return it.
558 static User *dyn_castGetElementPtr(Value *V) {
559   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
560   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
561     if (CE->getOpcode() == Instruction::GetElementPtr)
562       return cast<User>(V);
563   return false;
564 }
565
566 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
567 static ConstantInt *AddOne(ConstantInt *C) {
568   return cast<ConstantInt>(ConstantExpr::getAdd(C,
569                                          ConstantInt::get(C->getType(), 1)));
570 }
571 static ConstantInt *SubOne(ConstantInt *C) {
572   return cast<ConstantInt>(ConstantExpr::getSub(C,
573                                          ConstantInt::get(C->getType(), 1)));
574 }
575
576 /// GetConstantInType - Return a ConstantInt with the specified type and value.
577 ///
578 static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
579   if (Ty->isUnsigned()) 
580     return ConstantInt::get(Ty, Val);
581   else if (Ty->getTypeID() == Type::BoolTyID)
582     return ConstantBool::get(Val);
583   int64_t SVal = Val;
584   SVal <<= 64-Ty->getPrimitiveSizeInBits();
585   SVal >>= 64-Ty->getPrimitiveSizeInBits();
586   return ConstantInt::get(Ty, SVal);
587 }
588
589
590 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
591 /// known to be either zero or one and return them in the KnownZero/KnownOne
592 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
593 /// processing.
594 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
595                               uint64_t &KnownOne, unsigned Depth = 0) {
596   // Note, we cannot consider 'undef' to be "IsZero" here.  The problem is that
597   // we cannot optimize based on the assumption that it is zero without changing
598   // it to be an explicit zero.  If we don't change it to zero, other code could
599   // optimized based on the contradictory assumption that it is non-zero.
600   // Because instcombine aggressively folds operations with undef args anyway,
601   // this won't lose us code quality.
602   if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
603     // We know all of the bits for a constant!
604     KnownOne = CI->getZExtValue() & Mask;
605     KnownZero = ~KnownOne & Mask;
606     return;
607   }
608
609   KnownZero = KnownOne = 0;   // Don't know anything.
610   if (Depth == 6 || Mask == 0)
611     return;  // Limit search depth.
612
613   uint64_t KnownZero2, KnownOne2;
614   Instruction *I = dyn_cast<Instruction>(V);
615   if (!I) return;
616
617   Mask &= V->getType()->getIntegralTypeMask();
618   
619   switch (I->getOpcode()) {
620   case Instruction::And:
621     // If either the LHS or the RHS are Zero, the result is zero.
622     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
623     Mask &= ~KnownZero;
624     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
625     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
626     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
627     
628     // Output known-1 bits are only known if set in both the LHS & RHS.
629     KnownOne &= KnownOne2;
630     // Output known-0 are known to be clear if zero in either the LHS | RHS.
631     KnownZero |= KnownZero2;
632     return;
633   case Instruction::Or:
634     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
635     Mask &= ~KnownOne;
636     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
637     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
638     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
639     
640     // Output known-0 bits are only known if clear in both the LHS & RHS.
641     KnownZero &= KnownZero2;
642     // Output known-1 are known to be set if set in either the LHS | RHS.
643     KnownOne |= KnownOne2;
644     return;
645   case Instruction::Xor: {
646     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
647     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
648     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
649     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
650     
651     // Output known-0 bits are known if clear or set in both the LHS & RHS.
652     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
653     // Output known-1 are known to be set if set in only one of the LHS, RHS.
654     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
655     KnownZero = KnownZeroOut;
656     return;
657   }
658   case Instruction::Select:
659     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
660     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
661     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
662     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
663
664     // Only known if known in both the LHS and RHS.
665     KnownOne &= KnownOne2;
666     KnownZero &= KnownZero2;
667     return;
668   case Instruction::Cast: {
669     const Type *SrcTy = I->getOperand(0)->getType();
670     if (!SrcTy->isIntegral()) return;
671     
672     // If this is an integer truncate or noop, just look in the input.
673     if (SrcTy->getPrimitiveSizeInBits() >= 
674            I->getType()->getPrimitiveSizeInBits()) {
675       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
676       return;
677     }
678
679     // Sign or Zero extension.  Compute the bits in the result that are not
680     // present in the input.
681     uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
682     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
683       
684     // Handle zero extension.
685     if (!SrcTy->isSigned()) {
686       Mask &= SrcTy->getIntegralTypeMask();
687       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
688       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
689       // The top bits are known to be zero.
690       KnownZero |= NewBits;
691     } else {
692       // Sign extension.
693       Mask &= SrcTy->getIntegralTypeMask();
694       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
695       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
696
697       // If the sign bit of the input is known set or clear, then we know the
698       // top bits of the result.
699       uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
700       if (KnownZero & InSignBit) {          // Input sign bit known zero
701         KnownZero |= NewBits;
702         KnownOne &= ~NewBits;
703       } else if (KnownOne & InSignBit) {    // Input sign bit known set
704         KnownOne |= NewBits;
705         KnownZero &= ~NewBits;
706       } else {                              // Input sign bit unknown
707         KnownZero &= ~NewBits;
708         KnownOne &= ~NewBits;
709       }
710     }
711     return;
712   }
713   case Instruction::Shl:
714     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
715     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
716       uint64_t ShiftAmt = SA->getZExtValue();
717       Mask >>= ShiftAmt;
718       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
719       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
720       KnownZero <<= ShiftAmt;
721       KnownOne  <<= ShiftAmt;
722       KnownZero |= (1ULL << ShiftAmt)-1;  // low bits known zero.
723       return;
724     }
725     break;
726   case Instruction::Shr:
727     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
728     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
729       // Compute the new bits that are at the top now.
730       uint64_t ShiftAmt = SA->getZExtValue();
731       uint64_t HighBits = (1ULL << ShiftAmt)-1;
732       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
733       
734       if (I->getType()->isUnsigned()) {   // Unsigned shift right.
735         Mask <<= ShiftAmt;
736         ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
737         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
738         KnownZero >>= ShiftAmt;
739         KnownOne  >>= ShiftAmt;
740         KnownZero |= HighBits;  // high bits known zero.
741       } else {
742         Mask <<= ShiftAmt;
743         ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
744         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
745         KnownZero >>= ShiftAmt;
746         KnownOne  >>= ShiftAmt;
747         
748         // Handle the sign bits.
749         uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
750         SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
751         
752         if (KnownZero & SignBit) {       // New bits are known zero.
753           KnownZero |= HighBits;
754         } else if (KnownOne & SignBit) { // New bits are known one.
755           KnownOne |= HighBits;
756         }
757       }
758       return;
759     }
760     break;
761   }
762 }
763
764 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
765 /// this predicate to simplify operations downstream.  Mask is known to be zero
766 /// for bits that V cannot have.
767 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
768   uint64_t KnownZero, KnownOne;
769   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
770   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
771   return (KnownZero & Mask) == Mask;
772 }
773
774 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
775 /// specified instruction is a constant integer.  If so, check to see if there
776 /// are any bits set in the constant that are not demanded.  If so, shrink the
777 /// constant and return true.
778 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
779                                    uint64_t Demanded) {
780   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
781   if (!OpC) return false;
782
783   // If there are no bits set that aren't demanded, nothing to do.
784   if ((~Demanded & OpC->getZExtValue()) == 0)
785     return false;
786
787   // This is producing any bits that are not needed, shrink the RHS.
788   uint64_t Val = Demanded & OpC->getZExtValue();
789   I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
790   return true;
791 }
792
793 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
794 // set of known zero and one bits, compute the maximum and minimum values that
795 // could have the specified known zero and known one bits, returning them in
796 // min/max.
797 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
798                                                    uint64_t KnownZero,
799                                                    uint64_t KnownOne,
800                                                    int64_t &Min, int64_t &Max) {
801   uint64_t TypeBits = Ty->getIntegralTypeMask();
802   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
803
804   uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
805   
806   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
807   // bit if it is unknown.
808   Min = KnownOne;
809   Max = KnownOne|UnknownBits;
810   
811   if (SignBit & UnknownBits) { // Sign bit is unknown
812     Min |= SignBit;
813     Max &= ~SignBit;
814   }
815   
816   // Sign extend the min/max values.
817   int ShAmt = 64-Ty->getPrimitiveSizeInBits();
818   Min = (Min << ShAmt) >> ShAmt;
819   Max = (Max << ShAmt) >> ShAmt;
820 }
821
822 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
823 // a set of known zero and one bits, compute the maximum and minimum values that
824 // could have the specified known zero and known one bits, returning them in
825 // min/max.
826 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
827                                                      uint64_t KnownZero,
828                                                      uint64_t KnownOne,
829                                                      uint64_t &Min,
830                                                      uint64_t &Max) {
831   uint64_t TypeBits = Ty->getIntegralTypeMask();
832   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
833   
834   // The minimum value is when the unknown bits are all zeros.
835   Min = KnownOne;
836   // The maximum value is when the unknown bits are all ones.
837   Max = KnownOne|UnknownBits;
838 }
839
840
841 /// SimplifyDemandedBits - Look at V.  At this point, we know that only the
842 /// DemandedMask bits of the result of V are ever used downstream.  If we can
843 /// use this information to simplify V, do so and return true.  Otherwise,
844 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
845 /// the expression (used to simplify the caller).  The KnownZero/One bits may
846 /// only be accurate for those bits in the DemandedMask.
847 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
848                                         uint64_t &KnownZero, uint64_t &KnownOne,
849                                         unsigned Depth) {
850   if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
851     // We know all of the bits for a constant!
852     KnownOne = CI->getZExtValue() & DemandedMask;
853     KnownZero = ~KnownOne & DemandedMask;
854     return false;
855   }
856   
857   KnownZero = KnownOne = 0;
858   if (!V->hasOneUse()) {    // Other users may use these bits.
859     if (Depth != 0) {       // Not at the root.
860       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
861       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
862       return false;
863     }
864     // If this is the root being simplified, allow it to have multiple uses,
865     // just set the DemandedMask to all bits.
866     DemandedMask = V->getType()->getIntegralTypeMask();
867   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
868     if (V != UndefValue::get(V->getType()))
869       return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
870     return false;
871   } else if (Depth == 6) {        // Limit search depth.
872     return false;
873   }
874   
875   Instruction *I = dyn_cast<Instruction>(V);
876   if (!I) return false;        // Only analyze instructions.
877
878   DemandedMask &= V->getType()->getIntegralTypeMask();
879   
880   uint64_t KnownZero2, KnownOne2;
881   switch (I->getOpcode()) {
882   default: break;
883   case Instruction::And:
884     // If either the LHS or the RHS are Zero, the result is zero.
885     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
886                              KnownZero, KnownOne, Depth+1))
887       return true;
888     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
889
890     // If something is known zero on the RHS, the bits aren't demanded on the
891     // LHS.
892     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
893                              KnownZero2, KnownOne2, Depth+1))
894       return true;
895     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
896
897     // If all of the demanded bits are known one on one side, return the other.
898     // These bits cannot contribute to the result of the 'and'.
899     if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
900       return UpdateValueUsesWith(I, I->getOperand(0));
901     if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
902       return UpdateValueUsesWith(I, I->getOperand(1));
903     
904     // If all of the demanded bits in the inputs are known zeros, return zero.
905     if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
906       return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
907       
908     // If the RHS is a constant, see if we can simplify it.
909     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
910       return UpdateValueUsesWith(I, I);
911       
912     // Output known-1 bits are only known if set in both the LHS & RHS.
913     KnownOne &= KnownOne2;
914     // Output known-0 are known to be clear if zero in either the LHS | RHS.
915     KnownZero |= KnownZero2;
916     break;
917   case Instruction::Or:
918     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
919                              KnownZero, KnownOne, Depth+1))
920       return true;
921     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
922     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne, 
923                              KnownZero2, KnownOne2, Depth+1))
924       return true;
925     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
926     
927     // If all of the demanded bits are known zero on one side, return the other.
928     // These bits cannot contribute to the result of the 'or'.
929     if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
930       return UpdateValueUsesWith(I, I->getOperand(0));
931     if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
932       return UpdateValueUsesWith(I, I->getOperand(1));
933
934     // If all of the potentially set bits on one side are known to be set on
935     // the other side, just use the 'other' side.
936     if ((DemandedMask & (~KnownZero) & KnownOne2) == 
937         (DemandedMask & (~KnownZero)))
938       return UpdateValueUsesWith(I, I->getOperand(0));
939     if ((DemandedMask & (~KnownZero2) & KnownOne) == 
940         (DemandedMask & (~KnownZero2)))
941       return UpdateValueUsesWith(I, I->getOperand(1));
942         
943     // If the RHS is a constant, see if we can simplify it.
944     if (ShrinkDemandedConstant(I, 1, DemandedMask))
945       return UpdateValueUsesWith(I, I);
946           
947     // Output known-0 bits are only known if clear in both the LHS & RHS.
948     KnownZero &= KnownZero2;
949     // Output known-1 are known to be set if set in either the LHS | RHS.
950     KnownOne |= KnownOne2;
951     break;
952   case Instruction::Xor: {
953     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
954                              KnownZero, KnownOne, Depth+1))
955       return true;
956     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
957     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
958                              KnownZero2, KnownOne2, Depth+1))
959       return true;
960     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
961     
962     // If all of the demanded bits are known zero on one side, return the other.
963     // These bits cannot contribute to the result of the 'xor'.
964     if ((DemandedMask & KnownZero) == DemandedMask)
965       return UpdateValueUsesWith(I, I->getOperand(0));
966     if ((DemandedMask & KnownZero2) == DemandedMask)
967       return UpdateValueUsesWith(I, I->getOperand(1));
968     
969     // Output known-0 bits are known if clear or set in both the LHS & RHS.
970     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
971     // Output known-1 are known to be set if set in only one of the LHS, RHS.
972     uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
973     
974     // If all of the unknown bits are known to be zero on one side or the other
975     // (but not both) turn this into an *inclusive* or.
976     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
977     if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
978       if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
979         Instruction *Or =
980           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
981                                    I->getName());
982         InsertNewInstBefore(Or, *I);
983         return UpdateValueUsesWith(I, Or);
984       }
985     }
986     
987     // If all of the demanded bits on one side are known, and all of the set
988     // bits on that side are also known to be set on the other side, turn this
989     // into an AND, as we know the bits will be cleared.
990     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
991     if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
992       if ((KnownOne & KnownOne2) == KnownOne) {
993         Constant *AndC = GetConstantInType(I->getType(), 
994                                            ~KnownOne & DemandedMask);
995         Instruction *And = 
996           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
997         InsertNewInstBefore(And, *I);
998         return UpdateValueUsesWith(I, And);
999       }
1000     }
1001     
1002     // If the RHS is a constant, see if we can simplify it.
1003     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1004     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1005       return UpdateValueUsesWith(I, I);
1006     
1007     KnownZero = KnownZeroOut;
1008     KnownOne  = KnownOneOut;
1009     break;
1010   }
1011   case Instruction::Select:
1012     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1013                              KnownZero, KnownOne, Depth+1))
1014       return true;
1015     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1016                              KnownZero2, KnownOne2, Depth+1))
1017       return true;
1018     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1019     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1020     
1021     // If the operands are constants, see if we can simplify them.
1022     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1023       return UpdateValueUsesWith(I, I);
1024     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1025       return UpdateValueUsesWith(I, I);
1026     
1027     // Only known if known in both the LHS and RHS.
1028     KnownOne &= KnownOne2;
1029     KnownZero &= KnownZero2;
1030     break;
1031   case Instruction::Cast: {
1032     const Type *SrcTy = I->getOperand(0)->getType();
1033     if (!SrcTy->isIntegral()) return false;
1034     
1035     // If this is an integer truncate or noop, just look in the input.
1036     if (SrcTy->getPrimitiveSizeInBits() >= 
1037         I->getType()->getPrimitiveSizeInBits()) {
1038       // Cast to bool is a comparison against 0, which demands all bits.  We
1039       // can't propagate anything useful up.
1040       if (I->getType() == Type::BoolTy)
1041         break;
1042       
1043       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1044                                KnownZero, KnownOne, Depth+1))
1045         return true;
1046       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1047       break;
1048     }
1049     
1050     // Sign or Zero extension.  Compute the bits in the result that are not
1051     // present in the input.
1052     uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1053     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1054     
1055     // Handle zero extension.
1056     if (!SrcTy->isSigned()) {
1057       DemandedMask &= SrcTy->getIntegralTypeMask();
1058       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1059                                KnownZero, KnownOne, Depth+1))
1060         return true;
1061       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1062       // The top bits are known to be zero.
1063       KnownZero |= NewBits;
1064     } else {
1065       // Sign extension.
1066       uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1067       int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1068
1069       // If any of the sign extended bits are demanded, we know that the sign
1070       // bit is demanded.
1071       if (NewBits & DemandedMask)
1072         InputDemandedBits |= InSignBit;
1073       
1074       if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1075                                KnownZero, KnownOne, Depth+1))
1076         return true;
1077       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1078       
1079       // If the sign bit of the input is known set or clear, then we know the
1080       // top bits of the result.
1081
1082       // If the input sign bit is known zero, or if the NewBits are not demanded
1083       // convert this into a zero extension.
1084       if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1085         // Convert to unsigned first.
1086         Instruction *NewVal;
1087         NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
1088                               I->getOperand(0)->getName());
1089         InsertNewInstBefore(NewVal, *I);
1090         // Then cast that to the destination type.
1091         NewVal = new CastInst(NewVal, I->getType(), I->getName());
1092         InsertNewInstBefore(NewVal, *I);
1093         return UpdateValueUsesWith(I, NewVal);
1094       } else if (KnownOne & InSignBit) {    // Input sign bit known set
1095         KnownOne |= NewBits;
1096         KnownZero &= ~NewBits;
1097       } else {                              // Input sign bit unknown
1098         KnownZero &= ~NewBits;
1099         KnownOne &= ~NewBits;
1100       }
1101     }
1102     break;
1103   }
1104   case Instruction::Shl:
1105     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1106       uint64_t ShiftAmt = SA->getZExtValue();
1107       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt, 
1108                                KnownZero, KnownOne, Depth+1))
1109         return true;
1110       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1111       KnownZero <<= ShiftAmt;
1112       KnownOne  <<= ShiftAmt;
1113       KnownZero |= (1ULL << ShiftAmt) - 1;  // low bits known zero.
1114     }
1115     break;
1116   case Instruction::Shr:
1117     // If this is an arithmetic shift right and only the low-bit is set, we can
1118     // always convert this into a logical shr, even if the shift amount is
1119     // variable.  The low bit of the shift cannot be an input sign bit unless
1120     // the shift amount is >= the size of the datatype, which is undefined.
1121     if (DemandedMask == 1 && I->getType()->isSigned()) {
1122       // Convert the input to unsigned.
1123       Instruction *NewVal = new CastInst(I->getOperand(0), 
1124                                          I->getType()->getUnsignedVersion(),
1125                                          I->getOperand(0)->getName());
1126       InsertNewInstBefore(NewVal, *I);
1127       // Perform the unsigned shift right.
1128       NewVal = new ShiftInst(Instruction::Shr, NewVal, I->getOperand(1),
1129                              I->getName());
1130       InsertNewInstBefore(NewVal, *I);
1131       // Then cast that to the destination type.
1132       NewVal = new CastInst(NewVal, I->getType(), I->getName());
1133       InsertNewInstBefore(NewVal, *I);
1134       return UpdateValueUsesWith(I, NewVal);
1135     }    
1136     
1137     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1138       unsigned ShiftAmt = SA->getZExtValue();
1139       
1140       // Compute the new bits that are at the top now.
1141       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1142       HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1143       uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1144       if (I->getType()->isUnsigned()) {   // Unsigned shift right.
1145         if (SimplifyDemandedBits(I->getOperand(0),
1146                                  (DemandedMask << ShiftAmt) & TypeMask,
1147                                  KnownZero, KnownOne, Depth+1))
1148           return true;
1149         assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1150         KnownZero &= TypeMask;
1151         KnownOne  &= TypeMask;
1152         KnownZero >>= ShiftAmt;
1153         KnownOne  >>= ShiftAmt;
1154         KnownZero |= HighBits;  // high bits known zero.
1155       } else {                            // Signed shift right.
1156         if (SimplifyDemandedBits(I->getOperand(0),
1157                                  (DemandedMask << ShiftAmt) & TypeMask,
1158                                  KnownZero, KnownOne, Depth+1))
1159           return true;
1160         assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1161         KnownZero &= TypeMask;
1162         KnownOne  &= TypeMask;
1163         KnownZero >>= ShiftAmt;
1164         KnownOne  >>= ShiftAmt;
1165         
1166         // Handle the sign bits.
1167         uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1168         SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
1169         
1170         // If the input sign bit is known to be zero, or if none of the top bits
1171         // are demanded, turn this into an unsigned shift right.
1172         if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1173           // Convert the input to unsigned.
1174           Instruction *NewVal;
1175           NewVal = new CastInst(I->getOperand(0), 
1176                                 I->getType()->getUnsignedVersion(),
1177                                 I->getOperand(0)->getName());
1178           InsertNewInstBefore(NewVal, *I);
1179           // Perform the unsigned shift right.
1180           NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
1181           InsertNewInstBefore(NewVal, *I);
1182           // Then cast that to the destination type.
1183           NewVal = new CastInst(NewVal, I->getType(), I->getName());
1184           InsertNewInstBefore(NewVal, *I);
1185           return UpdateValueUsesWith(I, NewVal);
1186         } else if (KnownOne & SignBit) { // New bits are known one.
1187           KnownOne |= HighBits;
1188         }
1189       }
1190     }
1191     break;
1192   }
1193   
1194   // If the client is only demanding bits that we know, return the known
1195   // constant.
1196   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1197     return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
1198   return false;
1199 }  
1200
1201
1202 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1203 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1204 /// actually used by the caller.  This method analyzes which elements of the
1205 /// operand are undef and returns that information in UndefElts.
1206 ///
1207 /// If the information about demanded elements can be used to simplify the
1208 /// operation, the operation is simplified, then the resultant value is
1209 /// returned.  This returns null if no change was made.
1210 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1211                                                 uint64_t &UndefElts,
1212                                                 unsigned Depth) {
1213   unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1214   assert(VWidth <= 64 && "Vector too wide to analyze!");
1215   uint64_t EltMask = ~0ULL >> (64-VWidth);
1216   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1217          "Invalid DemandedElts!");
1218
1219   if (isa<UndefValue>(V)) {
1220     // If the entire vector is undefined, just return this info.
1221     UndefElts = EltMask;
1222     return 0;
1223   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1224     UndefElts = EltMask;
1225     return UndefValue::get(V->getType());
1226   }
1227   
1228   UndefElts = 0;
1229   if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1230     const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1231     Constant *Undef = UndefValue::get(EltTy);
1232
1233     std::vector<Constant*> Elts;
1234     for (unsigned i = 0; i != VWidth; ++i)
1235       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1236         Elts.push_back(Undef);
1237         UndefElts |= (1ULL << i);
1238       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1239         Elts.push_back(Undef);
1240         UndefElts |= (1ULL << i);
1241       } else {                               // Otherwise, defined.
1242         Elts.push_back(CP->getOperand(i));
1243       }
1244         
1245     // If we changed the constant, return it.
1246     Constant *NewCP = ConstantPacked::get(Elts);
1247     return NewCP != CP ? NewCP : 0;
1248   } else if (isa<ConstantAggregateZero>(V)) {
1249     // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1250     // set to undef.
1251     const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1252     Constant *Zero = Constant::getNullValue(EltTy);
1253     Constant *Undef = UndefValue::get(EltTy);
1254     std::vector<Constant*> Elts;
1255     for (unsigned i = 0; i != VWidth; ++i)
1256       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1257     UndefElts = DemandedElts ^ EltMask;
1258     return ConstantPacked::get(Elts);
1259   }
1260   
1261   if (!V->hasOneUse()) {    // Other users may use these bits.
1262     if (Depth != 0) {       // Not at the root.
1263       // TODO: Just compute the UndefElts information recursively.
1264       return false;
1265     }
1266     return false;
1267   } else if (Depth == 10) {        // Limit search depth.
1268     return false;
1269   }
1270   
1271   Instruction *I = dyn_cast<Instruction>(V);
1272   if (!I) return false;        // Only analyze instructions.
1273   
1274   bool MadeChange = false;
1275   uint64_t UndefElts2;
1276   Value *TmpV;
1277   switch (I->getOpcode()) {
1278   default: break;
1279     
1280   case Instruction::InsertElement: {
1281     // If this is a variable index, we don't know which element it overwrites.
1282     // demand exactly the same input as we produce.
1283     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1284     if (Idx == 0) {
1285       // Note that we can't propagate undef elt info, because we don't know
1286       // which elt is getting updated.
1287       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1288                                         UndefElts2, Depth+1);
1289       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1290       break;
1291     }
1292     
1293     // If this is inserting an element that isn't demanded, remove this
1294     // insertelement.
1295     unsigned IdxNo = Idx->getZExtValue();
1296     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1297       return AddSoonDeadInstToWorklist(*I, 0);
1298     
1299     // Otherwise, the element inserted overwrites whatever was there, so the
1300     // input demanded set is simpler than the output set.
1301     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1302                                       DemandedElts & ~(1ULL << IdxNo),
1303                                       UndefElts, Depth+1);
1304     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1305
1306     // The inserted element is defined.
1307     UndefElts |= 1ULL << IdxNo;
1308     break;
1309   }
1310     
1311   case Instruction::And:
1312   case Instruction::Or:
1313   case Instruction::Xor:
1314   case Instruction::Add:
1315   case Instruction::Sub:
1316   case Instruction::Mul:
1317     // div/rem demand all inputs, because they don't want divide by zero.
1318     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1319                                       UndefElts, Depth+1);
1320     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1321     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1322                                       UndefElts2, Depth+1);
1323     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1324       
1325     // Output elements are undefined if both are undefined.  Consider things
1326     // like undef&0.  The result is known zero, not undef.
1327     UndefElts &= UndefElts2;
1328     break;
1329     
1330   case Instruction::Call: {
1331     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1332     if (!II) break;
1333     switch (II->getIntrinsicID()) {
1334     default: break;
1335       
1336     // Binary vector operations that work column-wise.  A dest element is a
1337     // function of the corresponding input elements from the two inputs.
1338     case Intrinsic::x86_sse_sub_ss:
1339     case Intrinsic::x86_sse_mul_ss:
1340     case Intrinsic::x86_sse_min_ss:
1341     case Intrinsic::x86_sse_max_ss:
1342     case Intrinsic::x86_sse2_sub_sd:
1343     case Intrinsic::x86_sse2_mul_sd:
1344     case Intrinsic::x86_sse2_min_sd:
1345     case Intrinsic::x86_sse2_max_sd:
1346       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1347                                         UndefElts, Depth+1);
1348       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1349       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1350                                         UndefElts2, Depth+1);
1351       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1352
1353       // If only the low elt is demanded and this is a scalarizable intrinsic,
1354       // scalarize it now.
1355       if (DemandedElts == 1) {
1356         switch (II->getIntrinsicID()) {
1357         default: break;
1358         case Intrinsic::x86_sse_sub_ss:
1359         case Intrinsic::x86_sse_mul_ss:
1360         case Intrinsic::x86_sse2_sub_sd:
1361         case Intrinsic::x86_sse2_mul_sd:
1362           // TODO: Lower MIN/MAX/ABS/etc
1363           Value *LHS = II->getOperand(1);
1364           Value *RHS = II->getOperand(2);
1365           // Extract the element as scalars.
1366           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1367           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1368           
1369           switch (II->getIntrinsicID()) {
1370           default: assert(0 && "Case stmts out of sync!");
1371           case Intrinsic::x86_sse_sub_ss:
1372           case Intrinsic::x86_sse2_sub_sd:
1373             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1374                                                         II->getName()), *II);
1375             break;
1376           case Intrinsic::x86_sse_mul_ss:
1377           case Intrinsic::x86_sse2_mul_sd:
1378             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1379                                                          II->getName()), *II);
1380             break;
1381           }
1382           
1383           Instruction *New =
1384             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1385                                   II->getName());
1386           InsertNewInstBefore(New, *II);
1387           AddSoonDeadInstToWorklist(*II, 0);
1388           return New;
1389         }            
1390       }
1391         
1392       // Output elements are undefined if both are undefined.  Consider things
1393       // like undef&0.  The result is known zero, not undef.
1394       UndefElts &= UndefElts2;
1395       break;
1396     }
1397     break;
1398   }
1399   }
1400   return MadeChange ? I : 0;
1401 }
1402
1403 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
1404 // true when both operands are equal...
1405 //
1406 static bool isTrueWhenEqual(Instruction &I) {
1407   return I.getOpcode() == Instruction::SetEQ ||
1408          I.getOpcode() == Instruction::SetGE ||
1409          I.getOpcode() == Instruction::SetLE;
1410 }
1411
1412 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1413 /// function is designed to check a chain of associative operators for a
1414 /// potential to apply a certain optimization.  Since the optimization may be
1415 /// applicable if the expression was reassociated, this checks the chain, then
1416 /// reassociates the expression as necessary to expose the optimization
1417 /// opportunity.  This makes use of a special Functor, which must define
1418 /// 'shouldApply' and 'apply' methods.
1419 ///
1420 template<typename Functor>
1421 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1422   unsigned Opcode = Root.getOpcode();
1423   Value *LHS = Root.getOperand(0);
1424
1425   // Quick check, see if the immediate LHS matches...
1426   if (F.shouldApply(LHS))
1427     return F.apply(Root);
1428
1429   // Otherwise, if the LHS is not of the same opcode as the root, return.
1430   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1431   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1432     // Should we apply this transform to the RHS?
1433     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1434
1435     // If not to the RHS, check to see if we should apply to the LHS...
1436     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1437       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1438       ShouldApply = true;
1439     }
1440
1441     // If the functor wants to apply the optimization to the RHS of LHSI,
1442     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1443     if (ShouldApply) {
1444       BasicBlock *BB = Root.getParent();
1445
1446       // Now all of the instructions are in the current basic block, go ahead
1447       // and perform the reassociation.
1448       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1449
1450       // First move the selected RHS to the LHS of the root...
1451       Root.setOperand(0, LHSI->getOperand(1));
1452
1453       // Make what used to be the LHS of the root be the user of the root...
1454       Value *ExtraOperand = TmpLHSI->getOperand(1);
1455       if (&Root == TmpLHSI) {
1456         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1457         return 0;
1458       }
1459       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1460       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1461       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1462       BasicBlock::iterator ARI = &Root; ++ARI;
1463       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1464       ARI = Root;
1465
1466       // Now propagate the ExtraOperand down the chain of instructions until we
1467       // get to LHSI.
1468       while (TmpLHSI != LHSI) {
1469         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1470         // Move the instruction to immediately before the chain we are
1471         // constructing to avoid breaking dominance properties.
1472         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1473         BB->getInstList().insert(ARI, NextLHSI);
1474         ARI = NextLHSI;
1475
1476         Value *NextOp = NextLHSI->getOperand(1);
1477         NextLHSI->setOperand(1, ExtraOperand);
1478         TmpLHSI = NextLHSI;
1479         ExtraOperand = NextOp;
1480       }
1481
1482       // Now that the instructions are reassociated, have the functor perform
1483       // the transformation...
1484       return F.apply(Root);
1485     }
1486
1487     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1488   }
1489   return 0;
1490 }
1491
1492
1493 // AddRHS - Implements: X + X --> X << 1
1494 struct AddRHS {
1495   Value *RHS;
1496   AddRHS(Value *rhs) : RHS(rhs) {}
1497   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1498   Instruction *apply(BinaryOperator &Add) const {
1499     return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1500                          ConstantInt::get(Type::UByteTy, 1));
1501   }
1502 };
1503
1504 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1505 //                 iff C1&C2 == 0
1506 struct AddMaskingAnd {
1507   Constant *C2;
1508   AddMaskingAnd(Constant *c) : C2(c) {}
1509   bool shouldApply(Value *LHS) const {
1510     ConstantInt *C1;
1511     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1512            ConstantExpr::getAnd(C1, C2)->isNullValue();
1513   }
1514   Instruction *apply(BinaryOperator &Add) const {
1515     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1516   }
1517 };
1518
1519 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1520                                              InstCombiner *IC) {
1521   if (isa<CastInst>(I)) {
1522     if (Constant *SOC = dyn_cast<Constant>(SO))
1523       return ConstantExpr::getCast(SOC, I.getType());
1524
1525     return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1526                                                 SO->getName() + ".cast"), I);
1527   }
1528
1529   // Figure out if the constant is the left or the right argument.
1530   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1531   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1532
1533   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1534     if (ConstIsRHS)
1535       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1536     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1537   }
1538
1539   Value *Op0 = SO, *Op1 = ConstOperand;
1540   if (!ConstIsRHS)
1541     std::swap(Op0, Op1);
1542   Instruction *New;
1543   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1544     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1545   else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1546     New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1547   else {
1548     assert(0 && "Unknown binary instruction type!");
1549     abort();
1550   }
1551   return IC->InsertNewInstBefore(New, I);
1552 }
1553
1554 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1555 // constant as the other operand, try to fold the binary operator into the
1556 // select arguments.  This also works for Cast instructions, which obviously do
1557 // not have a second operand.
1558 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1559                                      InstCombiner *IC) {
1560   // Don't modify shared select instructions
1561   if (!SI->hasOneUse()) return 0;
1562   Value *TV = SI->getOperand(1);
1563   Value *FV = SI->getOperand(2);
1564
1565   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1566     // Bool selects with constant operands can be folded to logical ops.
1567     if (SI->getType() == Type::BoolTy) return 0;
1568
1569     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1570     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1571
1572     return new SelectInst(SI->getCondition(), SelectTrueVal,
1573                           SelectFalseVal);
1574   }
1575   return 0;
1576 }
1577
1578
1579 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1580 /// node as operand #0, see if we can fold the instruction into the PHI (which
1581 /// is only possible if all operands to the PHI are constants).
1582 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1583   PHINode *PN = cast<PHINode>(I.getOperand(0));
1584   unsigned NumPHIValues = PN->getNumIncomingValues();
1585   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1586
1587   // Check to see if all of the operands of the PHI are constants.  If there is
1588   // one non-constant value, remember the BB it is.  If there is more than one
1589   // bail out.
1590   BasicBlock *NonConstBB = 0;
1591   for (unsigned i = 0; i != NumPHIValues; ++i)
1592     if (!isa<Constant>(PN->getIncomingValue(i))) {
1593       if (NonConstBB) return 0;  // More than one non-const value.
1594       NonConstBB = PN->getIncomingBlock(i);
1595       
1596       // If the incoming non-constant value is in I's block, we have an infinite
1597       // loop.
1598       if (NonConstBB == I.getParent())
1599         return 0;
1600     }
1601   
1602   // If there is exactly one non-constant value, we can insert a copy of the
1603   // operation in that block.  However, if this is a critical edge, we would be
1604   // inserting the computation one some other paths (e.g. inside a loop).  Only
1605   // do this if the pred block is unconditionally branching into the phi block.
1606   if (NonConstBB) {
1607     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1608     if (!BI || !BI->isUnconditional()) return 0;
1609   }
1610
1611   // Okay, we can do the transformation: create the new PHI node.
1612   PHINode *NewPN = new PHINode(I.getType(), I.getName());
1613   I.setName("");
1614   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1615   InsertNewInstBefore(NewPN, *PN);
1616
1617   // Next, add all of the operands to the PHI.
1618   if (I.getNumOperands() == 2) {
1619     Constant *C = cast<Constant>(I.getOperand(1));
1620     for (unsigned i = 0; i != NumPHIValues; ++i) {
1621       Value *InV;
1622       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1623         InV = ConstantExpr::get(I.getOpcode(), InC, C);
1624       } else {
1625         assert(PN->getIncomingBlock(i) == NonConstBB);
1626         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1627           InV = BinaryOperator::create(BO->getOpcode(),
1628                                        PN->getIncomingValue(i), C, "phitmp",
1629                                        NonConstBB->getTerminator());
1630         else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1631           InV = new ShiftInst(SI->getOpcode(),
1632                               PN->getIncomingValue(i), C, "phitmp",
1633                               NonConstBB->getTerminator());
1634         else
1635           assert(0 && "Unknown binop!");
1636         
1637         WorkList.push_back(cast<Instruction>(InV));
1638       }
1639       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1640     }
1641   } else {
1642     assert(isa<CastInst>(I) && "Unary op should be a cast!");
1643     const Type *RetTy = I.getType();
1644     for (unsigned i = 0; i != NumPHIValues; ++i) {
1645       Value *InV;
1646       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1647         InV = ConstantExpr::getCast(InC, RetTy);
1648       } else {
1649         assert(PN->getIncomingBlock(i) == NonConstBB);
1650         InV = new CastInst(PN->getIncomingValue(i), I.getType(), "phitmp",
1651                            NonConstBB->getTerminator());
1652         WorkList.push_back(cast<Instruction>(InV));
1653       }
1654       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1655     }
1656   }
1657   return ReplaceInstUsesWith(I, NewPN);
1658 }
1659
1660 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1661   bool Changed = SimplifyCommutative(I);
1662   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1663
1664   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1665     // X + undef -> undef
1666     if (isa<UndefValue>(RHS))
1667       return ReplaceInstUsesWith(I, RHS);
1668
1669     // X + 0 --> X
1670     if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1671       if (RHSC->isNullValue())
1672         return ReplaceInstUsesWith(I, LHS);
1673     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1674       if (CFP->isExactlyValue(-0.0))
1675         return ReplaceInstUsesWith(I, LHS);
1676     }
1677
1678     // X + (signbit) --> X ^ signbit
1679     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1680       uint64_t Val = CI->getZExtValue();
1681       if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1682         return BinaryOperator::createXor(LHS, RHS);
1683     }
1684
1685     if (isa<PHINode>(LHS))
1686       if (Instruction *NV = FoldOpIntoPhi(I))
1687         return NV;
1688     
1689     ConstantInt *XorRHS = 0;
1690     Value *XorLHS = 0;
1691     if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1692       unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1693       int64_t  RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1694       uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1695       
1696       uint64_t C0080Val = 1ULL << 31;
1697       int64_t CFF80Val = -C0080Val;
1698       unsigned Size = 32;
1699       do {
1700         if (TySizeBits > Size) {
1701           bool Found = false;
1702           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1703           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1704           if (RHSSExt == CFF80Val) {
1705             if (XorRHS->getZExtValue() == C0080Val)
1706               Found = true;
1707           } else if (RHSZExt == C0080Val) {
1708             if (XorRHS->getSExtValue() == CFF80Val)
1709               Found = true;
1710           }
1711           if (Found) {
1712             // This is a sign extend if the top bits are known zero.
1713             uint64_t Mask = ~0ULL;
1714             Mask <<= 64-(TySizeBits-Size);
1715             Mask &= XorLHS->getType()->getIntegralTypeMask();
1716             if (!MaskedValueIsZero(XorLHS, Mask))
1717               Size = 0;  // Not a sign ext, but can't be any others either.
1718             goto FoundSExt;
1719           }
1720         }
1721         Size >>= 1;
1722         C0080Val >>= Size;
1723         CFF80Val >>= Size;
1724       } while (Size >= 8);
1725       
1726 FoundSExt:
1727       const Type *MiddleType = 0;
1728       switch (Size) {
1729       default: break;
1730       case 32: MiddleType = Type::IntTy; break;
1731       case 16: MiddleType = Type::ShortTy; break;
1732       case 8:  MiddleType = Type::SByteTy; break;
1733       }
1734       if (MiddleType) {
1735         Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1736         InsertNewInstBefore(NewTrunc, I);
1737         return new CastInst(NewTrunc, I.getType());
1738       }
1739     }
1740   }
1741
1742   // X + X --> X << 1
1743   if (I.getType()->isInteger()) {
1744     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1745
1746     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1747       if (RHSI->getOpcode() == Instruction::Sub)
1748         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
1749           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1750     }
1751     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1752       if (LHSI->getOpcode() == Instruction::Sub)
1753         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
1754           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1755     }
1756   }
1757
1758   // -A + B  -->  B - A
1759   if (Value *V = dyn_castNegVal(LHS))
1760     return BinaryOperator::createSub(RHS, V);
1761
1762   // A + -B  -->  A - B
1763   if (!isa<Constant>(RHS))
1764     if (Value *V = dyn_castNegVal(RHS))
1765       return BinaryOperator::createSub(LHS, V);
1766
1767
1768   ConstantInt *C2;
1769   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1770     if (X == RHS)   // X*C + X --> X * (C+1)
1771       return BinaryOperator::createMul(RHS, AddOne(C2));
1772
1773     // X*C1 + X*C2 --> X * (C1+C2)
1774     ConstantInt *C1;
1775     if (X == dyn_castFoldableMul(RHS, C1))
1776       return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1777   }
1778
1779   // X + X*C --> X * (C+1)
1780   if (dyn_castFoldableMul(RHS, C2) == LHS)
1781     return BinaryOperator::createMul(LHS, AddOne(C2));
1782
1783
1784   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1785   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1786     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
1787
1788   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1789     Value *X = 0;
1790     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
1791       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1792       return BinaryOperator::createSub(C, X);
1793     }
1794
1795     // (X & FF00) + xx00  -> (X+xx00) & FF00
1796     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1797       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1798       if (Anded == CRHS) {
1799         // See if all bits from the first bit set in the Add RHS up are included
1800         // in the mask.  First, get the rightmost bit.
1801         uint64_t AddRHSV = CRHS->getZExtValue();
1802
1803         // Form a mask of all bits from the lowest bit added through the top.
1804         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1805         AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
1806
1807         // See if the and mask includes all of these bits.
1808         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
1809
1810         if (AddRHSHighBits == AddRHSHighBitsAnd) {
1811           // Okay, the xform is safe.  Insert the new add pronto.
1812           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1813                                                             LHS->getName()), I);
1814           return BinaryOperator::createAnd(NewAdd, C2);
1815         }
1816       }
1817     }
1818
1819     // Try to fold constant add into select arguments.
1820     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1821       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1822         return R;
1823   }
1824
1825   // add (cast *A to intptrtype) B -> cast (GEP (cast *A to sbyte*) B) -> intptrtype
1826   {
1827     CastInst* CI = dyn_cast<CastInst>(LHS);
1828     Value* Other = RHS;
1829     if (!CI) {
1830       CI = dyn_cast<CastInst>(RHS);
1831       Other = LHS;
1832     }
1833     if (CI && CI->getType()->isSized() && 
1834         (CI->getType()->getPrimitiveSize() == 
1835          TD->getIntPtrType()->getPrimitiveSize()) 
1836         && isa<PointerType>(CI->getOperand(0)->getType())) {
1837       Value* I2 = InsertCastBefore(CI->getOperand(0),
1838                                    PointerType::get(Type::SByteTy), I);
1839       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1840       return new CastInst(I2, CI->getType());
1841     }
1842   }
1843
1844   return Changed ? &I : 0;
1845 }
1846
1847 // isSignBit - Return true if the value represented by the constant only has the
1848 // highest order bit set.
1849 static bool isSignBit(ConstantInt *CI) {
1850   unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1851   return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1852 }
1853
1854 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1855 ///
1856 static Value *RemoveNoopCast(Value *V) {
1857   if (CastInst *CI = dyn_cast<CastInst>(V)) {
1858     const Type *CTy = CI->getType();
1859     const Type *OpTy = CI->getOperand(0)->getType();
1860     if (CTy->isInteger() && OpTy->isInteger()) {
1861       if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1862         return RemoveNoopCast(CI->getOperand(0));
1863     } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1864       return RemoveNoopCast(CI->getOperand(0));
1865   }
1866   return V;
1867 }
1868
1869 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1870   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1871
1872   if (Op0 == Op1)         // sub X, X  -> 0
1873     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1874
1875   // If this is a 'B = x-(-A)', change to B = x+A...
1876   if (Value *V = dyn_castNegVal(Op1))
1877     return BinaryOperator::createAdd(Op0, V);
1878
1879   if (isa<UndefValue>(Op0))
1880     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
1881   if (isa<UndefValue>(Op1))
1882     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
1883
1884   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1885     // Replace (-1 - A) with (~A)...
1886     if (C->isAllOnesValue())
1887       return BinaryOperator::createNot(Op1);
1888
1889     // C - ~X == X + (1+C)
1890     Value *X = 0;
1891     if (match(Op1, m_Not(m_Value(X))))
1892       return BinaryOperator::createAdd(X,
1893                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1894     // -((uint)X >> 31) -> ((int)X >> 31)
1895     // -((int)X >> 31) -> ((uint)X >> 31)
1896     if (C->isNullValue()) {
1897       Value *NoopCastedRHS = RemoveNoopCast(Op1);
1898       if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
1899         if (SI->getOpcode() == Instruction::Shr)
1900           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1901             const Type *NewTy;
1902             if (SI->getType()->isSigned())
1903               NewTy = SI->getType()->getUnsignedVersion();
1904             else
1905               NewTy = SI->getType()->getSignedVersion();
1906             // Check to see if we are shifting out everything but the sign bit.
1907             if (CU->getZExtValue() == 
1908                 SI->getType()->getPrimitiveSizeInBits()-1) {
1909               // Ok, the transformation is safe.  Insert a cast of the incoming
1910               // value, then the new shift, then the new cast.
1911               Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1912                                                  SI->getOperand(0)->getName());
1913               Value *InV = InsertNewInstBefore(FirstCast, I);
1914               Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1915                                                     CU, SI->getName());
1916               if (NewShift->getType() == I.getType())
1917                 return NewShift;
1918               else {
1919                 InV = InsertNewInstBefore(NewShift, I);
1920                 return new CastInst(NewShift, I.getType());
1921               }
1922             }
1923           }
1924     }
1925
1926     // Try to fold constant sub into select arguments.
1927     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1928       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1929         return R;
1930
1931     if (isa<PHINode>(Op0))
1932       if (Instruction *NV = FoldOpIntoPhi(I))
1933         return NV;
1934   }
1935
1936   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1937     if (Op1I->getOpcode() == Instruction::Add &&
1938         !Op0->getType()->isFloatingPoint()) {
1939       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
1940         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
1941       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
1942         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
1943       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1944         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1945           // C1-(X+C2) --> (C1-C2)-X
1946           return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1947                                            Op1I->getOperand(0));
1948       }
1949     }
1950
1951     if (Op1I->hasOneUse()) {
1952       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1953       // is not used by anyone else...
1954       //
1955       if (Op1I->getOpcode() == Instruction::Sub &&
1956           !Op1I->getType()->isFloatingPoint()) {
1957         // Swap the two operands of the subexpr...
1958         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1959         Op1I->setOperand(0, IIOp1);
1960         Op1I->setOperand(1, IIOp0);
1961
1962         // Create the new top level add instruction...
1963         return BinaryOperator::createAdd(Op0, Op1);
1964       }
1965
1966       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1967       //
1968       if (Op1I->getOpcode() == Instruction::And &&
1969           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1970         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1971
1972         Value *NewNot =
1973           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
1974         return BinaryOperator::createAnd(Op0, NewNot);
1975       }
1976
1977       // 0 - (X sdiv C)  -> (X sdiv -C)
1978       if (Op1I->getOpcode() == Instruction::Div)
1979         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
1980           if (CSI->getType()->isSigned() && CSI->isNullValue())
1981             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
1982               return BinaryOperator::createDiv(Op1I->getOperand(0),
1983                                                ConstantExpr::getNeg(DivRHS));
1984
1985       // X - X*C --> X * (1-C)
1986       ConstantInt *C2 = 0;
1987       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
1988         Constant *CP1 =
1989           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
1990         return BinaryOperator::createMul(Op0, CP1);
1991       }
1992     }
1993   }
1994
1995   if (!Op0->getType()->isFloatingPoint())
1996     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1997       if (Op0I->getOpcode() == Instruction::Add) {
1998         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
1999           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2000         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2001           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2002       } else if (Op0I->getOpcode() == Instruction::Sub) {
2003         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2004           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2005       }
2006
2007   ConstantInt *C1;
2008   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2009     if (X == Op1) { // X*C - X --> X * (C-1)
2010       Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2011       return BinaryOperator::createMul(Op1, CP1);
2012     }
2013
2014     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2015     if (X == dyn_castFoldableMul(Op1, C2))
2016       return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2017   }
2018   return 0;
2019 }
2020
2021 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
2022 /// really just returns true if the most significant (sign) bit is set.
2023 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
2024   if (RHS->getType()->isSigned()) {
2025     // True if source is LHS < 0 or LHS <= -1
2026     return Opcode == Instruction::SetLT && RHS->isNullValue() ||
2027            Opcode == Instruction::SetLE && RHS->isAllOnesValue();
2028   } else {
2029     ConstantInt *RHSC = cast<ConstantInt>(RHS);
2030     // True if source is LHS > 127 or LHS >= 128, where the constants depend on
2031     // the size of the integer type.
2032     if (Opcode == Instruction::SetGE)
2033       return RHSC->getZExtValue() ==
2034         1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
2035     if (Opcode == Instruction::SetGT)
2036       return RHSC->getZExtValue() ==
2037         (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2038   }
2039   return false;
2040 }
2041
2042 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2043   bool Changed = SimplifyCommutative(I);
2044   Value *Op0 = I.getOperand(0);
2045
2046   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2047     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2048
2049   // Simplify mul instructions with a constant RHS...
2050   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2051     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2052
2053       // ((X << C1)*C2) == (X * (C2 << C1))
2054       if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2055         if (SI->getOpcode() == Instruction::Shl)
2056           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2057             return BinaryOperator::createMul(SI->getOperand(0),
2058                                              ConstantExpr::getShl(CI, ShOp));
2059
2060       if (CI->isNullValue())
2061         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2062       if (CI->equalsInt(1))                  // X * 1  == X
2063         return ReplaceInstUsesWith(I, Op0);
2064       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2065         return BinaryOperator::createNeg(Op0, I.getName());
2066
2067       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2068       if (isPowerOf2_64(Val)) {          // Replace X*(2^C) with X << C
2069         uint64_t C = Log2_64(Val);
2070         return new ShiftInst(Instruction::Shl, Op0,
2071                              ConstantInt::get(Type::UByteTy, C));
2072       }
2073     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2074       if (Op1F->isNullValue())
2075         return ReplaceInstUsesWith(I, Op1);
2076
2077       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2078       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2079       if (Op1F->getValue() == 1.0)
2080         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2081     }
2082     
2083     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2084       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2085           isa<ConstantInt>(Op0I->getOperand(1))) {
2086         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2087         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2088                                                      Op1, "tmp");
2089         InsertNewInstBefore(Add, I);
2090         Value *C1C2 = ConstantExpr::getMul(Op1, 
2091                                            cast<Constant>(Op0I->getOperand(1)));
2092         return BinaryOperator::createAdd(Add, C1C2);
2093         
2094       }
2095
2096     // Try to fold constant mul into select arguments.
2097     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2098       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2099         return R;
2100
2101     if (isa<PHINode>(Op0))
2102       if (Instruction *NV = FoldOpIntoPhi(I))
2103         return NV;
2104   }
2105
2106   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2107     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2108       return BinaryOperator::createMul(Op0v, Op1v);
2109
2110   // If one of the operands of the multiply is a cast from a boolean value, then
2111   // we know the bool is either zero or one, so this is a 'masking' multiply.
2112   // See if we can simplify things based on how the boolean was originally
2113   // formed.
2114   CastInst *BoolCast = 0;
2115   if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
2116     if (CI->getOperand(0)->getType() == Type::BoolTy)
2117       BoolCast = CI;
2118   if (!BoolCast)
2119     if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
2120       if (CI->getOperand(0)->getType() == Type::BoolTy)
2121         BoolCast = CI;
2122   if (BoolCast) {
2123     if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2124       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2125       const Type *SCOpTy = SCIOp0->getType();
2126
2127       // If the setcc is true iff the sign bit of X is set, then convert this
2128       // multiply into a shift/and combination.
2129       if (isa<ConstantInt>(SCIOp1) &&
2130           isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
2131         // Shift the X value right to turn it into "all signbits".
2132         Constant *Amt = ConstantInt::get(Type::UByteTy,
2133                                           SCOpTy->getPrimitiveSizeInBits()-1);
2134         if (SCIOp0->getType()->isUnsigned()) {
2135           const Type *NewTy = SCIOp0->getType()->getSignedVersion();
2136           SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
2137                                                     SCIOp0->getName()), I);
2138         }
2139
2140         Value *V =
2141           InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
2142                                             BoolCast->getOperand(0)->getName()+
2143                                             ".mask"), I);
2144
2145         // If the multiply type is not the same as the source type, sign extend
2146         // or truncate to the multiply type.
2147         if (I.getType() != V->getType())
2148           V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
2149
2150         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2151         return BinaryOperator::createAnd(V, OtherOp);
2152       }
2153     }
2154   }
2155
2156   return Changed ? &I : 0;
2157 }
2158
2159 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
2160   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2161
2162   if (isa<UndefValue>(Op0))              // undef / X -> 0
2163     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2164   if (isa<UndefValue>(Op1))
2165     return ReplaceInstUsesWith(I, Op1);  // X / undef -> undef
2166
2167   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2168     // div X, 1 == X
2169     if (RHS->equalsInt(1))
2170       return ReplaceInstUsesWith(I, Op0);
2171
2172     // div X, -1 == -X
2173     if (RHS->isAllOnesValue())
2174       return BinaryOperator::createNeg(Op0);
2175
2176     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2177       if (LHS->getOpcode() == Instruction::Div)
2178         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2179           // (X / C1) / C2  -> X / (C1*C2)
2180           return BinaryOperator::createDiv(LHS->getOperand(0),
2181                                            ConstantExpr::getMul(RHS, LHSRHS));
2182         }
2183
2184     // Check to see if this is an unsigned division with an exact power of 2,
2185     // if so, convert to a right shift.
2186     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS)) 
2187       if (C->getType()->isUnsigned())
2188         if (uint64_t Val = C->getZExtValue())    // Don't break X / 0
2189           if (isPowerOf2_64(Val)) {
2190             uint64_t C = Log2_64(Val);
2191             return new ShiftInst(Instruction::Shr, Op0,
2192                                  ConstantInt::get(Type::UByteTy, C));
2193           }
2194
2195     // -X/C -> X/-C
2196     if (RHS->getType()->isSigned())
2197       if (Value *LHSNeg = dyn_castNegVal(Op0))
2198         return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2199
2200     if (!RHS->isNullValue()) {
2201       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2202         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2203           return R;
2204       if (isa<PHINode>(Op0))
2205         if (Instruction *NV = FoldOpIntoPhi(I))
2206           return NV;
2207     }
2208   }
2209
2210   // Handle div X, Cond?Y:Z
2211   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2212     // div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in the
2213     // same basic block, then we replace the select with Y, and the condition of
2214     // the select with false (if the cond value is in the same BB).  If the
2215     // select has uses other than the div, this allows them to be simplified
2216     // also.
2217     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2218       if (ST->isNullValue()) {
2219         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2220         if (CondI && CondI->getParent() == I.getParent())
2221           UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2222         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2223           I.setOperand(1, SI->getOperand(2));
2224         else
2225           UpdateValueUsesWith(SI, SI->getOperand(2));
2226         return &I;
2227       }
2228     // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2229     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2230       if (ST->isNullValue()) {
2231         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2232         if (CondI && CondI->getParent() == I.getParent())
2233           UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2234         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2235           I.setOperand(1, SI->getOperand(1));
2236         else
2237           UpdateValueUsesWith(SI, SI->getOperand(1));
2238         return &I;
2239       }
2240
2241     // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2242     // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
2243     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2244       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) 
2245         if (STO->getType()->isUnsigned() && SFO->getType()->isUnsigned()) {
2246           // STO == 0 and SFO == 0 handled above.
2247           uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2248           if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2249             unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2250             Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2251             Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
2252                                              TC, SI->getName()+".t");
2253             TSI = InsertNewInstBefore(TSI, I);
2254
2255             Constant *FC = ConstantInt::get(Type::UByteTy, FSA);
2256             Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
2257                                              FC, SI->getName()+".f");
2258             FSI = InsertNewInstBefore(FSI, I);
2259             return new SelectInst(SI->getOperand(0), TSI, FSI);
2260           }
2261         }
2262   }
2263
2264   // 0 / X == 0, we don't need to preserve faults!
2265   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2266     if (LHS->equalsInt(0))
2267       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2268
2269   if (I.getType()->isSigned()) {
2270     // If the sign bits of both operands are zero (i.e. we can prove they are
2271     // unsigned inputs), turn this into a udiv.
2272     uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2273     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2274       const Type *NTy = Op0->getType()->getUnsignedVersion();
2275       Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2276       InsertNewInstBefore(LHS, I);
2277       Value *RHS;
2278       if (Constant *R = dyn_cast<Constant>(Op1))
2279         RHS = ConstantExpr::getCast(R, NTy);
2280       else
2281         RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2282       Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
2283       InsertNewInstBefore(Div, I);
2284       return new CastInst(Div, I.getType());
2285     }      
2286   } else {
2287     // Known to be an unsigned division.
2288     if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2289       // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
2290       if (RHSI->getOpcode() == Instruction::Shl &&
2291           isa<ConstantInt>(RHSI->getOperand(0)) &&
2292           RHSI->getOperand(0)->getType()->isUnsigned()) {
2293         uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2294         if (isPowerOf2_64(C1)) {
2295           uint64_t C2 = Log2_64(C1);
2296           Value *Add = RHSI->getOperand(1);
2297           if (C2) {
2298             Constant *C2V = ConstantInt::get(Add->getType(), C2);
2299             Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
2300                                                                 "tmp"), I);
2301           }
2302           return new ShiftInst(Instruction::Shr, Op0, Add);
2303         }
2304       }
2305     }
2306   }
2307   
2308   return 0;
2309 }
2310
2311
2312 /// GetFactor - If we can prove that the specified value is at least a multiple
2313 /// of some factor, return that factor.
2314 static Constant *GetFactor(Value *V) {
2315   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2316     return CI;
2317   
2318   // Unless we can be tricky, we know this is a multiple of 1.
2319   Constant *Result = ConstantInt::get(V->getType(), 1);
2320   
2321   Instruction *I = dyn_cast<Instruction>(V);
2322   if (!I) return Result;
2323   
2324   if (I->getOpcode() == Instruction::Mul) {
2325     // Handle multiplies by a constant, etc.
2326     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2327                                 GetFactor(I->getOperand(1)));
2328   } else if (I->getOpcode() == Instruction::Shl) {
2329     // (X<<C) -> X * (1 << C)
2330     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2331       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2332       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2333     }
2334   } else if (I->getOpcode() == Instruction::And) {
2335     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2336       // X & 0xFFF0 is known to be a multiple of 16.
2337       unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2338       if (Zeros != V->getType()->getPrimitiveSizeInBits())
2339         return ConstantExpr::getShl(Result, 
2340                                     ConstantInt::get(Type::UByteTy, Zeros));
2341     }
2342   } else if (I->getOpcode() == Instruction::Cast) {
2343     Value *Op = I->getOperand(0);
2344     // Only handle int->int casts.
2345     if (!Op->getType()->isInteger()) return Result;
2346     return ConstantExpr::getCast(GetFactor(Op), V->getType());
2347   }    
2348   return Result;
2349 }
2350
2351 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
2352   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2353   
2354   // 0 % X == 0, we don't need to preserve faults!
2355   if (Constant *LHS = dyn_cast<Constant>(Op0))
2356     if (LHS->isNullValue())
2357       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2358
2359   if (isa<UndefValue>(Op0))              // undef % X -> 0
2360     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2361   if (isa<UndefValue>(Op1))
2362     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2363   
2364   if (I.getType()->isSigned()) {
2365     if (Value *RHSNeg = dyn_castNegVal(Op1))
2366       if (!isa<ConstantInt>(RHSNeg) || !RHSNeg->getType()->isSigned() ||
2367           cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2368         // X % -Y -> X % Y
2369         AddUsesToWorkList(I);
2370         I.setOperand(1, RHSNeg);
2371         return &I;
2372       }
2373    
2374     // If the top bits of both operands are zero (i.e. we can prove they are
2375     // unsigned inputs), turn this into a urem.
2376     uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2377     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2378       const Type *NTy = Op0->getType()->getUnsignedVersion();
2379       Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2380       InsertNewInstBefore(LHS, I);
2381       Value *RHS;
2382       if (Constant *R = dyn_cast<Constant>(Op1))
2383         RHS = ConstantExpr::getCast(R, NTy);
2384       else
2385         RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2386       Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
2387       InsertNewInstBefore(Rem, I);
2388       return new CastInst(Rem, I.getType());
2389     }
2390   }
2391
2392   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2393     // X % 0 == undef, we don't need to preserve faults!
2394     if (RHS->equalsInt(0))
2395       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2396     
2397     if (RHS->equalsInt(1))  // X % 1 == 0
2398       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2399
2400     // Check to see if this is an unsigned remainder with an exact power of 2,
2401     // if so, convert to a bitwise and.
2402     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2403       if (RHS->getType()->isUnsigned())
2404         if (isPowerOf2_64(C->getZExtValue()))
2405           return BinaryOperator::createAnd(Op0, SubOne(C));
2406
2407     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2408       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2409         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2410           return R;
2411       } else if (isa<PHINode>(Op0I)) {
2412         if (Instruction *NV = FoldOpIntoPhi(I))
2413           return NV;
2414       }
2415       
2416       // X*C1%C2 --> 0  iff  C1%C2 == 0
2417       if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
2418         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2419     }
2420   }
2421
2422   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2423     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
2424     if (I.getType()->isUnsigned() && 
2425         RHSI->getOpcode() == Instruction::Shl &&
2426         isa<ConstantInt>(RHSI->getOperand(0)) && 
2427         RHSI->getOperand(0)->getType()->isUnsigned()) {
2428       unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2429       if (isPowerOf2_64(C1)) {
2430         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2431         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2432                                                                    "tmp"), I);
2433         return BinaryOperator::createAnd(Op0, Add);
2434       }
2435     }
2436     
2437     // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2438     // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
2439     if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2440       // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2441       // the same basic block, then we replace the select with Y, and the
2442       // condition of the select with false (if the cond value is in the same
2443       // BB).  If the select has uses other than the div, this allows them to be
2444       // simplified also.
2445       if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2446         if (ST->isNullValue()) {
2447           Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2448           if (CondI && CondI->getParent() == I.getParent())
2449             UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2450           else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2451             I.setOperand(1, SI->getOperand(2));
2452           else
2453             UpdateValueUsesWith(SI, SI->getOperand(2));
2454           return &I;
2455         }
2456       // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2457       if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2458         if (ST->isNullValue()) {
2459           Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2460           if (CondI && CondI->getParent() == I.getParent())
2461             UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2462           else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2463             I.setOperand(1, SI->getOperand(1));
2464           else
2465             UpdateValueUsesWith(SI, SI->getOperand(1));
2466           return &I;
2467         }
2468
2469       
2470       if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2471         if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) 
2472           if (STO->getType()->isUnsigned() && SFO->getType()->isUnsigned()) {
2473             // STO == 0 and SFO == 0 handled above.
2474             if (isPowerOf2_64(STO->getZExtValue()) && 
2475                 isPowerOf2_64(SFO->getZExtValue())) {
2476               Value *TrueAnd = InsertNewInstBefore(
2477                 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"),
2478                   I);
2479               Value *FalseAnd = InsertNewInstBefore(
2480                 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"),
2481                   I);
2482               return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2483             }
2484           }
2485     }
2486   }
2487   
2488   return 0;
2489 }
2490
2491 // isMaxValueMinusOne - return true if this is Max-1
2492 static bool isMaxValueMinusOne(const ConstantInt *C) {
2493   if (C->getType()->isUnsigned()) 
2494     return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
2495
2496   // Calculate 0111111111..11111
2497   unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2498   int64_t Val = INT64_MAX;             // All ones
2499   Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
2500   return C->getSExtValue() == Val-1;
2501 }
2502
2503 // isMinValuePlusOne - return true if this is Min+1
2504 static bool isMinValuePlusOne(const ConstantInt *C) {
2505   if (C->getType()->isUnsigned())
2506     return C->getZExtValue() == 1;
2507
2508   // Calculate 1111111111000000000000
2509   unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2510   int64_t Val = -1;                    // All ones
2511   Val <<= TypeBits-1;                  // Shift over to the right spot
2512   return C->getSExtValue() == Val+1;
2513 }
2514
2515 // isOneBitSet - Return true if there is exactly one bit set in the specified
2516 // constant.
2517 static bool isOneBitSet(const ConstantInt *CI) {
2518   uint64_t V = CI->getZExtValue();
2519   return V && (V & (V-1)) == 0;
2520 }
2521
2522 #if 0   // Currently unused
2523 // isLowOnes - Return true if the constant is of the form 0+1+.
2524 static bool isLowOnes(const ConstantInt *CI) {
2525   uint64_t V = CI->getZExtValue();
2526
2527   // There won't be bits set in parts that the type doesn't contain.
2528   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2529
2530   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2531   return U && V && (U & V) == 0;
2532 }
2533 #endif
2534
2535 // isHighOnes - Return true if the constant is of the form 1+0+.
2536 // This is the same as lowones(~X).
2537 static bool isHighOnes(const ConstantInt *CI) {
2538   uint64_t V = ~CI->getZExtValue();
2539   if (~V == 0) return false;  // 0's does not match "1+"
2540
2541   // There won't be bits set in parts that the type doesn't contain.
2542   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2543
2544   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2545   return U && V && (U & V) == 0;
2546 }
2547
2548
2549 /// getSetCondCode - Encode a setcc opcode into a three bit mask.  These bits
2550 /// are carefully arranged to allow folding of expressions such as:
2551 ///
2552 ///      (A < B) | (A > B) --> (A != B)
2553 ///
2554 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2555 /// represents that the comparison is true if A == B, and bit value '1' is true
2556 /// if A < B.
2557 ///
2558 static unsigned getSetCondCode(const SetCondInst *SCI) {
2559   switch (SCI->getOpcode()) {
2560     // False -> 0
2561   case Instruction::SetGT: return 1;
2562   case Instruction::SetEQ: return 2;
2563   case Instruction::SetGE: return 3;
2564   case Instruction::SetLT: return 4;
2565   case Instruction::SetNE: return 5;
2566   case Instruction::SetLE: return 6;
2567     // True -> 7
2568   default:
2569     assert(0 && "Invalid SetCC opcode!");
2570     return 0;
2571   }
2572 }
2573
2574 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
2575 /// opcode and two operands into either a constant true or false, or a brand new
2576 /// SetCC instruction.
2577 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2578   switch (Opcode) {
2579   case 0: return ConstantBool::getFalse();
2580   case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2581   case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2582   case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2583   case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2584   case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2585   case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2586   case 7: return ConstantBool::getTrue();
2587   default: assert(0 && "Illegal SetCCCode!"); return 0;
2588   }
2589 }
2590
2591 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2592 struct FoldSetCCLogical {
2593   InstCombiner &IC;
2594   Value *LHS, *RHS;
2595   FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2596     : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2597   bool shouldApply(Value *V) const {
2598     if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2599       return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2600               SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2601     return false;
2602   }
2603   Instruction *apply(BinaryOperator &Log) const {
2604     SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2605     if (SCI->getOperand(0) != LHS) {
2606       assert(SCI->getOperand(1) == LHS);
2607       SCI->swapOperands();  // Swap the LHS and RHS of the SetCC
2608     }
2609
2610     unsigned LHSCode = getSetCondCode(SCI);
2611     unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2612     unsigned Code;
2613     switch (Log.getOpcode()) {
2614     case Instruction::And: Code = LHSCode & RHSCode; break;
2615     case Instruction::Or:  Code = LHSCode | RHSCode; break;
2616     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2617     default: assert(0 && "Illegal logical opcode!"); return 0;
2618     }
2619
2620     Value *RV = getSetCCValue(Code, LHS, RHS);
2621     if (Instruction *I = dyn_cast<Instruction>(RV))
2622       return I;
2623     // Otherwise, it's a constant boolean value...
2624     return IC.ReplaceInstUsesWith(Log, RV);
2625   }
2626 };
2627
2628 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
2629 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
2630 // guaranteed to be either a shift instruction or a binary operator.
2631 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2632                                     ConstantIntegral *OpRHS,
2633                                     ConstantIntegral *AndRHS,
2634                                     BinaryOperator &TheAnd) {
2635   Value *X = Op->getOperand(0);
2636   Constant *Together = 0;
2637   if (!isa<ShiftInst>(Op))
2638     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2639
2640   switch (Op->getOpcode()) {
2641   case Instruction::Xor:
2642     if (Op->hasOneUse()) {
2643       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2644       std::string OpName = Op->getName(); Op->setName("");
2645       Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2646       InsertNewInstBefore(And, TheAnd);
2647       return BinaryOperator::createXor(And, Together);
2648     }
2649     break;
2650   case Instruction::Or:
2651     if (Together == AndRHS) // (X | C) & C --> C
2652       return ReplaceInstUsesWith(TheAnd, AndRHS);
2653
2654     if (Op->hasOneUse() && Together != OpRHS) {
2655       // (X | C1) & C2 --> (X | (C1&C2)) & C2
2656       std::string Op0Name = Op->getName(); Op->setName("");
2657       Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2658       InsertNewInstBefore(Or, TheAnd);
2659       return BinaryOperator::createAnd(Or, AndRHS);
2660     }
2661     break;
2662   case Instruction::Add:
2663     if (Op->hasOneUse()) {
2664       // Adding a one to a single bit bit-field should be turned into an XOR
2665       // of the bit.  First thing to check is to see if this AND is with a
2666       // single bit constant.
2667       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
2668
2669       // Clear bits that are not part of the constant.
2670       AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
2671
2672       // If there is only one bit set...
2673       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2674         // Ok, at this point, we know that we are masking the result of the
2675         // ADD down to exactly one bit.  If the constant we are adding has
2676         // no bits set below this bit, then we can eliminate the ADD.
2677         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
2678
2679         // Check to see if any bits below the one bit set in AndRHSV are set.
2680         if ((AddRHS & (AndRHSV-1)) == 0) {
2681           // If not, the only thing that can effect the output of the AND is
2682           // the bit specified by AndRHSV.  If that bit is set, the effect of
2683           // the XOR is to toggle the bit.  If it is clear, then the ADD has
2684           // no effect.
2685           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2686             TheAnd.setOperand(0, X);
2687             return &TheAnd;
2688           } else {
2689             std::string Name = Op->getName(); Op->setName("");
2690             // Pull the XOR out of the AND.
2691             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2692             InsertNewInstBefore(NewAnd, TheAnd);
2693             return BinaryOperator::createXor(NewAnd, AndRHS);
2694           }
2695         }
2696       }
2697     }
2698     break;
2699
2700   case Instruction::Shl: {
2701     // We know that the AND will not produce any of the bits shifted in, so if
2702     // the anded constant includes them, clear them now!
2703     //
2704     Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2705     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2706     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2707
2708     if (CI == ShlMask) {   // Masking out bits that the shift already masks
2709       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
2710     } else if (CI != AndRHS) {                  // Reducing bits set in and.
2711       TheAnd.setOperand(1, CI);
2712       return &TheAnd;
2713     }
2714     break;
2715   }
2716   case Instruction::Shr:
2717     // We know that the AND will not produce any of the bits shifted in, so if
2718     // the anded constant includes them, clear them now!  This only applies to
2719     // unsigned shifts, because a signed shr may bring in set bits!
2720     //
2721     if (AndRHS->getType()->isUnsigned()) {
2722       Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2723       Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2724       Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2725
2726       if (CI == ShrMask) {   // Masking out bits that the shift already masks.
2727         return ReplaceInstUsesWith(TheAnd, Op);
2728       } else if (CI != AndRHS) {
2729         TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
2730         return &TheAnd;
2731       }
2732     } else {   // Signed shr.
2733       // See if this is shifting in some sign extension, then masking it out
2734       // with an and.
2735       if (Op->hasOneUse()) {
2736         Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2737         Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2738         Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2739         if (CI == AndRHS) {          // Masking out bits shifted in.
2740           // Make the argument unsigned.
2741           Value *ShVal = Op->getOperand(0);
2742           ShVal = InsertCastBefore(ShVal,
2743                                    ShVal->getType()->getUnsignedVersion(),
2744                                    TheAnd);
2745           ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2746                                                     OpRHS, Op->getName()),
2747                                       TheAnd);
2748           Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2749           ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2750                                                              TheAnd.getName()),
2751                                       TheAnd);
2752           return new CastInst(ShVal, Op->getType());
2753         }
2754       }
2755     }
2756     break;
2757   }
2758   return 0;
2759 }
2760
2761
2762 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2763 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
2764 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi.  IB is the location to
2765 /// insert new instructions.
2766 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2767                                            bool Inside, Instruction &IB) {
2768   assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2769          "Lo is not <= Hi in range emission code!");
2770   if (Inside) {
2771     if (Lo == Hi)  // Trivially false.
2772       return new SetCondInst(Instruction::SetNE, V, V);
2773     if (cast<ConstantIntegral>(Lo)->isMinValue())
2774       return new SetCondInst(Instruction::SetLT, V, Hi);
2775
2776     Constant *AddCST = ConstantExpr::getNeg(Lo);
2777     Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2778     InsertNewInstBefore(Add, IB);
2779     // Convert to unsigned for the comparison.
2780     const Type *UnsType = Add->getType()->getUnsignedVersion();
2781     Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2782     AddCST = ConstantExpr::getAdd(AddCST, Hi);
2783     AddCST = ConstantExpr::getCast(AddCST, UnsType);
2784     return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2785   }
2786
2787   if (Lo == Hi)  // Trivially true.
2788     return new SetCondInst(Instruction::SetEQ, V, V);
2789
2790   Hi = SubOne(cast<ConstantInt>(Hi));
2791
2792   // V < 0 || V >= Hi ->'V > Hi-1'
2793   if (cast<ConstantIntegral>(Lo)->isMinValue())
2794     return new SetCondInst(Instruction::SetGT, V, Hi);
2795
2796   // Emit X-Lo > Hi-Lo-1
2797   Constant *AddCST = ConstantExpr::getNeg(Lo);
2798   Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2799   InsertNewInstBefore(Add, IB);
2800   // Convert to unsigned for the comparison.
2801   const Type *UnsType = Add->getType()->getUnsignedVersion();
2802   Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2803   AddCST = ConstantExpr::getAdd(AddCST, Hi);
2804   AddCST = ConstantExpr::getCast(AddCST, UnsType);
2805   return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2806 }
2807
2808 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2809 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
2810 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
2811 // not, since all 1s are not contiguous.
2812 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2813   uint64_t V = Val->getZExtValue();
2814   if (!isShiftedMask_64(V)) return false;
2815
2816   // look for the first zero bit after the run of ones
2817   MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2818   // look for the first non-zero bit
2819   ME = 64-CountLeadingZeros_64(V);
2820   return true;
2821 }
2822
2823
2824
2825 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2826 /// where isSub determines whether the operator is a sub.  If we can fold one of
2827 /// the following xforms:
2828 /// 
2829 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2830 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2831 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2832 ///
2833 /// return (A +/- B).
2834 ///
2835 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2836                                         ConstantIntegral *Mask, bool isSub,
2837                                         Instruction &I) {
2838   Instruction *LHSI = dyn_cast<Instruction>(LHS);
2839   if (!LHSI || LHSI->getNumOperands() != 2 ||
2840       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2841
2842   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2843
2844   switch (LHSI->getOpcode()) {
2845   default: return 0;
2846   case Instruction::And:
2847     if (ConstantExpr::getAnd(N, Mask) == Mask) {
2848       // If the AndRHS is a power of two minus one (0+1+), this is simple.
2849       if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
2850         break;
2851
2852       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2853       // part, we don't need any explicit masks to take them out of A.  If that
2854       // is all N is, ignore it.
2855       unsigned MB, ME;
2856       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
2857         uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2858         Mask >>= 64-MB+1;
2859         if (MaskedValueIsZero(RHS, Mask))
2860           break;
2861       }
2862     }
2863     return 0;
2864   case Instruction::Or:
2865   case Instruction::Xor:
2866     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2867     if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
2868         ConstantExpr::getAnd(N, Mask)->isNullValue())
2869       break;
2870     return 0;
2871   }
2872   
2873   Instruction *New;
2874   if (isSub)
2875     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2876   else
2877     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2878   return InsertNewInstBefore(New, I);
2879 }
2880
2881 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
2882   bool Changed = SimplifyCommutative(I);
2883   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2884
2885   if (isa<UndefValue>(Op1))                         // X & undef -> 0
2886     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2887
2888   // and X, X = X
2889   if (Op0 == Op1)
2890     return ReplaceInstUsesWith(I, Op1);
2891
2892   // See if we can simplify any instructions used by the instruction whose sole 
2893   // purpose is to compute bits we don't care about.
2894   uint64_t KnownZero, KnownOne;
2895   if (!isa<PackedType>(I.getType()) &&
2896       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2897                            KnownZero, KnownOne))
2898     return &I;
2899   
2900   if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
2901     uint64_t AndRHSMask = AndRHS->getZExtValue();
2902     uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
2903     uint64_t NotAndRHS = AndRHSMask^TypeMask;
2904
2905     // Optimize a variety of ((val OP C1) & C2) combinations...
2906     if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2907       Instruction *Op0I = cast<Instruction>(Op0);
2908       Value *Op0LHS = Op0I->getOperand(0);
2909       Value *Op0RHS = Op0I->getOperand(1);
2910       switch (Op0I->getOpcode()) {
2911       case Instruction::Xor:
2912       case Instruction::Or:
2913         // If the mask is only needed on one incoming arm, push it up.
2914         if (Op0I->hasOneUse()) {
2915           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2916             // Not masking anything out for the LHS, move to RHS.
2917             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2918                                                    Op0RHS->getName()+".masked");
2919             InsertNewInstBefore(NewRHS, I);
2920             return BinaryOperator::create(
2921                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
2922           }
2923           if (!isa<Constant>(Op0RHS) &&
2924               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2925             // Not masking anything out for the RHS, move to LHS.
2926             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2927                                                    Op0LHS->getName()+".masked");
2928             InsertNewInstBefore(NewLHS, I);
2929             return BinaryOperator::create(
2930                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2931           }
2932         }
2933
2934         break;
2935       case Instruction::Add:
2936         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2937         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2938         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2939         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2940           return BinaryOperator::createAnd(V, AndRHS);
2941         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2942           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
2943         break;
2944
2945       case Instruction::Sub:
2946         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2947         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2948         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2949         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2950           return BinaryOperator::createAnd(V, AndRHS);
2951         break;
2952       }
2953
2954       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2955         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
2956           return Res;
2957     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2958       const Type *SrcTy = CI->getOperand(0)->getType();
2959
2960       // If this is an integer truncation or change from signed-to-unsigned, and
2961       // if the source is an and/or with immediate, transform it.  This
2962       // frequently occurs for bitfield accesses.
2963       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2964         if (SrcTy->getPrimitiveSizeInBits() >= 
2965               I.getType()->getPrimitiveSizeInBits() &&
2966             CastOp->getNumOperands() == 2)
2967           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
2968             if (CastOp->getOpcode() == Instruction::And) {
2969               // Change: and (cast (and X, C1) to T), C2
2970               // into  : and (cast X to T), trunc(C1)&C2
2971               // This will folds the two ands together, which may allow other
2972               // simplifications.
2973               Instruction *NewCast =
2974                 new CastInst(CastOp->getOperand(0), I.getType(),
2975                              CastOp->getName()+".shrunk");
2976               NewCast = InsertNewInstBefore(NewCast, I);
2977               
2978               Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2979               C3 = ConstantExpr::getAnd(C3, AndRHS);            // trunc(C1)&C2
2980               return BinaryOperator::createAnd(NewCast, C3);
2981             } else if (CastOp->getOpcode() == Instruction::Or) {
2982               // Change: and (cast (or X, C1) to T), C2
2983               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2984               Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2985               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
2986                 return ReplaceInstUsesWith(I, AndRHS);
2987             }
2988       }
2989     }
2990
2991     // Try to fold constant and into select arguments.
2992     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2993       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2994         return R;
2995     if (isa<PHINode>(Op0))
2996       if (Instruction *NV = FoldOpIntoPhi(I))
2997         return NV;
2998   }
2999
3000   Value *Op0NotVal = dyn_castNotVal(Op0);
3001   Value *Op1NotVal = dyn_castNotVal(Op1);
3002
3003   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3004     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3005
3006   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3007   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3008     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3009                                                I.getName()+".demorgan");
3010     InsertNewInstBefore(Or, I);
3011     return BinaryOperator::createNot(Or);
3012   }
3013   
3014   {
3015     Value *A = 0, *B = 0;
3016     ConstantInt *C1 = 0, *C2 = 0;
3017     if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3018       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3019         return ReplaceInstUsesWith(I, Op1);
3020     if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3021       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3022         return ReplaceInstUsesWith(I, Op0);
3023     
3024     if (Op0->hasOneUse() &&
3025         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3026       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3027         I.swapOperands();     // Simplify below
3028         std::swap(Op0, Op1);
3029       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3030         cast<BinaryOperator>(Op0)->swapOperands();
3031         I.swapOperands();     // Simplify below
3032         std::swap(Op0, Op1);
3033       }
3034     }
3035     if (Op1->hasOneUse() &&
3036         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3037       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3038         cast<BinaryOperator>(Op1)->swapOperands();
3039         std::swap(A, B);
3040       }
3041       if (A == Op0) {                                // A&(A^B) -> A & ~B
3042         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3043         InsertNewInstBefore(NotB, I);
3044         return BinaryOperator::createAnd(A, NotB);
3045       }
3046     }
3047   }
3048   
3049
3050   if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
3051     // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
3052     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3053       return R;
3054
3055     Value *LHSVal, *RHSVal;
3056     ConstantInt *LHSCst, *RHSCst;
3057     Instruction::BinaryOps LHSCC, RHSCC;
3058     if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3059       if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3060         if (LHSVal == RHSVal &&    // Found (X setcc C1) & (X setcc C2)
3061             // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
3062             LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
3063             RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3064           // Ensure that the larger constant is on the RHS.
3065           Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3066           SetCondInst *LHS = cast<SetCondInst>(Op0);
3067           if (cast<ConstantBool>(Cmp)->getValue()) {
3068             std::swap(LHS, RHS);
3069             std::swap(LHSCst, RHSCst);
3070             std::swap(LHSCC, RHSCC);
3071           }
3072
3073           // At this point, we know we have have two setcc instructions
3074           // comparing a value against two constants and and'ing the result
3075           // together.  Because of the above check, we know that we only have
3076           // SetEQ, SetNE, SetLT, and SetGT here.  We also know (from the
3077           // FoldSetCCLogical check above), that the two constants are not
3078           // equal.
3079           assert(LHSCst != RHSCst && "Compares not folded above?");
3080
3081           switch (LHSCC) {
3082           default: assert(0 && "Unknown integer condition code!");
3083           case Instruction::SetEQ:
3084             switch (RHSCC) {
3085             default: assert(0 && "Unknown integer condition code!");
3086             case Instruction::SetEQ:  // (X == 13 & X == 15) -> false
3087             case Instruction::SetGT:  // (X == 13 & X > 15)  -> false
3088               return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3089             case Instruction::SetNE:  // (X == 13 & X != 15) -> X == 13
3090             case Instruction::SetLT:  // (X == 13 & X < 15)  -> X == 13
3091               return ReplaceInstUsesWith(I, LHS);
3092             }
3093           case Instruction::SetNE:
3094             switch (RHSCC) {
3095             default: assert(0 && "Unknown integer condition code!");
3096             case Instruction::SetLT:
3097               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
3098                 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
3099               break;                        // (X != 13 & X < 15) -> no change
3100             case Instruction::SetEQ:        // (X != 13 & X == 15) -> X == 15
3101             case Instruction::SetGT:        // (X != 13 & X > 15)  -> X > 15
3102               return ReplaceInstUsesWith(I, RHS);
3103             case Instruction::SetNE:
3104               if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
3105                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3106                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3107                                                       LHSVal->getName()+".off");
3108                 InsertNewInstBefore(Add, I);
3109                 const Type *UnsType = Add->getType()->getUnsignedVersion();
3110                 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3111                 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
3112                 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3113                 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3114               }
3115               break;                        // (X != 13 & X != 15) -> no change
3116             }
3117             break;
3118           case Instruction::SetLT:
3119             switch (RHSCC) {
3120             default: assert(0 && "Unknown integer condition code!");
3121             case Instruction::SetEQ:  // (X < 13 & X == 15) -> false
3122             case Instruction::SetGT:  // (X < 13 & X > 15)  -> false
3123               return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3124             case Instruction::SetNE:  // (X < 13 & X != 15) -> X < 13
3125             case Instruction::SetLT:  // (X < 13 & X < 15) -> X < 13
3126               return ReplaceInstUsesWith(I, LHS);
3127             }
3128           case Instruction::SetGT:
3129             switch (RHSCC) {
3130             default: assert(0 && "Unknown integer condition code!");
3131             case Instruction::SetEQ:  // (X > 13 & X == 15) -> X > 13
3132               return ReplaceInstUsesWith(I, LHS);
3133             case Instruction::SetGT:  // (X > 13 & X > 15)  -> X > 15
3134               return ReplaceInstUsesWith(I, RHS);
3135             case Instruction::SetNE:
3136               if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3137                 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3138               break;                        // (X > 13 & X != 15) -> no change
3139             case Instruction::SetLT:   // (X > 13 & X < 15) -> (X-14) <u 1
3140               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
3141             }
3142           }
3143         }
3144   }
3145
3146   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3147   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3148     const Type *SrcTy = Op0C->getOperand(0)->getType();
3149     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3150       if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3151           // Only do this if the casts both really cause code to be generated.
3152           ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3153           ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3154         Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3155                                                        Op1C->getOperand(0),
3156                                                        I.getName());
3157         InsertNewInstBefore(NewOp, I);
3158         return new CastInst(NewOp, I.getType());
3159       }
3160   }
3161
3162   return Changed ? &I : 0;
3163 }
3164
3165 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3166 /// in the result.  If it does, and if the specified byte hasn't been filled in
3167 /// yet, fill it in and return false.
3168 static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3169   Instruction *I = dyn_cast<Instruction>(V);
3170   if (I == 0) return true;
3171
3172   // If this is an or instruction, it is an inner node of the bswap.
3173   if (I->getOpcode() == Instruction::Or)
3174     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3175            CollectBSwapParts(I->getOperand(1), ByteValues);
3176   
3177   // If this is a shift by a constant int, and it is "24", then its operand
3178   // defines a byte.  We only handle unsigned types here.
3179   if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3180     // Not shifting the entire input by N-1 bytes?
3181     if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
3182         8*(ByteValues.size()-1))
3183       return true;
3184     
3185     unsigned DestNo;
3186     if (I->getOpcode() == Instruction::Shl) {
3187       // X << 24 defines the top byte with the lowest of the input bytes.
3188       DestNo = ByteValues.size()-1;
3189     } else {
3190       // X >>u 24 defines the low byte with the highest of the input bytes.
3191       DestNo = 0;
3192     }
3193     
3194     // If the destination byte value is already defined, the values are or'd
3195     // together, which isn't a bswap (unless it's an or of the same bits).
3196     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3197       return true;
3198     ByteValues[DestNo] = I->getOperand(0);
3199     return false;
3200   }
3201   
3202   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3203   // don't have this.
3204   Value *Shift = 0, *ShiftLHS = 0;
3205   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3206   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3207       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3208     return true;
3209   Instruction *SI = cast<Instruction>(Shift);
3210
3211   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3212   if (ShiftAmt->getZExtValue() & 7 ||
3213       ShiftAmt->getZExtValue() > 8*ByteValues.size())
3214     return true;
3215   
3216   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3217   unsigned DestByte;
3218   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3219     if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
3220       break;
3221   // Unknown mask for bswap.
3222   if (DestByte == ByteValues.size()) return true;
3223   
3224   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3225   unsigned SrcByte;
3226   if (SI->getOpcode() == Instruction::Shl)
3227     SrcByte = DestByte - ShiftBytes;
3228   else
3229     SrcByte = DestByte + ShiftBytes;
3230   
3231   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3232   if (SrcByte != ByteValues.size()-DestByte-1)
3233     return true;
3234   
3235   // If the destination byte value is already defined, the values are or'd
3236   // together, which isn't a bswap (unless it's an or of the same bits).
3237   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3238     return true;
3239   ByteValues[DestByte] = SI->getOperand(0);
3240   return false;
3241 }
3242
3243 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3244 /// If so, insert the new bswap intrinsic and return it.
3245 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3246   // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3247   if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3248     return 0;
3249   
3250   /// ByteValues - For each byte of the result, we keep track of which value
3251   /// defines each byte.
3252   std::vector<Value*> ByteValues;
3253   ByteValues.resize(I.getType()->getPrimitiveSize());
3254     
3255   // Try to find all the pieces corresponding to the bswap.
3256   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3257       CollectBSwapParts(I.getOperand(1), ByteValues))
3258     return 0;
3259   
3260   // Check to see if all of the bytes come from the same value.
3261   Value *V = ByteValues[0];
3262   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3263   
3264   // Check to make sure that all of the bytes come from the same value.
3265   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3266     if (ByteValues[i] != V)
3267       return 0;
3268     
3269   // If they do then *success* we can turn this into a bswap.  Figure out what
3270   // bswap to make it into.
3271   Module *M = I.getParent()->getParent()->getParent();
3272   const char *FnName = 0;
3273   if (I.getType() == Type::UShortTy)
3274     FnName = "llvm.bswap.i16";
3275   else if (I.getType() == Type::UIntTy)
3276     FnName = "llvm.bswap.i32";
3277   else if (I.getType() == Type::ULongTy)
3278     FnName = "llvm.bswap.i64";
3279   else
3280     assert(0 && "Unknown integer type!");
3281   Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3282   
3283   return new CallInst(F, V);
3284 }
3285
3286
3287 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3288   bool Changed = SimplifyCommutative(I);
3289   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3290
3291   if (isa<UndefValue>(Op1))
3292     return ReplaceInstUsesWith(I,                         // X | undef -> -1
3293                                ConstantIntegral::getAllOnesValue(I.getType()));
3294
3295   // or X, X = X
3296   if (Op0 == Op1)
3297     return ReplaceInstUsesWith(I, Op0);
3298
3299   // See if we can simplify any instructions used by the instruction whose sole 
3300   // purpose is to compute bits we don't care about.
3301   uint64_t KnownZero, KnownOne;
3302   if (!isa<PackedType>(I.getType()) &&
3303       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3304                            KnownZero, KnownOne))
3305     return &I;
3306   
3307   // or X, -1 == -1
3308   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3309     ConstantInt *C1 = 0; Value *X = 0;
3310     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3311     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3312       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3313       Op0->setName("");
3314       InsertNewInstBefore(Or, I);
3315       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3316     }
3317
3318     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3319     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3320       std::string Op0Name = Op0->getName(); Op0->setName("");
3321       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3322       InsertNewInstBefore(Or, I);
3323       return BinaryOperator::createXor(Or,
3324                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3325     }
3326
3327     // Try to fold constant and into select arguments.
3328     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3329       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3330         return R;
3331     if (isa<PHINode>(Op0))
3332       if (Instruction *NV = FoldOpIntoPhi(I))
3333         return NV;
3334   }
3335
3336   Value *A = 0, *B = 0;
3337   ConstantInt *C1 = 0, *C2 = 0;
3338
3339   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3340     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3341       return ReplaceInstUsesWith(I, Op1);
3342   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3343     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3344       return ReplaceInstUsesWith(I, Op0);
3345
3346   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3347   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3348   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3349       match(Op1, m_Or(m_Value(), m_Value())) ||
3350       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3351        match(Op1, m_Shift(m_Value(), m_Value())))) {
3352     if (Instruction *BSwap = MatchBSwap(I))
3353       return BSwap;
3354   }
3355   
3356   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3357   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3358       MaskedValueIsZero(Op1, C1->getZExtValue())) {
3359     Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3360     Op0->setName("");
3361     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3362   }
3363
3364   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3365   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3366       MaskedValueIsZero(Op0, C1->getZExtValue())) {
3367     Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3368     Op0->setName("");
3369     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3370   }
3371
3372   // (A & C1)|(B & C2)
3373   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3374       match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3375
3376     if (A == B)  // (A & C1)|(A & C2) == A & (C1|C2)
3377       return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3378
3379
3380     // If we have: ((V + N) & C1) | (V & C2)
3381     // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3382     // replace with V+N.
3383     if (C1 == ConstantExpr::getNot(C2)) {
3384       Value *V1 = 0, *V2 = 0;
3385       if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
3386           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3387         // Add commutes, try both ways.
3388         if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3389           return ReplaceInstUsesWith(I, A);
3390         if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3391           return ReplaceInstUsesWith(I, A);
3392       }
3393       // Or commutes, try both ways.
3394       if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
3395           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3396         // Add commutes, try both ways.
3397         if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3398           return ReplaceInstUsesWith(I, B);
3399         if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3400           return ReplaceInstUsesWith(I, B);
3401       }
3402     }
3403   }
3404
3405   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
3406     if (A == Op1)   // ~A | A == -1
3407       return ReplaceInstUsesWith(I,
3408                                 ConstantIntegral::getAllOnesValue(I.getType()));
3409   } else {
3410     A = 0;
3411   }
3412   // Note, A is still live here!
3413   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
3414     if (Op0 == B)
3415       return ReplaceInstUsesWith(I,
3416                                 ConstantIntegral::getAllOnesValue(I.getType()));
3417
3418     // (~A | ~B) == (~(A & B)) - De Morgan's Law
3419     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3420       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3421                                               I.getName()+".demorgan"), I);
3422       return BinaryOperator::createNot(And);
3423     }
3424   }
3425
3426   // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
3427   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
3428     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3429       return R;
3430
3431     Value *LHSVal, *RHSVal;
3432     ConstantInt *LHSCst, *RHSCst;
3433     Instruction::BinaryOps LHSCC, RHSCC;
3434     if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3435       if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3436         if (LHSVal == RHSVal &&    // Found (X setcc C1) | (X setcc C2)
3437             // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
3438             LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
3439             RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3440           // Ensure that the larger constant is on the RHS.
3441           Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3442           SetCondInst *LHS = cast<SetCondInst>(Op0);
3443           if (cast<ConstantBool>(Cmp)->getValue()) {
3444             std::swap(LHS, RHS);
3445             std::swap(LHSCst, RHSCst);
3446             std::swap(LHSCC, RHSCC);
3447           }
3448
3449           // At this point, we know we have have two setcc instructions
3450           // comparing a value against two constants and or'ing the result
3451           // together.  Because of the above check, we know that we only have
3452           // SetEQ, SetNE, SetLT, and SetGT here.  We also know (from the
3453           // FoldSetCCLogical check above), that the two constants are not
3454           // equal.
3455           assert(LHSCst != RHSCst && "Compares not folded above?");
3456
3457           switch (LHSCC) {
3458           default: assert(0 && "Unknown integer condition code!");
3459           case Instruction::SetEQ:
3460             switch (RHSCC) {
3461             default: assert(0 && "Unknown integer condition code!");
3462             case Instruction::SetEQ:
3463               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3464                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3465                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3466                                                       LHSVal->getName()+".off");
3467                 InsertNewInstBefore(Add, I);
3468                 const Type *UnsType = Add->getType()->getUnsignedVersion();
3469                 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3470                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3471                 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3472                 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3473               }
3474               break;                  // (X == 13 | X == 15) -> no change
3475
3476             case Instruction::SetGT:  // (X == 13 | X > 14) -> no change
3477               break;
3478             case Instruction::SetNE:  // (X == 13 | X != 15) -> X != 15
3479             case Instruction::SetLT:  // (X == 13 | X < 15)  -> X < 15
3480               return ReplaceInstUsesWith(I, RHS);
3481             }
3482             break;
3483           case Instruction::SetNE:
3484             switch (RHSCC) {
3485             default: assert(0 && "Unknown integer condition code!");
3486             case Instruction::SetEQ:        // (X != 13 | X == 15) -> X != 13
3487             case Instruction::SetGT:        // (X != 13 | X > 15)  -> X != 13
3488               return ReplaceInstUsesWith(I, LHS);
3489             case Instruction::SetNE:        // (X != 13 | X != 15) -> true
3490             case Instruction::SetLT:        // (X != 13 | X < 15)  -> true
3491               return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3492             }
3493             break;
3494           case Instruction::SetLT:
3495             switch (RHSCC) {
3496             default: assert(0 && "Unknown integer condition code!");
3497             case Instruction::SetEQ:  // (X < 13 | X == 14) -> no change
3498               break;
3499             case Instruction::SetGT:  // (X < 13 | X > 15)  -> (X-13) > 2
3500               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
3501             case Instruction::SetNE:  // (X < 13 | X != 15) -> X != 15
3502             case Instruction::SetLT:  // (X < 13 | X < 15) -> X < 15
3503               return ReplaceInstUsesWith(I, RHS);
3504             }
3505             break;
3506           case Instruction::SetGT:
3507             switch (RHSCC) {
3508             default: assert(0 && "Unknown integer condition code!");
3509             case Instruction::SetEQ:  // (X > 13 | X == 15) -> X > 13
3510             case Instruction::SetGT:  // (X > 13 | X > 15)  -> X > 13
3511               return ReplaceInstUsesWith(I, LHS);
3512             case Instruction::SetNE:  // (X > 13 | X != 15)  -> true
3513             case Instruction::SetLT:  // (X > 13 | X < 15) -> true
3514               return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3515             }
3516           }
3517         }
3518   }
3519     
3520   // fold (or (cast A), (cast B)) -> (cast (or A, B))
3521   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3522     const Type *SrcTy = Op0C->getOperand(0)->getType();
3523     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3524       if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3525           // Only do this if the casts both really cause code to be generated.
3526           ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3527           ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3528         Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3529                                                       Op1C->getOperand(0),
3530                                                       I.getName());
3531         InsertNewInstBefore(NewOp, I);
3532         return new CastInst(NewOp, I.getType());
3533       }
3534   }
3535       
3536
3537   return Changed ? &I : 0;
3538 }
3539
3540 // XorSelf - Implements: X ^ X --> 0
3541 struct XorSelf {
3542   Value *RHS;
3543   XorSelf(Value *rhs) : RHS(rhs) {}
3544   bool shouldApply(Value *LHS) const { return LHS == RHS; }
3545   Instruction *apply(BinaryOperator &Xor) const {
3546     return &Xor;
3547   }
3548 };
3549
3550
3551 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3552   bool Changed = SimplifyCommutative(I);
3553   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3554
3555   if (isa<UndefValue>(Op1))
3556     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
3557
3558   // xor X, X = 0, even if X is nested in a sequence of Xor's.
3559   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3560     assert(Result == &I && "AssociativeOpt didn't work?");
3561     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3562   }
3563   
3564   // See if we can simplify any instructions used by the instruction whose sole 
3565   // purpose is to compute bits we don't care about.
3566   uint64_t KnownZero, KnownOne;
3567   if (!isa<PackedType>(I.getType()) &&
3568       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3569                            KnownZero, KnownOne))
3570     return &I;
3571
3572   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3573     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3574       // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
3575       if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
3576         if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
3577           return new SetCondInst(SCI->getInverseCondition(),
3578                                  SCI->getOperand(0), SCI->getOperand(1));
3579
3580       // ~(c-X) == X-c-1 == X+(-c-1)
3581       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3582         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3583           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3584           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3585                                               ConstantInt::get(I.getType(), 1));
3586           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3587         }
3588
3589       // ~(~X & Y) --> (X | ~Y)
3590       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3591         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3592         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3593           Instruction *NotY =
3594             BinaryOperator::createNot(Op0I->getOperand(1),
3595                                       Op0I->getOperand(1)->getName()+".not");
3596           InsertNewInstBefore(NotY, I);
3597           return BinaryOperator::createOr(Op0NotVal, NotY);
3598         }
3599       }
3600
3601       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3602         if (Op0I->getOpcode() == Instruction::Add) {
3603           // ~(X-c) --> (-c-1)-X
3604           if (RHS->isAllOnesValue()) {
3605             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3606             return BinaryOperator::createSub(
3607                            ConstantExpr::getSub(NegOp0CI,
3608                                              ConstantInt::get(I.getType(), 1)),
3609                                           Op0I->getOperand(0));
3610           }
3611         } else if (Op0I->getOpcode() == Instruction::Or) {
3612           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3613           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3614             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3615             // Anything in both C1 and C2 is known to be zero, remove it from
3616             // NewRHS.
3617             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3618             NewRHS = ConstantExpr::getAnd(NewRHS, 
3619                                           ConstantExpr::getNot(CommonBits));
3620             WorkList.push_back(Op0I);
3621             I.setOperand(0, Op0I->getOperand(0));
3622             I.setOperand(1, NewRHS);
3623             return &I;
3624           }
3625         }
3626     }
3627
3628     // Try to fold constant and into select arguments.
3629     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3630       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3631         return R;
3632     if (isa<PHINode>(Op0))
3633       if (Instruction *NV = FoldOpIntoPhi(I))
3634         return NV;
3635   }
3636
3637   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
3638     if (X == Op1)
3639       return ReplaceInstUsesWith(I,
3640                                 ConstantIntegral::getAllOnesValue(I.getType()));
3641
3642   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
3643     if (X == Op0)
3644       return ReplaceInstUsesWith(I,
3645                                 ConstantIntegral::getAllOnesValue(I.getType()));
3646
3647   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3648     if (Op1I->getOpcode() == Instruction::Or) {
3649       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
3650         Op1I->swapOperands();
3651         I.swapOperands();
3652         std::swap(Op0, Op1);
3653       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
3654         I.swapOperands();     // Simplified below.
3655         std::swap(Op0, Op1);
3656       }
3657     } else if (Op1I->getOpcode() == Instruction::Xor) {
3658       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
3659         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3660       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
3661         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
3662     } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3663       if (Op1I->getOperand(0) == Op0)                      // A^(A&B) -> A^(B&A)
3664         Op1I->swapOperands();
3665       if (Op0 == Op1I->getOperand(1)) {                    // A^(B&A) -> (B&A)^A
3666         I.swapOperands();     // Simplified below.
3667         std::swap(Op0, Op1);
3668       }
3669     }
3670
3671   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3672     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
3673       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
3674         Op0I->swapOperands();
3675       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
3676         Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3677         InsertNewInstBefore(NotB, I);
3678         return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
3679       }
3680     } else if (Op0I->getOpcode() == Instruction::Xor) {
3681       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
3682         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3683       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
3684         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3685     } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3686       if (Op0I->getOperand(0) == Op1)                      // (A&B)^A -> (B&A)^A
3687         Op0I->swapOperands();
3688       if (Op0I->getOperand(1) == Op1 &&                    // (B&A)^A == ~B & A
3689           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
3690         Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3691         InsertNewInstBefore(N, I);
3692         return BinaryOperator::createAnd(N, Op1);
3693       }
3694     }
3695
3696   // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3697   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3698     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3699       return R;
3700
3701   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3702   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3703     const Type *SrcTy = Op0C->getOperand(0)->getType();
3704     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3705       if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3706           // Only do this if the casts both really cause code to be generated.
3707           ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3708           ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3709         Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3710                                                        Op1C->getOperand(0),
3711                                                        I.getName());
3712         InsertNewInstBefore(NewOp, I);
3713         return new CastInst(NewOp, I.getType());
3714       }
3715   }
3716     
3717   return Changed ? &I : 0;
3718 }
3719
3720 /// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3721 /// overflowed for this type.
3722 static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3723                             ConstantInt *In2) {
3724   Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3725   return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3726 }
3727
3728 static bool isPositive(ConstantInt *C) {
3729   return C->getSExtValue() >= 0;
3730 }
3731
3732 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3733 /// overflowed for this type.
3734 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3735                             ConstantInt *In2) {
3736   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3737
3738   if (In1->getType()->isUnsigned())
3739     return cast<ConstantInt>(Result)->getZExtValue() <
3740            cast<ConstantInt>(In1)->getZExtValue();
3741   if (isPositive(In1) != isPositive(In2))
3742     return false;
3743   if (isPositive(In1))
3744     return cast<ConstantInt>(Result)->getSExtValue() <
3745            cast<ConstantInt>(In1)->getSExtValue();
3746   return cast<ConstantInt>(Result)->getSExtValue() >
3747          cast<ConstantInt>(In1)->getSExtValue();
3748 }
3749
3750 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3751 /// code necessary to compute the offset from the base pointer (without adding
3752 /// in the base pointer).  Return the result as a signed integer of intptr size.
3753 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3754   TargetData &TD = IC.getTargetData();
3755   gep_type_iterator GTI = gep_type_begin(GEP);
3756   const Type *UIntPtrTy = TD.getIntPtrType();
3757   const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3758   Value *Result = Constant::getNullValue(SIntPtrTy);
3759
3760   // Build a mask for high order bits.
3761   uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
3762
3763   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3764     Value *Op = GEP->getOperand(i);
3765     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
3766     Constant *Scale = ConstantExpr::getCast(ConstantInt::get(UIntPtrTy, Size),
3767                                             SIntPtrTy);
3768     if (Constant *OpC = dyn_cast<Constant>(Op)) {
3769       if (!OpC->isNullValue()) {
3770         OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
3771         Scale = ConstantExpr::getMul(OpC, Scale);
3772         if (Constant *RC = dyn_cast<Constant>(Result))
3773           Result = ConstantExpr::getAdd(RC, Scale);
3774         else {
3775           // Emit an add instruction.
3776           Result = IC.InsertNewInstBefore(
3777              BinaryOperator::createAdd(Result, Scale,
3778                                        GEP->getName()+".offs"), I);
3779         }
3780       }
3781     } else {
3782       // Convert to correct type.
3783       Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3784                                                Op->getName()+".c"), I);
3785       if (Size != 1)
3786         // We'll let instcombine(mul) convert this to a shl if possible.
3787         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3788                                                     GEP->getName()+".idx"), I);
3789
3790       // Emit an add instruction.
3791       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
3792                                                     GEP->getName()+".offs"), I);
3793     }
3794   }
3795   return Result;
3796 }
3797
3798 /// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3799 /// else.  At this point we know that the GEP is on the LHS of the comparison.
3800 Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3801                                         Instruction::BinaryOps Cond,
3802                                         Instruction &I) {
3803   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
3804
3805   if (CastInst *CI = dyn_cast<CastInst>(RHS))
3806     if (isa<PointerType>(CI->getOperand(0)->getType()))
3807       RHS = CI->getOperand(0);
3808
3809   Value *PtrBase = GEPLHS->getOperand(0);
3810   if (PtrBase == RHS) {
3811     // As an optimization, we don't actually have to compute the actual value of
3812     // OFFSET if this is a seteq or setne comparison, just return whether each
3813     // index is zero or not.
3814     if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3815       Instruction *InVal = 0;
3816       gep_type_iterator GTI = gep_type_begin(GEPLHS);
3817       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
3818         bool EmitIt = true;
3819         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3820           if (isa<UndefValue>(C))  // undef index -> undef.
3821             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3822           if (C->isNullValue())
3823             EmitIt = false;
3824           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3825             EmitIt = false;  // This is indexing into a zero sized array?
3826           } else if (isa<ConstantInt>(C))
3827             return ReplaceInstUsesWith(I, // No comparison is needed here.
3828                                  ConstantBool::get(Cond == Instruction::SetNE));
3829         }
3830
3831         if (EmitIt) {
3832           Instruction *Comp =
3833             new SetCondInst(Cond, GEPLHS->getOperand(i),
3834                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3835           if (InVal == 0)
3836             InVal = Comp;
3837           else {
3838             InVal = InsertNewInstBefore(InVal, I);
3839             InsertNewInstBefore(Comp, I);
3840             if (Cond == Instruction::SetNE)   // True if any are unequal
3841               InVal = BinaryOperator::createOr(InVal, Comp);
3842             else                              // True if all are equal
3843               InVal = BinaryOperator::createAnd(InVal, Comp);
3844           }
3845         }
3846       }
3847
3848       if (InVal)
3849         return InVal;
3850       else
3851         ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3852                             ConstantBool::get(Cond == Instruction::SetEQ));
3853     }
3854
3855     // Only lower this if the setcc is the only user of the GEP or if we expect
3856     // the result to fold to a constant!
3857     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3858       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
3859       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3860       return new SetCondInst(Cond, Offset,
3861                              Constant::getNullValue(Offset->getType()));
3862     }
3863   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
3864     // If the base pointers are different, but the indices are the same, just
3865     // compare the base pointer.
3866     if (PtrBase != GEPRHS->getOperand(0)) {
3867       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
3868       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
3869                         GEPRHS->getOperand(0)->getType();
3870       if (IndicesTheSame)
3871         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3872           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3873             IndicesTheSame = false;
3874             break;
3875           }
3876
3877       // If all indices are the same, just compare the base pointers.
3878       if (IndicesTheSame)
3879         return new SetCondInst(Cond, GEPLHS->getOperand(0),
3880                                GEPRHS->getOperand(0));
3881
3882       // Otherwise, the base pointers are different and the indices are
3883       // different, bail out.
3884       return 0;
3885     }
3886
3887     // If one of the GEPs has all zero indices, recurse.
3888     bool AllZeros = true;
3889     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3890       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3891           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3892         AllZeros = false;
3893         break;
3894       }
3895     if (AllZeros)
3896       return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3897                           SetCondInst::getSwappedCondition(Cond), I);
3898
3899     // If the other GEP has all zero indices, recurse.
3900     AllZeros = true;
3901     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3902       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3903           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3904         AllZeros = false;
3905         break;
3906       }
3907     if (AllZeros)
3908       return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3909
3910     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3911       // If the GEPs only differ by one index, compare it.
3912       unsigned NumDifferences = 0;  // Keep track of # differences.
3913       unsigned DiffOperand = 0;     // The operand that differs.
3914       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3915         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3916           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3917                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
3918             // Irreconcilable differences.
3919             NumDifferences = 2;
3920             break;
3921           } else {
3922             if (NumDifferences++) break;
3923             DiffOperand = i;
3924           }
3925         }
3926
3927       if (NumDifferences == 0)   // SAME GEP?
3928         return ReplaceInstUsesWith(I, // No comparison is needed here.
3929                                  ConstantBool::get(Cond == Instruction::SetEQ));
3930       else if (NumDifferences == 1) {
3931         Value *LHSV = GEPLHS->getOperand(DiffOperand);
3932         Value *RHSV = GEPRHS->getOperand(DiffOperand);
3933
3934         // Convert the operands to signed values to make sure to perform a
3935         // signed comparison.
3936         const Type *NewTy = LHSV->getType()->getSignedVersion();
3937         if (LHSV->getType() != NewTy)
3938           LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3939                                                   LHSV->getName()), I);
3940         if (RHSV->getType() != NewTy)
3941           RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3942                                                   RHSV->getName()), I);
3943         return new SetCondInst(Cond, LHSV, RHSV);
3944       }
3945     }
3946
3947     // Only lower this if the setcc is the only user of the GEP or if we expect
3948     // the result to fold to a constant!
3949     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3950         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3951       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
3952       Value *L = EmitGEPOffset(GEPLHS, I, *this);
3953       Value *R = EmitGEPOffset(GEPRHS, I, *this);
3954       return new SetCondInst(Cond, L, R);
3955     }
3956   }
3957   return 0;
3958 }
3959
3960
3961 Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
3962   bool Changed = SimplifyCommutative(I);
3963   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3964   const Type *Ty = Op0->getType();
3965
3966   // setcc X, X
3967   if (Op0 == Op1)
3968     return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
3969
3970   if (isa<UndefValue>(Op1))                  // X setcc undef -> undef
3971     return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3972
3973   // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3974   // addresses never equal each other!  We already know that Op0 != Op1.
3975   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3976        isa<ConstantPointerNull>(Op0)) &&
3977       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
3978        isa<ConstantPointerNull>(Op1)))
3979     return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3980
3981   // setcc's with boolean values can always be turned into bitwise operations
3982   if (Ty == Type::BoolTy) {
3983     switch (I.getOpcode()) {
3984     default: assert(0 && "Invalid setcc instruction!");
3985     case Instruction::SetEQ: {     //  seteq bool %A, %B -> ~(A^B)
3986       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
3987       InsertNewInstBefore(Xor, I);
3988       return BinaryOperator::createNot(Xor);
3989     }
3990     case Instruction::SetNE:
3991       return BinaryOperator::createXor(Op0, Op1);
3992
3993     case Instruction::SetGT:
3994       std::swap(Op0, Op1);                   // Change setgt -> setlt
3995       // FALL THROUGH
3996     case Instruction::SetLT: {               // setlt bool A, B -> ~X & Y
3997       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3998       InsertNewInstBefore(Not, I);
3999       return BinaryOperator::createAnd(Not, Op1);
4000     }
4001     case Instruction::SetGE:
4002       std::swap(Op0, Op1);                   // Change setge -> setle
4003       // FALL THROUGH
4004     case Instruction::SetLE: {     //  setle bool %A, %B -> ~A | B
4005       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4006       InsertNewInstBefore(Not, I);
4007       return BinaryOperator::createOr(Not, Op1);
4008     }
4009     }
4010   }
4011
4012   // See if we are doing a comparison between a constant and an instruction that
4013   // can be folded into the comparison.
4014   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4015     // Check to see if we are comparing against the minimum or maximum value...
4016     if (CI->isMinValue()) {
4017       if (I.getOpcode() == Instruction::SetLT)       // A < MIN -> FALSE
4018         return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4019       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN -> TRUE
4020         return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4021       if (I.getOpcode() == Instruction::SetLE)       // A <= MIN -> A == MIN
4022         return BinaryOperator::createSetEQ(Op0, Op1);
4023       if (I.getOpcode() == Instruction::SetGT)       // A > MIN -> A != MIN
4024         return BinaryOperator::createSetNE(Op0, Op1);
4025
4026     } else if (CI->isMaxValue()) {
4027       if (I.getOpcode() == Instruction::SetGT)       // A > MAX -> FALSE
4028         return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4029       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX -> TRUE
4030         return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4031       if (I.getOpcode() == Instruction::SetGE)       // A >= MAX -> A == MAX
4032         return BinaryOperator::createSetEQ(Op0, Op1);
4033       if (I.getOpcode() == Instruction::SetLT)       // A < MAX -> A != MAX
4034         return BinaryOperator::createSetNE(Op0, Op1);
4035
4036       // Comparing against a value really close to min or max?
4037     } else if (isMinValuePlusOne(CI)) {
4038       if (I.getOpcode() == Instruction::SetLT)       // A < MIN+1 -> A == MIN
4039         return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4040       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN-1 -> A != MIN
4041         return BinaryOperator::createSetNE(Op0, SubOne(CI));
4042
4043     } else if (isMaxValueMinusOne(CI)) {
4044       if (I.getOpcode() == Instruction::SetGT)       // A > MAX-1 -> A == MAX
4045         return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4046       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX-1 -> A != MAX
4047         return BinaryOperator::createSetNE(Op0, AddOne(CI));
4048     }
4049
4050     // If we still have a setle or setge instruction, turn it into the
4051     // appropriate setlt or setgt instruction.  Since the border cases have
4052     // already been handled above, this requires little checking.
4053     //
4054     if (I.getOpcode() == Instruction::SetLE)
4055       return BinaryOperator::createSetLT(Op0, AddOne(CI));
4056     if (I.getOpcode() == Instruction::SetGE)
4057       return BinaryOperator::createSetGT(Op0, SubOne(CI));
4058
4059     
4060     // See if we can fold the comparison based on bits known to be zero or one
4061     // in the input.
4062     uint64_t KnownZero, KnownOne;
4063     if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4064                              KnownZero, KnownOne, 0))
4065       return &I;
4066         
4067     // Given the known and unknown bits, compute a range that the LHS could be
4068     // in.
4069     if (KnownOne | KnownZero) {
4070       if (Ty->isUnsigned()) {   // Unsigned comparison.
4071         uint64_t Min, Max;
4072         uint64_t RHSVal = CI->getZExtValue();
4073         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4074                                                  Min, Max);
4075         switch (I.getOpcode()) {  // LE/GE have been folded already.
4076         default: assert(0 && "Unknown setcc opcode!");
4077         case Instruction::SetEQ:
4078           if (Max < RHSVal || Min > RHSVal)
4079             return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4080           break;
4081         case Instruction::SetNE:
4082           if (Max < RHSVal || Min > RHSVal)
4083             return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4084           break;
4085         case Instruction::SetLT:
4086           if (Max < RHSVal)
4087             return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4088           if (Min > RHSVal)
4089             return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4090           break;
4091         case Instruction::SetGT:
4092           if (Min > RHSVal)
4093             return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4094           if (Max < RHSVal)
4095             return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4096           break;
4097         }
4098       } else {              // Signed comparison.
4099         int64_t Min, Max;
4100         int64_t RHSVal = CI->getSExtValue();
4101         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4102                                                Min, Max);
4103         switch (I.getOpcode()) {  // LE/GE have been folded already.
4104         default: assert(0 && "Unknown setcc opcode!");
4105         case Instruction::SetEQ:
4106           if (Max < RHSVal || Min > RHSVal)
4107             return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4108           break;
4109         case Instruction::SetNE:
4110           if (Max < RHSVal || Min > RHSVal)
4111             return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4112           break;
4113         case Instruction::SetLT:
4114           if (Max < RHSVal)
4115             return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4116           if (Min > RHSVal)
4117             return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4118           break;
4119         case Instruction::SetGT:
4120           if (Min > RHSVal)
4121             return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4122           if (Max < RHSVal)
4123             return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4124           break;
4125         }
4126       }
4127     }
4128           
4129     
4130     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4131       switch (LHSI->getOpcode()) {
4132       case Instruction::And:
4133         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4134             LHSI->getOperand(0)->hasOneUse()) {
4135           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4136
4137           // If an operand is an AND of a truncating cast, we can widen the
4138           // and/compare to be the input width without changing the value
4139           // produced, eliminating a cast.
4140           if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4141             // We can do this transformation if either the AND constant does not
4142             // have its sign bit set or if it is an equality comparison. 
4143             // Extending a relational comparison when we're checking the sign
4144             // bit would not work.
4145             if (Cast->hasOneUse() && Cast->isTruncIntCast() && 
4146                 (I.isEquality() ||
4147                  (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4148                  (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4149               ConstantInt *NewCST;
4150               ConstantInt *NewCI;
4151               if (Cast->getOperand(0)->getType()->isSigned()) {
4152                 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4153                                            AndCST->getZExtValue());
4154                 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4155                                           CI->getZExtValue());
4156               } else {
4157                 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4158                                            AndCST->getZExtValue());
4159                 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4160                                           CI->getZExtValue());
4161               }
4162               Instruction *NewAnd = 
4163                 BinaryOperator::createAnd(Cast->getOperand(0), NewCST, 
4164                                           LHSI->getName());
4165               InsertNewInstBefore(NewAnd, I);
4166               return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4167             }
4168           }
4169           
4170           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4171           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
4172           // happens a LOT in code produced by the C front-end, for bitfield
4173           // access.
4174           ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
4175
4176           // Check to see if there is a noop-cast between the shift and the and.
4177           if (!Shift) {
4178             if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4179               if (CI->getOperand(0)->getType()->isIntegral() &&
4180                   CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4181                      CI->getType()->getPrimitiveSizeInBits())
4182                 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4183           }
4184
4185           ConstantInt *ShAmt;
4186           ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4187           const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
4188           const Type *AndTy = AndCST->getType();          // Type of the and.
4189
4190           // We can fold this as long as we can't shift unknown bits
4191           // into the mask.  This can only happen with signed shift
4192           // rights, as they sign-extend.
4193           if (ShAmt) {
4194             bool CanFold = Shift->isLogicalShift();
4195             if (!CanFold) {
4196               // To test for the bad case of the signed shr, see if any
4197               // of the bits shifted in could be tested after the mask.
4198               int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
4199               if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4200
4201               Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
4202               Constant *ShVal =
4203                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy), 
4204                                      OShAmt);
4205               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4206                 CanFold = true;
4207             }
4208
4209             if (CanFold) {
4210               Constant *NewCst;
4211               if (Shift->getOpcode() == Instruction::Shl)
4212                 NewCst = ConstantExpr::getUShr(CI, ShAmt);
4213               else
4214                 NewCst = ConstantExpr::getShl(CI, ShAmt);
4215
4216               // Check to see if we are shifting out any of the bits being
4217               // compared.
4218               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4219                 // If we shifted bits out, the fold is not going to work out.
4220                 // As a special case, check to see if this means that the
4221                 // result is always true or false now.
4222                 if (I.getOpcode() == Instruction::SetEQ)
4223                   return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4224                 if (I.getOpcode() == Instruction::SetNE)
4225                   return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4226               } else {
4227                 I.setOperand(1, NewCst);
4228                 Constant *NewAndCST;
4229                 if (Shift->getOpcode() == Instruction::Shl)
4230                   NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
4231                 else
4232                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4233                 LHSI->setOperand(1, NewAndCST);
4234                 if (AndTy == Ty) 
4235                   LHSI->setOperand(0, Shift->getOperand(0));
4236                 else {
4237                   Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
4238                                                     *Shift);
4239                   LHSI->setOperand(0, NewCast);
4240                 }
4241                 WorkList.push_back(Shift); // Shift is dead.
4242                 AddUsesToWorkList(I);
4243                 return &I;
4244               }
4245             }
4246           }
4247           
4248           // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
4249           // preferable because it allows the C<<Y expression to be hoisted out
4250           // of a loop if Y is invariant and X is not.
4251           if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4252               I.isEquality() && !Shift->isArithmeticShift() &&
4253               isa<Instruction>(Shift->getOperand(0))) {
4254             // Compute C << Y.
4255             Value *NS;
4256             if (Shift->getOpcode() == Instruction::Shr) {
4257               NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4258                                  "tmp");
4259             } else {
4260               // Make sure we insert a logical shift.
4261               Constant *NewAndCST = AndCST;
4262               if (AndCST->getType()->isSigned())
4263                 NewAndCST = ConstantExpr::getCast(AndCST,
4264                                       AndCST->getType()->getUnsignedVersion());
4265               NS = new ShiftInst(Instruction::Shr, NewAndCST,
4266                                  Shift->getOperand(1), "tmp");
4267             }
4268             InsertNewInstBefore(cast<Instruction>(NS), I);
4269
4270             // If C's sign doesn't agree with the and, insert a cast now.
4271             if (NS->getType() != LHSI->getType())
4272               NS = InsertCastBefore(NS, LHSI->getType(), I);
4273
4274             Value *ShiftOp = Shift->getOperand(0);
4275             if (ShiftOp->getType() != LHSI->getType())
4276               ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
4277               
4278             // Compute X & (C << Y).
4279             Instruction *NewAnd =
4280               BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4281             InsertNewInstBefore(NewAnd, I);
4282             
4283             I.setOperand(0, NewAnd);
4284             return &I;
4285           }
4286         }
4287         break;
4288
4289       case Instruction::Shl:         // (setcc (shl X, ShAmt), CI)
4290         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4291           if (I.isEquality()) {
4292             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4293
4294             // Check that the shift amount is in range.  If not, don't perform
4295             // undefined shifts.  When the shift is visited it will be
4296             // simplified.
4297             if (ShAmt->getZExtValue() >= TypeBits)
4298               break;
4299
4300             // If we are comparing against bits always shifted out, the
4301             // comparison cannot succeed.
4302             Constant *Comp =
4303               ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
4304             if (Comp != CI) {// Comparing against a bit that we know is zero.
4305               bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4306               Constant *Cst = ConstantBool::get(IsSetNE);
4307               return ReplaceInstUsesWith(I, Cst);
4308             }
4309
4310             if (LHSI->hasOneUse()) {
4311               // Otherwise strength reduce the shift into an and.
4312               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4313               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4314
4315               Constant *Mask;
4316               if (CI->getType()->isUnsigned()) {
4317                 Mask = ConstantInt::get(CI->getType(), Val);
4318               } else if (ShAmtVal != 0) {
4319                 Mask = ConstantInt::get(CI->getType(), Val);
4320               } else {
4321                 Mask = ConstantInt::getAllOnesValue(CI->getType());
4322               }
4323
4324               Instruction *AndI =
4325                 BinaryOperator::createAnd(LHSI->getOperand(0),
4326                                           Mask, LHSI->getName()+".mask");
4327               Value *And = InsertNewInstBefore(AndI, I);
4328               return new SetCondInst(I.getOpcode(), And,
4329                                      ConstantExpr::getUShr(CI, ShAmt));
4330             }
4331           }
4332         }
4333         break;
4334
4335       case Instruction::Shr:         // (setcc (shr X, ShAmt), CI)
4336         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4337           if (I.isEquality()) {
4338             // Check that the shift amount is in range.  If not, don't perform
4339             // undefined shifts.  When the shift is visited it will be
4340             // simplified.
4341             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4342             if (ShAmt->getZExtValue() >= TypeBits)
4343               break;
4344
4345             // If we are comparing against bits always shifted out, the
4346             // comparison cannot succeed.
4347             Constant *Comp =
4348               ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
4349
4350             if (Comp != CI) {// Comparing against a bit that we know is zero.
4351               bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4352               Constant *Cst = ConstantBool::get(IsSetNE);
4353               return ReplaceInstUsesWith(I, Cst);
4354             }
4355
4356             if (LHSI->hasOneUse() || CI->isNullValue()) {
4357               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4358
4359               // Otherwise strength reduce the shift into an and.
4360               uint64_t Val = ~0ULL;          // All ones.
4361               Val <<= ShAmtVal;              // Shift over to the right spot.
4362
4363               Constant *Mask;
4364               if (CI->getType()->isUnsigned()) {
4365                 Val &= ~0ULL >> (64-TypeBits);
4366                 Mask = ConstantInt::get(CI->getType(), Val);
4367               } else {
4368                 Mask = ConstantInt::get(CI->getType(), Val);
4369               }
4370
4371               Instruction *AndI =
4372                 BinaryOperator::createAnd(LHSI->getOperand(0),
4373                                           Mask, LHSI->getName()+".mask");
4374               Value *And = InsertNewInstBefore(AndI, I);
4375               return new SetCondInst(I.getOpcode(), And,
4376                                      ConstantExpr::getShl(CI, ShAmt));
4377             }
4378           }
4379         }
4380         break;
4381
4382       case Instruction::Div:
4383         // Fold: (div X, C1) op C2 -> range check
4384         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4385           // Fold this div into the comparison, producing a range check.
4386           // Determine, based on the divide type, what the range is being
4387           // checked.  If there is an overflow on the low or high side, remember
4388           // it, otherwise compute the range [low, hi) bounding the new value.
4389           bool LoOverflow = false, HiOverflow = 0;
4390           ConstantInt *LoBound = 0, *HiBound = 0;
4391
4392           ConstantInt *Prod;
4393           bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
4394
4395           Instruction::BinaryOps Opcode = I.getOpcode();
4396
4397           if (DivRHS->isNullValue()) {  // Don't hack on divide by zeros.
4398           } else if (LHSI->getType()->isUnsigned()) {  // udiv
4399             LoBound = Prod;
4400             LoOverflow = ProdOV;
4401             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4402           } else if (isPositive(DivRHS)) {             // Divisor is > 0.
4403             if (CI->isNullValue()) {       // (X / pos) op 0
4404               // Can't overflow.
4405               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4406               HiBound = DivRHS;
4407             } else if (isPositive(CI)) {   // (X / pos) op pos
4408               LoBound = Prod;
4409               LoOverflow = ProdOV;
4410               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4411             } else {                       // (X / pos) op neg
4412               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4413               LoOverflow = AddWithOverflow(LoBound, Prod,
4414                                            cast<ConstantInt>(DivRHSH));
4415               HiBound = Prod;
4416               HiOverflow = ProdOV;
4417             }
4418           } else {                                     // Divisor is < 0.
4419             if (CI->isNullValue()) {       // (X / neg) op 0
4420               LoBound = AddOne(DivRHS);
4421               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
4422               if (HiBound == DivRHS)
4423                 LoBound = 0;  // - INTMIN = INTMIN
4424             } else if (isPositive(CI)) {   // (X / neg) op pos
4425               HiOverflow = LoOverflow = ProdOV;
4426               if (!LoOverflow)
4427                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4428               HiBound = AddOne(Prod);
4429             } else {                       // (X / neg) op neg
4430               LoBound = Prod;
4431               LoOverflow = HiOverflow = ProdOV;
4432               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4433             }
4434
4435             // Dividing by a negate swaps the condition.
4436             Opcode = SetCondInst::getSwappedCondition(Opcode);
4437           }
4438
4439           if (LoBound) {
4440             Value *X = LHSI->getOperand(0);
4441             switch (Opcode) {
4442             default: assert(0 && "Unhandled setcc opcode!");
4443             case Instruction::SetEQ:
4444               if (LoOverflow && HiOverflow)
4445                 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4446               else if (HiOverflow)
4447                 return new SetCondInst(Instruction::SetGE, X, LoBound);
4448               else if (LoOverflow)
4449                 return new SetCondInst(Instruction::SetLT, X, HiBound);
4450               else
4451                 return InsertRangeTest(X, LoBound, HiBound, true, I);
4452             case Instruction::SetNE:
4453               if (LoOverflow && HiOverflow)
4454                 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4455               else if (HiOverflow)
4456                 return new SetCondInst(Instruction::SetLT, X, LoBound);
4457               else if (LoOverflow)
4458                 return new SetCondInst(Instruction::SetGE, X, HiBound);
4459               else
4460                 return InsertRangeTest(X, LoBound, HiBound, false, I);
4461             case Instruction::SetLT:
4462               if (LoOverflow)
4463                 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4464               return new SetCondInst(Instruction::SetLT, X, LoBound);
4465             case Instruction::SetGT:
4466               if (HiOverflow)
4467                 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4468               return new SetCondInst(Instruction::SetGE, X, HiBound);
4469             }
4470           }
4471         }
4472         break;
4473       }
4474
4475     // Simplify seteq and setne instructions...
4476     if (I.isEquality()) {
4477       bool isSetNE = I.getOpcode() == Instruction::SetNE;
4478
4479       // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
4480       // the second operand is a constant, simplify a bit.
4481       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4482         switch (BO->getOpcode()) {
4483 #if 0
4484         case Instruction::SRem:
4485           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4486           if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4487               BO->hasOneUse()) {
4488             int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4489             if (V > 1 && isPowerOf2_64(V)) {
4490               Value *NewRem = InsertNewInstBefore(
4491                   BinaryOperator::createURem(BO->getOperand(0), 
4492                                              BO->getOperand(1),
4493                                              BO->getName()), I);
4494               return BinaryOperator::create(
4495                 I.getOpcode(), NewRem, 
4496                 Constant::getNullValue(NewRem->getType()));
4497             }
4498           }
4499           break;
4500 #endif
4501
4502         case Instruction::Rem:
4503           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4504           if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4505               BO->hasOneUse() && BO->getOperand(1)->getType()->isSigned()) {
4506             int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4507             if (V > 1 && isPowerOf2_64(V)) {
4508               unsigned L2 = Log2_64(V);
4509               const Type *UTy = BO->getType()->getUnsignedVersion();
4510               Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
4511                                                              UTy, "tmp"), I);
4512               Constant *RHSCst = ConstantInt::get(UTy, 1ULL << L2);
4513               Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
4514                                                     RHSCst, BO->getName()), I);
4515               return BinaryOperator::create(I.getOpcode(), NewRem,
4516                                             Constant::getNullValue(UTy));
4517             }
4518           }
4519           break;
4520         case Instruction::Add:
4521           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4522           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4523             if (BO->hasOneUse())
4524               return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4525                                      ConstantExpr::getSub(CI, BOp1C));
4526           } else if (CI->isNullValue()) {
4527             // Replace ((add A, B) != 0) with (A != -B) if A or B is
4528             // efficiently invertible, or if the add has just this one use.
4529             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
4530
4531             if (Value *NegVal = dyn_castNegVal(BOp1))
4532               return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4533             else if (Value *NegVal = dyn_castNegVal(BOp0))
4534               return new SetCondInst(I.getOpcode(), NegVal, BOp1);
4535             else if (BO->hasOneUse()) {
4536               Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4537               BO->setName("");
4538               InsertNewInstBefore(Neg, I);
4539               return new SetCondInst(I.getOpcode(), BOp0, Neg);
4540             }
4541           }
4542           break;
4543         case Instruction::Xor:
4544           // For the xor case, we can xor two constants together, eliminating
4545           // the explicit xor.
4546           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4547             return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
4548                                   ConstantExpr::getXor(CI, BOC));
4549
4550           // FALLTHROUGH
4551         case Instruction::Sub:
4552           // Replace (([sub|xor] A, B) != 0) with (A != B)
4553           if (CI->isNullValue())
4554             return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4555                                    BO->getOperand(1));
4556           break;
4557
4558         case Instruction::Or:
4559           // If bits are being or'd in that are not present in the constant we
4560           // are comparing against, then the comparison could never succeed!
4561           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
4562             Constant *NotCI = ConstantExpr::getNot(CI);
4563             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
4564               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
4565           }
4566           break;
4567
4568         case Instruction::And:
4569           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4570             // If bits are being compared against that are and'd out, then the
4571             // comparison can never succeed!
4572             if (!ConstantExpr::getAnd(CI,
4573                                       ConstantExpr::getNot(BOC))->isNullValue())
4574               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
4575
4576             // If we have ((X & C) == C), turn it into ((X & C) != 0).
4577             if (CI == BOC && isOneBitSet(CI))
4578               return new SetCondInst(isSetNE ? Instruction::SetEQ :
4579                                      Instruction::SetNE, Op0,
4580                                      Constant::getNullValue(CI->getType()));
4581
4582             // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4583             // to be a signed value as appropriate.
4584             if (isSignBit(BOC)) {
4585               Value *X = BO->getOperand(0);
4586               // If 'X' is not signed, insert a cast now...
4587               if (!BOC->getType()->isSigned()) {
4588                 const Type *DestTy = BOC->getType()->getSignedVersion();
4589                 X = InsertCastBefore(X, DestTy, I);
4590               }
4591               return new SetCondInst(isSetNE ? Instruction::SetLT :
4592                                          Instruction::SetGE, X,
4593                                      Constant::getNullValue(X->getType()));
4594             }
4595
4596             // ((X & ~7) == 0) --> X < 8
4597             if (CI->isNullValue() && isHighOnes(BOC)) {
4598               Value *X = BO->getOperand(0);
4599               Constant *NegX = ConstantExpr::getNeg(BOC);
4600
4601               // If 'X' is signed, insert a cast now.
4602               if (NegX->getType()->isSigned()) {
4603                 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4604                 X = InsertCastBefore(X, DestTy, I);
4605                 NegX = ConstantExpr::getCast(NegX, DestTy);
4606               }
4607
4608               return new SetCondInst(isSetNE ? Instruction::SetGE :
4609                                      Instruction::SetLT, X, NegX);
4610             }
4611
4612           }
4613         default: break;
4614         }
4615       }
4616     } else {  // Not a SetEQ/SetNE
4617       // If the LHS is a cast from an integral value of the same size,
4618       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4619         Value *CastOp = Cast->getOperand(0);
4620         const Type *SrcTy = CastOp->getType();
4621         unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
4622         if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
4623             SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
4624           assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
4625                  "Source and destination signednesses should differ!");
4626           if (Cast->getType()->isSigned()) {
4627             // If this is a signed comparison, check for comparisons in the
4628             // vicinity of zero.
4629             if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4630               // X < 0  => x > 127
4631               return BinaryOperator::createSetGT(CastOp,
4632                          ConstantInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
4633             else if (I.getOpcode() == Instruction::SetGT &&
4634                      cast<ConstantInt>(CI)->getSExtValue() == -1)
4635               // X > -1  => x < 128
4636               return BinaryOperator::createSetLT(CastOp,
4637                          ConstantInt::get(SrcTy, 1ULL << (SrcTySize-1)));
4638           } else {
4639             ConstantInt *CUI = cast<ConstantInt>(CI);
4640             if (I.getOpcode() == Instruction::SetLT &&
4641                 CUI->getZExtValue() == 1ULL << (SrcTySize-1))
4642               // X < 128 => X > -1
4643               return BinaryOperator::createSetGT(CastOp,
4644                                                  ConstantInt::get(SrcTy, -1));
4645             else if (I.getOpcode() == Instruction::SetGT &&
4646                      CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
4647               // X > 127 => X < 0
4648               return BinaryOperator::createSetLT(CastOp,
4649                                                  Constant::getNullValue(SrcTy));
4650           }
4651         }
4652       }
4653     }
4654   }
4655
4656   // Handle setcc with constant RHS's that can be integer, FP or pointer.
4657   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4658     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4659       switch (LHSI->getOpcode()) {
4660       case Instruction::GetElementPtr:
4661         if (RHSC->isNullValue()) {
4662           // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4663           bool isAllZeros = true;
4664           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4665             if (!isa<Constant>(LHSI->getOperand(i)) ||
4666                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4667               isAllZeros = false;
4668               break;
4669             }
4670           if (isAllZeros)
4671             return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4672                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
4673         }
4674         break;
4675
4676       case Instruction::PHI:
4677         if (Instruction *NV = FoldOpIntoPhi(I))
4678           return NV;
4679         break;
4680       case Instruction::Select:
4681         // If either operand of the select is a constant, we can fold the
4682         // comparison into the select arms, which will cause one to be
4683         // constant folded and the select turned into a bitwise or.
4684         Value *Op1 = 0, *Op2 = 0;
4685         if (LHSI->hasOneUse()) {
4686           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4687             // Fold the known value into the constant operand.
4688             Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4689             // Insert a new SetCC of the other select operand.
4690             Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4691                                                       LHSI->getOperand(2), RHSC,
4692                                                       I.getName()), I);
4693           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4694             // Fold the known value into the constant operand.
4695             Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4696             // Insert a new SetCC of the other select operand.
4697             Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4698                                                       LHSI->getOperand(1), RHSC,
4699                                                       I.getName()), I);
4700           }
4701         }
4702
4703         if (Op1)
4704           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4705         break;
4706       }
4707   }
4708
4709   // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4710   if (User *GEP = dyn_castGetElementPtr(Op0))
4711     if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4712       return NI;
4713   if (User *GEP = dyn_castGetElementPtr(Op1))
4714     if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4715                            SetCondInst::getSwappedCondition(I.getOpcode()), I))
4716       return NI;
4717
4718   // Test to see if the operands of the setcc are casted versions of other
4719   // values.  If the cast can be stripped off both arguments, we do so now.
4720   if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4721     Value *CastOp0 = CI->getOperand(0);
4722     if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
4723         (isa<Constant>(Op1) || isa<CastInst>(Op1)) && I.isEquality()) {
4724       // We keep moving the cast from the left operand over to the right
4725       // operand, where it can often be eliminated completely.
4726       Op0 = CastOp0;
4727
4728       // If operand #1 is a cast instruction, see if we can eliminate it as
4729       // well.
4730       if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4731         if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
4732                                                                Op0->getType()))
4733           Op1 = CI2->getOperand(0);
4734
4735       // If Op1 is a constant, we can fold the cast into the constant.
4736       if (Op1->getType() != Op0->getType())
4737         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4738           Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4739         } else {
4740           // Otherwise, cast the RHS right before the setcc
4741           Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
4742           InsertNewInstBefore(cast<Instruction>(Op1), I);
4743         }
4744       return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4745     }
4746
4747     // Handle the special case of: setcc (cast bool to X), <cst>
4748     // This comes up when you have code like
4749     //   int X = A < B;
4750     //   if (X) ...
4751     // For generality, we handle any zero-extension of any operand comparison
4752     // with a constant or another cast from the same type.
4753     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4754       if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4755         return R;
4756   }
4757   
4758   if (I.isEquality()) {
4759     Value *A, *B;
4760     if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4761         (A == Op1 || B == Op1)) {
4762       // (A^B) == A  ->  B == 0
4763       Value *OtherVal = A == Op1 ? B : A;
4764       return BinaryOperator::create(I.getOpcode(), OtherVal,
4765                                     Constant::getNullValue(A->getType()));
4766     } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4767                (A == Op0 || B == Op0)) {
4768       // A == (A^B)  ->  B == 0
4769       Value *OtherVal = A == Op0 ? B : A;
4770       return BinaryOperator::create(I.getOpcode(), OtherVal,
4771                                     Constant::getNullValue(A->getType()));
4772     } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4773       // (A-B) == A  ->  B == 0
4774       return BinaryOperator::create(I.getOpcode(), B,
4775                                     Constant::getNullValue(B->getType()));
4776     } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4777       // A == (A-B)  ->  B == 0
4778       return BinaryOperator::create(I.getOpcode(), B,
4779                                     Constant::getNullValue(B->getType()));
4780     }
4781   }
4782   return Changed ? &I : 0;
4783 }
4784
4785 // visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4786 // We only handle extending casts so far.
4787 //
4788 Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4789   Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4790   const Type *SrcTy = LHSCIOp->getType();
4791   const Type *DestTy = SCI.getOperand(0)->getType();
4792   Value *RHSCIOp;
4793
4794   if (!DestTy->isIntegral() || !SrcTy->isIntegral())
4795     return 0;
4796
4797   unsigned SrcBits  = SrcTy->getPrimitiveSizeInBits();
4798   unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4799   if (SrcBits >= DestBits) return 0;  // Only handle extending cast.
4800
4801   // Is this a sign or zero extension?
4802   bool isSignSrc  = SrcTy->isSigned();
4803   bool isSignDest = DestTy->isSigned();
4804
4805   if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4806     // Not an extension from the same type?
4807     RHSCIOp = CI->getOperand(0);
4808     if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4809   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4810     // Compute the constant that would happen if we truncated to SrcTy then
4811     // reextended to DestTy.
4812     Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4813
4814     if (ConstantExpr::getCast(Res, DestTy) == CI) {
4815       // Make sure that src sign and dest sign match. For example,
4816       //
4817       // %A = cast short %X to uint
4818       // %B = setgt uint %A, 1330
4819       //
4820       // It is incorrect to transform this into 
4821       //
4822       // %B = setgt short %X, 1330 
4823       // 
4824       // because %A may have negative value. 
4825       // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
4826       // OR operation is EQ/NE.
4827       if (isSignSrc == isSignDest || SrcTy == Type::BoolTy || SCI.isEquality())
4828         RHSCIOp = Res;
4829       else
4830         return 0;
4831     } else {
4832       // If the value cannot be represented in the shorter type, we cannot emit
4833       // a simple comparison.
4834       if (SCI.getOpcode() == Instruction::SetEQ)
4835         return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
4836       if (SCI.getOpcode() == Instruction::SetNE)
4837         return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
4838
4839       // Evaluate the comparison for LT.
4840       Value *Result;
4841       if (DestTy->isSigned()) {
4842         // We're performing a signed comparison.
4843         if (isSignSrc) {
4844           // Signed extend and signed comparison.
4845           if (cast<ConstantInt>(CI)->getSExtValue() < 0)// X < (small) --> false
4846             Result = ConstantBool::getFalse();
4847           else
4848             Result = ConstantBool::getTrue();           // X < (large) --> true
4849         } else {
4850           // Unsigned extend and signed comparison.
4851           if (cast<ConstantInt>(CI)->getSExtValue() < 0)
4852             Result = ConstantBool::getFalse();
4853           else
4854             Result = ConstantBool::getTrue();
4855         }
4856       } else {
4857         // We're performing an unsigned comparison.
4858         if (!isSignSrc) {
4859           // Unsigned extend & compare -> always true.
4860           Result = ConstantBool::getTrue();
4861         } else {
4862           // We're performing an unsigned comp with a sign extended value.
4863           // This is true if the input is >= 0. [aka >s -1]
4864           Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4865           Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4866                                                   NegOne, SCI.getName()), SCI);
4867         }
4868       }
4869
4870       // Finally, return the value computed.
4871       if (SCI.getOpcode() == Instruction::SetLT) {
4872         return ReplaceInstUsesWith(SCI, Result);
4873       } else {
4874         assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4875         if (Constant *CI = dyn_cast<Constant>(Result))
4876           return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4877         else
4878           return BinaryOperator::createNot(Result);
4879       }
4880     }
4881   } else {
4882     return 0;
4883   }
4884
4885   // Okay, just insert a compare of the reduced operands now!
4886   return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4887 }
4888
4889 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
4890   assert(I.getOperand(1)->getType() == Type::UByteTy);
4891   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4892   bool isLeftShift = I.getOpcode() == Instruction::Shl;
4893
4894   // shl X, 0 == X and shr X, 0 == X
4895   // shl 0, X == 0 and shr 0, X == 0
4896   if (Op1 == Constant::getNullValue(Type::UByteTy) ||
4897       Op0 == Constant::getNullValue(Op0->getType()))
4898     return ReplaceInstUsesWith(I, Op0);
4899   
4900   if (isa<UndefValue>(Op0)) {            // undef >>s X -> undef
4901     if (!isLeftShift && I.getType()->isSigned())
4902       return ReplaceInstUsesWith(I, Op0);
4903     else                         // undef << X -> 0   AND  undef >>u X -> 0
4904       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4905   }
4906   if (isa<UndefValue>(Op1)) {
4907     if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
4908       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4909     else
4910       return ReplaceInstUsesWith(I, Op0);          // X >>s undef -> X
4911   }
4912
4913   // shr int -1, X = -1   (for any arithmetic shift rights of ~0)
4914   if (!isLeftShift)
4915     if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
4916       if (CSI->isAllOnesValue())
4917         return ReplaceInstUsesWith(I, CSI);
4918
4919   // Try to fold constant and into select arguments.
4920   if (isa<Constant>(Op0))
4921     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
4922       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4923         return R;
4924
4925   // See if we can turn a signed shr into an unsigned shr.
4926   if (I.isArithmeticShift()) {
4927     if (MaskedValueIsZero(Op0,
4928                           1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
4929       Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4930       V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4931                                             I.getName()), I);
4932       return new CastInst(V, I.getType());
4933     }
4934   }
4935
4936   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
4937     if (CUI->getType()->isUnsigned())
4938       if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4939         return Res;
4940   return 0;
4941 }
4942
4943 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
4944                                                ShiftInst &I) {
4945   bool isLeftShift = I.getOpcode() == Instruction::Shl;
4946   bool isSignedShift = Op0->getType()->isSigned();
4947   bool isUnsignedShift = !isSignedShift;
4948
4949   // See if we can simplify any instructions used by the instruction whose sole 
4950   // purpose is to compute bits we don't care about.
4951   uint64_t KnownZero, KnownOne;
4952   if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4953                            KnownZero, KnownOne))
4954     return &I;
4955   
4956   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4957   // of a signed value.
4958   //
4959   unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4960   if (Op1->getZExtValue() >= TypeBits) {
4961     if (isUnsignedShift || isLeftShift)
4962       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4963     else {
4964       I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
4965       return &I;
4966     }
4967   }
4968   
4969   // ((X*C1) << C2) == (X * (C1 << C2))
4970   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4971     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4972       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4973         return BinaryOperator::createMul(BO->getOperand(0),
4974                                          ConstantExpr::getShl(BOOp, Op1));
4975   
4976   // Try to fold constant and into select arguments.
4977   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4978     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4979       return R;
4980   if (isa<PHINode>(Op0))
4981     if (Instruction *NV = FoldOpIntoPhi(I))
4982       return NV;
4983   
4984   if (Op0->hasOneUse()) {
4985     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4986       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
4987       Value *V1, *V2;
4988       ConstantInt *CC;
4989       switch (Op0BO->getOpcode()) {
4990         default: break;
4991         case Instruction::Add:
4992         case Instruction::And:
4993         case Instruction::Or:
4994         case Instruction::Xor:
4995           // These operators commute.
4996           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
4997           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4998               match(Op0BO->getOperand(1),
4999                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5000             Instruction *YS = new ShiftInst(Instruction::Shl, 
5001                                             Op0BO->getOperand(0), Op1,
5002                                             Op0BO->getName());
5003             InsertNewInstBefore(YS, I); // (Y << C)
5004             Instruction *X = 
5005               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5006                                      Op0BO->getOperand(1)->getName());
5007             InsertNewInstBefore(X, I);  // (X + (Y << C))
5008             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5009             C2 = ConstantExpr::getShl(C2, Op1);
5010             return BinaryOperator::createAnd(X, C2);
5011           }
5012           
5013           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
5014           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5015               match(Op0BO->getOperand(1),
5016                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5017                           m_ConstantInt(CC))) && V2 == Op1 &&
5018       cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
5019             Instruction *YS = new ShiftInst(Instruction::Shl, 
5020                                             Op0BO->getOperand(0), Op1,
5021                                             Op0BO->getName());
5022             InsertNewInstBefore(YS, I); // (Y << C)
5023             Instruction *XM =
5024               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5025                                         V1->getName()+".mask");
5026             InsertNewInstBefore(XM, I); // X & (CC << C)
5027             
5028             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5029           }
5030           
5031           // FALL THROUGH.
5032         case Instruction::Sub:
5033           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5034           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5035               match(Op0BO->getOperand(0),
5036                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5037             Instruction *YS = new ShiftInst(Instruction::Shl, 
5038                                             Op0BO->getOperand(1), Op1,
5039                                             Op0BO->getName());
5040             InsertNewInstBefore(YS, I); // (Y << C)
5041             Instruction *X =
5042               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5043                                      Op0BO->getOperand(0)->getName());
5044             InsertNewInstBefore(X, I);  // (X + (Y << C))
5045             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5046             C2 = ConstantExpr::getShl(C2, Op1);
5047             return BinaryOperator::createAnd(X, C2);
5048           }
5049           
5050           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
5051           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5052               match(Op0BO->getOperand(0),
5053                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5054                           m_ConstantInt(CC))) && V2 == Op1 &&
5055               cast<BinaryOperator>(Op0BO->getOperand(0))
5056                   ->getOperand(0)->hasOneUse()) {
5057             Instruction *YS = new ShiftInst(Instruction::Shl, 
5058                                             Op0BO->getOperand(1), Op1,
5059                                             Op0BO->getName());
5060             InsertNewInstBefore(YS, I); // (Y << C)
5061             Instruction *XM =
5062               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5063                                         V1->getName()+".mask");
5064             InsertNewInstBefore(XM, I); // X & (CC << C)
5065             
5066             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5067           }
5068           
5069           break;
5070       }
5071       
5072       
5073       // If the operand is an bitwise operator with a constant RHS, and the
5074       // shift is the only use, we can pull it out of the shift.
5075       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5076         bool isValid = true;     // Valid only for And, Or, Xor
5077         bool highBitSet = false; // Transform if high bit of constant set?
5078         
5079         switch (Op0BO->getOpcode()) {
5080           default: isValid = false; break;   // Do not perform transform!
5081           case Instruction::Add:
5082             isValid = isLeftShift;
5083             break;
5084           case Instruction::Or:
5085           case Instruction::Xor:
5086             highBitSet = false;
5087             break;
5088           case Instruction::And:
5089             highBitSet = true;
5090             break;
5091         }
5092         
5093         // If this is a signed shift right, and the high bit is modified
5094         // by the logical operation, do not perform the transformation.
5095         // The highBitSet boolean indicates the value of the high bit of
5096         // the constant which would cause it to be modified for this
5097         // operation.
5098         //
5099         if (isValid && !isLeftShift && isSignedShift) {
5100           uint64_t Val = Op0C->getZExtValue();
5101           isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5102         }
5103         
5104         if (isValid) {
5105           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5106           
5107           Instruction *NewShift =
5108             new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5109                           Op0BO->getName());
5110           Op0BO->setName("");
5111           InsertNewInstBefore(NewShift, I);
5112           
5113           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5114                                         NewRHS);
5115         }
5116       }
5117     }
5118   }
5119   
5120   // Find out if this is a shift of a shift by a constant.
5121   ShiftInst *ShiftOp = 0;
5122   if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
5123     ShiftOp = Op0SI;
5124   else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5125     // If this is a noop-integer case of a shift instruction, use the shift.
5126     if (CI->getOperand(0)->getType()->isInteger() &&
5127         CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
5128         CI->getType()->getPrimitiveSizeInBits() &&
5129         isa<ShiftInst>(CI->getOperand(0))) {
5130       ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5131     }
5132   }
5133   
5134   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5135     // Find the operands and properties of the input shift.  Note that the
5136     // signedness of the input shift may differ from the current shift if there
5137     // is a noop cast between the two.
5138     bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5139     bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
5140     bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
5141     
5142     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5143
5144     unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5145     unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
5146     
5147     // Check for (A << c1) << c2   and   (A >> c1) >> c2.
5148     if (isLeftShift == isShiftOfLeftShift) {
5149       // Do not fold these shifts if the first one is signed and the second one
5150       // is unsigned and this is a right shift.  Further, don't do any folding
5151       // on them.
5152       if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5153         return 0;
5154       
5155       unsigned Amt = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
5156       if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5157         Amt = Op0->getType()->getPrimitiveSizeInBits();
5158       
5159       Value *Op = ShiftOp->getOperand(0);
5160       if (isShiftOfSignedShift != isSignedShift)
5161         Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
5162       return new ShiftInst(I.getOpcode(), Op,
5163                            ConstantInt::get(Type::UByteTy, Amt));
5164     }
5165     
5166     // Check for (A << c1) >> c2 or (A >> c1) << c2.  If we are dealing with
5167     // signed types, we can only support the (A >> c1) << c2 configuration,
5168     // because it can not turn an arbitrary bit of A into a sign bit.
5169     if (isUnsignedShift || isLeftShift) {
5170       // Calculate bitmask for what gets shifted off the edge.
5171       Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5172       if (isLeftShift)
5173         C = ConstantExpr::getShl(C, ShiftAmt1C);
5174       else
5175         C = ConstantExpr::getUShr(C, ShiftAmt1C);
5176       
5177       Value *Op = ShiftOp->getOperand(0);
5178       if (isShiftOfSignedShift != isSignedShift)
5179         Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
5180       
5181       Instruction *Mask =
5182         BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5183       InsertNewInstBefore(Mask, I);
5184       
5185       // Figure out what flavor of shift we should use...
5186       if (ShiftAmt1 == ShiftAmt2) {
5187         return ReplaceInstUsesWith(I, Mask);  // (A << c) >> c  === A & c2
5188       } else if (ShiftAmt1 < ShiftAmt2) {
5189         return new ShiftInst(I.getOpcode(), Mask,
5190                          ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
5191       } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5192         if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5193           // Make sure to emit an unsigned shift right, not a signed one.
5194           Mask = InsertNewInstBefore(new CastInst(Mask, 
5195                                         Mask->getType()->getUnsignedVersion(),
5196                                                   Op->getName()), I);
5197           Mask = new ShiftInst(Instruction::Shr, Mask,
5198                          ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5199           InsertNewInstBefore(Mask, I);
5200           return new CastInst(Mask, I.getType());
5201         } else {
5202           return new ShiftInst(ShiftOp->getOpcode(), Mask,
5203                     ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5204         }
5205       } else {
5206         // (X >>s C1) << C2  where C1 > C2  === (X >>s (C1-C2)) & mask
5207         Op = InsertNewInstBefore(new CastInst(Mask,
5208                                               I.getType()->getSignedVersion(),
5209                                               Mask->getName()), I);
5210         Instruction *Shift =
5211           new ShiftInst(ShiftOp->getOpcode(), Op,
5212                         ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5213         InsertNewInstBefore(Shift, I);
5214         
5215         C = ConstantIntegral::getAllOnesValue(Shift->getType());
5216         C = ConstantExpr::getShl(C, Op1);
5217         Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5218         InsertNewInstBefore(Mask, I);
5219         return new CastInst(Mask, I.getType());
5220       }
5221     } else {
5222       // We can handle signed (X << C1) >>s C2 if it's a sign extend.  In
5223       // this case, C1 == C2 and C1 is 8, 16, or 32.
5224       if (ShiftAmt1 == ShiftAmt2) {
5225         const Type *SExtType = 0;
5226         switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
5227         case 8 : SExtType = Type::SByteTy; break;
5228         case 16: SExtType = Type::ShortTy; break;
5229         case 32: SExtType = Type::IntTy; break;
5230         }
5231         
5232         if (SExtType) {
5233           Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
5234                                                SExtType, "sext");
5235           InsertNewInstBefore(NewTrunc, I);
5236           return new CastInst(NewTrunc, I.getType());
5237         }
5238       }
5239     }
5240   }
5241   return 0;
5242 }
5243
5244
5245 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5246 /// expression.  If so, decompose it, returning some value X, such that Val is
5247 /// X*Scale+Offset.
5248 ///
5249 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5250                                         unsigned &Offset) {
5251   assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
5252   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5253     if (CI->getType()->isUnsigned()) {
5254       Offset = CI->getZExtValue();
5255       Scale  = 1;
5256       return ConstantInt::get(Type::UIntTy, 0);
5257     }
5258   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5259     if (I->getNumOperands() == 2) {
5260       if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5261         if (CUI->getType()->isUnsigned()) {
5262           if (I->getOpcode() == Instruction::Shl) {
5263             // This is a value scaled by '1 << the shift amt'.
5264             Scale = 1U << CUI->getZExtValue();
5265             Offset = 0;
5266             return I->getOperand(0);
5267           } else if (I->getOpcode() == Instruction::Mul) {
5268             // This value is scaled by 'CUI'.
5269             Scale = CUI->getZExtValue();
5270             Offset = 0;
5271             return I->getOperand(0);
5272           } else if (I->getOpcode() == Instruction::Add) {
5273             // We have X+C.  Check to see if we really have (X*C2)+C1, 
5274             // where C1 is divisible by C2.
5275             unsigned SubScale;
5276             Value *SubVal = 
5277               DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5278             Offset += CUI->getZExtValue();
5279             if (SubScale > 1 && (Offset % SubScale == 0)) {
5280               Scale = SubScale;
5281               return SubVal;
5282             }
5283           }
5284         }
5285       }
5286     }
5287   }
5288
5289   // Otherwise, we can't look past this.
5290   Scale = 1;
5291   Offset = 0;
5292   return Val;
5293 }
5294
5295
5296 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5297 /// try to eliminate the cast by moving the type information into the alloc.
5298 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5299                                                    AllocationInst &AI) {
5300   const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
5301   if (!PTy) return 0;   // Not casting the allocation to a pointer type.
5302   
5303   // Remove any uses of AI that are dead.
5304   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5305   std::vector<Instruction*> DeadUsers;
5306   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5307     Instruction *User = cast<Instruction>(*UI++);
5308     if (isInstructionTriviallyDead(User)) {
5309       while (UI != E && *UI == User)
5310         ++UI; // If this instruction uses AI more than once, don't break UI.
5311       
5312       // Add operands to the worklist.
5313       AddUsesToWorkList(*User);
5314       ++NumDeadInst;
5315       DEBUG(std::cerr << "IC: DCE: " << *User);
5316       
5317       User->eraseFromParent();
5318       removeFromWorkList(User);
5319     }
5320   }
5321   
5322   // Get the type really allocated and the type casted to.
5323   const Type *AllocElTy = AI.getAllocatedType();
5324   const Type *CastElTy = PTy->getElementType();
5325   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
5326
5327   unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5328   unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
5329   if (CastElTyAlign < AllocElTyAlign) return 0;
5330
5331   // If the allocation has multiple uses, only promote it if we are strictly
5332   // increasing the alignment of the resultant allocation.  If we keep it the
5333   // same, we open the door to infinite loops of various kinds.
5334   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5335
5336   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5337   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
5338   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
5339
5340   // See if we can satisfy the modulus by pulling a scale out of the array
5341   // size argument.
5342   unsigned ArraySizeScale, ArrayOffset;
5343   Value *NumElements = // See if the array size is a decomposable linear expr.
5344     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5345  
5346   // If we can now satisfy the modulus, by using a non-1 scale, we really can
5347   // do the xform.
5348   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5349       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
5350
5351   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5352   Value *Amt = 0;
5353   if (Scale == 1) {
5354     Amt = NumElements;
5355   } else {
5356     // If the allocation size is constant, form a constant mul expression
5357     Amt = ConstantInt::get(Type::UIntTy, Scale);
5358     if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5359       Amt = ConstantExpr::getMul(
5360               cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5361     // otherwise multiply the amount and the number of elements
5362     else if (Scale != 1) {
5363       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5364       Amt = InsertNewInstBefore(Tmp, AI);
5365     }
5366   }
5367   
5368   if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5369     Value *Off = ConstantInt::get(Type::UIntTy, Offset);
5370     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5371     Amt = InsertNewInstBefore(Tmp, AI);
5372   }
5373   
5374   std::string Name = AI.getName(); AI.setName("");
5375   AllocationInst *New;
5376   if (isa<MallocInst>(AI))
5377     New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
5378   else
5379     New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
5380   InsertNewInstBefore(New, AI);
5381   
5382   // If the allocation has multiple uses, insert a cast and change all things
5383   // that used it to use the new cast.  This will also hack on CI, but it will
5384   // die soon.
5385   if (!AI.hasOneUse()) {
5386     AddUsesToWorkList(AI);
5387     CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
5388     InsertNewInstBefore(NewCast, AI);
5389     AI.replaceAllUsesWith(NewCast);
5390   }
5391   return ReplaceInstUsesWith(CI, New);
5392 }
5393
5394 /// CanEvaluateInDifferentType - Return true if we can take the specified value
5395 /// and return it without inserting any new casts.  This is used by code that
5396 /// tries to decide whether promoting or shrinking integer operations to wider
5397 /// or smaller types will allow us to eliminate a truncate or extend.
5398 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5399                                        int &NumCastsRemoved) {
5400   if (isa<Constant>(V)) return true;
5401   
5402   Instruction *I = dyn_cast<Instruction>(V);
5403   if (!I || !I->hasOneUse()) return false;
5404   
5405   switch (I->getOpcode()) {
5406   case Instruction::And:
5407   case Instruction::Or:
5408   case Instruction::Xor:
5409     // These operators can all arbitrarily be extended or truncated.
5410     return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5411            CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5412   case Instruction::Cast:
5413     // If this is a cast from the destination type, we can trivially eliminate
5414     // it, and this will remove a cast overall.
5415     if (I->getOperand(0)->getType() == Ty) {
5416       // If the first operand is itself a cast, and is eliminable, do not count
5417       // this as an eliminable cast.  We would prefer to eliminate those two
5418       // casts first.
5419       if (CastInst *OpCast = dyn_cast<CastInst>(I->getOperand(0)))
5420         return true;
5421       
5422       ++NumCastsRemoved;
5423       return true;
5424     }
5425     // TODO: Can handle more cases here.
5426     break;
5427   }
5428   
5429   return false;
5430 }
5431
5432 /// EvaluateInDifferentType - Given an expression that 
5433 /// CanEvaluateInDifferentType returns true for, actually insert the code to
5434 /// evaluate the expression.
5435 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5436   if (Constant *C = dyn_cast<Constant>(V))
5437     return ConstantExpr::getCast(C, Ty);
5438
5439   // Otherwise, it must be an instruction.
5440   Instruction *I = cast<Instruction>(V);
5441   Instruction *Res = 0;
5442   switch (I->getOpcode()) {
5443   case Instruction::And:
5444   case Instruction::Or:
5445   case Instruction::Xor: {
5446     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5447     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5448     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5449                                  LHS, RHS, I->getName());
5450     break;
5451   }
5452   case Instruction::Cast:
5453     // If this is a cast from the destination type, return the input.
5454     if (I->getOperand(0)->getType() == Ty)
5455       return I->getOperand(0);
5456     
5457     // TODO: Can handle more cases here.
5458     assert(0 && "Unreachable!");
5459     break;
5460   }
5461   
5462   return InsertNewInstBefore(Res, *I);
5463 }
5464
5465
5466 // CastInst simplification
5467 //
5468 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
5469   Value *Src = CI.getOperand(0);
5470
5471   // If the user is casting a value to the same type, eliminate this cast
5472   // instruction...
5473   if (CI.getType() == Src->getType())
5474     return ReplaceInstUsesWith(CI, Src);
5475
5476   if (isa<UndefValue>(Src))   // cast undef -> undef
5477     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5478
5479   // If casting the result of another cast instruction, try to eliminate this
5480   // one!
5481   //
5482   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
5483     Value *A = CSrc->getOperand(0);
5484     if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5485                                CI.getType(), TD)) {
5486       // This instruction now refers directly to the cast's src operand.  This
5487       // has a good chance of making CSrc dead.
5488       CI.setOperand(0, CSrc->getOperand(0));
5489       return &CI;
5490     }
5491
5492     // If this is an A->B->A cast, and we are dealing with integral types, try
5493     // to convert this into a logical 'and' instruction.
5494     //
5495     if (A->getType()->isInteger() &&
5496         CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
5497         CSrc->getType()->isUnsigned() &&   // B->A cast must zero extend
5498         CSrc->getType()->getPrimitiveSizeInBits() <
5499                     CI.getType()->getPrimitiveSizeInBits()&&
5500         A->getType()->getPrimitiveSizeInBits() ==
5501               CI.getType()->getPrimitiveSizeInBits()) {
5502       assert(CSrc->getType() != Type::ULongTy &&
5503              "Cannot have type bigger than ulong!");
5504       uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
5505       Constant *AndOp = ConstantInt::get(A->getType()->getUnsignedVersion(),
5506                                           AndValue);
5507       AndOp = ConstantExpr::getCast(AndOp, A->getType());
5508       Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5509       if (And->getType() != CI.getType()) {
5510         And->setName(CSrc->getName()+".mask");
5511         InsertNewInstBefore(And, CI);
5512         And = new CastInst(And, CI.getType());
5513       }
5514       return And;
5515     }
5516   }
5517   
5518   // If this is a cast to bool, turn it into the appropriate setne instruction.
5519   if (CI.getType() == Type::BoolTy)
5520     return BinaryOperator::createSetNE(CI.getOperand(0),
5521                        Constant::getNullValue(CI.getOperand(0)->getType()));
5522
5523   // See if we can simplify any instructions used by the LHS whose sole 
5524   // purpose is to compute bits we don't care about.
5525   if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5526     uint64_t KnownZero, KnownOne;
5527     if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5528                              KnownZero, KnownOne))
5529       return &CI;
5530   }
5531   
5532   // If casting the result of a getelementptr instruction with no offset, turn
5533   // this into a cast of the original pointer!
5534   //
5535   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
5536     bool AllZeroOperands = true;
5537     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5538       if (!isa<Constant>(GEP->getOperand(i)) ||
5539           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5540         AllZeroOperands = false;
5541         break;
5542       }
5543     if (AllZeroOperands) {
5544       CI.setOperand(0, GEP->getOperand(0));
5545       return &CI;
5546     }
5547   }
5548
5549   // If we are casting a malloc or alloca to a pointer to a type of the same
5550   // size, rewrite the allocation instruction to allocate the "right" type.
5551   //
5552   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
5553     if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5554       return V;
5555
5556   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5557     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5558       return NV;
5559   if (isa<PHINode>(Src))
5560     if (Instruction *NV = FoldOpIntoPhi(CI))
5561       return NV;
5562   
5563   // If the source and destination are pointers, and this cast is equivalent to
5564   // a getelementptr X, 0, 0, 0...  turn it into the appropriate getelementptr.
5565   // This can enhance SROA and other transforms that want type-safe pointers.
5566   if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5567     if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5568       const Type *DstTy = DstPTy->getElementType();
5569       const Type *SrcTy = SrcPTy->getElementType();
5570       
5571       Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5572       unsigned NumZeros = 0;
5573       while (SrcTy != DstTy && 
5574              isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy) &&
5575              SrcTy->getNumContainedTypes() /* not "{}" */) {
5576         SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5577         ++NumZeros;
5578       }
5579
5580       // If we found a path from the src to dest, create the getelementptr now.
5581       if (SrcTy == DstTy) {
5582         std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5583         return new GetElementPtrInst(Src, Idxs);
5584       }
5585     }
5586       
5587   // If the source value is an instruction with only this use, we can attempt to
5588   // propagate the cast into the instruction.  Also, only handle integral types
5589   // for now.
5590   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
5591     if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
5592         CI.getType()->isInteger()) {  // Don't mess with casts to bool here
5593       
5594       int NumCastsRemoved = 0;
5595       if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5596         // If this cast is a truncate, evaluting in a different type always
5597         // eliminates the cast, so it is always a win.  If this is a noop-cast
5598         // this just removes a noop cast which isn't pointful, but simplifies
5599         // the code.  If this is a zero-extension, we need to do an AND to
5600         // maintain the clear top-part of the computation, so we require that
5601         // the input have eliminated at least one cast.  If this is a sign
5602         // extension, we insert two new casts (to do the extension) so we
5603         // require that two casts have been eliminated.
5604         bool DoXForm;
5605         switch (getCastType(Src->getType(), CI.getType())) {
5606         default: assert(0 && "Unknown cast type!");
5607         case Noop:
5608         case Truncate:
5609           DoXForm = true;
5610           break;
5611         case Zeroext:
5612           DoXForm = NumCastsRemoved >= 1;
5613           break;
5614         case Signext:
5615           DoXForm = NumCastsRemoved >= 2;
5616           break;
5617         }
5618         
5619         if (DoXForm) {
5620           Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5621           assert(Res->getType() == CI.getType());
5622           switch (getCastType(Src->getType(), CI.getType())) {
5623           default: assert(0 && "Unknown cast type!");
5624           case Noop:
5625           case Truncate:
5626             // Just replace this cast with the result.
5627             return ReplaceInstUsesWith(CI, Res);
5628           case Zeroext: {
5629             // We need to emit an AND to clear the high bits.
5630             unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5631             unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5632             assert(SrcBitSize < DestBitSize && "Not a zext?");
5633             Constant *C = 
5634               ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
5635             C = ConstantExpr::getCast(C, CI.getType());
5636             return BinaryOperator::createAnd(Res, C);
5637           }
5638           case Signext:
5639             // We need to emit a cast to truncate, then a cast to sext.
5640             return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5641                                 CI.getType());
5642           }
5643         }
5644       }
5645       
5646       const Type *DestTy = CI.getType();
5647       unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5648       unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
5649
5650       Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5651       Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5652
5653       switch (SrcI->getOpcode()) {
5654       case Instruction::Add:
5655       case Instruction::Mul:
5656       case Instruction::And:
5657       case Instruction::Or:
5658       case Instruction::Xor:
5659         // If we are discarding information, or just changing the sign, rewrite.
5660         if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5661           // Don't insert two casts if they cannot be eliminated.  We allow two
5662           // casts to be inserted if the sizes are the same.  This could only be
5663           // converting signedness, which is a noop.
5664           if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5665               !ValueRequiresCast(Op0, DestTy, TD)) {
5666             Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5667             Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5668             return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5669                              ->getOpcode(), Op0c, Op1c);
5670           }
5671         }
5672
5673         // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
5674         if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
5675             Op1 == ConstantBool::getTrue() &&
5676             (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5677           Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5678           return BinaryOperator::createXor(New,
5679                                            ConstantInt::get(CI.getType(), 1));
5680         }
5681         break;
5682       case Instruction::Shl:
5683         // Allow changing the sign of the source operand.  Do not allow changing
5684         // the size of the shift, UNLESS the shift amount is a constant.  We
5685         // mush not change variable sized shifts to a smaller size, because it
5686         // is undefined to shift more bits out than exist in the value.
5687         if (DestBitSize == SrcBitSize ||
5688             (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5689           Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5690           return new ShiftInst(Instruction::Shl, Op0c, Op1);
5691         }
5692         break;
5693       case Instruction::Shr:
5694         // If this is a signed shr, and if all bits shifted in are about to be
5695         // truncated off, turn it into an unsigned shr to allow greater
5696         // simplifications.
5697         if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
5698             isa<ConstantInt>(Op1)) {
5699           unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
5700           if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5701             // Convert to unsigned.
5702             Value *N1 = InsertOperandCastBefore(Op0,
5703                                      Op0->getType()->getUnsignedVersion(), &CI);
5704             // Insert the new shift, which is now unsigned.
5705             N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
5706                                                    Op1, Src->getName()), CI);
5707             return new CastInst(N1, CI.getType());
5708           }
5709         }
5710         break;
5711
5712       case Instruction::SetEQ:
5713       case Instruction::SetNE:
5714         // We if we are just checking for a seteq of a single bit and casting it
5715         // to an integer.  If so, shift the bit to the appropriate place then
5716         // cast to integer to avoid the comparison.
5717         if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
5718           uint64_t Op1CV = Op1C->getZExtValue();
5719           // cast (X == 0) to int --> X^1        iff X has only the low bit set.
5720           // cast (X == 0) to int --> (X>>1)^1   iff X has only the 2nd bit set.
5721           // cast (X == 1) to int --> X          iff X has only the low bit set.
5722           // cast (X == 2) to int --> X>>1       iff X has only the 2nd bit set.
5723           // cast (X != 0) to int --> X          iff X has only the low bit set.
5724           // cast (X != 0) to int --> X>>1       iff X has only the 2nd bit set.
5725           // cast (X != 1) to int --> X^1        iff X has only the low bit set.
5726           // cast (X != 2) to int --> (X>>1)^1   iff X has only the 2nd bit set.
5727           if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5728             // If Op1C some other power of two, convert:
5729             uint64_t KnownZero, KnownOne;
5730             uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5731             ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5732             
5733             if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5734               bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5735               if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5736                 // (X&4) == 2 --> false
5737                 // (X&4) != 2 --> true
5738                 Constant *Res = ConstantBool::get(isSetNE);
5739                 Res = ConstantExpr::getCast(Res, CI.getType());
5740                 return ReplaceInstUsesWith(CI, Res);
5741               }
5742               
5743               unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5744               Value *In = Op0;
5745               if (ShiftAmt) {
5746                 // Perform an unsigned shr by shiftamt.  Convert input to
5747                 // unsigned if it is signed.
5748                 if (In->getType()->isSigned())
5749                   In = InsertNewInstBefore(new CastInst(In,
5750                         In->getType()->getUnsignedVersion(), In->getName()),CI);
5751                 // Insert the shift to put the result in the low bit.
5752                 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
5753                                      ConstantInt::get(Type::UByteTy, ShiftAmt),
5754                                      In->getName()+".lobit"), CI);
5755               }
5756               
5757               if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5758                 Constant *One = ConstantInt::get(In->getType(), 1);
5759                 In = BinaryOperator::createXor(In, One, "tmp");
5760                 InsertNewInstBefore(cast<Instruction>(In), CI);
5761               }
5762               
5763               if (CI.getType() == In->getType())
5764                 return ReplaceInstUsesWith(CI, In);
5765               else
5766                 return new CastInst(In, CI.getType());
5767             }
5768           }
5769         }
5770         break;
5771       }
5772     }
5773     
5774     if (SrcI->hasOneUse()) {
5775       if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5776         // Okay, we have (cast (shuffle ..)).  We know this cast is a bitconvert
5777         // because the inputs are known to be a vector.  Check to see if this is
5778         // a cast to a vector with the same # elts.
5779         if (isa<PackedType>(CI.getType()) && 
5780             cast<PackedType>(CI.getType())->getNumElements() == 
5781                   SVI->getType()->getNumElements()) {
5782           CastInst *Tmp;
5783           // If either of the operands is a cast from CI.getType(), then
5784           // evaluating the shuffle in the casted destination's type will allow
5785           // us to eliminate at least one cast.
5786           if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
5787                Tmp->getOperand(0)->getType() == CI.getType()) ||
5788               ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
5789                Tmp->getOperand(0)->getType() == CI.getType())) {
5790             Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5791                                                  CI.getType(), &CI);
5792             Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5793                                                  CI.getType(), &CI);
5794             // Return a new shuffle vector.  Use the same element ID's, as we
5795             // know the vector types match #elts.
5796             return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5797           }
5798         }
5799       }
5800     }
5801   }
5802       
5803   return 0;
5804 }
5805
5806 /// GetSelectFoldableOperands - We want to turn code that looks like this:
5807 ///   %C = or %A, %B
5808 ///   %D = select %cond, %C, %A
5809 /// into:
5810 ///   %C = select %cond, %B, 0
5811 ///   %D = or %A, %C
5812 ///
5813 /// Assuming that the specified instruction is an operand to the select, return
5814 /// a bitmask indicating which operands of this instruction are foldable if they
5815 /// equal the other incoming value of the select.
5816 ///
5817 static unsigned GetSelectFoldableOperands(Instruction *I) {
5818   switch (I->getOpcode()) {
5819   case Instruction::Add:
5820   case Instruction::Mul:
5821   case Instruction::And:
5822   case Instruction::Or:
5823   case Instruction::Xor:
5824     return 3;              // Can fold through either operand.
5825   case Instruction::Sub:   // Can only fold on the amount subtracted.
5826   case Instruction::Shl:   // Can only fold on the shift amount.
5827   case Instruction::Shr:
5828     return 1;
5829   default:
5830     return 0;              // Cannot fold
5831   }
5832 }
5833
5834 /// GetSelectFoldableConstant - For the same transformation as the previous
5835 /// function, return the identity constant that goes into the select.
5836 static Constant *GetSelectFoldableConstant(Instruction *I) {
5837   switch (I->getOpcode()) {
5838   default: assert(0 && "This cannot happen!"); abort();
5839   case Instruction::Add:
5840   case Instruction::Sub:
5841   case Instruction::Or:
5842   case Instruction::Xor:
5843     return Constant::getNullValue(I->getType());
5844   case Instruction::Shl:
5845   case Instruction::Shr:
5846     return Constant::getNullValue(Type::UByteTy);
5847   case Instruction::And:
5848     return ConstantInt::getAllOnesValue(I->getType());
5849   case Instruction::Mul:
5850     return ConstantInt::get(I->getType(), 1);
5851   }
5852 }
5853
5854 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5855 /// have the same opcode and only one use each.  Try to simplify this.
5856 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5857                                           Instruction *FI) {
5858   if (TI->getNumOperands() == 1) {
5859     // If this is a non-volatile load or a cast from the same type,
5860     // merge.
5861     if (TI->getOpcode() == Instruction::Cast) {
5862       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5863         return 0;
5864     } else {
5865       return 0;  // unknown unary op.
5866     }
5867
5868     // Fold this by inserting a select from the input values.
5869     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5870                                        FI->getOperand(0), SI.getName()+".v");
5871     InsertNewInstBefore(NewSI, SI);
5872     return new CastInst(NewSI, TI->getType());
5873   }
5874
5875   // Only handle binary operators here.
5876   if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5877     return 0;
5878
5879   // Figure out if the operations have any operands in common.
5880   Value *MatchOp, *OtherOpT, *OtherOpF;
5881   bool MatchIsOpZero;
5882   if (TI->getOperand(0) == FI->getOperand(0)) {
5883     MatchOp  = TI->getOperand(0);
5884     OtherOpT = TI->getOperand(1);
5885     OtherOpF = FI->getOperand(1);
5886     MatchIsOpZero = true;
5887   } else if (TI->getOperand(1) == FI->getOperand(1)) {
5888     MatchOp  = TI->getOperand(1);
5889     OtherOpT = TI->getOperand(0);
5890     OtherOpF = FI->getOperand(0);
5891     MatchIsOpZero = false;
5892   } else if (!TI->isCommutative()) {
5893     return 0;
5894   } else if (TI->getOperand(0) == FI->getOperand(1)) {
5895     MatchOp  = TI->getOperand(0);
5896     OtherOpT = TI->getOperand(1);
5897     OtherOpF = FI->getOperand(0);
5898     MatchIsOpZero = true;
5899   } else if (TI->getOperand(1) == FI->getOperand(0)) {
5900     MatchOp  = TI->getOperand(1);
5901     OtherOpT = TI->getOperand(0);
5902     OtherOpF = FI->getOperand(1);
5903     MatchIsOpZero = true;
5904   } else {
5905     return 0;
5906   }
5907
5908   // If we reach here, they do have operations in common.
5909   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5910                                      OtherOpF, SI.getName()+".v");
5911   InsertNewInstBefore(NewSI, SI);
5912
5913   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5914     if (MatchIsOpZero)
5915       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5916     else
5917       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5918   } else {
5919     if (MatchIsOpZero)
5920       return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5921     else
5922       return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5923   }
5924 }
5925
5926 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
5927   Value *CondVal = SI.getCondition();
5928   Value *TrueVal = SI.getTrueValue();
5929   Value *FalseVal = SI.getFalseValue();
5930
5931   // select true, X, Y  -> X
5932   // select false, X, Y -> Y
5933   if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
5934     return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
5935
5936   // select C, X, X -> X
5937   if (TrueVal == FalseVal)
5938     return ReplaceInstUsesWith(SI, TrueVal);
5939
5940   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
5941     return ReplaceInstUsesWith(SI, FalseVal);
5942   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
5943     return ReplaceInstUsesWith(SI, TrueVal);
5944   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
5945     if (isa<Constant>(TrueVal))
5946       return ReplaceInstUsesWith(SI, TrueVal);
5947     else
5948       return ReplaceInstUsesWith(SI, FalseVal);
5949   }
5950
5951   if (SI.getType() == Type::BoolTy)
5952     if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5953       if (C->getValue()) {
5954         // Change: A = select B, true, C --> A = or B, C
5955         return BinaryOperator::createOr(CondVal, FalseVal);
5956       } else {
5957         // Change: A = select B, false, C --> A = and !B, C
5958         Value *NotCond =
5959           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5960                                              "not."+CondVal->getName()), SI);
5961         return BinaryOperator::createAnd(NotCond, FalseVal);
5962       }
5963     } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5964       if (C->getValue() == false) {
5965         // Change: A = select B, C, false --> A = and B, C
5966         return BinaryOperator::createAnd(CondVal, TrueVal);
5967       } else {
5968         // Change: A = select B, C, true --> A = or !B, C
5969         Value *NotCond =
5970           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5971                                              "not."+CondVal->getName()), SI);
5972         return BinaryOperator::createOr(NotCond, TrueVal);
5973       }
5974     }
5975
5976   // Selecting between two integer constants?
5977   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5978     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5979       // select C, 1, 0 -> cast C to int
5980       if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
5981         return new CastInst(CondVal, SI.getType());
5982       } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
5983         // select C, 0, 1 -> cast !C to int
5984         Value *NotCond =
5985           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5986                                                "not."+CondVal->getName()), SI);
5987         return new CastInst(NotCond, SI.getType());
5988       }
5989
5990       if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
5991
5992         // (x <s 0) ? -1 : 0 -> sra x, 31
5993         // (x >u 2147483647) ? -1 : 0 -> sra x, 31
5994         if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
5995           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
5996             bool CanXForm = false;
5997             if (CmpCst->getType()->isSigned())
5998               CanXForm = CmpCst->isNullValue() && 
5999                          IC->getOpcode() == Instruction::SetLT;
6000             else {
6001               unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
6002               CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
6003                          IC->getOpcode() == Instruction::SetGT;
6004             }
6005             
6006             if (CanXForm) {
6007               // The comparison constant and the result are not neccessarily the
6008               // same width.  In any case, the first step to do is make sure
6009               // that X is signed.
6010               Value *X = IC->getOperand(0);
6011               if (!X->getType()->isSigned())
6012                 X = InsertCastBefore(X, X->getType()->getSignedVersion(), SI);
6013               
6014               // Now that X is signed, we have to make the all ones value.  Do
6015               // this by inserting a new SRA.
6016               unsigned Bits = X->getType()->getPrimitiveSizeInBits();
6017               Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
6018               Instruction *SRA = new ShiftInst(Instruction::Shr, X,
6019                                                ShAmt, "ones");
6020               InsertNewInstBefore(SRA, SI);
6021               
6022               // Finally, convert to the type of the select RHS.  If this is
6023               // smaller than the compare value, it will truncate the ones to
6024               // fit. If it is larger, it will sext the ones to fit.
6025               return new CastInst(SRA, SI.getType());
6026             }
6027           }
6028
6029
6030         // If one of the constants is zero (we know they can't both be) and we
6031         // have a setcc instruction with zero, and we have an 'and' with the
6032         // non-constant value, eliminate this whole mess.  This corresponds to
6033         // cases like this: ((X & 27) ? 27 : 0)
6034         if (TrueValC->isNullValue() || FalseValC->isNullValue())
6035           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
6036               cast<Constant>(IC->getOperand(1))->isNullValue())
6037             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6038               if (ICA->getOpcode() == Instruction::And &&
6039                   isa<ConstantInt>(ICA->getOperand(1)) &&
6040                   (ICA->getOperand(1) == TrueValC ||
6041                    ICA->getOperand(1) == FalseValC) &&
6042                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6043                 // Okay, now we know that everything is set up, we just don't
6044                 // know whether we have a setne or seteq and whether the true or
6045                 // false val is the zero.
6046                 bool ShouldNotVal = !TrueValC->isNullValue();
6047                 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
6048                 Value *V = ICA;
6049                 if (ShouldNotVal)
6050                   V = InsertNewInstBefore(BinaryOperator::create(
6051                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
6052                 return ReplaceInstUsesWith(SI, V);
6053               }
6054       }
6055     }
6056
6057   // See if we are selecting two values based on a comparison of the two values.
6058   if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6059     if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6060       // Transform (X == Y) ? X : Y  -> Y
6061       if (SCI->getOpcode() == Instruction::SetEQ)
6062         return ReplaceInstUsesWith(SI, FalseVal);
6063       // Transform (X != Y) ? X : Y  -> X
6064       if (SCI->getOpcode() == Instruction::SetNE)
6065         return ReplaceInstUsesWith(SI, TrueVal);
6066       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6067
6068     } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6069       // Transform (X == Y) ? Y : X  -> X
6070       if (SCI->getOpcode() == Instruction::SetEQ)
6071         return ReplaceInstUsesWith(SI, FalseVal);
6072       // Transform (X != Y) ? Y : X  -> Y
6073       if (SCI->getOpcode() == Instruction::SetNE)
6074         return ReplaceInstUsesWith(SI, TrueVal);
6075       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6076     }
6077   }
6078
6079   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6080     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6081       if (TI->hasOneUse() && FI->hasOneUse()) {
6082         bool isInverse = false;
6083         Instruction *AddOp = 0, *SubOp = 0;
6084
6085         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6086         if (TI->getOpcode() == FI->getOpcode())
6087           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6088             return IV;
6089
6090         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
6091         // even legal for FP.
6092         if (TI->getOpcode() == Instruction::Sub &&
6093             FI->getOpcode() == Instruction::Add) {
6094           AddOp = FI; SubOp = TI;
6095         } else if (FI->getOpcode() == Instruction::Sub &&
6096                    TI->getOpcode() == Instruction::Add) {
6097           AddOp = TI; SubOp = FI;
6098         }
6099
6100         if (AddOp) {
6101           Value *OtherAddOp = 0;
6102           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6103             OtherAddOp = AddOp->getOperand(1);
6104           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6105             OtherAddOp = AddOp->getOperand(0);
6106           }
6107
6108           if (OtherAddOp) {
6109             // So at this point we know we have (Y -> OtherAddOp):
6110             //        select C, (add X, Y), (sub X, Z)
6111             Value *NegVal;  // Compute -Z
6112             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6113               NegVal = ConstantExpr::getNeg(C);
6114             } else {
6115               NegVal = InsertNewInstBefore(
6116                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
6117             }
6118
6119             Value *NewTrueOp = OtherAddOp;
6120             Value *NewFalseOp = NegVal;
6121             if (AddOp != TI)
6122               std::swap(NewTrueOp, NewFalseOp);
6123             Instruction *NewSel =
6124               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6125
6126             NewSel = InsertNewInstBefore(NewSel, SI);
6127             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
6128           }
6129         }
6130       }
6131
6132   // See if we can fold the select into one of our operands.
6133   if (SI.getType()->isInteger()) {
6134     // See the comment above GetSelectFoldableOperands for a description of the
6135     // transformation we are doing here.
6136     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6137       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6138           !isa<Constant>(FalseVal))
6139         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6140           unsigned OpToFold = 0;
6141           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6142             OpToFold = 1;
6143           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6144             OpToFold = 2;
6145           }
6146
6147           if (OpToFold) {
6148             Constant *C = GetSelectFoldableConstant(TVI);
6149             std::string Name = TVI->getName(); TVI->setName("");
6150             Instruction *NewSel =
6151               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6152                              Name);
6153             InsertNewInstBefore(NewSel, SI);
6154             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6155               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6156             else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6157               return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6158             else {
6159               assert(0 && "Unknown instruction!!");
6160             }
6161           }
6162         }
6163
6164     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6165       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6166           !isa<Constant>(TrueVal))
6167         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6168           unsigned OpToFold = 0;
6169           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6170             OpToFold = 1;
6171           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6172             OpToFold = 2;
6173           }
6174
6175           if (OpToFold) {
6176             Constant *C = GetSelectFoldableConstant(FVI);
6177             std::string Name = FVI->getName(); FVI->setName("");
6178             Instruction *NewSel =
6179               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6180                              Name);
6181             InsertNewInstBefore(NewSel, SI);
6182             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6183               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6184             else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6185               return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6186             else {
6187               assert(0 && "Unknown instruction!!");
6188             }
6189           }
6190         }
6191   }
6192
6193   if (BinaryOperator::isNot(CondVal)) {
6194     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6195     SI.setOperand(1, FalseVal);
6196     SI.setOperand(2, TrueVal);
6197     return &SI;
6198   }
6199
6200   return 0;
6201 }
6202
6203 /// GetKnownAlignment - If the specified pointer has an alignment that we can
6204 /// determine, return it, otherwise return 0.
6205 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6206   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6207     unsigned Align = GV->getAlignment();
6208     if (Align == 0 && TD) 
6209       Align = TD->getTypeAlignment(GV->getType()->getElementType());
6210     return Align;
6211   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6212     unsigned Align = AI->getAlignment();
6213     if (Align == 0 && TD) {
6214       if (isa<AllocaInst>(AI))
6215         Align = TD->getTypeAlignment(AI->getType()->getElementType());
6216       else if (isa<MallocInst>(AI)) {
6217         // Malloc returns maximally aligned memory.
6218         Align = TD->getTypeAlignment(AI->getType()->getElementType());
6219         Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6220         Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6221       }
6222     }
6223     return Align;
6224   } else if (isa<CastInst>(V) ||
6225              (isa<ConstantExpr>(V) && 
6226               cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
6227     User *CI = cast<User>(V);
6228     if (isa<PointerType>(CI->getOperand(0)->getType()))
6229       return GetKnownAlignment(CI->getOperand(0), TD);
6230     return 0;
6231   } else if (isa<GetElementPtrInst>(V) ||
6232              (isa<ConstantExpr>(V) && 
6233               cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6234     User *GEPI = cast<User>(V);
6235     unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6236     if (BaseAlignment == 0) return 0;
6237     
6238     // If all indexes are zero, it is just the alignment of the base pointer.
6239     bool AllZeroOperands = true;
6240     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6241       if (!isa<Constant>(GEPI->getOperand(i)) ||
6242           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6243         AllZeroOperands = false;
6244         break;
6245       }
6246     if (AllZeroOperands)
6247       return BaseAlignment;
6248     
6249     // Otherwise, if the base alignment is >= the alignment we expect for the
6250     // base pointer type, then we know that the resultant pointer is aligned at
6251     // least as much as its type requires.
6252     if (!TD) return 0;
6253
6254     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6255     if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
6256         <= BaseAlignment) {
6257       const Type *GEPTy = GEPI->getType();
6258       return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6259     }
6260     return 0;
6261   }
6262   return 0;
6263 }
6264
6265
6266 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
6267 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
6268 /// the heavy lifting.
6269 ///
6270 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
6271   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6272   if (!II) return visitCallSite(&CI);
6273   
6274   // Intrinsics cannot occur in an invoke, so handle them here instead of in
6275   // visitCallSite.
6276   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
6277     bool Changed = false;
6278
6279     // memmove/cpy/set of zero bytes is a noop.
6280     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6281       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6282
6283       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6284         if (CI->getZExtValue() == 1) {
6285           // Replace the instruction with just byte operations.  We would
6286           // transform other cases to loads/stores, but we don't know if
6287           // alignment is sufficient.
6288         }
6289     }
6290
6291     // If we have a memmove and the source operation is a constant global,
6292     // then the source and dest pointers can't alias, so we can change this
6293     // into a call to memcpy.
6294     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
6295       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6296         if (GVSrc->isConstant()) {
6297           Module *M = CI.getParent()->getParent()->getParent();
6298           const char *Name;
6299           if (CI.getCalledFunction()->getFunctionType()->getParamType(3) == 
6300               Type::UIntTy)
6301             Name = "llvm.memcpy.i32";
6302           else
6303             Name = "llvm.memcpy.i64";
6304           Function *MemCpy = M->getOrInsertFunction(Name,
6305                                      CI.getCalledFunction()->getFunctionType());
6306           CI.setOperand(0, MemCpy);
6307           Changed = true;
6308         }
6309     }
6310
6311     // If we can determine a pointer alignment that is bigger than currently
6312     // set, update the alignment.
6313     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6314       unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6315       unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6316       unsigned Align = std::min(Alignment1, Alignment2);
6317       if (MI->getAlignment()->getZExtValue() < Align) {
6318         MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
6319         Changed = true;
6320       }
6321     } else if (isa<MemSetInst>(MI)) {
6322       unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
6323       if (MI->getAlignment()->getZExtValue() < Alignment) {
6324         MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
6325         Changed = true;
6326       }
6327     }
6328           
6329     if (Changed) return II;
6330   } else {
6331     switch (II->getIntrinsicID()) {
6332     default: break;
6333     case Intrinsic::ppc_altivec_lvx:
6334     case Intrinsic::ppc_altivec_lvxl:
6335     case Intrinsic::x86_sse_loadu_ps:
6336     case Intrinsic::x86_sse2_loadu_pd:
6337     case Intrinsic::x86_sse2_loadu_dq:
6338       // Turn PPC lvx     -> load if the pointer is known aligned.
6339       // Turn X86 loadups -> load if the pointer is known aligned.
6340       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6341         Value *Ptr = InsertCastBefore(II->getOperand(1),
6342                                       PointerType::get(II->getType()), CI);
6343         return new LoadInst(Ptr);
6344       }
6345       break;
6346     case Intrinsic::ppc_altivec_stvx:
6347     case Intrinsic::ppc_altivec_stvxl:
6348       // Turn stvx -> store if the pointer is known aligned.
6349       if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
6350         const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6351         Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
6352         return new StoreInst(II->getOperand(1), Ptr);
6353       }
6354       break;
6355     case Intrinsic::x86_sse_storeu_ps:
6356     case Intrinsic::x86_sse2_storeu_pd:
6357     case Intrinsic::x86_sse2_storeu_dq:
6358     case Intrinsic::x86_sse2_storel_dq:
6359       // Turn X86 storeu -> store if the pointer is known aligned.
6360       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6361         const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6362         Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
6363         return new StoreInst(II->getOperand(2), Ptr);
6364       }
6365       break;
6366       
6367     case Intrinsic::x86_sse_cvttss2si: {
6368       // These intrinsics only demands the 0th element of its input vector.  If
6369       // we can simplify the input based on that, do so now.
6370       uint64_t UndefElts;
6371       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
6372                                                 UndefElts)) {
6373         II->setOperand(1, V);
6374         return II;
6375       }
6376       break;
6377     }
6378       
6379     case Intrinsic::ppc_altivec_vperm:
6380       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6381       if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6382         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6383         
6384         // Check that all of the elements are integer constants or undefs.
6385         bool AllEltsOk = true;
6386         for (unsigned i = 0; i != 16; ++i) {
6387           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
6388               !isa<UndefValue>(Mask->getOperand(i))) {
6389             AllEltsOk = false;
6390             break;
6391           }
6392         }
6393         
6394         if (AllEltsOk) {
6395           // Cast the input vectors to byte vectors.
6396           Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
6397           Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
6398           Value *Result = UndefValue::get(Op0->getType());
6399           
6400           // Only extract each element once.
6401           Value *ExtractedElts[32];
6402           memset(ExtractedElts, 0, sizeof(ExtractedElts));
6403           
6404           for (unsigned i = 0; i != 16; ++i) {
6405             if (isa<UndefValue>(Mask->getOperand(i)))
6406               continue;
6407             unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
6408             Idx &= 31;  // Match the hardware behavior.
6409             
6410             if (ExtractedElts[Idx] == 0) {
6411               Instruction *Elt = 
6412                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
6413               InsertNewInstBefore(Elt, CI);
6414               ExtractedElts[Idx] = Elt;
6415             }
6416           
6417             // Insert this value into the result vector.
6418             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
6419             InsertNewInstBefore(cast<Instruction>(Result), CI);
6420           }
6421           return new CastInst(Result, CI.getType());
6422         }
6423       }
6424       break;
6425
6426     case Intrinsic::stackrestore: {
6427       // If the save is right next to the restore, remove the restore.  This can
6428       // happen when variable allocas are DCE'd.
6429       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6430         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6431           BasicBlock::iterator BI = SS;
6432           if (&*++BI == II)
6433             return EraseInstFromFunction(CI);
6434         }
6435       }
6436       
6437       // If the stack restore is in a return/unwind block and if there are no
6438       // allocas or calls between the restore and the return, nuke the restore.
6439       TerminatorInst *TI = II->getParent()->getTerminator();
6440       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6441         BasicBlock::iterator BI = II;
6442         bool CannotRemove = false;
6443         for (++BI; &*BI != TI; ++BI) {
6444           if (isa<AllocaInst>(BI) ||
6445               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6446             CannotRemove = true;
6447             break;
6448           }
6449         }
6450         if (!CannotRemove)
6451           return EraseInstFromFunction(CI);
6452       }
6453       break;
6454     }
6455     }
6456   }
6457
6458   return visitCallSite(II);
6459 }
6460
6461 // InvokeInst simplification
6462 //
6463 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
6464   return visitCallSite(&II);
6465 }
6466
6467 // visitCallSite - Improvements for call and invoke instructions.
6468 //
6469 Instruction *InstCombiner::visitCallSite(CallSite CS) {
6470   bool Changed = false;
6471
6472   // If the callee is a constexpr cast of a function, attempt to move the cast
6473   // to the arguments of the call/invoke.
6474   if (transformConstExprCastCall(CS)) return 0;
6475
6476   Value *Callee = CS.getCalledValue();
6477
6478   if (Function *CalleeF = dyn_cast<Function>(Callee))
6479     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6480       Instruction *OldCall = CS.getInstruction();
6481       // If the call and callee calling conventions don't match, this call must
6482       // be unreachable, as the call is undefined.
6483       new StoreInst(ConstantBool::getTrue(),
6484                     UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6485       if (!OldCall->use_empty())
6486         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6487       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
6488         return EraseInstFromFunction(*OldCall);
6489       return 0;
6490     }
6491
6492   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6493     // This instruction is not reachable, just remove it.  We insert a store to
6494     // undef so that we know that this code is not reachable, despite the fact
6495     // that we can't modify the CFG here.
6496     new StoreInst(ConstantBool::getTrue(),
6497                   UndefValue::get(PointerType::get(Type::BoolTy)),
6498                   CS.getInstruction());
6499
6500     if (!CS.getInstruction()->use_empty())
6501       CS.getInstruction()->
6502         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6503
6504     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6505       // Don't break the CFG, insert a dummy cond branch.
6506       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
6507                      ConstantBool::getTrue(), II);
6508     }
6509     return EraseInstFromFunction(*CS.getInstruction());
6510   }
6511
6512   const PointerType *PTy = cast<PointerType>(Callee->getType());
6513   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6514   if (FTy->isVarArg()) {
6515     // See if we can optimize any arguments passed through the varargs area of
6516     // the call.
6517     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6518            E = CS.arg_end(); I != E; ++I)
6519       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6520         // If this cast does not effect the value passed through the varargs
6521         // area, we can eliminate the use of the cast.
6522         Value *Op = CI->getOperand(0);
6523         if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6524           *I = Op;
6525           Changed = true;
6526         }
6527       }
6528   }
6529
6530   return Changed ? CS.getInstruction() : 0;
6531 }
6532
6533 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
6534 // attempt to move the cast to the arguments of the call/invoke.
6535 //
6536 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6537   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6538   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
6539   if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
6540     return false;
6541   Function *Callee = cast<Function>(CE->getOperand(0));
6542   Instruction *Caller = CS.getInstruction();
6543
6544   // Okay, this is a cast from a function to a different type.  Unless doing so
6545   // would cause a type conversion of one of our arguments, change this call to
6546   // be a direct call with arguments casted to the appropriate types.
6547   //
6548   const FunctionType *FT = Callee->getFunctionType();
6549   const Type *OldRetTy = Caller->getType();
6550
6551   // Check to see if we are changing the return type...
6552   if (OldRetTy != FT->getReturnType()) {
6553     if (Callee->isExternal() &&
6554         !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6555           (isa<PointerType>(FT->getReturnType()) && 
6556            TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
6557         && !Caller->use_empty())
6558       return false;   // Cannot transform this return value...
6559
6560     // If the callsite is an invoke instruction, and the return value is used by
6561     // a PHI node in a successor, we cannot change the return type of the call
6562     // because there is no place to put the cast instruction (without breaking
6563     // the critical edge).  Bail out in this case.
6564     if (!Caller->use_empty())
6565       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6566         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6567              UI != E; ++UI)
6568           if (PHINode *PN = dyn_cast<PHINode>(*UI))
6569             if (PN->getParent() == II->getNormalDest() ||
6570                 PN->getParent() == II->getUnwindDest())
6571               return false;
6572   }
6573
6574   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6575   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
6576
6577   CallSite::arg_iterator AI = CS.arg_begin();
6578   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6579     const Type *ParamTy = FT->getParamType(i);
6580     const Type *ActTy = (*AI)->getType();
6581     ConstantInt* c = dyn_cast<ConstantInt>(*AI);
6582     //Either we can cast directly, or we can upconvert the argument
6583     bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6584       (ParamTy->isIntegral() && ActTy->isIntegral() &&
6585        ParamTy->isSigned() == ActTy->isSigned() &&
6586        ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6587       (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
6588        c->getSExtValue() > 0);
6589     if (Callee->isExternal() && !isConvertible) return false;
6590   }
6591
6592   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6593       Callee->isExternal())
6594     return false;   // Do not delete arguments unless we have a function body...
6595
6596   // Okay, we decided that this is a safe thing to do: go ahead and start
6597   // inserting cast instructions as necessary...
6598   std::vector<Value*> Args;
6599   Args.reserve(NumActualArgs);
6600
6601   AI = CS.arg_begin();
6602   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6603     const Type *ParamTy = FT->getParamType(i);
6604     if ((*AI)->getType() == ParamTy) {
6605       Args.push_back(*AI);
6606     } else {
6607       Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6608                                          *Caller));
6609     }
6610   }
6611
6612   // If the function takes more arguments than the call was taking, add them
6613   // now...
6614   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6615     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6616
6617   // If we are removing arguments to the function, emit an obnoxious warning...
6618   if (FT->getNumParams() < NumActualArgs)
6619     if (!FT->isVarArg()) {
6620       std::cerr << "WARNING: While resolving call to function '"
6621                 << Callee->getName() << "' arguments were dropped!\n";
6622     } else {
6623       // Add all of the arguments in their promoted form to the arg list...
6624       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6625         const Type *PTy = getPromotedType((*AI)->getType());
6626         if (PTy != (*AI)->getType()) {
6627           // Must promote to pass through va_arg area!
6628           Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6629           InsertNewInstBefore(Cast, *Caller);
6630           Args.push_back(Cast);
6631         } else {
6632           Args.push_back(*AI);
6633         }
6634       }
6635     }
6636
6637   if (FT->getReturnType() == Type::VoidTy)
6638     Caller->setName("");   // Void type should not have a name...
6639
6640   Instruction *NC;
6641   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6642     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
6643                         Args, Caller->getName(), Caller);
6644     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
6645   } else {
6646     NC = new CallInst(Callee, Args, Caller->getName(), Caller);
6647     if (cast<CallInst>(Caller)->isTailCall())
6648       cast<CallInst>(NC)->setTailCall();
6649    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
6650   }
6651
6652   // Insert a cast of the return type as necessary...
6653   Value *NV = NC;
6654   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6655     if (NV->getType() != Type::VoidTy) {
6656       NV = NC = new CastInst(NC, Caller->getType(), "tmp");
6657
6658       // If this is an invoke instruction, we should insert it after the first
6659       // non-phi, instruction in the normal successor block.
6660       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6661         BasicBlock::iterator I = II->getNormalDest()->begin();
6662         while (isa<PHINode>(I)) ++I;
6663         InsertNewInstBefore(NC, *I);
6664       } else {
6665         // Otherwise, it's a call, just insert cast right after the call instr
6666         InsertNewInstBefore(NC, *Caller);
6667       }
6668       AddUsersToWorkList(*Caller);
6669     } else {
6670       NV = UndefValue::get(Caller->getType());
6671     }
6672   }
6673
6674   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6675     Caller->replaceAllUsesWith(NV);
6676   Caller->getParent()->getInstList().erase(Caller);
6677   removeFromWorkList(Caller);
6678   return true;
6679 }
6680
6681
6682 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6683 // operator and they all are only used by the PHI, PHI together their
6684 // inputs, and do the operation once, to the result of the PHI.
6685 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6686   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6687
6688   // Scan the instruction, looking for input operations that can be folded away.
6689   // If all input operands to the phi are the same instruction (e.g. a cast from
6690   // the same type or "+42") we can pull the operation through the PHI, reducing
6691   // code size and simplifying code.
6692   Constant *ConstantOp = 0;
6693   const Type *CastSrcTy = 0;
6694   if (isa<CastInst>(FirstInst)) {
6695     CastSrcTy = FirstInst->getOperand(0)->getType();
6696   } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
6697     // Can fold binop or shift if the RHS is a constant.
6698     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
6699     if (ConstantOp == 0) return 0;
6700   } else {
6701     return 0;  // Cannot fold this operation.
6702   }
6703
6704   // Check to see if all arguments are the same operation.
6705   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6706     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6707     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6708     if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6709       return 0;
6710     if (CastSrcTy) {
6711       if (I->getOperand(0)->getType() != CastSrcTy)
6712         return 0;  // Cast operation must match.
6713     } else if (I->getOperand(1) != ConstantOp) {
6714       return 0;
6715     }
6716   }
6717
6718   // Okay, they are all the same operation.  Create a new PHI node of the
6719   // correct type, and PHI together all of the LHS's of the instructions.
6720   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6721                                PN.getName()+".in");
6722   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
6723
6724   Value *InVal = FirstInst->getOperand(0);
6725   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
6726
6727   // Add all operands to the new PHI.
6728   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6729     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6730     if (NewInVal != InVal)
6731       InVal = 0;
6732     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6733   }
6734
6735   Value *PhiVal;
6736   if (InVal) {
6737     // The new PHI unions all of the same values together.  This is really
6738     // common, so we handle it intelligently here for compile-time speed.
6739     PhiVal = InVal;
6740     delete NewPN;
6741   } else {
6742     InsertNewInstBefore(NewPN, PN);
6743     PhiVal = NewPN;
6744   }
6745
6746   // Insert and return the new operation.
6747   if (isa<CastInst>(FirstInst))
6748     return new CastInst(PhiVal, PN.getType());
6749   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
6750     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
6751   else
6752     return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
6753                          PhiVal, ConstantOp);
6754 }
6755
6756 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6757 /// that is dead.
6758 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6759   if (PN->use_empty()) return true;
6760   if (!PN->hasOneUse()) return false;
6761
6762   // Remember this node, and if we find the cycle, return.
6763   if (!PotentiallyDeadPHIs.insert(PN).second)
6764     return true;
6765
6766   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6767     return DeadPHICycle(PU, PotentiallyDeadPHIs);
6768
6769   return false;
6770 }
6771
6772 // PHINode simplification
6773 //
6774 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
6775   // If LCSSA is around, don't mess with Phi nodes
6776   if (mustPreserveAnalysisID(LCSSAID)) return 0;
6777   
6778   if (Value *V = PN.hasConstantValue())
6779     return ReplaceInstUsesWith(PN, V);
6780
6781   // If the only user of this instruction is a cast instruction, and all of the
6782   // incoming values are constants, change this PHI to merge together the casted
6783   // constants.
6784   if (PN.hasOneUse())
6785     if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
6786       if (CI->getType() != PN.getType()) {  // noop casts will be folded
6787         bool AllConstant = true;
6788         for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
6789           if (!isa<Constant>(PN.getIncomingValue(i))) {
6790             AllConstant = false;
6791             break;
6792           }
6793         if (AllConstant) {
6794           // Make a new PHI with all casted values.
6795           PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
6796           for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
6797             Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
6798             New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
6799                              PN.getIncomingBlock(i));
6800           }
6801
6802           // Update the cast instruction.
6803           CI->setOperand(0, New);
6804           WorkList.push_back(CI);    // revisit the cast instruction to fold.
6805           WorkList.push_back(New);   // Make sure to revisit the new Phi
6806           return &PN;                // PN is now dead!
6807         }
6808       }
6809
6810   // If all PHI operands are the same operation, pull them through the PHI,
6811   // reducing code size.
6812   if (isa<Instruction>(PN.getIncomingValue(0)) &&
6813       PN.getIncomingValue(0)->hasOneUse())
6814     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
6815       return Result;
6816
6817   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
6818   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
6819   // PHI)... break the cycle.
6820   if (PN.hasOneUse())
6821     if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
6822       std::set<PHINode*> PotentiallyDeadPHIs;
6823       PotentiallyDeadPHIs.insert(&PN);
6824       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
6825         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
6826     }
6827
6828   return 0;
6829 }
6830
6831 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
6832                                       Instruction *InsertPoint,
6833                                       InstCombiner *IC) {
6834   unsigned PS = IC->getTargetData().getPointerSize();
6835   const Type *VTy = V->getType();
6836   if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
6837     // We must insert a cast to ensure we sign-extend.
6838     V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
6839                                              V->getName()), *InsertPoint);
6840   return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
6841                                  *InsertPoint);
6842 }
6843
6844
6845 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
6846   Value *PtrOp = GEP.getOperand(0);
6847   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
6848   // If so, eliminate the noop.
6849   if (GEP.getNumOperands() == 1)
6850     return ReplaceInstUsesWith(GEP, PtrOp);
6851
6852   if (isa<UndefValue>(GEP.getOperand(0)))
6853     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
6854
6855   bool HasZeroPointerIndex = false;
6856   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
6857     HasZeroPointerIndex = C->isNullValue();
6858
6859   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
6860     return ReplaceInstUsesWith(GEP, PtrOp);
6861
6862   // Eliminate unneeded casts for indices.
6863   bool MadeChange = false;
6864   gep_type_iterator GTI = gep_type_begin(GEP);
6865   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
6866     if (isa<SequentialType>(*GTI)) {
6867       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
6868         Value *Src = CI->getOperand(0);
6869         const Type *SrcTy = Src->getType();
6870         const Type *DestTy = CI->getType();
6871         if (Src->getType()->isInteger()) {
6872           if (SrcTy->getPrimitiveSizeInBits() ==
6873                        DestTy->getPrimitiveSizeInBits()) {
6874             // We can always eliminate a cast from ulong or long to the other.
6875             // We can always eliminate a cast from uint to int or the other on
6876             // 32-bit pointer platforms.
6877             if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
6878               MadeChange = true;
6879               GEP.setOperand(i, Src);
6880             }
6881           } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6882                      SrcTy->getPrimitiveSize() == 4) {
6883             // We can always eliminate a cast from int to [u]long.  We can
6884             // eliminate a cast from uint to [u]long iff the target is a 32-bit
6885             // pointer target.
6886             if (SrcTy->isSigned() ||
6887                 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
6888               MadeChange = true;
6889               GEP.setOperand(i, Src);
6890             }
6891           }
6892         }
6893       }
6894       // If we are using a wider index than needed for this platform, shrink it
6895       // to what we need.  If the incoming value needs a cast instruction,
6896       // insert it.  This explicit cast can make subsequent optimizations more
6897       // obvious.
6898       Value *Op = GEP.getOperand(i);
6899       if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
6900         if (Constant *C = dyn_cast<Constant>(Op)) {
6901           GEP.setOperand(i, ConstantExpr::getCast(C,
6902                                      TD->getIntPtrType()->getSignedVersion()));
6903           MadeChange = true;
6904         } else {
6905           Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
6906                                                 Op->getName()), GEP);
6907           GEP.setOperand(i, Op);
6908           MadeChange = true;
6909         }
6910
6911       // If this is a constant idx, make sure to canonicalize it to be a signed
6912       // operand, otherwise CSE and other optimizations are pessimized.
6913       if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
6914         if (CUI->getType()->isUnsigned()) {
6915           GEP.setOperand(i, 
6916             ConstantExpr::getCast(CUI, CUI->getType()->getSignedVersion()));
6917           MadeChange = true;
6918         }
6919     }
6920   if (MadeChange) return &GEP;
6921
6922   // Combine Indices - If the source pointer to this getelementptr instruction
6923   // is a getelementptr instruction, combine the indices of the two
6924   // getelementptr instructions into a single instruction.
6925   //
6926   std::vector<Value*> SrcGEPOperands;
6927   if (User *Src = dyn_castGetElementPtr(PtrOp))
6928     SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
6929
6930   if (!SrcGEPOperands.empty()) {
6931     // Note that if our source is a gep chain itself that we wait for that
6932     // chain to be resolved before we perform this transformation.  This
6933     // avoids us creating a TON of code in some cases.
6934     //
6935     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6936         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6937       return 0;   // Wait until our source is folded to completion.
6938
6939     std::vector<Value *> Indices;
6940
6941     // Find out whether the last index in the source GEP is a sequential idx.
6942     bool EndsWithSequential = false;
6943     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6944            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
6945       EndsWithSequential = !isa<StructType>(*I);
6946
6947     // Can we combine the two pointer arithmetics offsets?
6948     if (EndsWithSequential) {
6949       // Replace: gep (gep %P, long B), long A, ...
6950       // With:    T = long A+B; gep %P, T, ...
6951       //
6952       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
6953       if (SO1 == Constant::getNullValue(SO1->getType())) {
6954         Sum = GO1;
6955       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6956         Sum = SO1;
6957       } else {
6958         // If they aren't the same type, convert both to an integer of the
6959         // target's pointer size.
6960         if (SO1->getType() != GO1->getType()) {
6961           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6962             SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6963           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6964             GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6965           } else {
6966             unsigned PS = TD->getPointerSize();
6967             if (SO1->getType()->getPrimitiveSize() == PS) {
6968               // Convert GO1 to SO1's type.
6969               GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6970
6971             } else if (GO1->getType()->getPrimitiveSize() == PS) {
6972               // Convert SO1 to GO1's type.
6973               SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6974             } else {
6975               const Type *PT = TD->getIntPtrType();
6976               SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6977               GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6978             }
6979           }
6980         }
6981         if (isa<Constant>(SO1) && isa<Constant>(GO1))
6982           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6983         else {
6984           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6985           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
6986         }
6987       }
6988
6989       // Recycle the GEP we already have if possible.
6990       if (SrcGEPOperands.size() == 2) {
6991         GEP.setOperand(0, SrcGEPOperands[0]);
6992         GEP.setOperand(1, Sum);
6993         return &GEP;
6994       } else {
6995         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6996                        SrcGEPOperands.end()-1);
6997         Indices.push_back(Sum);
6998         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6999       }
7000     } else if (isa<Constant>(*GEP.idx_begin()) &&
7001                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
7002                SrcGEPOperands.size() != 1) {
7003       // Otherwise we can do the fold if the first index of the GEP is a zero
7004       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7005                      SrcGEPOperands.end());
7006       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7007     }
7008
7009     if (!Indices.empty())
7010       return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
7011
7012   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
7013     // GEP of global variable.  If all of the indices for this GEP are
7014     // constants, we can promote this to a constexpr instead of an instruction.
7015
7016     // Scan for nonconstants...
7017     std::vector<Constant*> Indices;
7018     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7019     for (; I != E && isa<Constant>(*I); ++I)
7020       Indices.push_back(cast<Constant>(*I));
7021
7022     if (I == E) {  // If they are all constants...
7023       Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
7024
7025       // Replace all uses of the GEP with the new constexpr...
7026       return ReplaceInstUsesWith(GEP, CE);
7027     }
7028   } else if (Value *X = isCast(PtrOp)) {  // Is the operand a cast?
7029     if (!isa<PointerType>(X->getType())) {
7030       // Not interesting.  Source pointer must be a cast from pointer.
7031     } else if (HasZeroPointerIndex) {
7032       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7033       // into     : GEP [10 x ubyte]* X, long 0, ...
7034       //
7035       // This occurs when the program declares an array extern like "int X[];"
7036       //
7037       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7038       const PointerType *XTy = cast<PointerType>(X->getType());
7039       if (const ArrayType *XATy =
7040           dyn_cast<ArrayType>(XTy->getElementType()))
7041         if (const ArrayType *CATy =
7042             dyn_cast<ArrayType>(CPTy->getElementType()))
7043           if (CATy->getElementType() == XATy->getElementType()) {
7044             // At this point, we know that the cast source type is a pointer
7045             // to an array of the same type as the destination pointer
7046             // array.  Because the array type is never stepped over (there
7047             // is a leading zero) we can fold the cast into this GEP.
7048             GEP.setOperand(0, X);
7049             return &GEP;
7050           }
7051     } else if (GEP.getNumOperands() == 2) {
7052       // Transform things like:
7053       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7054       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
7055       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7056       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7057       if (isa<ArrayType>(SrcElTy) &&
7058           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7059           TD->getTypeSize(ResElTy)) {
7060         Value *V = InsertNewInstBefore(
7061                new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7062                                      GEP.getOperand(1), GEP.getName()), GEP);
7063         return new CastInst(V, GEP.getType());
7064       }
7065       
7066       // Transform things like:
7067       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7068       //   (where tmp = 8*tmp2) into:
7069       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7070       
7071       if (isa<ArrayType>(SrcElTy) &&
7072           (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7073         uint64_t ArrayEltSize =
7074             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7075         
7076         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
7077         // allow either a mul, shift, or constant here.
7078         Value *NewIdx = 0;
7079         ConstantInt *Scale = 0;
7080         if (ArrayEltSize == 1) {
7081           NewIdx = GEP.getOperand(1);
7082           Scale = ConstantInt::get(NewIdx->getType(), 1);
7083         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
7084           NewIdx = ConstantInt::get(CI->getType(), 1);
7085           Scale = CI;
7086         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7087           if (Inst->getOpcode() == Instruction::Shl &&
7088               isa<ConstantInt>(Inst->getOperand(1))) {
7089             unsigned ShAmt =
7090               cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
7091             if (Inst->getType()->isSigned())
7092               Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7093             else
7094               Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7095             NewIdx = Inst->getOperand(0);
7096           } else if (Inst->getOpcode() == Instruction::Mul &&
7097                      isa<ConstantInt>(Inst->getOperand(1))) {
7098             Scale = cast<ConstantInt>(Inst->getOperand(1));
7099             NewIdx = Inst->getOperand(0);
7100           }
7101         }
7102
7103         // If the index will be to exactly the right offset with the scale taken
7104         // out, perform the transformation.
7105         if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7106           if (ConstantInt *C = dyn_cast<ConstantInt>(Scale))
7107             Scale = ConstantInt::get(Scale->getType(),
7108                                       Scale->getZExtValue() / ArrayEltSize);
7109           if (Scale->getZExtValue() != 1) {
7110             Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
7111             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7112             NewIdx = InsertNewInstBefore(Sc, GEP);
7113           }
7114
7115           // Insert the new GEP instruction.
7116           Instruction *Idx =
7117             new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7118                                   NewIdx, GEP.getName());
7119           Idx = InsertNewInstBefore(Idx, GEP);
7120           return new CastInst(Idx, GEP.getType());
7121         }
7122       }
7123     }
7124   }
7125
7126   return 0;
7127 }
7128
7129 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7130   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7131   if (AI.isArrayAllocation())    // Check C != 1
7132     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7133       const Type *NewTy = 
7134         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
7135       AllocationInst *New = 0;
7136
7137       // Create and insert the replacement instruction...
7138       if (isa<MallocInst>(AI))
7139         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
7140       else {
7141         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
7142         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
7143       }
7144
7145       InsertNewInstBefore(New, AI);
7146
7147       // Scan to the end of the allocation instructions, to skip over a block of
7148       // allocas if possible...
7149       //
7150       BasicBlock::iterator It = New;
7151       while (isa<AllocationInst>(*It)) ++It;
7152
7153       // Now that I is pointing to the first non-allocation-inst in the block,
7154       // insert our getelementptr instruction...
7155       //
7156       Value *NullIdx = Constant::getNullValue(Type::IntTy);
7157       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7158                                        New->getName()+".sub", It);
7159
7160       // Now make everything use the getelementptr instead of the original
7161       // allocation.
7162       return ReplaceInstUsesWith(AI, V);
7163     } else if (isa<UndefValue>(AI.getArraySize())) {
7164       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7165     }
7166
7167   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7168   // Note that we only do this for alloca's, because malloc should allocate and
7169   // return a unique pointer, even for a zero byte allocation.
7170   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
7171       TD->getTypeSize(AI.getAllocatedType()) == 0)
7172     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7173
7174   return 0;
7175 }
7176
7177 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7178   Value *Op = FI.getOperand(0);
7179
7180   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7181   if (CastInst *CI = dyn_cast<CastInst>(Op))
7182     if (isa<PointerType>(CI->getOperand(0)->getType())) {
7183       FI.setOperand(0, CI->getOperand(0));
7184       return &FI;
7185     }
7186
7187   // free undef -> unreachable.
7188   if (isa<UndefValue>(Op)) {
7189     // Insert a new store to null because we cannot modify the CFG here.
7190     new StoreInst(ConstantBool::getTrue(),
7191                   UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7192     return EraseInstFromFunction(FI);
7193   }
7194
7195   // If we have 'free null' delete the instruction.  This can happen in stl code
7196   // when lots of inlining happens.
7197   if (isa<ConstantPointerNull>(Op))
7198     return EraseInstFromFunction(FI);
7199
7200   return 0;
7201 }
7202
7203
7204 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
7205 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7206   User *CI = cast<User>(LI.getOperand(0));
7207   Value *CastOp = CI->getOperand(0);
7208
7209   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7210   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7211     const Type *SrcPTy = SrcTy->getElementType();
7212
7213     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
7214         isa<PackedType>(DestPTy)) {
7215       // If the source is an array, the code below will not succeed.  Check to
7216       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
7217       // constants.
7218       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7219         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7220           if (ASrcTy->getNumElements() != 0) {
7221             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7222             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7223             SrcTy = cast<PointerType>(CastOp->getType());
7224             SrcPTy = SrcTy->getElementType();
7225           }
7226
7227       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
7228            isa<PackedType>(SrcPTy)) &&
7229           // Do not allow turning this into a load of an integer, which is then
7230           // casted to a pointer, this pessimizes pointer analysis a lot.
7231           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
7232           IC.getTargetData().getTypeSize(SrcPTy) ==
7233                IC.getTargetData().getTypeSize(DestPTy)) {
7234
7235         // Okay, we are casting from one integer or pointer type to another of
7236         // the same size.  Instead of casting the pointer before the load, cast
7237         // the result of the loaded value.
7238         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7239                                                              CI->getName(),
7240                                                          LI.isVolatile()),LI);
7241         // Now cast the result of the load.
7242         return new CastInst(NewLoad, LI.getType());
7243       }
7244     }
7245   }
7246   return 0;
7247 }
7248
7249 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
7250 /// from this value cannot trap.  If it is not obviously safe to load from the
7251 /// specified pointer, we do a quick local scan of the basic block containing
7252 /// ScanFrom, to determine if the address is already accessed.
7253 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7254   // If it is an alloca or global variable, it is always safe to load from.
7255   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7256
7257   // Otherwise, be a little bit agressive by scanning the local block where we
7258   // want to check to see if the pointer is already being loaded or stored
7259   // from/to.  If so, the previous load or store would have already trapped,
7260   // so there is no harm doing an extra load (also, CSE will later eliminate
7261   // the load entirely).
7262   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7263
7264   while (BBI != E) {
7265     --BBI;
7266
7267     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7268       if (LI->getOperand(0) == V) return true;
7269     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7270       if (SI->getOperand(1) == V) return true;
7271
7272   }
7273   return false;
7274 }
7275
7276 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7277   Value *Op = LI.getOperand(0);
7278
7279   // load (cast X) --> cast (load X) iff safe
7280   if (CastInst *CI = dyn_cast<CastInst>(Op))
7281     if (Instruction *Res = InstCombineLoadCast(*this, LI))
7282       return Res;
7283
7284   // None of the following transforms are legal for volatile loads.
7285   if (LI.isVolatile()) return 0;
7286   
7287   if (&LI.getParent()->front() != &LI) {
7288     BasicBlock::iterator BBI = &LI; --BBI;
7289     // If the instruction immediately before this is a store to the same
7290     // address, do a simple form of store->load forwarding.
7291     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7292       if (SI->getOperand(1) == LI.getOperand(0))
7293         return ReplaceInstUsesWith(LI, SI->getOperand(0));
7294     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7295       if (LIB->getOperand(0) == LI.getOperand(0))
7296         return ReplaceInstUsesWith(LI, LIB);
7297   }
7298
7299   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7300     if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7301         isa<UndefValue>(GEPI->getOperand(0))) {
7302       // Insert a new store to null instruction before the load to indicate
7303       // that this code is not reachable.  We do this instead of inserting
7304       // an unreachable instruction directly because we cannot modify the
7305       // CFG.
7306       new StoreInst(UndefValue::get(LI.getType()),
7307                     Constant::getNullValue(Op->getType()), &LI);
7308       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7309     }
7310
7311   if (Constant *C = dyn_cast<Constant>(Op)) {
7312     // load null/undef -> undef
7313     if ((C->isNullValue() || isa<UndefValue>(C))) {
7314       // Insert a new store to null instruction before the load to indicate that
7315       // this code is not reachable.  We do this instead of inserting an
7316       // unreachable instruction directly because we cannot modify the CFG.
7317       new StoreInst(UndefValue::get(LI.getType()),
7318                     Constant::getNullValue(Op->getType()), &LI);
7319       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7320     }
7321
7322     // Instcombine load (constant global) into the value loaded.
7323     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7324       if (GV->isConstant() && !GV->isExternal())
7325         return ReplaceInstUsesWith(LI, GV->getInitializer());
7326
7327     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7328     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7329       if (CE->getOpcode() == Instruction::GetElementPtr) {
7330         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7331           if (GV->isConstant() && !GV->isExternal())
7332             if (Constant *V = 
7333                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
7334               return ReplaceInstUsesWith(LI, V);
7335         if (CE->getOperand(0)->isNullValue()) {
7336           // Insert a new store to null instruction before the load to indicate
7337           // that this code is not reachable.  We do this instead of inserting
7338           // an unreachable instruction directly because we cannot modify the
7339           // CFG.
7340           new StoreInst(UndefValue::get(LI.getType()),
7341                         Constant::getNullValue(Op->getType()), &LI);
7342           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7343         }
7344
7345       } else if (CE->getOpcode() == Instruction::Cast) {
7346         if (Instruction *Res = InstCombineLoadCast(*this, LI))
7347           return Res;
7348       }
7349   }
7350
7351   if (Op->hasOneUse()) {
7352     // Change select and PHI nodes to select values instead of addresses: this
7353     // helps alias analysis out a lot, allows many others simplifications, and
7354     // exposes redundancy in the code.
7355     //
7356     // Note that we cannot do the transformation unless we know that the
7357     // introduced loads cannot trap!  Something like this is valid as long as
7358     // the condition is always false: load (select bool %C, int* null, int* %G),
7359     // but it would not be valid if we transformed it to load from null
7360     // unconditionally.
7361     //
7362     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7363       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
7364       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7365           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
7366         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
7367                                      SI->getOperand(1)->getName()+".val"), LI);
7368         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
7369                                      SI->getOperand(2)->getName()+".val"), LI);
7370         return new SelectInst(SI->getCondition(), V1, V2);
7371       }
7372
7373       // load (select (cond, null, P)) -> load P
7374       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7375         if (C->isNullValue()) {
7376           LI.setOperand(0, SI->getOperand(2));
7377           return &LI;
7378         }
7379
7380       // load (select (cond, P, null)) -> load P
7381       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7382         if (C->isNullValue()) {
7383           LI.setOperand(0, SI->getOperand(1));
7384           return &LI;
7385         }
7386
7387     } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
7388       // load (phi (&V1, &V2, &V3))  --> phi(load &V1, load &V2, load &V3)
7389       bool Safe = PN->getParent() == LI.getParent();
7390
7391       // Scan all of the instructions between the PHI and the load to make
7392       // sure there are no instructions that might possibly alter the value
7393       // loaded from the PHI.
7394       if (Safe) {
7395         BasicBlock::iterator I = &LI;
7396         for (--I; !isa<PHINode>(I); --I)
7397           if (isa<StoreInst>(I) || isa<CallInst>(I)) {
7398             Safe = false;
7399             break;
7400           }
7401       }
7402
7403       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
7404         if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
7405                                     PN->getIncomingBlock(i)->getTerminator()))
7406           Safe = false;
7407
7408       if (Safe) {
7409         // Create the PHI.
7410         PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
7411         InsertNewInstBefore(NewPN, *PN);
7412         std::map<BasicBlock*,Value*> LoadMap;  // Don't insert duplicate loads
7413
7414         for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7415           BasicBlock *BB = PN->getIncomingBlock(i);
7416           Value *&TheLoad = LoadMap[BB];
7417           if (TheLoad == 0) {
7418             Value *InVal = PN->getIncomingValue(i);
7419             TheLoad = InsertNewInstBefore(new LoadInst(InVal,
7420                                                        InVal->getName()+".val"),
7421                                           *BB->getTerminator());
7422           }
7423           NewPN->addIncoming(TheLoad, BB);
7424         }
7425         return ReplaceInstUsesWith(LI, NewPN);
7426       }
7427     }
7428   }
7429   return 0;
7430 }
7431
7432 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7433 /// when possible.
7434 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7435   User *CI = cast<User>(SI.getOperand(1));
7436   Value *CastOp = CI->getOperand(0);
7437
7438   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7439   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7440     const Type *SrcPTy = SrcTy->getElementType();
7441
7442     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7443       // If the source is an array, the code below will not succeed.  Check to
7444       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
7445       // constants.
7446       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7447         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7448           if (ASrcTy->getNumElements() != 0) {
7449             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7450             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7451             SrcTy = cast<PointerType>(CastOp->getType());
7452             SrcPTy = SrcTy->getElementType();
7453           }
7454
7455       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
7456           IC.getTargetData().getTypeSize(SrcPTy) ==
7457                IC.getTargetData().getTypeSize(DestPTy)) {
7458
7459         // Okay, we are casting from one integer or pointer type to another of
7460         // the same size.  Instead of casting the pointer before the store, cast
7461         // the value to be stored.
7462         Value *NewCast;
7463         if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7464           NewCast = ConstantExpr::getCast(C, SrcPTy);
7465         else
7466           NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
7467                                                         SrcPTy,
7468                                          SI.getOperand(0)->getName()+".c"), SI);
7469
7470         return new StoreInst(NewCast, CastOp);
7471       }
7472     }
7473   }
7474   return 0;
7475 }
7476
7477 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7478   Value *Val = SI.getOperand(0);
7479   Value *Ptr = SI.getOperand(1);
7480
7481   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
7482     EraseInstFromFunction(SI);
7483     ++NumCombined;
7484     return 0;
7485   }
7486
7487   // Do really simple DSE, to catch cases where there are several consequtive
7488   // stores to the same location, separated by a few arithmetic operations. This
7489   // situation often occurs with bitfield accesses.
7490   BasicBlock::iterator BBI = &SI;
7491   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7492        --ScanInsts) {
7493     --BBI;
7494     
7495     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7496       // Prev store isn't volatile, and stores to the same location?
7497       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7498         ++NumDeadStore;
7499         ++BBI;
7500         EraseInstFromFunction(*PrevSI);
7501         continue;
7502       }
7503       break;
7504     }
7505     
7506     // If this is a load, we have to stop.  However, if the loaded value is from
7507     // the pointer we're loading and is producing the pointer we're storing,
7508     // then *this* store is dead (X = load P; store X -> P).
7509     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7510       if (LI == Val && LI->getOperand(0) == Ptr) {
7511         EraseInstFromFunction(SI);
7512         ++NumCombined;
7513         return 0;
7514       }
7515       // Otherwise, this is a load from some other location.  Stores before it
7516       // may not be dead.
7517       break;
7518     }
7519     
7520     // Don't skip over loads or things that can modify memory.
7521     if (BBI->mayWriteToMemory())
7522       break;
7523   }
7524   
7525   
7526   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
7527
7528   // store X, null    -> turns into 'unreachable' in SimplifyCFG
7529   if (isa<ConstantPointerNull>(Ptr)) {
7530     if (!isa<UndefValue>(Val)) {
7531       SI.setOperand(0, UndefValue::get(Val->getType()));
7532       if (Instruction *U = dyn_cast<Instruction>(Val))
7533         WorkList.push_back(U);  // Dropped a use.
7534       ++NumCombined;
7535     }
7536     return 0;  // Do not modify these!
7537   }
7538
7539   // store undef, Ptr -> noop
7540   if (isa<UndefValue>(Val)) {
7541     EraseInstFromFunction(SI);
7542     ++NumCombined;
7543     return 0;
7544   }
7545
7546   // If the pointer destination is a cast, see if we can fold the cast into the
7547   // source instead.
7548   if (CastInst *CI = dyn_cast<CastInst>(Ptr))
7549     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7550       return Res;
7551   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7552     if (CE->getOpcode() == Instruction::Cast)
7553       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7554         return Res;
7555
7556   
7557   // If this store is the last instruction in the basic block, and if the block
7558   // ends with an unconditional branch, try to move it to the successor block.
7559   BBI = &SI; ++BBI;
7560   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7561     if (BI->isUnconditional()) {
7562       // Check to see if the successor block has exactly two incoming edges.  If
7563       // so, see if the other predecessor contains a store to the same location.
7564       // if so, insert a PHI node (if needed) and move the stores down.
7565       BasicBlock *Dest = BI->getSuccessor(0);
7566
7567       pred_iterator PI = pred_begin(Dest);
7568       BasicBlock *Other = 0;
7569       if (*PI != BI->getParent())
7570         Other = *PI;
7571       ++PI;
7572       if (PI != pred_end(Dest)) {
7573         if (*PI != BI->getParent())
7574           if (Other)
7575             Other = 0;
7576           else
7577             Other = *PI;
7578         if (++PI != pred_end(Dest))
7579           Other = 0;
7580       }
7581       if (Other) {  // If only one other pred...
7582         BBI = Other->getTerminator();
7583         // Make sure this other block ends in an unconditional branch and that
7584         // there is an instruction before the branch.
7585         if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7586             BBI != Other->begin()) {
7587           --BBI;
7588           StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7589           
7590           // If this instruction is a store to the same location.
7591           if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7592             // Okay, we know we can perform this transformation.  Insert a PHI
7593             // node now if we need it.
7594             Value *MergedVal = OtherStore->getOperand(0);
7595             if (MergedVal != SI.getOperand(0)) {
7596               PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7597               PN->reserveOperandSpace(2);
7598               PN->addIncoming(SI.getOperand(0), SI.getParent());
7599               PN->addIncoming(OtherStore->getOperand(0), Other);
7600               MergedVal = InsertNewInstBefore(PN, Dest->front());
7601             }
7602             
7603             // Advance to a place where it is safe to insert the new store and
7604             // insert it.
7605             BBI = Dest->begin();
7606             while (isa<PHINode>(BBI)) ++BBI;
7607             InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7608                                               OtherStore->isVolatile()), *BBI);
7609
7610             // Nuke the old stores.
7611             EraseInstFromFunction(SI);
7612             EraseInstFromFunction(*OtherStore);
7613             ++NumCombined;
7614             return 0;
7615           }
7616         }
7617       }
7618     }
7619   
7620   return 0;
7621 }
7622
7623
7624 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7625   // Change br (not X), label True, label False to: br X, label False, True
7626   Value *X = 0;
7627   BasicBlock *TrueDest;
7628   BasicBlock *FalseDest;
7629   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7630       !isa<Constant>(X)) {
7631     // Swap Destinations and condition...
7632     BI.setCondition(X);
7633     BI.setSuccessor(0, FalseDest);
7634     BI.setSuccessor(1, TrueDest);
7635     return &BI;
7636   }
7637
7638   // Cannonicalize setne -> seteq
7639   Instruction::BinaryOps Op; Value *Y;
7640   if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7641                       TrueDest, FalseDest)))
7642     if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7643          Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7644       SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7645       std::string Name = I->getName(); I->setName("");
7646       Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7647       Value *NewSCC =  BinaryOperator::create(NewOpcode, X, Y, Name, I);
7648       // Swap Destinations and condition...
7649       BI.setCondition(NewSCC);
7650       BI.setSuccessor(0, FalseDest);
7651       BI.setSuccessor(1, TrueDest);
7652       removeFromWorkList(I);
7653       I->getParent()->getInstList().erase(I);
7654       WorkList.push_back(cast<Instruction>(NewSCC));
7655       return &BI;
7656     }
7657
7658   return 0;
7659 }
7660
7661 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7662   Value *Cond = SI.getCondition();
7663   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7664     if (I->getOpcode() == Instruction::Add)
7665       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7666         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7667         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
7668           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
7669                                                 AddRHS));
7670         SI.setOperand(0, I->getOperand(0));
7671         WorkList.push_back(I);
7672         return &SI;
7673       }
7674   }
7675   return 0;
7676 }
7677
7678 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7679 /// is to leave as a vector operation.
7680 static bool CheapToScalarize(Value *V, bool isConstant) {
7681   if (isa<ConstantAggregateZero>(V)) 
7682     return true;
7683   if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7684     if (isConstant) return true;
7685     // If all elts are the same, we can extract.
7686     Constant *Op0 = C->getOperand(0);
7687     for (unsigned i = 1; i < C->getNumOperands(); ++i)
7688       if (C->getOperand(i) != Op0)
7689         return false;
7690     return true;
7691   }
7692   Instruction *I = dyn_cast<Instruction>(V);
7693   if (!I) return false;
7694   
7695   // Insert element gets simplified to the inserted element or is deleted if
7696   // this is constant idx extract element and its a constant idx insertelt.
7697   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7698       isa<ConstantInt>(I->getOperand(2)))
7699     return true;
7700   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7701     return true;
7702   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7703     if (BO->hasOneUse() &&
7704         (CheapToScalarize(BO->getOperand(0), isConstant) ||
7705          CheapToScalarize(BO->getOperand(1), isConstant)))
7706       return true;
7707   
7708   return false;
7709 }
7710
7711 /// getShuffleMask - Read and decode a shufflevector mask.  It turns undef
7712 /// elements into values that are larger than the #elts in the input.
7713 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7714   unsigned NElts = SVI->getType()->getNumElements();
7715   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7716     return std::vector<unsigned>(NElts, 0);
7717   if (isa<UndefValue>(SVI->getOperand(2)))
7718     return std::vector<unsigned>(NElts, 2*NElts);
7719
7720   std::vector<unsigned> Result;
7721   const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7722   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
7723     if (isa<UndefValue>(CP->getOperand(i)))
7724       Result.push_back(NElts*2);  // undef -> 8
7725     else
7726       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
7727   return Result;
7728 }
7729
7730 /// FindScalarElement - Given a vector and an element number, see if the scalar
7731 /// value is already around as a register, for example if it were inserted then
7732 /// extracted from the vector.
7733 static Value *FindScalarElement(Value *V, unsigned EltNo) {
7734   assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7735   const PackedType *PTy = cast<PackedType>(V->getType());
7736   unsigned Width = PTy->getNumElements();
7737   if (EltNo >= Width)  // Out of range access.
7738     return UndefValue::get(PTy->getElementType());
7739   
7740   if (isa<UndefValue>(V))
7741     return UndefValue::get(PTy->getElementType());
7742   else if (isa<ConstantAggregateZero>(V))
7743     return Constant::getNullValue(PTy->getElementType());
7744   else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7745     return CP->getOperand(EltNo);
7746   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7747     // If this is an insert to a variable element, we don't know what it is.
7748     if (!isa<ConstantInt>(III->getOperand(2))) 
7749       return 0;
7750     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
7751     
7752     // If this is an insert to the element we are looking for, return the
7753     // inserted value.
7754     if (EltNo == IIElt) 
7755       return III->getOperand(1);
7756     
7757     // Otherwise, the insertelement doesn't modify the value, recurse on its
7758     // vector input.
7759     return FindScalarElement(III->getOperand(0), EltNo);
7760   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
7761     unsigned InEl = getShuffleMask(SVI)[EltNo];
7762     if (InEl < Width)
7763       return FindScalarElement(SVI->getOperand(0), InEl);
7764     else if (InEl < Width*2)
7765       return FindScalarElement(SVI->getOperand(1), InEl - Width);
7766     else
7767       return UndefValue::get(PTy->getElementType());
7768   }
7769   
7770   // Otherwise, we don't know.
7771   return 0;
7772 }
7773
7774 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
7775
7776   // If packed val is undef, replace extract with scalar undef.
7777   if (isa<UndefValue>(EI.getOperand(0)))
7778     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7779
7780   // If packed val is constant 0, replace extract with scalar 0.
7781   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7782     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7783   
7784   if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7785     // If packed val is constant with uniform operands, replace EI
7786     // with that operand
7787     Constant *op0 = C->getOperand(0);
7788     for (unsigned i = 1; i < C->getNumOperands(); ++i)
7789       if (C->getOperand(i) != op0) {
7790         op0 = 0; 
7791         break;
7792       }
7793     if (op0)
7794       return ReplaceInstUsesWith(EI, op0);
7795   }
7796   
7797   // If extracting a specified index from the vector, see if we can recursively
7798   // find a previously computed scalar that was inserted into the vector.
7799   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
7800     // This instruction only demands the single element from the input vector.
7801     // If the input vector has a single use, simplify it based on this use
7802     // property.
7803     uint64_t IndexVal = IdxC->getZExtValue();
7804     if (EI.getOperand(0)->hasOneUse()) {
7805       uint64_t UndefElts;
7806       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
7807                                                 1 << IndexVal,
7808                                                 UndefElts)) {
7809         EI.setOperand(0, V);
7810         return &EI;
7811       }
7812     }
7813     
7814     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
7815       return ReplaceInstUsesWith(EI, Elt);
7816   }
7817   
7818   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
7819     if (I->hasOneUse()) {
7820       // Push extractelement into predecessor operation if legal and
7821       // profitable to do so
7822       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
7823         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
7824         if (CheapToScalarize(BO, isConstantElt)) {
7825           ExtractElementInst *newEI0 = 
7826             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
7827                                    EI.getName()+".lhs");
7828           ExtractElementInst *newEI1 =
7829             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
7830                                    EI.getName()+".rhs");
7831           InsertNewInstBefore(newEI0, EI);
7832           InsertNewInstBefore(newEI1, EI);
7833           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
7834         }
7835       } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7836         Value *Ptr = InsertCastBefore(I->getOperand(0),
7837                                       PointerType::get(EI.getType()), EI);
7838         GetElementPtrInst *GEP = 
7839           new GetElementPtrInst(Ptr, EI.getOperand(1),
7840                                 I->getName() + ".gep");
7841         InsertNewInstBefore(GEP, EI);
7842         return new LoadInst(GEP);
7843       }
7844     }
7845     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
7846       // Extracting the inserted element?
7847       if (IE->getOperand(2) == EI.getOperand(1))
7848         return ReplaceInstUsesWith(EI, IE->getOperand(1));
7849       // If the inserted and extracted elements are constants, they must not
7850       // be the same value, extract from the pre-inserted value instead.
7851       if (isa<Constant>(IE->getOperand(2)) &&
7852           isa<Constant>(EI.getOperand(1))) {
7853         AddUsesToWorkList(EI);
7854         EI.setOperand(0, IE->getOperand(0));
7855         return &EI;
7856       }
7857     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
7858       // If this is extracting an element from a shufflevector, figure out where
7859       // it came from and extract from the appropriate input element instead.
7860       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
7861         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
7862         Value *Src;
7863         if (SrcIdx < SVI->getType()->getNumElements())
7864           Src = SVI->getOperand(0);
7865         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
7866           SrcIdx -= SVI->getType()->getNumElements();
7867           Src = SVI->getOperand(1);
7868         } else {
7869           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7870         }
7871         return new ExtractElementInst(Src, SrcIdx);
7872       }
7873     }
7874   }
7875   return 0;
7876 }
7877
7878 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
7879 /// elements from either LHS or RHS, return the shuffle mask and true. 
7880 /// Otherwise, return false.
7881 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
7882                                          std::vector<Constant*> &Mask) {
7883   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
7884          "Invalid CollectSingleShuffleElements");
7885   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7886
7887   if (isa<UndefValue>(V)) {
7888     Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7889     return true;
7890   } else if (V == LHS) {
7891     for (unsigned i = 0; i != NumElts; ++i)
7892       Mask.push_back(ConstantInt::get(Type::UIntTy, i));
7893     return true;
7894   } else if (V == RHS) {
7895     for (unsigned i = 0; i != NumElts; ++i)
7896       Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
7897     return true;
7898   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7899     // If this is an insert of an extract from some other vector, include it.
7900     Value *VecOp    = IEI->getOperand(0);
7901     Value *ScalarOp = IEI->getOperand(1);
7902     Value *IdxOp    = IEI->getOperand(2);
7903     
7904     if (!isa<ConstantInt>(IdxOp))
7905       return false;
7906     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
7907     
7908     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
7909       // Okay, we can handle this if the vector we are insertinting into is
7910       // transitively ok.
7911       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7912         // If so, update the mask to reflect the inserted undef.
7913         Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
7914         return true;
7915       }      
7916     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
7917       if (isa<ConstantInt>(EI->getOperand(1)) &&
7918           EI->getOperand(0)->getType() == V->getType()) {
7919         unsigned ExtractedIdx =
7920           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
7921         
7922         // This must be extracting from either LHS or RHS.
7923         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
7924           // Okay, we can handle this if the vector we are insertinting into is
7925           // transitively ok.
7926           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7927             // If so, update the mask to reflect the inserted value.
7928             if (EI->getOperand(0) == LHS) {
7929               Mask[InsertedIdx & (NumElts-1)] = 
7930                  ConstantInt::get(Type::UIntTy, ExtractedIdx);
7931             } else {
7932               assert(EI->getOperand(0) == RHS);
7933               Mask[InsertedIdx & (NumElts-1)] = 
7934                 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
7935               
7936             }
7937             return true;
7938           }
7939         }
7940       }
7941     }
7942   }
7943   // TODO: Handle shufflevector here!
7944   
7945   return false;
7946 }
7947
7948 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
7949 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
7950 /// that computes V and the LHS value of the shuffle.
7951 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
7952                                      Value *&RHS) {
7953   assert(isa<PackedType>(V->getType()) && 
7954          (RHS == 0 || V->getType() == RHS->getType()) &&
7955          "Invalid shuffle!");
7956   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7957
7958   if (isa<UndefValue>(V)) {
7959     Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7960     return V;
7961   } else if (isa<ConstantAggregateZero>(V)) {
7962     Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
7963     return V;
7964   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7965     // If this is an insert of an extract from some other vector, include it.
7966     Value *VecOp    = IEI->getOperand(0);
7967     Value *ScalarOp = IEI->getOperand(1);
7968     Value *IdxOp    = IEI->getOperand(2);
7969     
7970     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7971       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7972           EI->getOperand(0)->getType() == V->getType()) {
7973         unsigned ExtractedIdx =
7974           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
7975         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
7976         
7977         // Either the extracted from or inserted into vector must be RHSVec,
7978         // otherwise we'd end up with a shuffle of three inputs.
7979         if (EI->getOperand(0) == RHS || RHS == 0) {
7980           RHS = EI->getOperand(0);
7981           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
7982           Mask[InsertedIdx & (NumElts-1)] = 
7983             ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
7984           return V;
7985         }
7986         
7987         if (VecOp == RHS) {
7988           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
7989           // Everything but the extracted element is replaced with the RHS.
7990           for (unsigned i = 0; i != NumElts; ++i) {
7991             if (i != InsertedIdx)
7992               Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
7993           }
7994           return V;
7995         }
7996         
7997         // If this insertelement is a chain that comes from exactly these two
7998         // vectors, return the vector and the effective shuffle.
7999         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8000           return EI->getOperand(0);
8001         
8002       }
8003     }
8004   }
8005   // TODO: Handle shufflevector here!
8006   
8007   // Otherwise, can't do anything fancy.  Return an identity vector.
8008   for (unsigned i = 0; i != NumElts; ++i)
8009     Mask.push_back(ConstantInt::get(Type::UIntTy, i));
8010   return V;
8011 }
8012
8013 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8014   Value *VecOp    = IE.getOperand(0);
8015   Value *ScalarOp = IE.getOperand(1);
8016   Value *IdxOp    = IE.getOperand(2);
8017   
8018   // If the inserted element was extracted from some other vector, and if the 
8019   // indexes are constant, try to turn this into a shufflevector operation.
8020   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8021     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8022         EI->getOperand(0)->getType() == IE.getType()) {
8023       unsigned NumVectorElts = IE.getType()->getNumElements();
8024       unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8025       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8026       
8027       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8028         return ReplaceInstUsesWith(IE, VecOp);
8029       
8030       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
8031         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8032       
8033       // If we are extracting a value from a vector, then inserting it right
8034       // back into the same place, just use the input vector.
8035       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8036         return ReplaceInstUsesWith(IE, VecOp);      
8037       
8038       // We could theoretically do this for ANY input.  However, doing so could
8039       // turn chains of insertelement instructions into a chain of shufflevector
8040       // instructions, and right now we do not merge shufflevectors.  As such,
8041       // only do this in a situation where it is clear that there is benefit.
8042       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8043         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
8044         // the values of VecOp, except then one read from EIOp0.
8045         // Build a new shuffle mask.
8046         std::vector<Constant*> Mask;
8047         if (isa<UndefValue>(VecOp))
8048           Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8049         else {
8050           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
8051           Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
8052                                                        NumVectorElts));
8053         } 
8054         Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
8055         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8056                                      ConstantPacked::get(Mask));
8057       }
8058       
8059       // If this insertelement isn't used by some other insertelement, turn it
8060       // (and any insertelements it points to), into one big shuffle.
8061       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8062         std::vector<Constant*> Mask;
8063         Value *RHS = 0;
8064         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8065         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8066         // We now have a shuffle of LHS, RHS, Mask.
8067         return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
8068       }
8069     }
8070   }
8071
8072   return 0;
8073 }
8074
8075
8076 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8077   Value *LHS = SVI.getOperand(0);
8078   Value *RHS = SVI.getOperand(1);
8079   std::vector<unsigned> Mask = getShuffleMask(&SVI);
8080
8081   bool MadeChange = false;
8082   
8083   // Undefined shuffle mask -> undefined value.
8084   if (isa<UndefValue>(SVI.getOperand(2)))
8085     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8086   
8087   // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8088   // the undef, change them to undefs.
8089   
8090   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
8091   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8092   if (LHS == RHS || isa<UndefValue>(LHS)) {
8093     if (isa<UndefValue>(LHS) && LHS == RHS) {
8094       // shuffle(undef,undef,mask) -> undef.
8095       return ReplaceInstUsesWith(SVI, LHS);
8096     }
8097     
8098     // Remap any references to RHS to use LHS.
8099     std::vector<Constant*> Elts;
8100     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8101       if (Mask[i] >= 2*e)
8102         Elts.push_back(UndefValue::get(Type::UIntTy));
8103       else {
8104         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8105             (Mask[i] <  e && isa<UndefValue>(LHS)))
8106           Mask[i] = 2*e;     // Turn into undef.
8107         else
8108           Mask[i] &= (e-1);  // Force to LHS.
8109         Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
8110       }
8111     }
8112     SVI.setOperand(0, SVI.getOperand(1));
8113     SVI.setOperand(1, UndefValue::get(RHS->getType()));
8114     SVI.setOperand(2, ConstantPacked::get(Elts));
8115     LHS = SVI.getOperand(0);
8116     RHS = SVI.getOperand(1);
8117     MadeChange = true;
8118   }
8119   
8120   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
8121   bool isLHSID = true, isRHSID = true;
8122     
8123   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8124     if (Mask[i] >= e*2) continue;  // Ignore undef values.
8125     // Is this an identity shuffle of the LHS value?
8126     isLHSID &= (Mask[i] == i);
8127       
8128     // Is this an identity shuffle of the RHS value?
8129     isRHSID &= (Mask[i]-e == i);
8130   }
8131
8132   // Eliminate identity shuffles.
8133   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8134   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
8135   
8136   // If the LHS is a shufflevector itself, see if we can combine it with this
8137   // one without producing an unusual shuffle.  Here we are really conservative:
8138   // we are absolutely afraid of producing a shuffle mask not in the input
8139   // program, because the code gen may not be smart enough to turn a merged
8140   // shuffle into two specific shuffles: it may produce worse code.  As such,
8141   // we only merge two shuffles if the result is one of the two input shuffle
8142   // masks.  In this case, merging the shuffles just removes one instruction,
8143   // which we know is safe.  This is good for things like turning:
8144   // (splat(splat)) -> splat.
8145   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8146     if (isa<UndefValue>(RHS)) {
8147       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8148
8149       std::vector<unsigned> NewMask;
8150       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8151         if (Mask[i] >= 2*e)
8152           NewMask.push_back(2*e);
8153         else
8154           NewMask.push_back(LHSMask[Mask[i]]);
8155       
8156       // If the result mask is equal to the src shuffle or this shuffle mask, do
8157       // the replacement.
8158       if (NewMask == LHSMask || NewMask == Mask) {
8159         std::vector<Constant*> Elts;
8160         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8161           if (NewMask[i] >= e*2) {
8162             Elts.push_back(UndefValue::get(Type::UIntTy));
8163           } else {
8164             Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
8165           }
8166         }
8167         return new ShuffleVectorInst(LHSSVI->getOperand(0),
8168                                      LHSSVI->getOperand(1),
8169                                      ConstantPacked::get(Elts));
8170       }
8171     }
8172   }
8173   
8174   return MadeChange ? &SVI : 0;
8175 }
8176
8177
8178
8179 void InstCombiner::removeFromWorkList(Instruction *I) {
8180   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8181                  WorkList.end());
8182 }
8183
8184
8185 /// TryToSinkInstruction - Try to move the specified instruction from its
8186 /// current block into the beginning of DestBlock, which can only happen if it's
8187 /// safe to move the instruction past all of the instructions between it and the
8188 /// end of its block.
8189 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8190   assert(I->hasOneUse() && "Invariants didn't hold!");
8191
8192   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8193   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
8194
8195   // Do not sink alloca instructions out of the entry block.
8196   if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8197     return false;
8198
8199   // We can only sink load instructions if there is nothing between the load and
8200   // the end of block that could change the value.
8201   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8202     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8203          Scan != E; ++Scan)
8204       if (Scan->mayWriteToMemory())
8205         return false;
8206   }
8207
8208   BasicBlock::iterator InsertPos = DestBlock->begin();
8209   while (isa<PHINode>(InsertPos)) ++InsertPos;
8210
8211   I->moveBefore(InsertPos);
8212   ++NumSunkInst;
8213   return true;
8214 }
8215
8216 /// OptimizeConstantExpr - Given a constant expression and target data layout
8217 /// information, symbolically evaluation the constant expr to something simpler
8218 /// if possible.
8219 static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8220   if (!TD) return CE;
8221   
8222   Constant *Ptr = CE->getOperand(0);
8223   if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8224       cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8225     // If this is a constant expr gep that is effectively computing an
8226     // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8227     bool isFoldableGEP = true;
8228     for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8229       if (!isa<ConstantInt>(CE->getOperand(i)))
8230         isFoldableGEP = false;
8231     if (isFoldableGEP) {
8232       std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8233       uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
8234       Constant *C = ConstantInt::get(Type::ULongTy, Offset);
8235       C = ConstantExpr::getCast(C, TD->getIntPtrType());
8236       return ConstantExpr::getCast(C, CE->getType());
8237     }
8238   }
8239   
8240   return CE;
8241 }
8242
8243
8244 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8245 /// all reachable code to the worklist.
8246 ///
8247 /// This has a couple of tricks to make the code faster and more powerful.  In
8248 /// particular, we constant fold and DCE instructions as we go, to avoid adding
8249 /// them to the worklist (this significantly speeds up instcombine on code where
8250 /// many instructions are dead or constant).  Additionally, if we find a branch
8251 /// whose condition is a known constant, we only visit the reachable successors.
8252 ///
8253 static void AddReachableCodeToWorklist(BasicBlock *BB, 
8254                                        std::set<BasicBlock*> &Visited,
8255                                        std::vector<Instruction*> &WorkList,
8256                                        const TargetData *TD) {
8257   // We have now visited this block!  If we've already been here, bail out.
8258   if (!Visited.insert(BB).second) return;
8259     
8260   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8261     Instruction *Inst = BBI++;
8262     
8263     // DCE instruction if trivially dead.
8264     if (isInstructionTriviallyDead(Inst)) {
8265       ++NumDeadInst;
8266       DEBUG(std::cerr << "IC: DCE: " << *Inst);
8267       Inst->eraseFromParent();
8268       continue;
8269     }
8270     
8271     // ConstantProp instruction if trivially constant.
8272     if (Constant *C = ConstantFoldInstruction(Inst)) {
8273       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8274         C = OptimizeConstantExpr(CE, TD);
8275       DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
8276       Inst->replaceAllUsesWith(C);
8277       ++NumConstProp;
8278       Inst->eraseFromParent();
8279       continue;
8280     }
8281     
8282     WorkList.push_back(Inst);
8283   }
8284
8285   // Recursively visit successors.  If this is a branch or switch on a constant,
8286   // only visit the reachable successor.
8287   TerminatorInst *TI = BB->getTerminator();
8288   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8289     if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8290       bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
8291       AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8292                                  TD);
8293       return;
8294     }
8295   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8296     if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8297       // See if this is an explicit destination.
8298       for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8299         if (SI->getCaseValue(i) == Cond) {
8300           AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
8301           return;
8302         }
8303       
8304       // Otherwise it is the default destination.
8305       AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
8306       return;
8307     }
8308   }
8309   
8310   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
8311     AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
8312 }
8313
8314 bool InstCombiner::runOnFunction(Function &F) {
8315   bool Changed = false;
8316   TD = &getAnalysis<TargetData>();
8317
8318   {
8319     // Do a depth-first traversal of the function, populate the worklist with
8320     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
8321     // track of which blocks we visit.
8322     std::set<BasicBlock*> Visited;
8323     AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
8324
8325     // Do a quick scan over the function.  If we find any blocks that are
8326     // unreachable, remove any instructions inside of them.  This prevents
8327     // the instcombine code from having to deal with some bad special cases.
8328     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8329       if (!Visited.count(BB)) {
8330         Instruction *Term = BB->getTerminator();
8331         while (Term != BB->begin()) {   // Remove instrs bottom-up
8332           BasicBlock::iterator I = Term; --I;
8333
8334           DEBUG(std::cerr << "IC: DCE: " << *I);
8335           ++NumDeadInst;
8336
8337           if (!I->use_empty())
8338             I->replaceAllUsesWith(UndefValue::get(I->getType()));
8339           I->eraseFromParent();
8340         }
8341       }
8342   }
8343
8344   while (!WorkList.empty()) {
8345     Instruction *I = WorkList.back();  // Get an instruction from the worklist
8346     WorkList.pop_back();
8347
8348     // Check to see if we can DCE the instruction.
8349     if (isInstructionTriviallyDead(I)) {
8350       // Add operands to the worklist.
8351       if (I->getNumOperands() < 4)
8352         AddUsesToWorkList(*I);
8353       ++NumDeadInst;
8354
8355       DEBUG(std::cerr << "IC: DCE: " << *I);
8356
8357       I->eraseFromParent();
8358       removeFromWorkList(I);
8359       continue;
8360     }
8361
8362     // Instruction isn't dead, see if we can constant propagate it.
8363     if (Constant *C = ConstantFoldInstruction(I)) {
8364       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8365         C = OptimizeConstantExpr(CE, TD);
8366       DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
8367
8368       // Add operands to the worklist.
8369       AddUsesToWorkList(*I);
8370       ReplaceInstUsesWith(*I, C);
8371
8372       ++NumConstProp;
8373       I->eraseFromParent();
8374       removeFromWorkList(I);
8375       continue;
8376     }
8377
8378     // See if we can trivially sink this instruction to a successor basic block.
8379     if (I->hasOneUse()) {
8380       BasicBlock *BB = I->getParent();
8381       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8382       if (UserParent != BB) {
8383         bool UserIsSuccessor = false;
8384         // See if the user is one of our successors.
8385         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8386           if (*SI == UserParent) {
8387             UserIsSuccessor = true;
8388             break;
8389           }
8390
8391         // If the user is one of our immediate successors, and if that successor
8392         // only has us as a predecessors (we'd have to split the critical edge
8393         // otherwise), we can keep going.
8394         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8395             next(pred_begin(UserParent)) == pred_end(UserParent))
8396           // Okay, the CFG is simple enough, try to sink this instruction.
8397           Changed |= TryToSinkInstruction(I, UserParent);
8398       }
8399     }
8400
8401     // Now that we have an instruction, try combining it to simplify it...
8402     if (Instruction *Result = visit(*I)) {
8403       ++NumCombined;
8404       // Should we replace the old instruction with a new one?
8405       if (Result != I) {
8406         DEBUG(std::cerr << "IC: Old = " << *I
8407                         << "    New = " << *Result);
8408
8409         // Everything uses the new instruction now.
8410         I->replaceAllUsesWith(Result);
8411
8412         // Push the new instruction and any users onto the worklist.
8413         WorkList.push_back(Result);
8414         AddUsersToWorkList(*Result);
8415
8416         // Move the name to the new instruction first...
8417         std::string OldName = I->getName(); I->setName("");
8418         Result->setName(OldName);
8419
8420         // Insert the new instruction into the basic block...
8421         BasicBlock *InstParent = I->getParent();
8422         BasicBlock::iterator InsertPos = I;
8423
8424         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
8425           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8426             ++InsertPos;
8427
8428         InstParent->getInstList().insert(InsertPos, Result);
8429
8430         // Make sure that we reprocess all operands now that we reduced their
8431         // use counts.
8432         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8433           if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8434             WorkList.push_back(OpI);
8435
8436         // Instructions can end up on the worklist more than once.  Make sure
8437         // we do not process an instruction that has been deleted.
8438         removeFromWorkList(I);
8439
8440         // Erase the old instruction.
8441         InstParent->getInstList().erase(I);
8442       } else {
8443         DEBUG(std::cerr << "IC: MOD = " << *I);
8444
8445         // If the instruction was modified, it's possible that it is now dead.
8446         // if so, remove it.
8447         if (isInstructionTriviallyDead(I)) {
8448           // Make sure we process all operands now that we are reducing their
8449           // use counts.
8450           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8451             if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8452               WorkList.push_back(OpI);
8453
8454           // Instructions may end up in the worklist more than once.  Erase all
8455           // occurrences of this instruction.
8456           removeFromWorkList(I);
8457           I->eraseFromParent();
8458         } else {
8459           WorkList.push_back(Result);
8460           AddUsersToWorkList(*Result);
8461         }
8462       }
8463       Changed = true;
8464     }
8465   }
8466
8467   return Changed;
8468 }
8469
8470 FunctionPass *llvm::createInstructionCombiningPass() {
8471   return new InstCombiner();
8472 }
8473