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