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