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