a02aa5dff8bbe174224a3b5959b85e8583e76ef1
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG.  This pass is where
12 // algebraic simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/LLVMContext.h"
40 #include "llvm/Pass.h"
41 #include "llvm/DerivedTypes.h"
42 #include "llvm/GlobalVariable.h"
43 #include "llvm/Operator.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Analysis/ValueTracking.h"
46 #include "llvm/Target/TargetData.h"
47 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
48 #include "llvm/Transforms/Utils/Local.h"
49 #include "llvm/Support/CallSite.h"
50 #include "llvm/Support/ConstantRange.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/GetElementPtrTypeIterator.h"
54 #include "llvm/Support/InstVisitor.h"
55 #include "llvm/Support/IRBuilder.h"
56 #include "llvm/Support/MathExtras.h"
57 #include "llvm/Support/PatternMatch.h"
58 #include "llvm/Support/Compiler.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include "llvm/ADT/DenseMap.h"
61 #include "llvm/ADT/SmallVector.h"
62 #include "llvm/ADT/SmallPtrSet.h"
63 #include "llvm/ADT/Statistic.h"
64 #include "llvm/ADT/STLExtras.h"
65 #include <algorithm>
66 #include <climits>
67 using namespace llvm;
68 using namespace llvm::PatternMatch;
69
70 STATISTIC(NumCombined , "Number of insts combined");
71 STATISTIC(NumConstProp, "Number of constant folds");
72 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74 STATISTIC(NumSunkInst , "Number of instructions sunk");
75
76 namespace {
77   /// InstCombineWorklist - This is the worklist management logic for
78   /// InstCombine.
79   class InstCombineWorklist {
80     SmallVector<Instruction*, 256> Worklist;
81     DenseMap<Instruction*, unsigned> WorklistMap;
82     
83     void operator=(const InstCombineWorklist&RHS);   // DO NOT IMPLEMENT
84     InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
85   public:
86     InstCombineWorklist() {}
87     
88     bool isEmpty() const { return Worklist.empty(); }
89     
90     /// Add - Add the specified instruction to the worklist if it isn't already
91     /// in it.
92     void Add(Instruction *I) {
93       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
94         Worklist.push_back(I);
95     }
96     
97     void AddValue(Value *V) {
98       if (Instruction *I = dyn_cast<Instruction>(V))
99         Add(I);
100     }
101     
102     // Remove - remove I from the worklist if it exists.
103     void Remove(Instruction *I) {
104       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
105       if (It == WorklistMap.end()) return; // Not in worklist.
106       
107       // Don't bother moving everything down, just null out the slot.
108       Worklist[It->second] = 0;
109       
110       WorklistMap.erase(It);
111     }
112     
113     Instruction *RemoveOne() {
114       Instruction *I = Worklist.back();
115       Worklist.pop_back();
116       WorklistMap.erase(I);
117       return I;
118     }
119
120     /// AddUsersToWorkList - When an instruction is simplified, add all users of
121     /// the instruction to the work lists because they might get more simplified
122     /// now.
123     ///
124     void AddUsersToWorkList(Instruction &I) {
125       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
126            UI != UE; ++UI)
127         Add(cast<Instruction>(*UI));
128     }
129     
130     
131     /// Zap - check that the worklist is empty and nuke the backing store for
132     /// the map if it is large.
133     void Zap() {
134       assert(WorklistMap.empty() && "Worklist empty, but map not?");
135       
136       // Do an explicit clear, this shrinks the map if needed.
137       WorklistMap.clear();
138     }
139   };
140 } // end anonymous namespace.
141
142
143 namespace {
144   /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
145   /// just like the normal insertion helper, but also adds any new instructions
146   /// to the instcombine worklist.
147   class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
148     InstCombineWorklist &Worklist;
149   public:
150     InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
151     
152     void InsertHelper(Instruction *I, const Twine &Name,
153                       BasicBlock *BB, BasicBlock::iterator InsertPt) const {
154       IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
155       Worklist.Add(I);
156     }
157   };
158 } // end anonymous namespace
159
160
161 namespace {
162   class VISIBILITY_HIDDEN InstCombiner
163     : public FunctionPass,
164       public InstVisitor<InstCombiner, Instruction*> {
165     TargetData *TD;
166     bool MustPreserveLCSSA;
167   public:
168     /// Worklist - All of the instructions that need to be simplified.
169     InstCombineWorklist Worklist;
170
171     /// Builder - This is an IRBuilder that automatically inserts new
172     /// instructions into the worklist when they are created.
173     typedef IRBuilder<true, ConstantFolder, InstCombineIRInserter> BuilderTy;
174     BuilderTy *Builder;
175         
176     static char ID; // Pass identification, replacement for typeid
177     InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
178
179     LLVMContext *Context;
180     LLVMContext *getContext() const { return Context; }
181
182   public:
183     virtual bool runOnFunction(Function &F);
184     
185     bool DoOneIteration(Function &F, unsigned ItNum);
186
187     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
188       AU.addPreservedID(LCSSAID);
189       AU.setPreservesCFG();
190     }
191
192     TargetData *getTargetData() const { return TD; }
193
194     // Visitation implementation - Implement instruction combining for different
195     // instruction types.  The semantics are as follows:
196     // Return Value:
197     //    null        - No change was made
198     //     I          - Change was made, I is still valid, I may be dead though
199     //   otherwise    - Change was made, replace I with returned instruction
200     //
201     Instruction *visitAdd(BinaryOperator &I);
202     Instruction *visitFAdd(BinaryOperator &I);
203     Instruction *visitSub(BinaryOperator &I);
204     Instruction *visitFSub(BinaryOperator &I);
205     Instruction *visitMul(BinaryOperator &I);
206     Instruction *visitFMul(BinaryOperator &I);
207     Instruction *visitURem(BinaryOperator &I);
208     Instruction *visitSRem(BinaryOperator &I);
209     Instruction *visitFRem(BinaryOperator &I);
210     bool SimplifyDivRemOfSelect(BinaryOperator &I);
211     Instruction *commonRemTransforms(BinaryOperator &I);
212     Instruction *commonIRemTransforms(BinaryOperator &I);
213     Instruction *commonDivTransforms(BinaryOperator &I);
214     Instruction *commonIDivTransforms(BinaryOperator &I);
215     Instruction *visitUDiv(BinaryOperator &I);
216     Instruction *visitSDiv(BinaryOperator &I);
217     Instruction *visitFDiv(BinaryOperator &I);
218     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
219     Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
220     Instruction *visitAnd(BinaryOperator &I);
221     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
222     Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
223     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
224                                      Value *A, Value *B, Value *C);
225     Instruction *visitOr (BinaryOperator &I);
226     Instruction *visitXor(BinaryOperator &I);
227     Instruction *visitShl(BinaryOperator &I);
228     Instruction *visitAShr(BinaryOperator &I);
229     Instruction *visitLShr(BinaryOperator &I);
230     Instruction *commonShiftTransforms(BinaryOperator &I);
231     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
232                                       Constant *RHSC);
233     Instruction *visitFCmpInst(FCmpInst &I);
234     Instruction *visitICmpInst(ICmpInst &I);
235     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
236     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
237                                                 Instruction *LHS,
238                                                 ConstantInt *RHS);
239     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
240                                 ConstantInt *DivRHS);
241
242     Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
243                              ICmpInst::Predicate Cond, Instruction &I);
244     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
245                                      BinaryOperator &I);
246     Instruction *commonCastTransforms(CastInst &CI);
247     Instruction *commonIntCastTransforms(CastInst &CI);
248     Instruction *commonPointerCastTransforms(CastInst &CI);
249     Instruction *visitTrunc(TruncInst &CI);
250     Instruction *visitZExt(ZExtInst &CI);
251     Instruction *visitSExt(SExtInst &CI);
252     Instruction *visitFPTrunc(FPTruncInst &CI);
253     Instruction *visitFPExt(CastInst &CI);
254     Instruction *visitFPToUI(FPToUIInst &FI);
255     Instruction *visitFPToSI(FPToSIInst &FI);
256     Instruction *visitUIToFP(CastInst &CI);
257     Instruction *visitSIToFP(CastInst &CI);
258     Instruction *visitPtrToInt(PtrToIntInst &CI);
259     Instruction *visitIntToPtr(IntToPtrInst &CI);
260     Instruction *visitBitCast(BitCastInst &CI);
261     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
262                                 Instruction *FI);
263     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
264     Instruction *visitSelectInst(SelectInst &SI);
265     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
266     Instruction *visitCallInst(CallInst &CI);
267     Instruction *visitInvokeInst(InvokeInst &II);
268     Instruction *visitPHINode(PHINode &PN);
269     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
270     Instruction *visitAllocationInst(AllocationInst &AI);
271     Instruction *visitFreeInst(FreeInst &FI);
272     Instruction *visitLoadInst(LoadInst &LI);
273     Instruction *visitStoreInst(StoreInst &SI);
274     Instruction *visitBranchInst(BranchInst &BI);
275     Instruction *visitSwitchInst(SwitchInst &SI);
276     Instruction *visitInsertElementInst(InsertElementInst &IE);
277     Instruction *visitExtractElementInst(ExtractElementInst &EI);
278     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
279     Instruction *visitExtractValueInst(ExtractValueInst &EV);
280
281     // visitInstruction - Specify what to return for unhandled instructions...
282     Instruction *visitInstruction(Instruction &I) { return 0; }
283
284   private:
285     Instruction *visitCallSite(CallSite CS);
286     bool transformConstExprCastCall(CallSite CS);
287     Instruction *transformCallThroughTrampoline(CallSite CS);
288     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
289                                    bool DoXform = true);
290     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
291     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
292
293
294   public:
295     // InsertNewInstBefore - insert an instruction New before instruction Old
296     // in the program.  Add the new instruction to the worklist.
297     //
298     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
299       assert(New && New->getParent() == 0 &&
300              "New instruction already inserted into a basic block!");
301       BasicBlock *BB = Old.getParent();
302       BB->getInstList().insert(&Old, New);  // Insert inst
303       Worklist.Add(New);
304       return New;
305     }
306         
307     // ReplaceInstUsesWith - This method is to be used when an instruction is
308     // found to be dead, replacable with another preexisting expression.  Here
309     // we add all uses of I to the worklist, replace all uses of I with the new
310     // value, then return I, so that the inst combiner will know that I was
311     // modified.
312     //
313     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
314       Worklist.AddUsersToWorkList(I);   // Add all modified instrs to worklist.
315       
316       // If we are replacing the instruction with itself, this must be in a
317       // segment of unreachable code, so just clobber the instruction.
318       if (&I == V) 
319         V = UndefValue::get(I.getType());
320         
321       I.replaceAllUsesWith(V);
322       return &I;
323     }
324
325     // EraseInstFromFunction - When dealing with an instruction that has side
326     // effects or produces a void value, we can't rely on DCE to delete the
327     // instruction.  Instead, visit methods should return the value returned by
328     // this function.
329     Instruction *EraseInstFromFunction(Instruction &I) {
330       assert(I.use_empty() && "Cannot erase instruction that is used!");
331       // Make sure that we reprocess all operands now that we reduced their
332       // use counts.
333       if (I.getNumOperands() < 8) {
334         for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
335           if (Instruction *Op = dyn_cast<Instruction>(*i))
336             Worklist.Add(Op);
337       }
338       Worklist.Remove(&I);
339       I.eraseFromParent();
340       return 0;  // Don't do anything with FI
341     }
342         
343     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
344                            APInt &KnownOne, unsigned Depth = 0) const {
345       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
346     }
347     
348     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
349                            unsigned Depth = 0) const {
350       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
351     }
352     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
353       return llvm::ComputeNumSignBits(Op, TD, Depth);
354     }
355
356   private:
357
358     /// SimplifyCommutative - This performs a few simplifications for 
359     /// commutative operators.
360     bool SimplifyCommutative(BinaryOperator &I);
361
362     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
363     /// most-complex to least-complex order.
364     bool SimplifyCompare(CmpInst &I);
365
366     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
367     /// based on the demanded bits.
368     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
369                                    APInt& KnownZero, APInt& KnownOne,
370                                    unsigned Depth);
371     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
372                               APInt& KnownZero, APInt& KnownOne,
373                               unsigned Depth=0);
374         
375     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
376     /// SimplifyDemandedBits knows about.  See if the instruction has any
377     /// properties that allow us to simplify its operands.
378     bool SimplifyDemandedInstructionBits(Instruction &Inst);
379         
380     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
381                                       APInt& UndefElts, unsigned Depth = 0);
382       
383     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
384     // PHI node as operand #0, see if we can fold the instruction into the PHI
385     // (which is only possible if all operands to the PHI are constants).
386     Instruction *FoldOpIntoPhi(Instruction &I);
387
388     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
389     // operator and they all are only used by the PHI, PHI together their
390     // inputs, and do the operation once, to the result of the PHI.
391     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
392     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
393     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
394
395     
396     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
397                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
398     
399     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
400                               bool isSub, Instruction &I);
401     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
402                                  bool isSigned, bool Inside, Instruction &IB);
403     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
404     Instruction *MatchBSwap(BinaryOperator &I);
405     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
406     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
407     Instruction *SimplifyMemSet(MemSetInst *MI);
408
409
410     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
411
412     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
413                                     unsigned CastOpc, int &NumCastsRemoved);
414     unsigned GetOrEnforceKnownAlignment(Value *V,
415                                         unsigned PrefAlign = 0);
416
417   };
418 } // end anonymous namespace
419
420 char InstCombiner::ID = 0;
421 static RegisterPass<InstCombiner>
422 X("instcombine", "Combine redundant instructions");
423
424 // getComplexity:  Assign a complexity or rank value to LLVM Values...
425 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
426 static unsigned getComplexity(Value *V) {
427   if (isa<Instruction>(V)) {
428     if (BinaryOperator::isNeg(V) ||
429         BinaryOperator::isFNeg(V) ||
430         BinaryOperator::isNot(V))
431       return 3;
432     return 4;
433   }
434   if (isa<Argument>(V)) return 3;
435   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
436 }
437
438 // isOnlyUse - Return true if this instruction will be deleted if we stop using
439 // it.
440 static bool isOnlyUse(Value *V) {
441   return V->hasOneUse() || isa<Constant>(V);
442 }
443
444 // getPromotedType - Return the specified type promoted as it would be to pass
445 // though a va_arg area...
446 static const Type *getPromotedType(const Type *Ty) {
447   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
448     if (ITy->getBitWidth() < 32)
449       return Type::getInt32Ty(Ty->getContext());
450   }
451   return Ty;
452 }
453
454 /// getBitCastOperand - If the specified operand is a CastInst, a constant
455 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
456 /// operand value, otherwise return null.
457 static Value *getBitCastOperand(Value *V) {
458   if (Operator *O = dyn_cast<Operator>(V)) {
459     if (O->getOpcode() == Instruction::BitCast)
460       return O->getOperand(0);
461     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
462       if (GEP->hasAllZeroIndices())
463         return GEP->getPointerOperand();
464   }
465   return 0;
466 }
467
468 /// This function is a wrapper around CastInst::isEliminableCastPair. It
469 /// simply extracts arguments and returns what that function returns.
470 static Instruction::CastOps 
471 isEliminableCastPair(
472   const CastInst *CI, ///< The first cast instruction
473   unsigned opcode,       ///< The opcode of the second cast instruction
474   const Type *DstTy,     ///< The target type for the second cast instruction
475   TargetData *TD         ///< The target data for pointer size
476 ) {
477
478   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
479   const Type *MidTy = CI->getType();                  // B from above
480
481   // Get the opcodes of the two Cast instructions
482   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
483   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
484
485   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
486                                                 DstTy,
487                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
488   
489   // We don't want to form an inttoptr or ptrtoint that converts to an integer
490   // type that differs from the pointer size.
491   if ((Res == Instruction::IntToPtr &&
492           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
493       (Res == Instruction::PtrToInt &&
494           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
495     Res = 0;
496   
497   return Instruction::CastOps(Res);
498 }
499
500 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
501 /// in any code being generated.  It does not require codegen if V is simple
502 /// enough or if the cast can be folded into other casts.
503 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
504                               const Type *Ty, TargetData *TD) {
505   if (V->getType() == Ty || isa<Constant>(V)) return false;
506   
507   // If this is another cast that can be eliminated, it isn't codegen either.
508   if (const CastInst *CI = dyn_cast<CastInst>(V))
509     if (isEliminableCastPair(CI, opcode, Ty, TD))
510       return false;
511   return true;
512 }
513
514 // SimplifyCommutative - This performs a few simplifications for commutative
515 // operators:
516 //
517 //  1. Order operands such that they are listed from right (least complex) to
518 //     left (most complex).  This puts constants before unary operators before
519 //     binary operators.
520 //
521 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
522 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
523 //
524 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
525   bool Changed = false;
526   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
527     Changed = !I.swapOperands();
528
529   if (!I.isAssociative()) return Changed;
530   Instruction::BinaryOps Opcode = I.getOpcode();
531   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
532     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
533       if (isa<Constant>(I.getOperand(1))) {
534         Constant *Folded = ConstantExpr::get(I.getOpcode(),
535                                              cast<Constant>(I.getOperand(1)),
536                                              cast<Constant>(Op->getOperand(1)));
537         I.setOperand(0, Op->getOperand(0));
538         I.setOperand(1, Folded);
539         return true;
540       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
541         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
542             isOnlyUse(Op) && isOnlyUse(Op1)) {
543           Constant *C1 = cast<Constant>(Op->getOperand(1));
544           Constant *C2 = cast<Constant>(Op1->getOperand(1));
545
546           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
547           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
548           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
549                                                     Op1->getOperand(0),
550                                                     Op1->getName(), &I);
551           Worklist.Add(New);
552           I.setOperand(0, New);
553           I.setOperand(1, Folded);
554           return true;
555         }
556     }
557   return Changed;
558 }
559
560 /// SimplifyCompare - For a CmpInst this function just orders the operands
561 /// so that theyare listed from right (least complex) to left (most complex).
562 /// This puts constants before unary operators before binary operators.
563 bool InstCombiner::SimplifyCompare(CmpInst &I) {
564   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
565     return false;
566   I.swapOperands();
567   // Compare instructions are not associative so there's nothing else we can do.
568   return true;
569 }
570
571 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
572 // if the LHS is a constant zero (which is the 'negate' form).
573 //
574 static inline Value *dyn_castNegVal(Value *V) {
575   if (BinaryOperator::isNeg(V))
576     return BinaryOperator::getNegArgument(V);
577
578   // Constants can be considered to be negated values if they can be folded.
579   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
580     return ConstantExpr::getNeg(C);
581
582   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
583     if (C->getType()->getElementType()->isInteger())
584       return ConstantExpr::getNeg(C);
585
586   return 0;
587 }
588
589 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
590 // instruction if the LHS is a constant negative zero (which is the 'negate'
591 // form).
592 //
593 static inline Value *dyn_castFNegVal(Value *V) {
594   if (BinaryOperator::isFNeg(V))
595     return BinaryOperator::getFNegArgument(V);
596
597   // Constants can be considered to be negated values if they can be folded.
598   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
599     return ConstantExpr::getFNeg(C);
600
601   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
602     if (C->getType()->getElementType()->isFloatingPoint())
603       return ConstantExpr::getFNeg(C);
604
605   return 0;
606 }
607
608 static inline Value *dyn_castNotVal(Value *V) {
609   if (BinaryOperator::isNot(V))
610     return BinaryOperator::getNotArgument(V);
611
612   // Constants can be considered to be not'ed values...
613   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
614     return ConstantInt::get(C->getType(), ~C->getValue());
615   return 0;
616 }
617
618 // dyn_castFoldableMul - If this value is a multiply that can be folded into
619 // other computations (because it has a constant operand), return the
620 // non-constant operand of the multiply, and set CST to point to the multiplier.
621 // Otherwise, return null.
622 //
623 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
624   if (V->hasOneUse() && V->getType()->isInteger())
625     if (Instruction *I = dyn_cast<Instruction>(V)) {
626       if (I->getOpcode() == Instruction::Mul)
627         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
628           return I->getOperand(0);
629       if (I->getOpcode() == Instruction::Shl)
630         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
631           // The multiplier is really 1 << CST.
632           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
633           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
634           CST = ConstantInt::get(V->getType()->getContext(),
635                                  APInt(BitWidth, 1).shl(CSTVal));
636           return I->getOperand(0);
637         }
638     }
639   return 0;
640 }
641
642 /// AddOne - Add one to a ConstantInt
643 static Constant *AddOne(Constant *C) {
644   return ConstantExpr::getAdd(C, 
645     ConstantInt::get(C->getType(), 1));
646 }
647 /// SubOne - Subtract one from a ConstantInt
648 static Constant *SubOne(ConstantInt *C) {
649   return ConstantExpr::getSub(C, 
650     ConstantInt::get(C->getType(), 1));
651 }
652 /// MultiplyOverflows - True if the multiply can not be expressed in an int
653 /// this size.
654 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
655   uint32_t W = C1->getBitWidth();
656   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
657   if (sign) {
658     LHSExt.sext(W * 2);
659     RHSExt.sext(W * 2);
660   } else {
661     LHSExt.zext(W * 2);
662     RHSExt.zext(W * 2);
663   }
664
665   APInt MulExt = LHSExt * RHSExt;
666
667   if (sign) {
668     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
669     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
670     return MulExt.slt(Min) || MulExt.sgt(Max);
671   } else 
672     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
673 }
674
675
676 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
677 /// specified instruction is a constant integer.  If so, check to see if there
678 /// are any bits set in the constant that are not demanded.  If so, shrink the
679 /// constant and return true.
680 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
681                                    APInt Demanded) {
682   assert(I && "No instruction?");
683   assert(OpNo < I->getNumOperands() && "Operand index too large");
684
685   // If the operand is not a constant integer, nothing to do.
686   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
687   if (!OpC) return false;
688
689   // If there are no bits set that aren't demanded, nothing to do.
690   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
691   if ((~Demanded & OpC->getValue()) == 0)
692     return false;
693
694   // This instruction is producing bits that are not demanded. Shrink the RHS.
695   Demanded &= OpC->getValue();
696   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
697   return true;
698 }
699
700 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
701 // set of known zero and one bits, compute the maximum and minimum values that
702 // could have the specified known zero and known one bits, returning them in
703 // min/max.
704 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
705                                                    const APInt& KnownOne,
706                                                    APInt& Min, APInt& Max) {
707   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
708          KnownZero.getBitWidth() == Min.getBitWidth() &&
709          KnownZero.getBitWidth() == Max.getBitWidth() &&
710          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
711   APInt UnknownBits = ~(KnownZero|KnownOne);
712
713   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
714   // bit if it is unknown.
715   Min = KnownOne;
716   Max = KnownOne|UnknownBits;
717   
718   if (UnknownBits.isNegative()) { // Sign bit is unknown
719     Min.set(Min.getBitWidth()-1);
720     Max.clear(Max.getBitWidth()-1);
721   }
722 }
723
724 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
725 // a set of known zero and one bits, compute the maximum and minimum values that
726 // could have the specified known zero and known one bits, returning them in
727 // min/max.
728 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
729                                                      const APInt &KnownOne,
730                                                      APInt &Min, APInt &Max) {
731   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
732          KnownZero.getBitWidth() == Min.getBitWidth() &&
733          KnownZero.getBitWidth() == Max.getBitWidth() &&
734          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
735   APInt UnknownBits = ~(KnownZero|KnownOne);
736   
737   // The minimum value is when the unknown bits are all zeros.
738   Min = KnownOne;
739   // The maximum value is when the unknown bits are all ones.
740   Max = KnownOne|UnknownBits;
741 }
742
743 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
744 /// SimplifyDemandedBits knows about.  See if the instruction has any
745 /// properties that allow us to simplify its operands.
746 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
747   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
748   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
749   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
750   
751   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
752                                      KnownZero, KnownOne, 0);
753   if (V == 0) return false;
754   if (V == &Inst) return true;
755   ReplaceInstUsesWith(Inst, V);
756   return true;
757 }
758
759 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
760 /// specified instruction operand if possible, updating it in place.  It returns
761 /// true if it made any change and false otherwise.
762 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
763                                         APInt &KnownZero, APInt &KnownOne,
764                                         unsigned Depth) {
765   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
766                                           KnownZero, KnownOne, Depth);
767   if (NewVal == 0) return false;
768   U.set(NewVal);
769   return true;
770 }
771
772
773 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
774 /// value based on the demanded bits.  When this function is called, it is known
775 /// that only the bits set in DemandedMask of the result of V are ever used
776 /// downstream. Consequently, depending on the mask and V, it may be possible
777 /// to replace V with a constant or one of its operands. In such cases, this
778 /// function does the replacement and returns true. In all other cases, it
779 /// returns false after analyzing the expression and setting KnownOne and known
780 /// to be one in the expression.  KnownZero contains all the bits that are known
781 /// to be zero in the expression. These are provided to potentially allow the
782 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
783 /// the expression. KnownOne and KnownZero always follow the invariant that 
784 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
785 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
786 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
787 /// and KnownOne must all be the same.
788 ///
789 /// This returns null if it did not change anything and it permits no
790 /// simplification.  This returns V itself if it did some simplification of V's
791 /// operands based on the information about what bits are demanded. This returns
792 /// some other non-null value if it found out that V is equal to another value
793 /// in the context where the specified bits are demanded, but not for all users.
794 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
795                                              APInt &KnownZero, APInt &KnownOne,
796                                              unsigned Depth) {
797   assert(V != 0 && "Null pointer of Value???");
798   assert(Depth <= 6 && "Limit Search Depth");
799   uint32_t BitWidth = DemandedMask.getBitWidth();
800   const Type *VTy = V->getType();
801   assert((TD || !isa<PointerType>(VTy)) &&
802          "SimplifyDemandedBits needs to know bit widths!");
803   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
804          (!VTy->isIntOrIntVector() ||
805           VTy->getScalarSizeInBits() == BitWidth) &&
806          KnownZero.getBitWidth() == BitWidth &&
807          KnownOne.getBitWidth() == BitWidth &&
808          "Value *V, DemandedMask, KnownZero and KnownOne "
809          "must have same BitWidth");
810   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
811     // We know all of the bits for a constant!
812     KnownOne = CI->getValue() & DemandedMask;
813     KnownZero = ~KnownOne & DemandedMask;
814     return 0;
815   }
816   if (isa<ConstantPointerNull>(V)) {
817     // We know all of the bits for a constant!
818     KnownOne.clear();
819     KnownZero = DemandedMask;
820     return 0;
821   }
822
823   KnownZero.clear();
824   KnownOne.clear();
825   if (DemandedMask == 0) {   // Not demanding any bits from V.
826     if (isa<UndefValue>(V))
827       return 0;
828     return UndefValue::get(VTy);
829   }
830   
831   if (Depth == 6)        // Limit search depth.
832     return 0;
833   
834   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
835   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
836
837   Instruction *I = dyn_cast<Instruction>(V);
838   if (!I) {
839     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
840     return 0;        // Only analyze instructions.
841   }
842
843   // If there are multiple uses of this value and we aren't at the root, then
844   // we can't do any simplifications of the operands, because DemandedMask
845   // only reflects the bits demanded by *one* of the users.
846   if (Depth != 0 && !I->hasOneUse()) {
847     // Despite the fact that we can't simplify this instruction in all User's
848     // context, we can at least compute the knownzero/knownone bits, and we can
849     // do simplifications that apply to *just* the one user if we know that
850     // this instruction has a simpler value in that context.
851     if (I->getOpcode() == Instruction::And) {
852       // If either the LHS or the RHS are Zero, the result is zero.
853       ComputeMaskedBits(I->getOperand(1), DemandedMask,
854                         RHSKnownZero, RHSKnownOne, Depth+1);
855       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
856                         LHSKnownZero, LHSKnownOne, Depth+1);
857       
858       // If all of the demanded bits are known 1 on one side, return the other.
859       // These bits cannot contribute to the result of the 'and' in this
860       // context.
861       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
862           (DemandedMask & ~LHSKnownZero))
863         return I->getOperand(0);
864       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
865           (DemandedMask & ~RHSKnownZero))
866         return I->getOperand(1);
867       
868       // If all of the demanded bits in the inputs are known zeros, return zero.
869       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
870         return Constant::getNullValue(VTy);
871       
872     } else if (I->getOpcode() == Instruction::Or) {
873       // We can simplify (X|Y) -> X or Y in the user's context if we know that
874       // only bits from X or Y are demanded.
875       
876       // If either the LHS or the RHS are One, the result is One.
877       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
878                         RHSKnownZero, RHSKnownOne, Depth+1);
879       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
880                         LHSKnownZero, LHSKnownOne, Depth+1);
881       
882       // If all of the demanded bits are known zero on one side, return the
883       // other.  These bits cannot contribute to the result of the 'or' in this
884       // context.
885       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
886           (DemandedMask & ~LHSKnownOne))
887         return I->getOperand(0);
888       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
889           (DemandedMask & ~RHSKnownOne))
890         return I->getOperand(1);
891       
892       // If all of the potentially set bits on one side are known to be set on
893       // the other side, just use the 'other' side.
894       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
895           (DemandedMask & (~RHSKnownZero)))
896         return I->getOperand(0);
897       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
898           (DemandedMask & (~LHSKnownZero)))
899         return I->getOperand(1);
900     }
901     
902     // Compute the KnownZero/KnownOne bits to simplify things downstream.
903     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
904     return 0;
905   }
906   
907   // If this is the root being simplified, allow it to have multiple uses,
908   // just set the DemandedMask to all bits so that we can try to simplify the
909   // operands.  This allows visitTruncInst (for example) to simplify the
910   // operand of a trunc without duplicating all the logic below.
911   if (Depth == 0 && !V->hasOneUse())
912     DemandedMask = APInt::getAllOnesValue(BitWidth);
913   
914   switch (I->getOpcode()) {
915   default:
916     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
917     break;
918   case Instruction::And:
919     // If either the LHS or the RHS are Zero, the result is zero.
920     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
921                              RHSKnownZero, RHSKnownOne, Depth+1) ||
922         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
923                              LHSKnownZero, LHSKnownOne, Depth+1))
924       return I;
925     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
926     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
927
928     // If all of the demanded bits are known 1 on one side, return the other.
929     // These bits cannot contribute to the result of the 'and'.
930     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
931         (DemandedMask & ~LHSKnownZero))
932       return I->getOperand(0);
933     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
934         (DemandedMask & ~RHSKnownZero))
935       return I->getOperand(1);
936     
937     // If all of the demanded bits in the inputs are known zeros, return zero.
938     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
939       return Constant::getNullValue(VTy);
940       
941     // If the RHS is a constant, see if we can simplify it.
942     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
943       return I;
944       
945     // Output known-1 bits are only known if set in both the LHS & RHS.
946     RHSKnownOne &= LHSKnownOne;
947     // Output known-0 are known to be clear if zero in either the LHS | RHS.
948     RHSKnownZero |= LHSKnownZero;
949     break;
950   case Instruction::Or:
951     // If either the LHS or the RHS are One, the result is One.
952     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
953                              RHSKnownZero, RHSKnownOne, Depth+1) ||
954         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
955                              LHSKnownZero, LHSKnownOne, Depth+1))
956       return I;
957     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
958     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
959     
960     // If all of the demanded bits are known zero on one side, return the other.
961     // These bits cannot contribute to the result of the 'or'.
962     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
963         (DemandedMask & ~LHSKnownOne))
964       return I->getOperand(0);
965     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
966         (DemandedMask & ~RHSKnownOne))
967       return I->getOperand(1);
968
969     // If all of the potentially set bits on one side are known to be set on
970     // the other side, just use the 'other' side.
971     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
972         (DemandedMask & (~RHSKnownZero)))
973       return I->getOperand(0);
974     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
975         (DemandedMask & (~LHSKnownZero)))
976       return I->getOperand(1);
977         
978     // If the RHS is a constant, see if we can simplify it.
979     if (ShrinkDemandedConstant(I, 1, DemandedMask))
980       return I;
981           
982     // Output known-0 bits are only known if clear in both the LHS & RHS.
983     RHSKnownZero &= LHSKnownZero;
984     // Output known-1 are known to be set if set in either the LHS | RHS.
985     RHSKnownOne |= LHSKnownOne;
986     break;
987   case Instruction::Xor: {
988     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
989                              RHSKnownZero, RHSKnownOne, Depth+1) ||
990         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
991                              LHSKnownZero, LHSKnownOne, Depth+1))
992       return I;
993     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
994     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
995     
996     // If all of the demanded bits are known zero on one side, return the other.
997     // These bits cannot contribute to the result of the 'xor'.
998     if ((DemandedMask & RHSKnownZero) == DemandedMask)
999       return I->getOperand(0);
1000     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1001       return I->getOperand(1);
1002     
1003     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1004     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1005                          (RHSKnownOne & LHSKnownOne);
1006     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1007     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1008                         (RHSKnownOne & LHSKnownZero);
1009     
1010     // If all of the demanded bits are known to be zero on one side or the
1011     // other, turn this into an *inclusive* or.
1012     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1013     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0)
1014       return Builder->CreateOr(I->getOperand(0), I->getOperand(1),I->getName());
1015     
1016     // If all of the demanded bits on one side are known, and all of the set
1017     // bits on that side are also known to be set on the other side, turn this
1018     // into an AND, as we know the bits will be cleared.
1019     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1020     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1021       // all known
1022       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1023         Constant *AndC = Constant::getIntegerValue(VTy,
1024                                                    ~RHSKnownOne & DemandedMask);
1025         Instruction *And = 
1026           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1027         return InsertNewInstBefore(And, *I);
1028       }
1029     }
1030     
1031     // If the RHS is a constant, see if we can simplify it.
1032     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1033     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1034       return I;
1035     
1036     RHSKnownZero = KnownZeroOut;
1037     RHSKnownOne  = KnownOneOut;
1038     break;
1039   }
1040   case Instruction::Select:
1041     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1042                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1043         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1044                              LHSKnownZero, LHSKnownOne, Depth+1))
1045       return I;
1046     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1047     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1048     
1049     // If the operands are constants, see if we can simplify them.
1050     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1051         ShrinkDemandedConstant(I, 2, DemandedMask))
1052       return I;
1053     
1054     // Only known if known in both the LHS and RHS.
1055     RHSKnownOne &= LHSKnownOne;
1056     RHSKnownZero &= LHSKnownZero;
1057     break;
1058   case Instruction::Trunc: {
1059     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1060     DemandedMask.zext(truncBf);
1061     RHSKnownZero.zext(truncBf);
1062     RHSKnownOne.zext(truncBf);
1063     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1064                              RHSKnownZero, RHSKnownOne, Depth+1))
1065       return I;
1066     DemandedMask.trunc(BitWidth);
1067     RHSKnownZero.trunc(BitWidth);
1068     RHSKnownOne.trunc(BitWidth);
1069     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1070     break;
1071   }
1072   case Instruction::BitCast:
1073     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1074       return false;  // vector->int or fp->int?
1075
1076     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1077       if (const VectorType *SrcVTy =
1078             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1079         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1080           // Don't touch a bitcast between vectors of different element counts.
1081           return false;
1082       } else
1083         // Don't touch a scalar-to-vector bitcast.
1084         return false;
1085     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1086       // Don't touch a vector-to-scalar bitcast.
1087       return false;
1088
1089     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1090                              RHSKnownZero, RHSKnownOne, Depth+1))
1091       return I;
1092     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1093     break;
1094   case Instruction::ZExt: {
1095     // Compute the bits in the result that are not present in the input.
1096     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1097     
1098     DemandedMask.trunc(SrcBitWidth);
1099     RHSKnownZero.trunc(SrcBitWidth);
1100     RHSKnownOne.trunc(SrcBitWidth);
1101     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1102                              RHSKnownZero, RHSKnownOne, Depth+1))
1103       return I;
1104     DemandedMask.zext(BitWidth);
1105     RHSKnownZero.zext(BitWidth);
1106     RHSKnownOne.zext(BitWidth);
1107     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1108     // The top bits are known to be zero.
1109     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1110     break;
1111   }
1112   case Instruction::SExt: {
1113     // Compute the bits in the result that are not present in the input.
1114     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1115     
1116     APInt InputDemandedBits = DemandedMask & 
1117                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1118
1119     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1120     // If any of the sign extended bits are demanded, we know that the sign
1121     // bit is demanded.
1122     if ((NewBits & DemandedMask) != 0)
1123       InputDemandedBits.set(SrcBitWidth-1);
1124       
1125     InputDemandedBits.trunc(SrcBitWidth);
1126     RHSKnownZero.trunc(SrcBitWidth);
1127     RHSKnownOne.trunc(SrcBitWidth);
1128     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1129                              RHSKnownZero, RHSKnownOne, Depth+1))
1130       return I;
1131     InputDemandedBits.zext(BitWidth);
1132     RHSKnownZero.zext(BitWidth);
1133     RHSKnownOne.zext(BitWidth);
1134     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1135       
1136     // If the sign bit of the input is known set or clear, then we know the
1137     // top bits of the result.
1138
1139     // If the input sign bit is known zero, or if the NewBits are not demanded
1140     // convert this into a zero extension.
1141     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1142       // Convert to ZExt cast
1143       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1144       return InsertNewInstBefore(NewCast, *I);
1145     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1146       RHSKnownOne |= NewBits;
1147     }
1148     break;
1149   }
1150   case Instruction::Add: {
1151     // Figure out what the input bits are.  If the top bits of the and result
1152     // are not demanded, then the add doesn't demand them from its input
1153     // either.
1154     unsigned NLZ = DemandedMask.countLeadingZeros();
1155       
1156     // If there is a constant on the RHS, there are a variety of xformations
1157     // we can do.
1158     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1159       // If null, this should be simplified elsewhere.  Some of the xforms here
1160       // won't work if the RHS is zero.
1161       if (RHS->isZero())
1162         break;
1163       
1164       // If the top bit of the output is demanded, demand everything from the
1165       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1166       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1167
1168       // Find information about known zero/one bits in the input.
1169       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1170                                LHSKnownZero, LHSKnownOne, Depth+1))
1171         return I;
1172
1173       // If the RHS of the add has bits set that can't affect the input, reduce
1174       // the constant.
1175       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1176         return I;
1177       
1178       // Avoid excess work.
1179       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1180         break;
1181       
1182       // Turn it into OR if input bits are zero.
1183       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1184         Instruction *Or =
1185           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1186                                    I->getName());
1187         return InsertNewInstBefore(Or, *I);
1188       }
1189       
1190       // We can say something about the output known-zero and known-one bits,
1191       // depending on potential carries from the input constant and the
1192       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1193       // bits set and the RHS constant is 0x01001, then we know we have a known
1194       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1195       
1196       // To compute this, we first compute the potential carry bits.  These are
1197       // the bits which may be modified.  I'm not aware of a better way to do
1198       // this scan.
1199       const APInt &RHSVal = RHS->getValue();
1200       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1201       
1202       // Now that we know which bits have carries, compute the known-1/0 sets.
1203       
1204       // Bits are known one if they are known zero in one operand and one in the
1205       // other, and there is no input carry.
1206       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1207                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1208       
1209       // Bits are known zero if they are known zero in both operands and there
1210       // is no input carry.
1211       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1212     } else {
1213       // If the high-bits of this ADD are not demanded, then it does not demand
1214       // the high bits of its LHS or RHS.
1215       if (DemandedMask[BitWidth-1] == 0) {
1216         // Right fill the mask of bits for this ADD to demand the most
1217         // significant bit and all those below it.
1218         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1219         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1220                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1221             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1222                                  LHSKnownZero, LHSKnownOne, Depth+1))
1223           return I;
1224       }
1225     }
1226     break;
1227   }
1228   case Instruction::Sub:
1229     // If the high-bits of this SUB are not demanded, then it does not demand
1230     // the high bits of its LHS or RHS.
1231     if (DemandedMask[BitWidth-1] == 0) {
1232       // Right fill the mask of bits for this SUB to demand the most
1233       // significant bit and all those below it.
1234       uint32_t NLZ = DemandedMask.countLeadingZeros();
1235       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1236       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1237                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1238           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1239                                LHSKnownZero, LHSKnownOne, Depth+1))
1240         return I;
1241     }
1242     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1243     // the known zeros and ones.
1244     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1245     break;
1246   case Instruction::Shl:
1247     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1248       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1249       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1250       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1251                                RHSKnownZero, RHSKnownOne, Depth+1))
1252         return I;
1253       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1254       RHSKnownZero <<= ShiftAmt;
1255       RHSKnownOne  <<= ShiftAmt;
1256       // low bits known zero.
1257       if (ShiftAmt)
1258         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1259     }
1260     break;
1261   case Instruction::LShr:
1262     // For a logical shift right
1263     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1264       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1265       
1266       // Unsigned shift right.
1267       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1268       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1269                                RHSKnownZero, RHSKnownOne, Depth+1))
1270         return I;
1271       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1272       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1273       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1274       if (ShiftAmt) {
1275         // Compute the new bits that are at the top now.
1276         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1277         RHSKnownZero |= HighBits;  // high bits known zero.
1278       }
1279     }
1280     break;
1281   case Instruction::AShr:
1282     // If this is an arithmetic shift right and only the low-bit is set, we can
1283     // always convert this into a logical shr, even if the shift amount is
1284     // variable.  The low bit of the shift cannot be an input sign bit unless
1285     // the shift amount is >= the size of the datatype, which is undefined.
1286     if (DemandedMask == 1) {
1287       // Perform the logical shift right.
1288       Instruction *NewVal = BinaryOperator::CreateLShr(
1289                         I->getOperand(0), I->getOperand(1), I->getName());
1290       return InsertNewInstBefore(NewVal, *I);
1291     }    
1292
1293     // If the sign bit is the only bit demanded by this ashr, then there is no
1294     // need to do it, the shift doesn't change the high bit.
1295     if (DemandedMask.isSignBit())
1296       return I->getOperand(0);
1297     
1298     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1299       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1300       
1301       // Signed shift right.
1302       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1303       // If any of the "high bits" are demanded, we should set the sign bit as
1304       // demanded.
1305       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1306         DemandedMaskIn.set(BitWidth-1);
1307       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1308                                RHSKnownZero, RHSKnownOne, Depth+1))
1309         return I;
1310       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1311       // Compute the new bits that are at the top now.
1312       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1313       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1314       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1315         
1316       // Handle the sign bits.
1317       APInt SignBit(APInt::getSignBit(BitWidth));
1318       // Adjust to where it is now in the mask.
1319       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1320         
1321       // If the input sign bit is known to be zero, or if none of the top bits
1322       // are demanded, turn this into an unsigned shift right.
1323       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1324           (HighBits & ~DemandedMask) == HighBits) {
1325         // Perform the logical shift right.
1326         Instruction *NewVal = BinaryOperator::CreateLShr(
1327                           I->getOperand(0), SA, I->getName());
1328         return InsertNewInstBefore(NewVal, *I);
1329       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1330         RHSKnownOne |= HighBits;
1331       }
1332     }
1333     break;
1334   case Instruction::SRem:
1335     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1336       APInt RA = Rem->getValue().abs();
1337       if (RA.isPowerOf2()) {
1338         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1339           return I->getOperand(0);
1340
1341         APInt LowBits = RA - 1;
1342         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1343         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1344                                  LHSKnownZero, LHSKnownOne, Depth+1))
1345           return I;
1346
1347         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1348           LHSKnownZero |= ~LowBits;
1349
1350         KnownZero |= LHSKnownZero & DemandedMask;
1351
1352         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1353       }
1354     }
1355     break;
1356   case Instruction::URem: {
1357     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1358     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1359     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1360                              KnownZero2, KnownOne2, Depth+1) ||
1361         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1362                              KnownZero2, KnownOne2, Depth+1))
1363       return I;
1364
1365     unsigned Leaders = KnownZero2.countLeadingOnes();
1366     Leaders = std::max(Leaders,
1367                        KnownZero2.countLeadingOnes());
1368     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1369     break;
1370   }
1371   case Instruction::Call:
1372     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1373       switch (II->getIntrinsicID()) {
1374       default: break;
1375       case Intrinsic::bswap: {
1376         // If the only bits demanded come from one byte of the bswap result,
1377         // just shift the input byte into position to eliminate the bswap.
1378         unsigned NLZ = DemandedMask.countLeadingZeros();
1379         unsigned NTZ = DemandedMask.countTrailingZeros();
1380           
1381         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1382         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1383         // have 14 leading zeros, round to 8.
1384         NLZ &= ~7;
1385         NTZ &= ~7;
1386         // If we need exactly one byte, we can do this transformation.
1387         if (BitWidth-NLZ-NTZ == 8) {
1388           unsigned ResultBit = NTZ;
1389           unsigned InputBit = BitWidth-NTZ-8;
1390           
1391           // Replace this with either a left or right shift to get the byte into
1392           // the right place.
1393           Instruction *NewVal;
1394           if (InputBit > ResultBit)
1395             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1396                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1397           else
1398             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1399                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1400           NewVal->takeName(I);
1401           return InsertNewInstBefore(NewVal, *I);
1402         }
1403           
1404         // TODO: Could compute known zero/one bits based on the input.
1405         break;
1406       }
1407       }
1408     }
1409     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1410     break;
1411   }
1412   
1413   // If the client is only demanding bits that we know, return the known
1414   // constant.
1415   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1416     return Constant::getIntegerValue(VTy, RHSKnownOne);
1417   return false;
1418 }
1419
1420
1421 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1422 /// any number of elements. DemandedElts contains the set of elements that are
1423 /// actually used by the caller.  This method analyzes which elements of the
1424 /// operand are undef and returns that information in UndefElts.
1425 ///
1426 /// If the information about demanded elements can be used to simplify the
1427 /// operation, the operation is simplified, then the resultant value is
1428 /// returned.  This returns null if no change was made.
1429 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1430                                                 APInt& UndefElts,
1431                                                 unsigned Depth) {
1432   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1433   APInt EltMask(APInt::getAllOnesValue(VWidth));
1434   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1435
1436   if (isa<UndefValue>(V)) {
1437     // If the entire vector is undefined, just return this info.
1438     UndefElts = EltMask;
1439     return 0;
1440   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1441     UndefElts = EltMask;
1442     return UndefValue::get(V->getType());
1443   }
1444
1445   UndefElts = 0;
1446   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1447     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1448     Constant *Undef = UndefValue::get(EltTy);
1449
1450     std::vector<Constant*> Elts;
1451     for (unsigned i = 0; i != VWidth; ++i)
1452       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1453         Elts.push_back(Undef);
1454         UndefElts.set(i);
1455       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1456         Elts.push_back(Undef);
1457         UndefElts.set(i);
1458       } else {                               // Otherwise, defined.
1459         Elts.push_back(CP->getOperand(i));
1460       }
1461
1462     // If we changed the constant, return it.
1463     Constant *NewCP = ConstantVector::get(Elts);
1464     return NewCP != CP ? NewCP : 0;
1465   } else if (isa<ConstantAggregateZero>(V)) {
1466     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1467     // set to undef.
1468     
1469     // Check if this is identity. If so, return 0 since we are not simplifying
1470     // anything.
1471     if (DemandedElts == ((1ULL << VWidth) -1))
1472       return 0;
1473     
1474     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1475     Constant *Zero = Constant::getNullValue(EltTy);
1476     Constant *Undef = UndefValue::get(EltTy);
1477     std::vector<Constant*> Elts;
1478     for (unsigned i = 0; i != VWidth; ++i) {
1479       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1480       Elts.push_back(Elt);
1481     }
1482     UndefElts = DemandedElts ^ EltMask;
1483     return ConstantVector::get(Elts);
1484   }
1485   
1486   // Limit search depth.
1487   if (Depth == 10)
1488     return 0;
1489
1490   // If multiple users are using the root value, procede with
1491   // simplification conservatively assuming that all elements
1492   // are needed.
1493   if (!V->hasOneUse()) {
1494     // Quit if we find multiple users of a non-root value though.
1495     // They'll be handled when it's their turn to be visited by
1496     // the main instcombine process.
1497     if (Depth != 0)
1498       // TODO: Just compute the UndefElts information recursively.
1499       return 0;
1500
1501     // Conservatively assume that all elements are needed.
1502     DemandedElts = EltMask;
1503   }
1504   
1505   Instruction *I = dyn_cast<Instruction>(V);
1506   if (!I) return 0;        // Only analyze instructions.
1507   
1508   bool MadeChange = false;
1509   APInt UndefElts2(VWidth, 0);
1510   Value *TmpV;
1511   switch (I->getOpcode()) {
1512   default: break;
1513     
1514   case Instruction::InsertElement: {
1515     // If this is a variable index, we don't know which element it overwrites.
1516     // demand exactly the same input as we produce.
1517     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1518     if (Idx == 0) {
1519       // Note that we can't propagate undef elt info, because we don't know
1520       // which elt is getting updated.
1521       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1522                                         UndefElts2, Depth+1);
1523       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1524       break;
1525     }
1526     
1527     // If this is inserting an element that isn't demanded, remove this
1528     // insertelement.
1529     unsigned IdxNo = Idx->getZExtValue();
1530     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1531       Worklist.Add(I);
1532       return I->getOperand(0);
1533     }
1534     
1535     // Otherwise, the element inserted overwrites whatever was there, so the
1536     // input demanded set is simpler than the output set.
1537     APInt DemandedElts2 = DemandedElts;
1538     DemandedElts2.clear(IdxNo);
1539     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1540                                       UndefElts, Depth+1);
1541     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1542
1543     // The inserted element is defined.
1544     UndefElts.clear(IdxNo);
1545     break;
1546   }
1547   case Instruction::ShuffleVector: {
1548     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1549     uint64_t LHSVWidth =
1550       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1551     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1552     for (unsigned i = 0; i < VWidth; i++) {
1553       if (DemandedElts[i]) {
1554         unsigned MaskVal = Shuffle->getMaskValue(i);
1555         if (MaskVal != -1u) {
1556           assert(MaskVal < LHSVWidth * 2 &&
1557                  "shufflevector mask index out of range!");
1558           if (MaskVal < LHSVWidth)
1559             LeftDemanded.set(MaskVal);
1560           else
1561             RightDemanded.set(MaskVal - LHSVWidth);
1562         }
1563       }
1564     }
1565
1566     APInt UndefElts4(LHSVWidth, 0);
1567     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1568                                       UndefElts4, Depth+1);
1569     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1570
1571     APInt UndefElts3(LHSVWidth, 0);
1572     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1573                                       UndefElts3, Depth+1);
1574     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1575
1576     bool NewUndefElts = false;
1577     for (unsigned i = 0; i < VWidth; i++) {
1578       unsigned MaskVal = Shuffle->getMaskValue(i);
1579       if (MaskVal == -1u) {
1580         UndefElts.set(i);
1581       } else if (MaskVal < LHSVWidth) {
1582         if (UndefElts4[MaskVal]) {
1583           NewUndefElts = true;
1584           UndefElts.set(i);
1585         }
1586       } else {
1587         if (UndefElts3[MaskVal - LHSVWidth]) {
1588           NewUndefElts = true;
1589           UndefElts.set(i);
1590         }
1591       }
1592     }
1593
1594     if (NewUndefElts) {
1595       // Add additional discovered undefs.
1596       std::vector<Constant*> Elts;
1597       for (unsigned i = 0; i < VWidth; ++i) {
1598         if (UndefElts[i])
1599           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1600         else
1601           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1602                                           Shuffle->getMaskValue(i)));
1603       }
1604       I->setOperand(2, ConstantVector::get(Elts));
1605       MadeChange = true;
1606     }
1607     break;
1608   }
1609   case Instruction::BitCast: {
1610     // Vector->vector casts only.
1611     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1612     if (!VTy) break;
1613     unsigned InVWidth = VTy->getNumElements();
1614     APInt InputDemandedElts(InVWidth, 0);
1615     unsigned Ratio;
1616
1617     if (VWidth == InVWidth) {
1618       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1619       // elements as are demanded of us.
1620       Ratio = 1;
1621       InputDemandedElts = DemandedElts;
1622     } else if (VWidth > InVWidth) {
1623       // Untested so far.
1624       break;
1625       
1626       // If there are more elements in the result than there are in the source,
1627       // then an input element is live if any of the corresponding output
1628       // elements are live.
1629       Ratio = VWidth/InVWidth;
1630       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1631         if (DemandedElts[OutIdx])
1632           InputDemandedElts.set(OutIdx/Ratio);
1633       }
1634     } else {
1635       // Untested so far.
1636       break;
1637       
1638       // If there are more elements in the source than there are in the result,
1639       // then an input element is live if the corresponding output element is
1640       // live.
1641       Ratio = InVWidth/VWidth;
1642       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1643         if (DemandedElts[InIdx/Ratio])
1644           InputDemandedElts.set(InIdx);
1645     }
1646     
1647     // div/rem demand all inputs, because they don't want divide by zero.
1648     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1649                                       UndefElts2, Depth+1);
1650     if (TmpV) {
1651       I->setOperand(0, TmpV);
1652       MadeChange = true;
1653     }
1654     
1655     UndefElts = UndefElts2;
1656     if (VWidth > InVWidth) {
1657       llvm_unreachable("Unimp");
1658       // If there are more elements in the result than there are in the source,
1659       // then an output element is undef if the corresponding input element is
1660       // undef.
1661       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1662         if (UndefElts2[OutIdx/Ratio])
1663           UndefElts.set(OutIdx);
1664     } else if (VWidth < InVWidth) {
1665       llvm_unreachable("Unimp");
1666       // If there are more elements in the source than there are in the result,
1667       // then a result element is undef if all of the corresponding input
1668       // elements are undef.
1669       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1670       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1671         if (!UndefElts2[InIdx])            // Not undef?
1672           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1673     }
1674     break;
1675   }
1676   case Instruction::And:
1677   case Instruction::Or:
1678   case Instruction::Xor:
1679   case Instruction::Add:
1680   case Instruction::Sub:
1681   case Instruction::Mul:
1682     // div/rem demand all inputs, because they don't want divide by zero.
1683     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1684                                       UndefElts, Depth+1);
1685     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1686     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1687                                       UndefElts2, Depth+1);
1688     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1689       
1690     // Output elements are undefined if both are undefined.  Consider things
1691     // like undef&0.  The result is known zero, not undef.
1692     UndefElts &= UndefElts2;
1693     break;
1694     
1695   case Instruction::Call: {
1696     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1697     if (!II) break;
1698     switch (II->getIntrinsicID()) {
1699     default: break;
1700       
1701     // Binary vector operations that work column-wise.  A dest element is a
1702     // function of the corresponding input elements from the two inputs.
1703     case Intrinsic::x86_sse_sub_ss:
1704     case Intrinsic::x86_sse_mul_ss:
1705     case Intrinsic::x86_sse_min_ss:
1706     case Intrinsic::x86_sse_max_ss:
1707     case Intrinsic::x86_sse2_sub_sd:
1708     case Intrinsic::x86_sse2_mul_sd:
1709     case Intrinsic::x86_sse2_min_sd:
1710     case Intrinsic::x86_sse2_max_sd:
1711       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1712                                         UndefElts, Depth+1);
1713       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1714       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1715                                         UndefElts2, Depth+1);
1716       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1717
1718       // If only the low elt is demanded and this is a scalarizable intrinsic,
1719       // scalarize it now.
1720       if (DemandedElts == 1) {
1721         switch (II->getIntrinsicID()) {
1722         default: break;
1723         case Intrinsic::x86_sse_sub_ss:
1724         case Intrinsic::x86_sse_mul_ss:
1725         case Intrinsic::x86_sse2_sub_sd:
1726         case Intrinsic::x86_sse2_mul_sd:
1727           // TODO: Lower MIN/MAX/ABS/etc
1728           Value *LHS = II->getOperand(1);
1729           Value *RHS = II->getOperand(2);
1730           // Extract the element as scalars.
1731           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1732             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1733           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1734             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1735           
1736           switch (II->getIntrinsicID()) {
1737           default: llvm_unreachable("Case stmts out of sync!");
1738           case Intrinsic::x86_sse_sub_ss:
1739           case Intrinsic::x86_sse2_sub_sd:
1740             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1741                                                         II->getName()), *II);
1742             break;
1743           case Intrinsic::x86_sse_mul_ss:
1744           case Intrinsic::x86_sse2_mul_sd:
1745             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1746                                                          II->getName()), *II);
1747             break;
1748           }
1749           
1750           Instruction *New =
1751             InsertElementInst::Create(
1752               UndefValue::get(II->getType()), TmpV,
1753               ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1754           InsertNewInstBefore(New, *II);
1755           return New;
1756         }            
1757       }
1758         
1759       // Output elements are undefined if both are undefined.  Consider things
1760       // like undef&0.  The result is known zero, not undef.
1761       UndefElts &= UndefElts2;
1762       break;
1763     }
1764     break;
1765   }
1766   }
1767   return MadeChange ? I : 0;
1768 }
1769
1770
1771 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1772 /// function is designed to check a chain of associative operators for a
1773 /// potential to apply a certain optimization.  Since the optimization may be
1774 /// applicable if the expression was reassociated, this checks the chain, then
1775 /// reassociates the expression as necessary to expose the optimization
1776 /// opportunity.  This makes use of a special Functor, which must define
1777 /// 'shouldApply' and 'apply' methods.
1778 ///
1779 template<typename Functor>
1780 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1781   unsigned Opcode = Root.getOpcode();
1782   Value *LHS = Root.getOperand(0);
1783
1784   // Quick check, see if the immediate LHS matches...
1785   if (F.shouldApply(LHS))
1786     return F.apply(Root);
1787
1788   // Otherwise, if the LHS is not of the same opcode as the root, return.
1789   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1790   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1791     // Should we apply this transform to the RHS?
1792     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1793
1794     // If not to the RHS, check to see if we should apply to the LHS...
1795     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1796       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1797       ShouldApply = true;
1798     }
1799
1800     // If the functor wants to apply the optimization to the RHS of LHSI,
1801     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1802     if (ShouldApply) {
1803       // Now all of the instructions are in the current basic block, go ahead
1804       // and perform the reassociation.
1805       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1806
1807       // First move the selected RHS to the LHS of the root...
1808       Root.setOperand(0, LHSI->getOperand(1));
1809
1810       // Make what used to be the LHS of the root be the user of the root...
1811       Value *ExtraOperand = TmpLHSI->getOperand(1);
1812       if (&Root == TmpLHSI) {
1813         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1814         return 0;
1815       }
1816       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1817       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1818       BasicBlock::iterator ARI = &Root; ++ARI;
1819       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1820       ARI = Root;
1821
1822       // Now propagate the ExtraOperand down the chain of instructions until we
1823       // get to LHSI.
1824       while (TmpLHSI != LHSI) {
1825         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1826         // Move the instruction to immediately before the chain we are
1827         // constructing to avoid breaking dominance properties.
1828         NextLHSI->moveBefore(ARI);
1829         ARI = NextLHSI;
1830
1831         Value *NextOp = NextLHSI->getOperand(1);
1832         NextLHSI->setOperand(1, ExtraOperand);
1833         TmpLHSI = NextLHSI;
1834         ExtraOperand = NextOp;
1835       }
1836
1837       // Now that the instructions are reassociated, have the functor perform
1838       // the transformation...
1839       return F.apply(Root);
1840     }
1841
1842     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1843   }
1844   return 0;
1845 }
1846
1847 namespace {
1848
1849 // AddRHS - Implements: X + X --> X << 1
1850 struct AddRHS {
1851   Value *RHS;
1852   explicit AddRHS(Value *rhs) : RHS(rhs) {}
1853   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1854   Instruction *apply(BinaryOperator &Add) const {
1855     return BinaryOperator::CreateShl(Add.getOperand(0),
1856                                      ConstantInt::get(Add.getType(), 1));
1857   }
1858 };
1859
1860 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1861 //                 iff C1&C2 == 0
1862 struct AddMaskingAnd {
1863   Constant *C2;
1864   explicit AddMaskingAnd(Constant *c) : C2(c) {}
1865   bool shouldApply(Value *LHS) const {
1866     ConstantInt *C1;
1867     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1868            ConstantExpr::getAnd(C1, C2)->isNullValue();
1869   }
1870   Instruction *apply(BinaryOperator &Add) const {
1871     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1872   }
1873 };
1874
1875 }
1876
1877 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1878                                              InstCombiner *IC) {
1879   if (CastInst *CI = dyn_cast<CastInst>(&I))
1880     return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
1881
1882   // Figure out if the constant is the left or the right argument.
1883   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1884   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1885
1886   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1887     if (ConstIsRHS)
1888       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1889     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1890   }
1891
1892   Value *Op0 = SO, *Op1 = ConstOperand;
1893   if (!ConstIsRHS)
1894     std::swap(Op0, Op1);
1895   
1896   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1897     return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1898                                     SO->getName()+".op");
1899   if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1900     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1901                                    SO->getName()+".cmp");
1902   if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1903     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1904                                    SO->getName()+".cmp");
1905   llvm_unreachable("Unknown binary instruction type!");
1906 }
1907
1908 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1909 // constant as the other operand, try to fold the binary operator into the
1910 // select arguments.  This also works for Cast instructions, which obviously do
1911 // not have a second operand.
1912 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1913                                      InstCombiner *IC) {
1914   // Don't modify shared select instructions
1915   if (!SI->hasOneUse()) return 0;
1916   Value *TV = SI->getOperand(1);
1917   Value *FV = SI->getOperand(2);
1918
1919   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1920     // Bool selects with constant operands can be folded to logical ops.
1921     if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
1922
1923     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1924     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1925
1926     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1927                               SelectFalseVal);
1928   }
1929   return 0;
1930 }
1931
1932
1933 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1934 /// node as operand #0, see if we can fold the instruction into the PHI (which
1935 /// is only possible if all operands to the PHI are constants).
1936 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1937   PHINode *PN = cast<PHINode>(I.getOperand(0));
1938   unsigned NumPHIValues = PN->getNumIncomingValues();
1939   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1940
1941   // Check to see if all of the operands of the PHI are constants.  If there is
1942   // one non-constant value, remember the BB it is.  If there is more than one
1943   // or if *it* is a PHI, bail out.
1944   BasicBlock *NonConstBB = 0;
1945   for (unsigned i = 0; i != NumPHIValues; ++i)
1946     if (!isa<Constant>(PN->getIncomingValue(i))) {
1947       if (NonConstBB) return 0;  // More than one non-const value.
1948       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1949       NonConstBB = PN->getIncomingBlock(i);
1950       
1951       // If the incoming non-constant value is in I's block, we have an infinite
1952       // loop.
1953       if (NonConstBB == I.getParent())
1954         return 0;
1955     }
1956   
1957   // If there is exactly one non-constant value, we can insert a copy of the
1958   // operation in that block.  However, if this is a critical edge, we would be
1959   // inserting the computation one some other paths (e.g. inside a loop).  Only
1960   // do this if the pred block is unconditionally branching into the phi block.
1961   if (NonConstBB) {
1962     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1963     if (!BI || !BI->isUnconditional()) return 0;
1964   }
1965
1966   // Okay, we can do the transformation: create the new PHI node.
1967   PHINode *NewPN = PHINode::Create(I.getType(), "");
1968   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1969   InsertNewInstBefore(NewPN, *PN);
1970   NewPN->takeName(PN);
1971
1972   // Next, add all of the operands to the PHI.
1973   if (I.getNumOperands() == 2) {
1974     Constant *C = cast<Constant>(I.getOperand(1));
1975     for (unsigned i = 0; i != NumPHIValues; ++i) {
1976       Value *InV = 0;
1977       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1978         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1979           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1980         else
1981           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1982       } else {
1983         assert(PN->getIncomingBlock(i) == NonConstBB);
1984         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1985           InV = BinaryOperator::Create(BO->getOpcode(),
1986                                        PN->getIncomingValue(i), C, "phitmp",
1987                                        NonConstBB->getTerminator());
1988         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1989           InV = CmpInst::Create(CI->getOpcode(),
1990                                 CI->getPredicate(),
1991                                 PN->getIncomingValue(i), C, "phitmp",
1992                                 NonConstBB->getTerminator());
1993         else
1994           llvm_unreachable("Unknown binop!");
1995         
1996         Worklist.Add(cast<Instruction>(InV));
1997       }
1998       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1999     }
2000   } else { 
2001     CastInst *CI = cast<CastInst>(&I);
2002     const Type *RetTy = CI->getType();
2003     for (unsigned i = 0; i != NumPHIValues; ++i) {
2004       Value *InV;
2005       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2006         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2007       } else {
2008         assert(PN->getIncomingBlock(i) == NonConstBB);
2009         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2010                                I.getType(), "phitmp", 
2011                                NonConstBB->getTerminator());
2012         Worklist.Add(cast<Instruction>(InV));
2013       }
2014       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2015     }
2016   }
2017   return ReplaceInstUsesWith(I, NewPN);
2018 }
2019
2020
2021 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2022 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2023 /// This basically requires proving that the add in the original type would not
2024 /// overflow to change the sign bit or have a carry out.
2025 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2026   // There are different heuristics we can use for this.  Here are some simple
2027   // ones.
2028   
2029   // Add has the property that adding any two 2's complement numbers can only 
2030   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2031   // have at least two sign bits, we know that the addition of the two values will
2032   // sign extend fine.
2033   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2034     return true;
2035   
2036   
2037   // If one of the operands only has one non-zero bit, and if the other operand
2038   // has a known-zero bit in a more significant place than it (not including the
2039   // sign bit) the ripple may go up to and fill the zero, but won't change the
2040   // sign.  For example, (X & ~4) + 1.
2041   
2042   // TODO: Implement.
2043   
2044   return false;
2045 }
2046
2047
2048 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2049   bool Changed = SimplifyCommutative(I);
2050   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2051
2052   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2053     // X + undef -> undef
2054     if (isa<UndefValue>(RHS))
2055       return ReplaceInstUsesWith(I, RHS);
2056
2057     // X + 0 --> X
2058     if (RHSC->isNullValue())
2059       return ReplaceInstUsesWith(I, LHS);
2060
2061     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2062       // X + (signbit) --> X ^ signbit
2063       const APInt& Val = CI->getValue();
2064       uint32_t BitWidth = Val.getBitWidth();
2065       if (Val == APInt::getSignBit(BitWidth))
2066         return BinaryOperator::CreateXor(LHS, RHS);
2067       
2068       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2069       // (X & 254)+1 -> (X&254)|1
2070       if (SimplifyDemandedInstructionBits(I))
2071         return &I;
2072
2073       // zext(bool) + C -> bool ? C + 1 : C
2074       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2075         if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2076           return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2077     }
2078
2079     if (isa<PHINode>(LHS))
2080       if (Instruction *NV = FoldOpIntoPhi(I))
2081         return NV;
2082     
2083     ConstantInt *XorRHS = 0;
2084     Value *XorLHS = 0;
2085     if (isa<ConstantInt>(RHSC) &&
2086         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2087       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2088       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2089       
2090       uint32_t Size = TySizeBits / 2;
2091       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2092       APInt CFF80Val(-C0080Val);
2093       do {
2094         if (TySizeBits > Size) {
2095           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2096           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2097           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2098               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2099             // This is a sign extend if the top bits are known zero.
2100             if (!MaskedValueIsZero(XorLHS, 
2101                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2102               Size = 0;  // Not a sign ext, but can't be any others either.
2103             break;
2104           }
2105         }
2106         Size >>= 1;
2107         C0080Val = APIntOps::lshr(C0080Val, Size);
2108         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2109       } while (Size >= 1);
2110       
2111       // FIXME: This shouldn't be necessary. When the backends can handle types
2112       // with funny bit widths then this switch statement should be removed. It
2113       // is just here to get the size of the "middle" type back up to something
2114       // that the back ends can handle.
2115       const Type *MiddleType = 0;
2116       switch (Size) {
2117         default: break;
2118         case 32: MiddleType = Type::getInt32Ty(*Context); break;
2119         case 16: MiddleType = Type::getInt16Ty(*Context); break;
2120         case  8: MiddleType = Type::getInt8Ty(*Context); break;
2121       }
2122       if (MiddleType) {
2123         Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2124         return new SExtInst(NewTrunc, I.getType(), I.getName());
2125       }
2126     }
2127   }
2128
2129   if (I.getType() == Type::getInt1Ty(*Context))
2130     return BinaryOperator::CreateXor(LHS, RHS);
2131
2132   // X + X --> X << 1
2133   if (I.getType()->isInteger()) {
2134     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2135       return Result;
2136
2137     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2138       if (RHSI->getOpcode() == Instruction::Sub)
2139         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2140           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2141     }
2142     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2143       if (LHSI->getOpcode() == Instruction::Sub)
2144         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2145           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2146     }
2147   }
2148
2149   // -A + B  -->  B - A
2150   // -A + -B  -->  -(A + B)
2151   if (Value *LHSV = dyn_castNegVal(LHS)) {
2152     if (LHS->getType()->isIntOrIntVector()) {
2153       if (Value *RHSV = dyn_castNegVal(RHS)) {
2154         Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2155         return BinaryOperator::CreateNeg(NewAdd);
2156       }
2157     }
2158     
2159     return BinaryOperator::CreateSub(RHS, LHSV);
2160   }
2161
2162   // A + -B  -->  A - B
2163   if (!isa<Constant>(RHS))
2164     if (Value *V = dyn_castNegVal(RHS))
2165       return BinaryOperator::CreateSub(LHS, V);
2166
2167
2168   ConstantInt *C2;
2169   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2170     if (X == RHS)   // X*C + X --> X * (C+1)
2171       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2172
2173     // X*C1 + X*C2 --> X * (C1+C2)
2174     ConstantInt *C1;
2175     if (X == dyn_castFoldableMul(RHS, C1))
2176       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2177   }
2178
2179   // X + X*C --> X * (C+1)
2180   if (dyn_castFoldableMul(RHS, C2) == LHS)
2181     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2182
2183   // X + ~X --> -1   since   ~X = -X-1
2184   if (dyn_castNotVal(LHS) == RHS ||
2185       dyn_castNotVal(RHS) == LHS)
2186     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2187   
2188
2189   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2190   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2191     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2192       return R;
2193   
2194   // A+B --> A|B iff A and B have no bits set in common.
2195   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2196     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2197     APInt LHSKnownOne(IT->getBitWidth(), 0);
2198     APInt LHSKnownZero(IT->getBitWidth(), 0);
2199     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2200     if (LHSKnownZero != 0) {
2201       APInt RHSKnownOne(IT->getBitWidth(), 0);
2202       APInt RHSKnownZero(IT->getBitWidth(), 0);
2203       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2204       
2205       // No bits in common -> bitwise or.
2206       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2207         return BinaryOperator::CreateOr(LHS, RHS);
2208     }
2209   }
2210
2211   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2212   if (I.getType()->isIntOrIntVector()) {
2213     Value *W, *X, *Y, *Z;
2214     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2215         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2216       if (W != Y) {
2217         if (W == Z) {
2218           std::swap(Y, Z);
2219         } else if (Y == X) {
2220           std::swap(W, X);
2221         } else if (X == Z) {
2222           std::swap(Y, Z);
2223           std::swap(W, X);
2224         }
2225       }
2226
2227       if (W == Y) {
2228         Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2229         return BinaryOperator::CreateMul(W, NewAdd);
2230       }
2231     }
2232   }
2233
2234   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2235     Value *X = 0;
2236     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2237       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2238
2239     // (X & FF00) + xx00  -> (X+xx00) & FF00
2240     if (LHS->hasOneUse() &&
2241         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2242       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2243       if (Anded == CRHS) {
2244         // See if all bits from the first bit set in the Add RHS up are included
2245         // in the mask.  First, get the rightmost bit.
2246         const APInt& AddRHSV = CRHS->getValue();
2247
2248         // Form a mask of all bits from the lowest bit added through the top.
2249         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2250
2251         // See if the and mask includes all of these bits.
2252         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2253
2254         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2255           // Okay, the xform is safe.  Insert the new add pronto.
2256           Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2257           return BinaryOperator::CreateAnd(NewAdd, C2);
2258         }
2259       }
2260     }
2261
2262     // Try to fold constant add into select arguments.
2263     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2264       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2265         return R;
2266   }
2267
2268   // add (select X 0 (sub n A)) A  -->  select X A n
2269   {
2270     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2271     Value *A = RHS;
2272     if (!SI) {
2273       SI = dyn_cast<SelectInst>(RHS);
2274       A = LHS;
2275     }
2276     if (SI && SI->hasOneUse()) {
2277       Value *TV = SI->getTrueValue();
2278       Value *FV = SI->getFalseValue();
2279       Value *N;
2280
2281       // Can we fold the add into the argument of the select?
2282       // We check both true and false select arguments for a matching subtract.
2283       if (match(FV, m_Zero()) &&
2284           match(TV, m_Sub(m_Value(N), m_Specific(A))))
2285         // Fold the add into the true select value.
2286         return SelectInst::Create(SI->getCondition(), N, A);
2287       if (match(TV, m_Zero()) &&
2288           match(FV, m_Sub(m_Value(N), m_Specific(A))))
2289         // Fold the add into the false select value.
2290         return SelectInst::Create(SI->getCondition(), A, N);
2291     }
2292   }
2293
2294   // Check for (add (sext x), y), see if we can merge this into an
2295   // integer add followed by a sext.
2296   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2297     // (add (sext x), cst) --> (sext (add x, cst'))
2298     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2299       Constant *CI = 
2300         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2301       if (LHSConv->hasOneUse() &&
2302           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2303           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2304         // Insert the new, smaller add.
2305         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2306                                            CI, "addconv");
2307         return new SExtInst(NewAdd, I.getType());
2308       }
2309     }
2310     
2311     // (add (sext x), (sext y)) --> (sext (add int x, y))
2312     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2313       // Only do this if x/y have the same type, if at last one of them has a
2314       // single use (so we don't increase the number of sexts), and if the
2315       // integer add will not overflow.
2316       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2317           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2318           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2319                                    RHSConv->getOperand(0))) {
2320         // Insert the new integer add.
2321         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2322                                            RHSConv->getOperand(0), "addconv");
2323         return new SExtInst(NewAdd, I.getType());
2324       }
2325     }
2326   }
2327
2328   return Changed ? &I : 0;
2329 }
2330
2331 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2332   bool Changed = SimplifyCommutative(I);
2333   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2334
2335   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2336     // X + 0 --> X
2337     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2338       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2339                               (I.getType())->getValueAPF()))
2340         return ReplaceInstUsesWith(I, LHS);
2341     }
2342
2343     if (isa<PHINode>(LHS))
2344       if (Instruction *NV = FoldOpIntoPhi(I))
2345         return NV;
2346   }
2347
2348   // -A + B  -->  B - A
2349   // -A + -B  -->  -(A + B)
2350   if (Value *LHSV = dyn_castFNegVal(LHS))
2351     return BinaryOperator::CreateFSub(RHS, LHSV);
2352
2353   // A + -B  -->  A - B
2354   if (!isa<Constant>(RHS))
2355     if (Value *V = dyn_castFNegVal(RHS))
2356       return BinaryOperator::CreateFSub(LHS, V);
2357
2358   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2359   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2360     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2361       return ReplaceInstUsesWith(I, LHS);
2362
2363   // Check for (add double (sitofp x), y), see if we can merge this into an
2364   // integer add followed by a promotion.
2365   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2366     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2367     // ... if the constant fits in the integer value.  This is useful for things
2368     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2369     // requires a constant pool load, and generally allows the add to be better
2370     // instcombined.
2371     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2372       Constant *CI = 
2373       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2374       if (LHSConv->hasOneUse() &&
2375           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2376           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2377         // Insert the new integer add.
2378         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2379                                            CI, "addconv");
2380         return new SIToFPInst(NewAdd, I.getType());
2381       }
2382     }
2383     
2384     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2385     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2386       // Only do this if x/y have the same type, if at last one of them has a
2387       // single use (so we don't increase the number of int->fp conversions),
2388       // and if the integer add will not overflow.
2389       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2390           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2391           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2392                                    RHSConv->getOperand(0))) {
2393         // Insert the new integer add.
2394         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2395                                            RHSConv->getOperand(0), "addconv");
2396         return new SIToFPInst(NewAdd, I.getType());
2397       }
2398     }
2399   }
2400   
2401   return Changed ? &I : 0;
2402 }
2403
2404 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2405   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2406
2407   if (Op0 == Op1)                        // sub X, X  -> 0
2408     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2409
2410   // If this is a 'B = x-(-A)', change to B = x+A...
2411   if (Value *V = dyn_castNegVal(Op1))
2412     return BinaryOperator::CreateAdd(Op0, V);
2413
2414   if (isa<UndefValue>(Op0))
2415     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2416   if (isa<UndefValue>(Op1))
2417     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2418
2419   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2420     // Replace (-1 - A) with (~A)...
2421     if (C->isAllOnesValue())
2422       return BinaryOperator::CreateNot(Op1);
2423
2424     // C - ~X == X + (1+C)
2425     Value *X = 0;
2426     if (match(Op1, m_Not(m_Value(X))))
2427       return BinaryOperator::CreateAdd(X, AddOne(C));
2428
2429     // -(X >>u 31) -> (X >>s 31)
2430     // -(X >>s 31) -> (X >>u 31)
2431     if (C->isZero()) {
2432       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2433         if (SI->getOpcode() == Instruction::LShr) {
2434           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2435             // Check to see if we are shifting out everything but the sign bit.
2436             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2437                 SI->getType()->getPrimitiveSizeInBits()-1) {
2438               // Ok, the transformation is safe.  Insert AShr.
2439               return BinaryOperator::Create(Instruction::AShr, 
2440                                           SI->getOperand(0), CU, SI->getName());
2441             }
2442           }
2443         }
2444         else if (SI->getOpcode() == Instruction::AShr) {
2445           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2446             // Check to see if we are shifting out everything but the sign bit.
2447             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2448                 SI->getType()->getPrimitiveSizeInBits()-1) {
2449               // Ok, the transformation is safe.  Insert LShr. 
2450               return BinaryOperator::CreateLShr(
2451                                           SI->getOperand(0), CU, SI->getName());
2452             }
2453           }
2454         }
2455       }
2456     }
2457
2458     // Try to fold constant sub into select arguments.
2459     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2460       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2461         return R;
2462
2463     // C - zext(bool) -> bool ? C - 1 : C
2464     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2465       if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2466         return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2467   }
2468
2469   if (I.getType() == Type::getInt1Ty(*Context))
2470     return BinaryOperator::CreateXor(Op0, Op1);
2471
2472   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2473     if (Op1I->getOpcode() == Instruction::Add) {
2474       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2475         return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2476                                          I.getName());
2477       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2478         return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2479                                          I.getName());
2480       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2481         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2482           // C1-(X+C2) --> (C1-C2)-X
2483           return BinaryOperator::CreateSub(
2484             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2485       }
2486     }
2487
2488     if (Op1I->hasOneUse()) {
2489       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2490       // is not used by anyone else...
2491       //
2492       if (Op1I->getOpcode() == Instruction::Sub) {
2493         // Swap the two operands of the subexpr...
2494         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2495         Op1I->setOperand(0, IIOp1);
2496         Op1I->setOperand(1, IIOp0);
2497
2498         // Create the new top level add instruction...
2499         return BinaryOperator::CreateAdd(Op0, Op1);
2500       }
2501
2502       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2503       //
2504       if (Op1I->getOpcode() == Instruction::And &&
2505           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2506         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2507
2508         Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2509         return BinaryOperator::CreateAnd(Op0, NewNot);
2510       }
2511
2512       // 0 - (X sdiv C)  -> (X sdiv -C)
2513       if (Op1I->getOpcode() == Instruction::SDiv)
2514         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2515           if (CSI->isZero())
2516             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2517               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2518                                           ConstantExpr::getNeg(DivRHS));
2519
2520       // X - X*C --> X * (1-C)
2521       ConstantInt *C2 = 0;
2522       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2523         Constant *CP1 = 
2524           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2525                                              C2);
2526         return BinaryOperator::CreateMul(Op0, CP1);
2527       }
2528     }
2529   }
2530
2531   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2532     if (Op0I->getOpcode() == Instruction::Add) {
2533       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2534         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2535       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2536         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2537     } else if (Op0I->getOpcode() == Instruction::Sub) {
2538       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2539         return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2540                                          I.getName());
2541     }
2542   }
2543
2544   ConstantInt *C1;
2545   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2546     if (X == Op1)  // X*C - X --> X * (C-1)
2547       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2548
2549     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2550     if (X == dyn_castFoldableMul(Op1, C2))
2551       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2552   }
2553   return 0;
2554 }
2555
2556 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2557   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2558
2559   // If this is a 'B = x-(-A)', change to B = x+A...
2560   if (Value *V = dyn_castFNegVal(Op1))
2561     return BinaryOperator::CreateFAdd(Op0, V);
2562
2563   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2564     if (Op1I->getOpcode() == Instruction::FAdd) {
2565       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2566         return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2567                                           I.getName());
2568       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2569         return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2570                                           I.getName());
2571     }
2572   }
2573
2574   return 0;
2575 }
2576
2577 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2578 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2579 /// TrueIfSigned if the result of the comparison is true when the input value is
2580 /// signed.
2581 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2582                            bool &TrueIfSigned) {
2583   switch (pred) {
2584   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2585     TrueIfSigned = true;
2586     return RHS->isZero();
2587   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2588     TrueIfSigned = true;
2589     return RHS->isAllOnesValue();
2590   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2591     TrueIfSigned = false;
2592     return RHS->isAllOnesValue();
2593   case ICmpInst::ICMP_UGT:
2594     // True if LHS u> RHS and RHS == high-bit-mask - 1
2595     TrueIfSigned = true;
2596     return RHS->getValue() ==
2597       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2598   case ICmpInst::ICMP_UGE: 
2599     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2600     TrueIfSigned = true;
2601     return RHS->getValue().isSignBit();
2602   default:
2603     return false;
2604   }
2605 }
2606
2607 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2608   bool Changed = SimplifyCommutative(I);
2609   Value *Op0 = I.getOperand(0);
2610
2611   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2612     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2613
2614   // Simplify mul instructions with a constant RHS...
2615   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2616     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2617
2618       // ((X << C1)*C2) == (X * (C2 << C1))
2619       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2620         if (SI->getOpcode() == Instruction::Shl)
2621           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2622             return BinaryOperator::CreateMul(SI->getOperand(0),
2623                                         ConstantExpr::getShl(CI, ShOp));
2624
2625       if (CI->isZero())
2626         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2627       if (CI->equalsInt(1))                  // X * 1  == X
2628         return ReplaceInstUsesWith(I, Op0);
2629       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2630         return BinaryOperator::CreateNeg(Op0, I.getName());
2631
2632       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2633       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2634         return BinaryOperator::CreateShl(Op0,
2635                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2636       }
2637     } else if (isa<VectorType>(Op1->getType())) {
2638       if (Op1->isNullValue())
2639         return ReplaceInstUsesWith(I, Op1);
2640
2641       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2642         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2643           return BinaryOperator::CreateNeg(Op0, I.getName());
2644
2645         // As above, vector X*splat(1.0) -> X in all defined cases.
2646         if (Constant *Splat = Op1V->getSplatValue()) {
2647           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2648             if (CI->equalsInt(1))
2649               return ReplaceInstUsesWith(I, Op0);
2650         }
2651       }
2652     }
2653     
2654     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2655       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2656           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2657         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2658         Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1, "tmp");
2659         Value *C1C2 = Builder->CreateMul(Op1, Op0I->getOperand(1));
2660         return BinaryOperator::CreateAdd(Add, C1C2);
2661         
2662       }
2663
2664     // Try to fold constant mul into select arguments.
2665     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2666       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2667         return R;
2668
2669     if (isa<PHINode>(Op0))
2670       if (Instruction *NV = FoldOpIntoPhi(I))
2671         return NV;
2672   }
2673
2674   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2675     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2676       return BinaryOperator::CreateMul(Op0v, Op1v);
2677
2678   // (X / Y) *  Y = X - (X % Y)
2679   // (X / Y) * -Y = (X % Y) - X
2680   {
2681     Value *Op1 = I.getOperand(1);
2682     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2683     if (!BO ||
2684         (BO->getOpcode() != Instruction::UDiv && 
2685          BO->getOpcode() != Instruction::SDiv)) {
2686       Op1 = Op0;
2687       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2688     }
2689     Value *Neg = dyn_castNegVal(Op1);
2690     if (BO && BO->hasOneUse() &&
2691         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2692         (BO->getOpcode() == Instruction::UDiv ||
2693          BO->getOpcode() == Instruction::SDiv)) {
2694       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2695
2696       // If the division is exact, X % Y is zero.
2697       if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2698         if (SDiv->isExact()) {
2699           if (Op1BO == Op1)
2700             return ReplaceInstUsesWith(I, Op0BO);
2701           else
2702             return BinaryOperator::CreateNeg(Op0BO);
2703         }
2704
2705       Value *Rem;
2706       if (BO->getOpcode() == Instruction::UDiv)
2707         Rem = Builder->CreateURem(Op0BO, Op1BO);
2708       else
2709         Rem = Builder->CreateSRem(Op0BO, Op1BO);
2710       Rem->takeName(BO);
2711
2712       if (Op1BO == Op1)
2713         return BinaryOperator::CreateSub(Op0BO, Rem);
2714       return BinaryOperator::CreateSub(Rem, Op0BO);
2715     }
2716   }
2717
2718   if (I.getType() == Type::getInt1Ty(*Context))
2719     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2720
2721   // If one of the operands of the multiply is a cast from a boolean value, then
2722   // we know the bool is either zero or one, so this is a 'masking' multiply.
2723   // See if we can simplify things based on how the boolean was originally
2724   // formed.
2725   CastInst *BoolCast = 0;
2726   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2727     if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2728       BoolCast = CI;
2729   if (!BoolCast)
2730     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2731       if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2732         BoolCast = CI;
2733   if (BoolCast) {
2734     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2735       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2736       const Type *SCOpTy = SCIOp0->getType();
2737       bool TIS = false;
2738       
2739       // If the icmp is true iff the sign bit of X is set, then convert this
2740       // multiply into a shift/and combination.
2741       if (isa<ConstantInt>(SCIOp1) &&
2742           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2743           TIS) {
2744         // Shift the X value right to turn it into "all signbits".
2745         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2746                                           SCOpTy->getPrimitiveSizeInBits()-1);
2747         Value *V = Builder->CreateAShr(SCIOp0, Amt,
2748                                     BoolCast->getOperand(0)->getName()+".mask");
2749
2750         // If the multiply type is not the same as the source type, sign extend
2751         // or truncate to the multiply type.
2752         if (I.getType() != V->getType())
2753           V = Builder->CreateIntCast(V, I.getType(), true);
2754
2755         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2756         return BinaryOperator::CreateAnd(V, OtherOp);
2757       }
2758     }
2759   }
2760
2761   return Changed ? &I : 0;
2762 }
2763
2764 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2765   bool Changed = SimplifyCommutative(I);
2766   Value *Op0 = I.getOperand(0);
2767
2768   // Simplify mul instructions with a constant RHS...
2769   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2770     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2771       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2772       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2773       if (Op1F->isExactlyValue(1.0))
2774         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2775     } else if (isa<VectorType>(Op1->getType())) {
2776       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2777         // As above, vector X*splat(1.0) -> X in all defined cases.
2778         if (Constant *Splat = Op1V->getSplatValue()) {
2779           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2780             if (F->isExactlyValue(1.0))
2781               return ReplaceInstUsesWith(I, Op0);
2782         }
2783       }
2784     }
2785
2786     // Try to fold constant mul into select arguments.
2787     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2788       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2789         return R;
2790
2791     if (isa<PHINode>(Op0))
2792       if (Instruction *NV = FoldOpIntoPhi(I))
2793         return NV;
2794   }
2795
2796   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
2797     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2798       return BinaryOperator::CreateFMul(Op0v, Op1v);
2799
2800   return Changed ? &I : 0;
2801 }
2802
2803 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2804 /// instruction.
2805 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2806   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2807   
2808   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2809   int NonNullOperand = -1;
2810   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2811     if (ST->isNullValue())
2812       NonNullOperand = 2;
2813   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2814   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2815     if (ST->isNullValue())
2816       NonNullOperand = 1;
2817   
2818   if (NonNullOperand == -1)
2819     return false;
2820   
2821   Value *SelectCond = SI->getOperand(0);
2822   
2823   // Change the div/rem to use 'Y' instead of the select.
2824   I.setOperand(1, SI->getOperand(NonNullOperand));
2825   
2826   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2827   // problem.  However, the select, or the condition of the select may have
2828   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2829   // propagate the known value for the select into other uses of it, and
2830   // propagate a known value of the condition into its other users.
2831   
2832   // If the select and condition only have a single use, don't bother with this,
2833   // early exit.
2834   if (SI->use_empty() && SelectCond->hasOneUse())
2835     return true;
2836   
2837   // Scan the current block backward, looking for other uses of SI.
2838   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2839   
2840   while (BBI != BBFront) {
2841     --BBI;
2842     // If we found a call to a function, we can't assume it will return, so
2843     // information from below it cannot be propagated above it.
2844     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2845       break;
2846     
2847     // Replace uses of the select or its condition with the known values.
2848     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2849          I != E; ++I) {
2850       if (*I == SI) {
2851         *I = SI->getOperand(NonNullOperand);
2852         Worklist.Add(BBI);
2853       } else if (*I == SelectCond) {
2854         *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2855                                    ConstantInt::getFalse(*Context);
2856         Worklist.Add(BBI);
2857       }
2858     }
2859     
2860     // If we past the instruction, quit looking for it.
2861     if (&*BBI == SI)
2862       SI = 0;
2863     if (&*BBI == SelectCond)
2864       SelectCond = 0;
2865     
2866     // If we ran out of things to eliminate, break out of the loop.
2867     if (SelectCond == 0 && SI == 0)
2868       break;
2869     
2870   }
2871   return true;
2872 }
2873
2874
2875 /// This function implements the transforms on div instructions that work
2876 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2877 /// used by the visitors to those instructions.
2878 /// @brief Transforms common to all three div instructions
2879 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2880   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2881
2882   // undef / X -> 0        for integer.
2883   // undef / X -> undef    for FP (the undef could be a snan).
2884   if (isa<UndefValue>(Op0)) {
2885     if (Op0->getType()->isFPOrFPVector())
2886       return ReplaceInstUsesWith(I, Op0);
2887     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2888   }
2889
2890   // X / undef -> undef
2891   if (isa<UndefValue>(Op1))
2892     return ReplaceInstUsesWith(I, Op1);
2893
2894   return 0;
2895 }
2896
2897 /// This function implements the transforms common to both integer division
2898 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2899 /// division instructions.
2900 /// @brief Common integer divide transforms
2901 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2902   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2903
2904   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2905   if (Op0 == Op1) {
2906     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2907       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2908       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2909       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2910     }
2911
2912     Constant *CI = ConstantInt::get(I.getType(), 1);
2913     return ReplaceInstUsesWith(I, CI);
2914   }
2915   
2916   if (Instruction *Common = commonDivTransforms(I))
2917     return Common;
2918   
2919   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2920   // This does not apply for fdiv.
2921   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2922     return &I;
2923
2924   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2925     // div X, 1 == X
2926     if (RHS->equalsInt(1))
2927       return ReplaceInstUsesWith(I, Op0);
2928
2929     // (X / C1) / C2  -> X / (C1*C2)
2930     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2931       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2932         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2933           if (MultiplyOverflows(RHS, LHSRHS,
2934                                 I.getOpcode()==Instruction::SDiv))
2935             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2936           else 
2937             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2938                                       ConstantExpr::getMul(RHS, LHSRHS));
2939         }
2940
2941     if (!RHS->isZero()) { // avoid X udiv 0
2942       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2943         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2944           return R;
2945       if (isa<PHINode>(Op0))
2946         if (Instruction *NV = FoldOpIntoPhi(I))
2947           return NV;
2948     }
2949   }
2950
2951   // 0 / X == 0, we don't need to preserve faults!
2952   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2953     if (LHS->equalsInt(0))
2954       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2955
2956   // It can't be division by zero, hence it must be division by one.
2957   if (I.getType() == Type::getInt1Ty(*Context))
2958     return ReplaceInstUsesWith(I, Op0);
2959
2960   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2961     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2962       // div X, 1 == X
2963       if (X->isOne())
2964         return ReplaceInstUsesWith(I, Op0);
2965   }
2966
2967   return 0;
2968 }
2969
2970 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2971   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2972
2973   // Handle the integer div common cases
2974   if (Instruction *Common = commonIDivTransforms(I))
2975     return Common;
2976
2977   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2978     // X udiv C^2 -> X >> C
2979     // Check to see if this is an unsigned division with an exact power of 2,
2980     // if so, convert to a right shift.
2981     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2982       return BinaryOperator::CreateLShr(Op0, 
2983             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2984
2985     // X udiv C, where C >= signbit
2986     if (C->getValue().isNegative()) {
2987       Value *IC = Builder->CreateICmpULT( Op0, C);
2988       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2989                                 ConstantInt::get(I.getType(), 1));
2990     }
2991   }
2992
2993   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2994   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2995     if (RHSI->getOpcode() == Instruction::Shl &&
2996         isa<ConstantInt>(RHSI->getOperand(0))) {
2997       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2998       if (C1.isPowerOf2()) {
2999         Value *N = RHSI->getOperand(1);
3000         const Type *NTy = N->getType();
3001         if (uint32_t C2 = C1.logBase2())
3002           N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3003         return BinaryOperator::CreateLShr(Op0, N);
3004       }
3005     }
3006   }
3007   
3008   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3009   // where C1&C2 are powers of two.
3010   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3011     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3012       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3013         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3014         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3015           // Compute the shift amounts
3016           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3017           // Construct the "on true" case of the select
3018           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3019           Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3020   
3021           // Construct the "on false" case of the select
3022           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3023           Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
3024
3025           // construct the select instruction and return it.
3026           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3027         }
3028       }
3029   return 0;
3030 }
3031
3032 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3033   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3034
3035   // Handle the integer div common cases
3036   if (Instruction *Common = commonIDivTransforms(I))
3037     return Common;
3038
3039   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3040     // sdiv X, -1 == -X
3041     if (RHS->isAllOnesValue())
3042       return BinaryOperator::CreateNeg(Op0);
3043
3044     // sdiv X, C  -->  ashr X, log2(C)
3045     if (cast<SDivOperator>(&I)->isExact() &&
3046         RHS->getValue().isNonNegative() &&
3047         RHS->getValue().isPowerOf2()) {
3048       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3049                                             RHS->getValue().exactLogBase2());
3050       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3051     }
3052
3053     // -X/C  -->  X/-C  provided the negation doesn't overflow.
3054     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3055       if (isa<Constant>(Sub->getOperand(0)) &&
3056           cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3057           Sub->hasNoSignedWrap())
3058         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3059                                           ConstantExpr::getNeg(RHS));
3060   }
3061
3062   // If the sign bits of both operands are zero (i.e. we can prove they are
3063   // unsigned inputs), turn this into a udiv.
3064   if (I.getType()->isInteger()) {
3065     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3066     if (MaskedValueIsZero(Op0, Mask)) {
3067       if (MaskedValueIsZero(Op1, Mask)) {
3068         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3069         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3070       }
3071       ConstantInt *ShiftedInt;
3072       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3073           ShiftedInt->getValue().isPowerOf2()) {
3074         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3075         // Safe because the only negative value (1 << Y) can take on is
3076         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3077         // the sign bit set.
3078         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3079       }
3080     }
3081   }
3082   
3083   return 0;
3084 }
3085
3086 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3087   return commonDivTransforms(I);
3088 }
3089
3090 /// This function implements the transforms on rem instructions that work
3091 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3092 /// is used by the visitors to those instructions.
3093 /// @brief Transforms common to all three rem instructions
3094 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3095   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3096
3097   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3098     if (I.getType()->isFPOrFPVector())
3099       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3100     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3101   }
3102   if (isa<UndefValue>(Op1))
3103     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3104
3105   // Handle cases involving: rem X, (select Cond, Y, Z)
3106   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3107     return &I;
3108
3109   return 0;
3110 }
3111
3112 /// This function implements the transforms common to both integer remainder
3113 /// instructions (urem and srem). It is called by the visitors to those integer
3114 /// remainder instructions.
3115 /// @brief Common integer remainder transforms
3116 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3117   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3118
3119   if (Instruction *common = commonRemTransforms(I))
3120     return common;
3121
3122   // 0 % X == 0 for integer, we don't need to preserve faults!
3123   if (Constant *LHS = dyn_cast<Constant>(Op0))
3124     if (LHS->isNullValue())
3125       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3126
3127   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3128     // X % 0 == undef, we don't need to preserve faults!
3129     if (RHS->equalsInt(0))
3130       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3131     
3132     if (RHS->equalsInt(1))  // X % 1 == 0
3133       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3134
3135     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3136       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3137         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3138           return R;
3139       } else if (isa<PHINode>(Op0I)) {
3140         if (Instruction *NV = FoldOpIntoPhi(I))
3141           return NV;
3142       }
3143
3144       // See if we can fold away this rem instruction.
3145       if (SimplifyDemandedInstructionBits(I))
3146         return &I;
3147     }
3148   }
3149
3150   return 0;
3151 }
3152
3153 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3154   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3155
3156   if (Instruction *common = commonIRemTransforms(I))
3157     return common;
3158   
3159   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3160     // X urem C^2 -> X and C
3161     // Check to see if this is an unsigned remainder with an exact power of 2,
3162     // if so, convert to a bitwise and.
3163     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3164       if (C->getValue().isPowerOf2())
3165         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3166   }
3167
3168   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3169     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3170     if (RHSI->getOpcode() == Instruction::Shl &&
3171         isa<ConstantInt>(RHSI->getOperand(0))) {
3172       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3173         Constant *N1 = Constant::getAllOnesValue(I.getType());
3174         Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3175         return BinaryOperator::CreateAnd(Op0, Add);
3176       }
3177     }
3178   }
3179
3180   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3181   // where C1&C2 are powers of two.
3182   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3183     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3184       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3185         // STO == 0 and SFO == 0 handled above.
3186         if ((STO->getValue().isPowerOf2()) && 
3187             (SFO->getValue().isPowerOf2())) {
3188           Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3189                                               SI->getName()+".t");
3190           Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3191                                                SI->getName()+".f");
3192           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3193         }
3194       }
3195   }
3196   
3197   return 0;
3198 }
3199
3200 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3201   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3202
3203   // Handle the integer rem common cases
3204   if (Instruction *Common = commonIRemTransforms(I))
3205     return Common;
3206   
3207   if (Value *RHSNeg = dyn_castNegVal(Op1))
3208     if (!isa<Constant>(RHSNeg) ||
3209         (isa<ConstantInt>(RHSNeg) &&
3210          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3211       // X % -Y -> X % Y
3212       Worklist.AddValue(I.getOperand(1));
3213       I.setOperand(1, RHSNeg);
3214       return &I;
3215     }
3216
3217   // If the sign bits of both operands are zero (i.e. we can prove they are
3218   // unsigned inputs), turn this into a urem.
3219   if (I.getType()->isInteger()) {
3220     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3221     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3222       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3223       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3224     }
3225   }
3226
3227   // If it's a constant vector, flip any negative values positive.
3228   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3229     unsigned VWidth = RHSV->getNumOperands();
3230
3231     bool hasNegative = false;
3232     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3233       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3234         if (RHS->getValue().isNegative())
3235           hasNegative = true;
3236
3237     if (hasNegative) {
3238       std::vector<Constant *> Elts(VWidth);
3239       for (unsigned i = 0; i != VWidth; ++i) {
3240         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3241           if (RHS->getValue().isNegative())
3242             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3243           else
3244             Elts[i] = RHS;
3245         }
3246       }
3247
3248       Constant *NewRHSV = ConstantVector::get(Elts);
3249       if (NewRHSV != RHSV) {
3250         Worklist.AddValue(I.getOperand(1));
3251         I.setOperand(1, NewRHSV);
3252         return &I;
3253       }
3254     }
3255   }
3256
3257   return 0;
3258 }
3259
3260 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3261   return commonRemTransforms(I);
3262 }
3263
3264 // isOneBitSet - Return true if there is exactly one bit set in the specified
3265 // constant.
3266 static bool isOneBitSet(const ConstantInt *CI) {
3267   return CI->getValue().isPowerOf2();
3268 }
3269
3270 // isHighOnes - Return true if the constant is of the form 1+0+.
3271 // This is the same as lowones(~X).
3272 static bool isHighOnes(const ConstantInt *CI) {
3273   return (~CI->getValue() + 1).isPowerOf2();
3274 }
3275
3276 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3277 /// are carefully arranged to allow folding of expressions such as:
3278 ///
3279 ///      (A < B) | (A > B) --> (A != B)
3280 ///
3281 /// Note that this is only valid if the first and second predicates have the
3282 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3283 ///
3284 /// Three bits are used to represent the condition, as follows:
3285 ///   0  A > B
3286 ///   1  A == B
3287 ///   2  A < B
3288 ///
3289 /// <=>  Value  Definition
3290 /// 000     0   Always false
3291 /// 001     1   A >  B
3292 /// 010     2   A == B
3293 /// 011     3   A >= B
3294 /// 100     4   A <  B
3295 /// 101     5   A != B
3296 /// 110     6   A <= B
3297 /// 111     7   Always true
3298 ///  
3299 static unsigned getICmpCode(const ICmpInst *ICI) {
3300   switch (ICI->getPredicate()) {
3301     // False -> 0
3302   case ICmpInst::ICMP_UGT: return 1;  // 001
3303   case ICmpInst::ICMP_SGT: return 1;  // 001
3304   case ICmpInst::ICMP_EQ:  return 2;  // 010
3305   case ICmpInst::ICMP_UGE: return 3;  // 011
3306   case ICmpInst::ICMP_SGE: return 3;  // 011
3307   case ICmpInst::ICMP_ULT: return 4;  // 100
3308   case ICmpInst::ICMP_SLT: return 4;  // 100
3309   case ICmpInst::ICMP_NE:  return 5;  // 101
3310   case ICmpInst::ICMP_ULE: return 6;  // 110
3311   case ICmpInst::ICMP_SLE: return 6;  // 110
3312     // True -> 7
3313   default:
3314     llvm_unreachable("Invalid ICmp predicate!");
3315     return 0;
3316   }
3317 }
3318
3319 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3320 /// predicate into a three bit mask. It also returns whether it is an ordered
3321 /// predicate by reference.
3322 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3323   isOrdered = false;
3324   switch (CC) {
3325   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3326   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3327   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3328   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3329   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3330   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3331   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3332   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3333   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3334   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3335   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3336   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3337   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3338   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3339     // True -> 7
3340   default:
3341     // Not expecting FCMP_FALSE and FCMP_TRUE;
3342     llvm_unreachable("Unexpected FCmp predicate!");
3343     return 0;
3344   }
3345 }
3346
3347 /// getICmpValue - This is the complement of getICmpCode, which turns an
3348 /// opcode and two operands into either a constant true or false, or a brand 
3349 /// new ICmp instruction. The sign is passed in to determine which kind
3350 /// of predicate to use in the new icmp instruction.
3351 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3352                            LLVMContext *Context) {
3353   switch (code) {
3354   default: llvm_unreachable("Illegal ICmp code!");
3355   case  0: return ConstantInt::getFalse(*Context);
3356   case  1: 
3357     if (sign)
3358       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3359     else
3360       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3361   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3362   case  3: 
3363     if (sign)
3364       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3365     else
3366       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3367   case  4: 
3368     if (sign)
3369       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3370     else
3371       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3372   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3373   case  6: 
3374     if (sign)
3375       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3376     else
3377       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3378   case  7: return ConstantInt::getTrue(*Context);
3379   }
3380 }
3381
3382 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3383 /// opcode and two operands into either a FCmp instruction. isordered is passed
3384 /// in to determine which kind of predicate to use in the new fcmp instruction.
3385 static Value *getFCmpValue(bool isordered, unsigned code,
3386                            Value *LHS, Value *RHS, LLVMContext *Context) {
3387   switch (code) {
3388   default: llvm_unreachable("Illegal FCmp code!");
3389   case  0:
3390     if (isordered)
3391       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3392     else
3393       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3394   case  1: 
3395     if (isordered)
3396       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3397     else
3398       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3399   case  2: 
3400     if (isordered)
3401       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3402     else
3403       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3404   case  3: 
3405     if (isordered)
3406       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3407     else
3408       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3409   case  4: 
3410     if (isordered)
3411       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3412     else
3413       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3414   case  5: 
3415     if (isordered)
3416       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3417     else
3418       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3419   case  6: 
3420     if (isordered)
3421       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3422     else
3423       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3424   case  7: return ConstantInt::getTrue(*Context);
3425   }
3426 }
3427
3428 /// PredicatesFoldable - Return true if both predicates match sign or if at
3429 /// least one of them is an equality comparison (which is signless).
3430 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3431   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3432          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3433          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3434 }
3435
3436 namespace { 
3437 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3438 struct FoldICmpLogical {
3439   InstCombiner &IC;
3440   Value *LHS, *RHS;
3441   ICmpInst::Predicate pred;
3442   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3443     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3444       pred(ICI->getPredicate()) {}
3445   bool shouldApply(Value *V) const {
3446     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3447       if (PredicatesFoldable(pred, ICI->getPredicate()))
3448         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3449                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3450     return false;
3451   }
3452   Instruction *apply(Instruction &Log) const {
3453     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3454     if (ICI->getOperand(0) != LHS) {
3455       assert(ICI->getOperand(1) == LHS);
3456       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3457     }
3458
3459     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3460     unsigned LHSCode = getICmpCode(ICI);
3461     unsigned RHSCode = getICmpCode(RHSICI);
3462     unsigned Code;
3463     switch (Log.getOpcode()) {
3464     case Instruction::And: Code = LHSCode & RHSCode; break;
3465     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3466     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3467     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3468     }
3469
3470     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3471                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3472       
3473     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3474     if (Instruction *I = dyn_cast<Instruction>(RV))
3475       return I;
3476     // Otherwise, it's a constant boolean value...
3477     return IC.ReplaceInstUsesWith(Log, RV);
3478   }
3479 };
3480 } // end anonymous namespace
3481
3482 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3483 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3484 // guaranteed to be a binary operator.
3485 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3486                                     ConstantInt *OpRHS,
3487                                     ConstantInt *AndRHS,
3488                                     BinaryOperator &TheAnd) {
3489   Value *X = Op->getOperand(0);
3490   Constant *Together = 0;
3491   if (!Op->isShift())
3492     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3493
3494   switch (Op->getOpcode()) {
3495   case Instruction::Xor:
3496     if (Op->hasOneUse()) {
3497       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3498       Value *And = Builder->CreateAnd(X, AndRHS);
3499       And->takeName(Op);
3500       return BinaryOperator::CreateXor(And, Together);
3501     }
3502     break;
3503   case Instruction::Or:
3504     if (Together == AndRHS) // (X | C) & C --> C
3505       return ReplaceInstUsesWith(TheAnd, AndRHS);
3506
3507     if (Op->hasOneUse() && Together != OpRHS) {
3508       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3509       Value *Or = Builder->CreateOr(X, Together);
3510       Or->takeName(Op);
3511       return BinaryOperator::CreateAnd(Or, AndRHS);
3512     }
3513     break;
3514   case Instruction::Add:
3515     if (Op->hasOneUse()) {
3516       // Adding a one to a single bit bit-field should be turned into an XOR
3517       // of the bit.  First thing to check is to see if this AND is with a
3518       // single bit constant.
3519       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3520
3521       // If there is only one bit set...
3522       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3523         // Ok, at this point, we know that we are masking the result of the
3524         // ADD down to exactly one bit.  If the constant we are adding has
3525         // no bits set below this bit, then we can eliminate the ADD.
3526         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3527
3528         // Check to see if any bits below the one bit set in AndRHSV are set.
3529         if ((AddRHS & (AndRHSV-1)) == 0) {
3530           // If not, the only thing that can effect the output of the AND is
3531           // the bit specified by AndRHSV.  If that bit is set, the effect of
3532           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3533           // no effect.
3534           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3535             TheAnd.setOperand(0, X);
3536             return &TheAnd;
3537           } else {
3538             // Pull the XOR out of the AND.
3539             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3540             NewAnd->takeName(Op);
3541             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3542           }
3543         }
3544       }
3545     }
3546     break;
3547
3548   case Instruction::Shl: {
3549     // We know that the AND will not produce any of the bits shifted in, so if
3550     // the anded constant includes them, clear them now!
3551     //
3552     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3553     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3554     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3555     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3556
3557     if (CI->getValue() == ShlMask) { 
3558     // Masking out bits that the shift already masks
3559       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3560     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3561       TheAnd.setOperand(1, CI);
3562       return &TheAnd;
3563     }
3564     break;
3565   }
3566   case Instruction::LShr:
3567   {
3568     // We know that the AND will not produce any of the bits shifted in, so if
3569     // the anded constant includes them, clear them now!  This only applies to
3570     // unsigned shifts, because a signed shr may bring in set bits!
3571     //
3572     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3573     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3574     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3575     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3576
3577     if (CI->getValue() == ShrMask) {   
3578     // Masking out bits that the shift already masks.
3579       return ReplaceInstUsesWith(TheAnd, Op);
3580     } else if (CI != AndRHS) {
3581       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3582       return &TheAnd;
3583     }
3584     break;
3585   }
3586   case Instruction::AShr:
3587     // Signed shr.
3588     // See if this is shifting in some sign extension, then masking it out
3589     // with an and.
3590     if (Op->hasOneUse()) {
3591       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3592       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3593       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3594       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3595       if (C == AndRHS) {          // Masking out bits shifted in.
3596         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3597         // Make the argument unsigned.
3598         Value *ShVal = Op->getOperand(0);
3599         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
3600         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3601       }
3602     }
3603     break;
3604   }
3605   return 0;
3606 }
3607
3608
3609 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3610 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3611 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3612 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3613 /// insert new instructions.
3614 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3615                                            bool isSigned, bool Inside, 
3616                                            Instruction &IB) {
3617   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3618             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3619          "Lo is not <= Hi in range emission code!");
3620     
3621   if (Inside) {
3622     if (Lo == Hi)  // Trivially false.
3623       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3624
3625     // V >= Min && V < Hi --> V < Hi
3626     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3627       ICmpInst::Predicate pred = (isSigned ? 
3628         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3629       return new ICmpInst(pred, V, Hi);
3630     }
3631
3632     // Emit V-Lo <u Hi-Lo
3633     Constant *NegLo = ConstantExpr::getNeg(Lo);
3634     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3635     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3636     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3637   }
3638
3639   if (Lo == Hi)  // Trivially true.
3640     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3641
3642   // V < Min || V >= Hi -> V > Hi-1
3643   Hi = SubOne(cast<ConstantInt>(Hi));
3644   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3645     ICmpInst::Predicate pred = (isSigned ? 
3646         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3647     return new ICmpInst(pred, V, Hi);
3648   }
3649
3650   // Emit V-Lo >u Hi-1-Lo
3651   // Note that Hi has already had one subtracted from it, above.
3652   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3653   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3654   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3655   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3656 }
3657
3658 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3659 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3660 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3661 // not, since all 1s are not contiguous.
3662 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3663   const APInt& V = Val->getValue();
3664   uint32_t BitWidth = Val->getType()->getBitWidth();
3665   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3666
3667   // look for the first zero bit after the run of ones
3668   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3669   // look for the first non-zero bit
3670   ME = V.getActiveBits(); 
3671   return true;
3672 }
3673
3674 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3675 /// where isSub determines whether the operator is a sub.  If we can fold one of
3676 /// the following xforms:
3677 /// 
3678 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3679 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3680 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3681 ///
3682 /// return (A +/- B).
3683 ///
3684 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3685                                         ConstantInt *Mask, bool isSub,
3686                                         Instruction &I) {
3687   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3688   if (!LHSI || LHSI->getNumOperands() != 2 ||
3689       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3690
3691   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3692
3693   switch (LHSI->getOpcode()) {
3694   default: return 0;
3695   case Instruction::And:
3696     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3697       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3698       if ((Mask->getValue().countLeadingZeros() + 
3699            Mask->getValue().countPopulation()) == 
3700           Mask->getValue().getBitWidth())
3701         break;
3702
3703       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3704       // part, we don't need any explicit masks to take them out of A.  If that
3705       // is all N is, ignore it.
3706       uint32_t MB = 0, ME = 0;
3707       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3708         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3709         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3710         if (MaskedValueIsZero(RHS, Mask))
3711           break;
3712       }
3713     }
3714     return 0;
3715   case Instruction::Or:
3716   case Instruction::Xor:
3717     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3718     if ((Mask->getValue().countLeadingZeros() + 
3719          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3720         && ConstantExpr::getAnd(N, Mask)->isNullValue())
3721       break;
3722     return 0;
3723   }
3724   
3725   if (isSub)
3726     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3727   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
3728 }
3729
3730 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3731 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3732                                           ICmpInst *LHS, ICmpInst *RHS) {
3733   Value *Val, *Val2;
3734   ConstantInt *LHSCst, *RHSCst;
3735   ICmpInst::Predicate LHSCC, RHSCC;
3736   
3737   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3738   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3739                          m_ConstantInt(LHSCst))) ||
3740       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3741                          m_ConstantInt(RHSCst))))
3742     return 0;
3743   
3744   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3745   // where C is a power of 2
3746   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3747       LHSCst->getValue().isPowerOf2()) {
3748     Value *NewOr = Builder->CreateOr(Val, Val2);
3749     return new ICmpInst(LHSCC, NewOr, LHSCst);
3750   }
3751   
3752   // From here on, we only handle:
3753   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3754   if (Val != Val2) return 0;
3755   
3756   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3757   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3758       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3759       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3760       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3761     return 0;
3762   
3763   // We can't fold (ugt x, C) & (sgt x, C2).
3764   if (!PredicatesFoldable(LHSCC, RHSCC))
3765     return 0;
3766     
3767   // Ensure that the larger constant is on the RHS.
3768   bool ShouldSwap;
3769   if (ICmpInst::isSignedPredicate(LHSCC) ||
3770       (ICmpInst::isEquality(LHSCC) && 
3771        ICmpInst::isSignedPredicate(RHSCC)))
3772     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3773   else
3774     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3775     
3776   if (ShouldSwap) {
3777     std::swap(LHS, RHS);
3778     std::swap(LHSCst, RHSCst);
3779     std::swap(LHSCC, RHSCC);
3780   }
3781
3782   // At this point, we know we have have two icmp instructions
3783   // comparing a value against two constants and and'ing the result
3784   // together.  Because of the above check, we know that we only have
3785   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3786   // (from the FoldICmpLogical check above), that the two constants 
3787   // are not equal and that the larger constant is on the RHS
3788   assert(LHSCst != RHSCst && "Compares not folded above?");
3789
3790   switch (LHSCC) {
3791   default: llvm_unreachable("Unknown integer condition code!");
3792   case ICmpInst::ICMP_EQ:
3793     switch (RHSCC) {
3794     default: llvm_unreachable("Unknown integer condition code!");
3795     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3796     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3797     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3798       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3799     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3800     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3801     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3802       return ReplaceInstUsesWith(I, LHS);
3803     }
3804   case ICmpInst::ICMP_NE:
3805     switch (RHSCC) {
3806     default: llvm_unreachable("Unknown integer condition code!");
3807     case ICmpInst::ICMP_ULT:
3808       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3809         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3810       break;                        // (X != 13 & X u< 15) -> no change
3811     case ICmpInst::ICMP_SLT:
3812       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3813         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3814       break;                        // (X != 13 & X s< 15) -> no change
3815     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3816     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3817     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3818       return ReplaceInstUsesWith(I, RHS);
3819     case ICmpInst::ICMP_NE:
3820       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3821         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3822         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
3823         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3824                             ConstantInt::get(Add->getType(), 1));
3825       }
3826       break;                        // (X != 13 & X != 15) -> no change
3827     }
3828     break;
3829   case ICmpInst::ICMP_ULT:
3830     switch (RHSCC) {
3831     default: llvm_unreachable("Unknown integer condition code!");
3832     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3833     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3834       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3835     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3836       break;
3837     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3838     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3839       return ReplaceInstUsesWith(I, LHS);
3840     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3841       break;
3842     }
3843     break;
3844   case ICmpInst::ICMP_SLT:
3845     switch (RHSCC) {
3846     default: llvm_unreachable("Unknown integer condition code!");
3847     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3848     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3849       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3850     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3851       break;
3852     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3853     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3854       return ReplaceInstUsesWith(I, LHS);
3855     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3856       break;
3857     }
3858     break;
3859   case ICmpInst::ICMP_UGT:
3860     switch (RHSCC) {
3861     default: llvm_unreachable("Unknown integer condition code!");
3862     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3863     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3864       return ReplaceInstUsesWith(I, RHS);
3865     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3866       break;
3867     case ICmpInst::ICMP_NE:
3868       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3869         return new ICmpInst(LHSCC, Val, RHSCst);
3870       break;                        // (X u> 13 & X != 15) -> no change
3871     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3872       return InsertRangeTest(Val, AddOne(LHSCst),
3873                              RHSCst, false, true, I);
3874     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3875       break;
3876     }
3877     break;
3878   case ICmpInst::ICMP_SGT:
3879     switch (RHSCC) {
3880     default: llvm_unreachable("Unknown integer condition code!");
3881     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3882     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3883       return ReplaceInstUsesWith(I, RHS);
3884     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3885       break;
3886     case ICmpInst::ICMP_NE:
3887       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3888         return new ICmpInst(LHSCC, Val, RHSCst);
3889       break;                        // (X s> 13 & X != 15) -> no change
3890     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3891       return InsertRangeTest(Val, AddOne(LHSCst),
3892                              RHSCst, true, true, I);
3893     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3894       break;
3895     }
3896     break;
3897   }
3898  
3899   return 0;
3900 }
3901
3902 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3903                                           FCmpInst *RHS) {
3904   
3905   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3906       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3907     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3908     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3909       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3910         // If either of the constants are nans, then the whole thing returns
3911         // false.
3912         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3913           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3914         return new FCmpInst(FCmpInst::FCMP_ORD,
3915                             LHS->getOperand(0), RHS->getOperand(0));
3916       }
3917     
3918     // Handle vector zeros.  This occurs because the canonical form of
3919     // "fcmp ord x,x" is "fcmp ord x, 0".
3920     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3921         isa<ConstantAggregateZero>(RHS->getOperand(1)))
3922       return new FCmpInst(FCmpInst::FCMP_ORD,
3923                           LHS->getOperand(0), RHS->getOperand(0));
3924     return 0;
3925   }
3926   
3927   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3928   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3929   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3930   
3931   
3932   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3933     // Swap RHS operands to match LHS.
3934     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3935     std::swap(Op1LHS, Op1RHS);
3936   }
3937   
3938   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3939     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3940     if (Op0CC == Op1CC)
3941       return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3942     
3943     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
3944       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3945     if (Op0CC == FCmpInst::FCMP_TRUE)
3946       return ReplaceInstUsesWith(I, RHS);
3947     if (Op1CC == FCmpInst::FCMP_TRUE)
3948       return ReplaceInstUsesWith(I, LHS);
3949     
3950     bool Op0Ordered;
3951     bool Op1Ordered;
3952     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3953     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3954     if (Op1Pred == 0) {
3955       std::swap(LHS, RHS);
3956       std::swap(Op0Pred, Op1Pred);
3957       std::swap(Op0Ordered, Op1Ordered);
3958     }
3959     if (Op0Pred == 0) {
3960       // uno && ueq -> uno && (uno || eq) -> ueq
3961       // ord && olt -> ord && (ord && lt) -> olt
3962       if (Op0Ordered == Op1Ordered)
3963         return ReplaceInstUsesWith(I, RHS);
3964       
3965       // uno && oeq -> uno && (ord && eq) -> false
3966       // uno && ord -> false
3967       if (!Op0Ordered)
3968         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3969       // ord && ueq -> ord && (uno || eq) -> oeq
3970       return cast<Instruction>(getFCmpValue(true, Op1Pred,
3971                                             Op0LHS, Op0RHS, Context));
3972     }
3973   }
3974
3975   return 0;
3976 }
3977
3978
3979 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3980   bool Changed = SimplifyCommutative(I);
3981   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3982
3983   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3984     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3985
3986   // and X, X = X
3987   if (Op0 == Op1)
3988     return ReplaceInstUsesWith(I, Op1);
3989
3990   // See if we can simplify any instructions used by the instruction whose sole 
3991   // purpose is to compute bits we don't care about.
3992   if (SimplifyDemandedInstructionBits(I))
3993     return &I;
3994   if (isa<VectorType>(I.getType())) {
3995     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3996       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3997         return ReplaceInstUsesWith(I, I.getOperand(0));
3998     } else if (isa<ConstantAggregateZero>(Op1)) {
3999       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4000     }
4001   }
4002
4003   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4004     const APInt& AndRHSMask = AndRHS->getValue();
4005     APInt NotAndRHS(~AndRHSMask);
4006
4007     // Optimize a variety of ((val OP C1) & C2) combinations...
4008     if (isa<BinaryOperator>(Op0)) {
4009       Instruction *Op0I = cast<Instruction>(Op0);
4010       Value *Op0LHS = Op0I->getOperand(0);
4011       Value *Op0RHS = Op0I->getOperand(1);
4012       switch (Op0I->getOpcode()) {
4013       case Instruction::Xor:
4014       case Instruction::Or:
4015         // If the mask is only needed on one incoming arm, push it up.
4016         if (Op0I->hasOneUse()) {
4017           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4018             // Not masking anything out for the LHS, move to RHS.
4019             Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4020                                                Op0RHS->getName()+".masked");
4021             return BinaryOperator::Create(
4022                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4023           }
4024           if (!isa<Constant>(Op0RHS) &&
4025               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4026             // Not masking anything out for the RHS, move to LHS.
4027             Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4028                                                Op0LHS->getName()+".masked");
4029             return BinaryOperator::Create(
4030                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4031           }
4032         }
4033
4034         break;
4035       case Instruction::Add:
4036         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4037         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4038         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4039         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4040           return BinaryOperator::CreateAnd(V, AndRHS);
4041         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4042           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4043         break;
4044
4045       case Instruction::Sub:
4046         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4047         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4048         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4049         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4050           return BinaryOperator::CreateAnd(V, AndRHS);
4051
4052         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4053         // has 1's for all bits that the subtraction with A might affect.
4054         if (Op0I->hasOneUse()) {
4055           uint32_t BitWidth = AndRHSMask.getBitWidth();
4056           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4057           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4058
4059           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4060           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4061               MaskedValueIsZero(Op0LHS, Mask)) {
4062             Value *NewNeg = Builder->CreateNeg(Op0RHS);
4063             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4064           }
4065         }
4066         break;
4067
4068       case Instruction::Shl:
4069       case Instruction::LShr:
4070         // (1 << x) & 1 --> zext(x == 0)
4071         // (1 >> x) & 1 --> zext(x == 0)
4072         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4073           Value *NewICmp =
4074             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4075           return new ZExtInst(NewICmp, I.getType());
4076         }
4077         break;
4078       }
4079
4080       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4081         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4082           return Res;
4083     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4084       // If this is an integer truncation or change from signed-to-unsigned, and
4085       // if the source is an and/or with immediate, transform it.  This
4086       // frequently occurs for bitfield accesses.
4087       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4088         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4089             CastOp->getNumOperands() == 2)
4090           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4091             if (CastOp->getOpcode() == Instruction::And) {
4092               // Change: and (cast (and X, C1) to T), C2
4093               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4094               // This will fold the two constants together, which may allow 
4095               // other simplifications.
4096               Value *NewCast = Builder->CreateTruncOrBitCast(
4097                 CastOp->getOperand(0), I.getType(), 
4098                 CastOp->getName()+".shrunk");
4099               // trunc_or_bitcast(C1)&C2
4100               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4101               C3 = ConstantExpr::getAnd(C3, AndRHS);
4102               return BinaryOperator::CreateAnd(NewCast, C3);
4103             } else if (CastOp->getOpcode() == Instruction::Or) {
4104               // Change: and (cast (or X, C1) to T), C2
4105               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4106               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4107               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4108                 // trunc(C1)&C2
4109                 return ReplaceInstUsesWith(I, AndRHS);
4110             }
4111           }
4112       }
4113     }
4114
4115     // Try to fold constant and into select arguments.
4116     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4117       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4118         return R;
4119     if (isa<PHINode>(Op0))
4120       if (Instruction *NV = FoldOpIntoPhi(I))
4121         return NV;
4122   }
4123
4124   Value *Op0NotVal = dyn_castNotVal(Op0);
4125   Value *Op1NotVal = dyn_castNotVal(Op1);
4126
4127   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4128     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4129
4130   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4131   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4132     Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4133                                   I.getName()+".demorgan");
4134     return BinaryOperator::CreateNot(Or);
4135   }
4136   
4137   {
4138     Value *A = 0, *B = 0, *C = 0, *D = 0;
4139     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4140       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4141         return ReplaceInstUsesWith(I, Op1);
4142     
4143       // (A|B) & ~(A&B) -> A^B
4144       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4145         if ((A == C && B == D) || (A == D && B == C))
4146           return BinaryOperator::CreateXor(A, B);
4147       }
4148     }
4149     
4150     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4151       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4152         return ReplaceInstUsesWith(I, Op0);
4153
4154       // ~(A&B) & (A|B) -> A^B
4155       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4156         if ((A == C && B == D) || (A == D && B == C))
4157           return BinaryOperator::CreateXor(A, B);
4158       }
4159     }
4160     
4161     if (Op0->hasOneUse() &&
4162         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4163       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4164         I.swapOperands();     // Simplify below
4165         std::swap(Op0, Op1);
4166       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4167         cast<BinaryOperator>(Op0)->swapOperands();
4168         I.swapOperands();     // Simplify below
4169         std::swap(Op0, Op1);
4170       }
4171     }
4172
4173     if (Op1->hasOneUse() &&
4174         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4175       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4176         cast<BinaryOperator>(Op1)->swapOperands();
4177         std::swap(A, B);
4178       }
4179       if (A == Op0)                                // A&(A^B) -> A & ~B
4180         return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4181     }
4182
4183     // (A&((~A)|B)) -> A&B
4184     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4185         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4186       return BinaryOperator::CreateAnd(A, Op1);
4187     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4188         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4189       return BinaryOperator::CreateAnd(A, Op0);
4190   }
4191   
4192   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4193     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4194     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4195       return R;
4196
4197     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4198       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4199         return Res;
4200   }
4201
4202   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4203   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4204     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4205       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4206         const Type *SrcTy = Op0C->getOperand(0)->getType();
4207         if (SrcTy == Op1C->getOperand(0)->getType() &&
4208             SrcTy->isIntOrIntVector() &&
4209             // Only do this if the casts both really cause code to be generated.
4210             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4211                               I.getType(), TD) &&
4212             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4213                               I.getType(), TD)) {
4214           Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4215                                             Op1C->getOperand(0), I.getName());
4216           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4217         }
4218       }
4219     
4220   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4221   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4222     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4223       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4224           SI0->getOperand(1) == SI1->getOperand(1) &&
4225           (SI0->hasOneUse() || SI1->hasOneUse())) {
4226         Value *NewOp =
4227           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4228                              SI0->getName());
4229         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4230                                       SI1->getOperand(1));
4231       }
4232   }
4233
4234   // If and'ing two fcmp, try combine them into one.
4235   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4236     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4237       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4238         return Res;
4239   }
4240
4241   return Changed ? &I : 0;
4242 }
4243
4244 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4245 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4246 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4247 /// the expression came from the corresponding "byte swapped" byte in some other
4248 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4249 /// we know that the expression deposits the low byte of %X into the high byte
4250 /// of the bswap result and that all other bytes are zero.  This expression is
4251 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4252 /// match.
4253 ///
4254 /// This function returns true if the match was unsuccessful and false if so.
4255 /// On entry to the function the "OverallLeftShift" is a signed integer value
4256 /// indicating the number of bytes that the subexpression is later shifted.  For
4257 /// example, if the expression is later right shifted by 16 bits, the
4258 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4259 /// byte of ByteValues is actually being set.
4260 ///
4261 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4262 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4263 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4264 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4265 /// always in the local (OverallLeftShift) coordinate space.
4266 ///
4267 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4268                               SmallVector<Value*, 8> &ByteValues) {
4269   if (Instruction *I = dyn_cast<Instruction>(V)) {
4270     // If this is an or instruction, it may be an inner node of the bswap.
4271     if (I->getOpcode() == Instruction::Or) {
4272       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4273                                ByteValues) ||
4274              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4275                                ByteValues);
4276     }
4277   
4278     // If this is a logical shift by a constant multiple of 8, recurse with
4279     // OverallLeftShift and ByteMask adjusted.
4280     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4281       unsigned ShAmt = 
4282         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4283       // Ensure the shift amount is defined and of a byte value.
4284       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4285         return true;
4286
4287       unsigned ByteShift = ShAmt >> 3;
4288       if (I->getOpcode() == Instruction::Shl) {
4289         // X << 2 -> collect(X, +2)
4290         OverallLeftShift += ByteShift;
4291         ByteMask >>= ByteShift;
4292       } else {
4293         // X >>u 2 -> collect(X, -2)
4294         OverallLeftShift -= ByteShift;
4295         ByteMask <<= ByteShift;
4296         ByteMask &= (~0U >> (32-ByteValues.size()));
4297       }
4298
4299       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4300       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4301
4302       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4303                                ByteValues);
4304     }
4305
4306     // If this is a logical 'and' with a mask that clears bytes, clear the
4307     // corresponding bytes in ByteMask.
4308     if (I->getOpcode() == Instruction::And &&
4309         isa<ConstantInt>(I->getOperand(1))) {
4310       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4311       unsigned NumBytes = ByteValues.size();
4312       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4313       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4314       
4315       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4316         // If this byte is masked out by a later operation, we don't care what
4317         // the and mask is.
4318         if ((ByteMask & (1 << i)) == 0)
4319           continue;
4320         
4321         // If the AndMask is all zeros for this byte, clear the bit.
4322         APInt MaskB = AndMask & Byte;
4323         if (MaskB == 0) {
4324           ByteMask &= ~(1U << i);
4325           continue;
4326         }
4327         
4328         // If the AndMask is not all ones for this byte, it's not a bytezap.
4329         if (MaskB != Byte)
4330           return true;
4331
4332         // Otherwise, this byte is kept.
4333       }
4334
4335       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4336                                ByteValues);
4337     }
4338   }
4339   
4340   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4341   // the input value to the bswap.  Some observations: 1) if more than one byte
4342   // is demanded from this input, then it could not be successfully assembled
4343   // into a byteswap.  At least one of the two bytes would not be aligned with
4344   // their ultimate destination.
4345   if (!isPowerOf2_32(ByteMask)) return true;
4346   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4347   
4348   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4349   // is demanded, it needs to go into byte 0 of the result.  This means that the
4350   // byte needs to be shifted until it lands in the right byte bucket.  The
4351   // shift amount depends on the position: if the byte is coming from the high
4352   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4353   // low part, it must be shifted left.
4354   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4355   if (InputByteNo < ByteValues.size()/2) {
4356     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4357       return true;
4358   } else {
4359     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4360       return true;
4361   }
4362   
4363   // If the destination byte value is already defined, the values are or'd
4364   // together, which isn't a bswap (unless it's an or of the same bits).
4365   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4366     return true;
4367   ByteValues[DestByteNo] = V;
4368   return false;
4369 }
4370
4371 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4372 /// If so, insert the new bswap intrinsic and return it.
4373 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4374   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4375   if (!ITy || ITy->getBitWidth() % 16 || 
4376       // ByteMask only allows up to 32-byte values.
4377       ITy->getBitWidth() > 32*8) 
4378     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4379   
4380   /// ByteValues - For each byte of the result, we keep track of which value
4381   /// defines each byte.
4382   SmallVector<Value*, 8> ByteValues;
4383   ByteValues.resize(ITy->getBitWidth()/8);
4384     
4385   // Try to find all the pieces corresponding to the bswap.
4386   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4387   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4388     return 0;
4389   
4390   // Check to see if all of the bytes come from the same value.
4391   Value *V = ByteValues[0];
4392   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4393   
4394   // Check to make sure that all of the bytes come from the same value.
4395   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4396     if (ByteValues[i] != V)
4397       return 0;
4398   const Type *Tys[] = { ITy };
4399   Module *M = I.getParent()->getParent()->getParent();
4400   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4401   return CallInst::Create(F, V);
4402 }
4403
4404 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4405 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4406 /// we can simplify this expression to "cond ? C : D or B".
4407 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4408                                          Value *C, Value *D,
4409                                          LLVMContext *Context) {
4410   // If A is not a select of -1/0, this cannot match.
4411   Value *Cond = 0;
4412   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4413     return 0;
4414
4415   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4416   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4417     return SelectInst::Create(Cond, C, B);
4418   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4419     return SelectInst::Create(Cond, C, B);
4420   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4421   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4422     return SelectInst::Create(Cond, C, D);
4423   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4424     return SelectInst::Create(Cond, C, D);
4425   return 0;
4426 }
4427
4428 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4429 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4430                                          ICmpInst *LHS, ICmpInst *RHS) {
4431   Value *Val, *Val2;
4432   ConstantInt *LHSCst, *RHSCst;
4433   ICmpInst::Predicate LHSCC, RHSCC;
4434   
4435   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4436   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4437              m_ConstantInt(LHSCst))) ||
4438       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4439              m_ConstantInt(RHSCst))))
4440     return 0;
4441   
4442   // From here on, we only handle:
4443   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4444   if (Val != Val2) return 0;
4445   
4446   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4447   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4448       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4449       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4450       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4451     return 0;
4452   
4453   // We can't fold (ugt x, C) | (sgt x, C2).
4454   if (!PredicatesFoldable(LHSCC, RHSCC))
4455     return 0;
4456   
4457   // Ensure that the larger constant is on the RHS.
4458   bool ShouldSwap;
4459   if (ICmpInst::isSignedPredicate(LHSCC) ||
4460       (ICmpInst::isEquality(LHSCC) && 
4461        ICmpInst::isSignedPredicate(RHSCC)))
4462     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4463   else
4464     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4465   
4466   if (ShouldSwap) {
4467     std::swap(LHS, RHS);
4468     std::swap(LHSCst, RHSCst);
4469     std::swap(LHSCC, RHSCC);
4470   }
4471   
4472   // At this point, we know we have have two icmp instructions
4473   // comparing a value against two constants and or'ing the result
4474   // together.  Because of the above check, we know that we only have
4475   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4476   // FoldICmpLogical check above), that the two constants are not
4477   // equal.
4478   assert(LHSCst != RHSCst && "Compares not folded above?");
4479
4480   switch (LHSCC) {
4481   default: llvm_unreachable("Unknown integer condition code!");
4482   case ICmpInst::ICMP_EQ:
4483     switch (RHSCC) {
4484     default: llvm_unreachable("Unknown integer condition code!");
4485     case ICmpInst::ICMP_EQ:
4486       if (LHSCst == SubOne(RHSCst)) {
4487         // (X == 13 | X == 14) -> X-13 <u 2
4488         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4489         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4490         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4491         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4492       }
4493       break;                         // (X == 13 | X == 15) -> no change
4494     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4495     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4496       break;
4497     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4498     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4499     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4500       return ReplaceInstUsesWith(I, RHS);
4501     }
4502     break;
4503   case ICmpInst::ICMP_NE:
4504     switch (RHSCC) {
4505     default: llvm_unreachable("Unknown integer condition code!");
4506     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4507     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4508     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4509       return ReplaceInstUsesWith(I, LHS);
4510     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4511     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4512     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4513       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4514     }
4515     break;
4516   case ICmpInst::ICMP_ULT:
4517     switch (RHSCC) {
4518     default: llvm_unreachable("Unknown integer condition code!");
4519     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4520       break;
4521     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4522       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4523       // this can cause overflow.
4524       if (RHSCst->isMaxValue(false))
4525         return ReplaceInstUsesWith(I, LHS);
4526       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4527                              false, false, I);
4528     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4529       break;
4530     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4531     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4532       return ReplaceInstUsesWith(I, RHS);
4533     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4534       break;
4535     }
4536     break;
4537   case ICmpInst::ICMP_SLT:
4538     switch (RHSCC) {
4539     default: llvm_unreachable("Unknown integer condition code!");
4540     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4541       break;
4542     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4543       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4544       // this can cause overflow.
4545       if (RHSCst->isMaxValue(true))
4546         return ReplaceInstUsesWith(I, LHS);
4547       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4548                              true, false, I);
4549     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4550       break;
4551     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4552     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4553       return ReplaceInstUsesWith(I, RHS);
4554     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4555       break;
4556     }
4557     break;
4558   case ICmpInst::ICMP_UGT:
4559     switch (RHSCC) {
4560     default: llvm_unreachable("Unknown integer condition code!");
4561     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4562     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4563       return ReplaceInstUsesWith(I, LHS);
4564     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4565       break;
4566     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4567     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4568       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4569     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4570       break;
4571     }
4572     break;
4573   case ICmpInst::ICMP_SGT:
4574     switch (RHSCC) {
4575     default: llvm_unreachable("Unknown integer condition code!");
4576     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4577     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4578       return ReplaceInstUsesWith(I, LHS);
4579     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4580       break;
4581     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4582     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4583       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4584     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4585       break;
4586     }
4587     break;
4588   }
4589   return 0;
4590 }
4591
4592 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4593                                          FCmpInst *RHS) {
4594   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4595       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4596       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4597     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4598       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4599         // If either of the constants are nans, then the whole thing returns
4600         // true.
4601         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4602           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4603         
4604         // Otherwise, no need to compare the two constants, compare the
4605         // rest.
4606         return new FCmpInst(FCmpInst::FCMP_UNO,
4607                             LHS->getOperand(0), RHS->getOperand(0));
4608       }
4609     
4610     // Handle vector zeros.  This occurs because the canonical form of
4611     // "fcmp uno x,x" is "fcmp uno x, 0".
4612     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4613         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4614       return new FCmpInst(FCmpInst::FCMP_UNO,
4615                           LHS->getOperand(0), RHS->getOperand(0));
4616     
4617     return 0;
4618   }
4619   
4620   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4621   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4622   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4623   
4624   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4625     // Swap RHS operands to match LHS.
4626     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4627     std::swap(Op1LHS, Op1RHS);
4628   }
4629   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4630     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4631     if (Op0CC == Op1CC)
4632       return new FCmpInst((FCmpInst::Predicate)Op0CC,
4633                           Op0LHS, Op0RHS);
4634     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4635       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4636     if (Op0CC == FCmpInst::FCMP_FALSE)
4637       return ReplaceInstUsesWith(I, RHS);
4638     if (Op1CC == FCmpInst::FCMP_FALSE)
4639       return ReplaceInstUsesWith(I, LHS);
4640     bool Op0Ordered;
4641     bool Op1Ordered;
4642     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4643     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4644     if (Op0Ordered == Op1Ordered) {
4645       // If both are ordered or unordered, return a new fcmp with
4646       // or'ed predicates.
4647       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4648                                Op0LHS, Op0RHS, Context);
4649       if (Instruction *I = dyn_cast<Instruction>(RV))
4650         return I;
4651       // Otherwise, it's a constant boolean value...
4652       return ReplaceInstUsesWith(I, RV);
4653     }
4654   }
4655   return 0;
4656 }
4657
4658 /// FoldOrWithConstants - This helper function folds:
4659 ///
4660 ///     ((A | B) & C1) | (B & C2)
4661 ///
4662 /// into:
4663 /// 
4664 ///     (A & C1) | B
4665 ///
4666 /// when the XOR of the two constants is "all ones" (-1).
4667 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4668                                                Value *A, Value *B, Value *C) {
4669   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4670   if (!CI1) return 0;
4671
4672   Value *V1 = 0;
4673   ConstantInt *CI2 = 0;
4674   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4675
4676   APInt Xor = CI1->getValue() ^ CI2->getValue();
4677   if (!Xor.isAllOnesValue()) return 0;
4678
4679   if (V1 == A || V1 == B) {
4680     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
4681     return BinaryOperator::CreateOr(NewOp, V1);
4682   }
4683
4684   return 0;
4685 }
4686
4687 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4688   bool Changed = SimplifyCommutative(I);
4689   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4690
4691   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4692     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4693
4694   // or X, X = X
4695   if (Op0 == Op1)
4696     return ReplaceInstUsesWith(I, Op0);
4697
4698   // See if we can simplify any instructions used by the instruction whose sole 
4699   // purpose is to compute bits we don't care about.
4700   if (SimplifyDemandedInstructionBits(I))
4701     return &I;
4702   if (isa<VectorType>(I.getType())) {
4703     if (isa<ConstantAggregateZero>(Op1)) {
4704       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4705     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4706       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4707         return ReplaceInstUsesWith(I, I.getOperand(1));
4708     }
4709   }
4710
4711   // or X, -1 == -1
4712   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4713     ConstantInt *C1 = 0; Value *X = 0;
4714     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4715     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
4716         isOnlyUse(Op0)) {
4717       Value *Or = Builder->CreateOr(X, RHS);
4718       Or->takeName(Op0);
4719       return BinaryOperator::CreateAnd(Or, 
4720                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4721     }
4722
4723     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4724     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
4725         isOnlyUse(Op0)) {
4726       Value *Or = Builder->CreateOr(X, RHS);
4727       Or->takeName(Op0);
4728       return BinaryOperator::CreateXor(Or,
4729                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4730     }
4731
4732     // Try to fold constant and into select arguments.
4733     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4734       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4735         return R;
4736     if (isa<PHINode>(Op0))
4737       if (Instruction *NV = FoldOpIntoPhi(I))
4738         return NV;
4739   }
4740
4741   Value *A = 0, *B = 0;
4742   ConstantInt *C1 = 0, *C2 = 0;
4743
4744   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4745     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4746       return ReplaceInstUsesWith(I, Op1);
4747   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4748     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4749       return ReplaceInstUsesWith(I, Op0);
4750
4751   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4752   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4753   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4754       match(Op1, m_Or(m_Value(), m_Value())) ||
4755       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4756        match(Op1, m_Shift(m_Value(), m_Value())))) {
4757     if (Instruction *BSwap = MatchBSwap(I))
4758       return BSwap;
4759   }
4760   
4761   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4762   if (Op0->hasOneUse() &&
4763       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4764       MaskedValueIsZero(Op1, C1->getValue())) {
4765     Value *NOr = Builder->CreateOr(A, Op1);
4766     NOr->takeName(Op0);
4767     return BinaryOperator::CreateXor(NOr, C1);
4768   }
4769
4770   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4771   if (Op1->hasOneUse() &&
4772       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4773       MaskedValueIsZero(Op0, C1->getValue())) {
4774     Value *NOr = Builder->CreateOr(A, Op0);
4775     NOr->takeName(Op0);
4776     return BinaryOperator::CreateXor(NOr, C1);
4777   }
4778
4779   // (A & C)|(B & D)
4780   Value *C = 0, *D = 0;
4781   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4782       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4783     Value *V1 = 0, *V2 = 0, *V3 = 0;
4784     C1 = dyn_cast<ConstantInt>(C);
4785     C2 = dyn_cast<ConstantInt>(D);
4786     if (C1 && C2) {  // (A & C1)|(B & C2)
4787       // If we have: ((V + N) & C1) | (V & C2)
4788       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4789       // replace with V+N.
4790       if (C1->getValue() == ~C2->getValue()) {
4791         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4792             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4793           // Add commutes, try both ways.
4794           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4795             return ReplaceInstUsesWith(I, A);
4796           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4797             return ReplaceInstUsesWith(I, A);
4798         }
4799         // Or commutes, try both ways.
4800         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4801             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4802           // Add commutes, try both ways.
4803           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4804             return ReplaceInstUsesWith(I, B);
4805           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4806             return ReplaceInstUsesWith(I, B);
4807         }
4808       }
4809       V1 = 0; V2 = 0; V3 = 0;
4810     }
4811     
4812     // Check to see if we have any common things being and'ed.  If so, find the
4813     // terms for V1 & (V2|V3).
4814     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4815       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4816         V1 = A, V2 = C, V3 = D;
4817       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4818         V1 = A, V2 = B, V3 = C;
4819       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4820         V1 = C, V2 = A, V3 = D;
4821       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4822         V1 = C, V2 = A, V3 = B;
4823       
4824       if (V1) {
4825         Value *Or = Builder->CreateOr(V2, V3, "tmp");
4826         return BinaryOperator::CreateAnd(V1, Or);
4827       }
4828     }
4829
4830     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4831     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4832       return Match;
4833     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4834       return Match;
4835     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4836       return Match;
4837     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4838       return Match;
4839
4840     // ((A&~B)|(~A&B)) -> A^B
4841     if ((match(C, m_Not(m_Specific(D))) &&
4842          match(B, m_Not(m_Specific(A)))))
4843       return BinaryOperator::CreateXor(A, D);
4844     // ((~B&A)|(~A&B)) -> A^B
4845     if ((match(A, m_Not(m_Specific(D))) &&
4846          match(B, m_Not(m_Specific(C)))))
4847       return BinaryOperator::CreateXor(C, D);
4848     // ((A&~B)|(B&~A)) -> A^B
4849     if ((match(C, m_Not(m_Specific(B))) &&
4850          match(D, m_Not(m_Specific(A)))))
4851       return BinaryOperator::CreateXor(A, B);
4852     // ((~B&A)|(B&~A)) -> A^B
4853     if ((match(A, m_Not(m_Specific(B))) &&
4854          match(D, m_Not(m_Specific(C)))))
4855       return BinaryOperator::CreateXor(C, B);
4856   }
4857   
4858   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4859   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4860     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4861       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4862           SI0->getOperand(1) == SI1->getOperand(1) &&
4863           (SI0->hasOneUse() || SI1->hasOneUse())) {
4864         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4865                                          SI0->getName());
4866         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4867                                       SI1->getOperand(1));
4868       }
4869   }
4870
4871   // ((A|B)&1)|(B&-2) -> (A&1) | B
4872   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4873       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4874     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4875     if (Ret) return Ret;
4876   }
4877   // (B&-2)|((A|B)&1) -> (A&1) | B
4878   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4879       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4880     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4881     if (Ret) return Ret;
4882   }
4883
4884   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4885     if (A == Op1)   // ~A | A == -1
4886       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4887   } else {
4888     A = 0;
4889   }
4890   // Note, A is still live here!
4891   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4892     if (Op0 == B)
4893       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4894
4895     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4896     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4897       Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
4898       return BinaryOperator::CreateNot(And);
4899     }
4900   }
4901
4902   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4903   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4904     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4905       return R;
4906
4907     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4908       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4909         return Res;
4910   }
4911     
4912   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4913   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4914     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4915       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4916         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4917             !isa<ICmpInst>(Op1C->getOperand(0))) {
4918           const Type *SrcTy = Op0C->getOperand(0)->getType();
4919           if (SrcTy == Op1C->getOperand(0)->getType() &&
4920               SrcTy->isIntOrIntVector() &&
4921               // Only do this if the casts both really cause code to be
4922               // generated.
4923               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4924                                 I.getType(), TD) &&
4925               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4926                                 I.getType(), TD)) {
4927             Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4928                                              Op1C->getOperand(0), I.getName());
4929             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4930           }
4931         }
4932       }
4933   }
4934   
4935     
4936   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4937   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4938     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4939       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4940         return Res;
4941   }
4942
4943   return Changed ? &I : 0;
4944 }
4945
4946 namespace {
4947
4948 // XorSelf - Implements: X ^ X --> 0
4949 struct XorSelf {
4950   Value *RHS;
4951   XorSelf(Value *rhs) : RHS(rhs) {}
4952   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4953   Instruction *apply(BinaryOperator &Xor) const {
4954     return &Xor;
4955   }
4956 };
4957
4958 }
4959
4960 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4961   bool Changed = SimplifyCommutative(I);
4962   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4963
4964   if (isa<UndefValue>(Op1)) {
4965     if (isa<UndefValue>(Op0))
4966       // Handle undef ^ undef -> 0 special case. This is a common
4967       // idiom (misuse).
4968       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4969     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4970   }
4971
4972   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4973   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4974     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4975     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4976   }
4977   
4978   // See if we can simplify any instructions used by the instruction whose sole 
4979   // purpose is to compute bits we don't care about.
4980   if (SimplifyDemandedInstructionBits(I))
4981     return &I;
4982   if (isa<VectorType>(I.getType()))
4983     if (isa<ConstantAggregateZero>(Op1))
4984       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4985
4986   // Is this a ~ operation?
4987   if (Value *NotOp = dyn_castNotVal(&I)) {
4988     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4989     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4990     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4991       if (Op0I->getOpcode() == Instruction::And || 
4992           Op0I->getOpcode() == Instruction::Or) {
4993         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4994         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4995           Value *NotY =
4996             Builder->CreateNot(Op0I->getOperand(1),
4997                                Op0I->getOperand(1)->getName()+".not");
4998           if (Op0I->getOpcode() == Instruction::And)
4999             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5000           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5001         }
5002       }
5003     }
5004   }
5005   
5006   
5007   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5008     if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
5009       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5010       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5011         return new ICmpInst(ICI->getInversePredicate(),
5012                             ICI->getOperand(0), ICI->getOperand(1));
5013
5014       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5015         return new FCmpInst(FCI->getInversePredicate(),
5016                             FCI->getOperand(0), FCI->getOperand(1));
5017     }
5018
5019     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5020     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5021       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5022         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5023           Instruction::CastOps Opcode = Op0C->getOpcode();
5024           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5025               (RHS == ConstantExpr::getCast(Opcode, 
5026                                             ConstantInt::getTrue(*Context),
5027                                             Op0C->getDestTy()))) {
5028             CI->setPredicate(CI->getInversePredicate());
5029             return CastInst::Create(Opcode, CI, Op0C->getType());
5030           }
5031         }
5032       }
5033     }
5034
5035     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5036       // ~(c-X) == X-c-1 == X+(-c-1)
5037       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5038         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5039           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5040           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5041                                       ConstantInt::get(I.getType(), 1));
5042           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5043         }
5044           
5045       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5046         if (Op0I->getOpcode() == Instruction::Add) {
5047           // ~(X-c) --> (-c-1)-X
5048           if (RHS->isAllOnesValue()) {
5049             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5050             return BinaryOperator::CreateSub(
5051                            ConstantExpr::getSub(NegOp0CI,
5052                                       ConstantInt::get(I.getType(), 1)),
5053                                       Op0I->getOperand(0));
5054           } else if (RHS->getValue().isSignBit()) {
5055             // (X + C) ^ signbit -> (X + C + signbit)
5056             Constant *C = ConstantInt::get(*Context,
5057                                            RHS->getValue() + Op0CI->getValue());
5058             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5059
5060           }
5061         } else if (Op0I->getOpcode() == Instruction::Or) {
5062           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5063           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5064             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5065             // Anything in both C1 and C2 is known to be zero, remove it from
5066             // NewRHS.
5067             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5068             NewRHS = ConstantExpr::getAnd(NewRHS, 
5069                                        ConstantExpr::getNot(CommonBits));
5070             Worklist.Add(Op0I);
5071             I.setOperand(0, Op0I->getOperand(0));
5072             I.setOperand(1, NewRHS);
5073             return &I;
5074           }
5075         }
5076       }
5077     }
5078
5079     // Try to fold constant and into select arguments.
5080     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5081       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5082         return R;
5083     if (isa<PHINode>(Op0))
5084       if (Instruction *NV = FoldOpIntoPhi(I))
5085         return NV;
5086   }
5087
5088   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5089     if (X == Op1)
5090       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5091
5092   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5093     if (X == Op0)
5094       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5095
5096   
5097   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5098   if (Op1I) {
5099     Value *A, *B;
5100     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5101       if (A == Op0) {              // B^(B|A) == (A|B)^B
5102         Op1I->swapOperands();
5103         I.swapOperands();
5104         std::swap(Op0, Op1);
5105       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5106         I.swapOperands();     // Simplified below.
5107         std::swap(Op0, Op1);
5108       }
5109     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5110       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5111     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5112       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5113     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
5114                Op1I->hasOneUse()){
5115       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5116         Op1I->swapOperands();
5117         std::swap(A, B);
5118       }
5119       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5120         I.swapOperands();     // Simplified below.
5121         std::swap(Op0, Op1);
5122       }
5123     }
5124   }
5125   
5126   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5127   if (Op0I) {
5128     Value *A, *B;
5129     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5130         Op0I->hasOneUse()) {
5131       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5132         std::swap(A, B);
5133       if (B == Op1)                                  // (A|B)^B == A & ~B
5134         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5135     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5136       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5137     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5138       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5139     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
5140                Op0I->hasOneUse()){
5141       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5142         std::swap(A, B);
5143       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5144           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5145         return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5146       }
5147     }
5148   }
5149   
5150   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5151   if (Op0I && Op1I && Op0I->isShift() && 
5152       Op0I->getOpcode() == Op1I->getOpcode() && 
5153       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5154       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5155     Value *NewOp =
5156       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5157                          Op0I->getName());
5158     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5159                                   Op1I->getOperand(1));
5160   }
5161     
5162   if (Op0I && Op1I) {
5163     Value *A, *B, *C, *D;
5164     // (A & B)^(A | B) -> A ^ B
5165     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5166         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5167       if ((A == C && B == D) || (A == D && B == C)) 
5168         return BinaryOperator::CreateXor(A, B);
5169     }
5170     // (A | B)^(A & B) -> A ^ B
5171     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5172         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5173       if ((A == C && B == D) || (A == D && B == C)) 
5174         return BinaryOperator::CreateXor(A, B);
5175     }
5176     
5177     // (A & B)^(C & D)
5178     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5179         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5180         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5181       // (X & Y)^(X & Y) -> (Y^Z) & X
5182       Value *X = 0, *Y = 0, *Z = 0;
5183       if (A == C)
5184         X = A, Y = B, Z = D;
5185       else if (A == D)
5186         X = A, Y = B, Z = C;
5187       else if (B == C)
5188         X = B, Y = A, Z = D;
5189       else if (B == D)
5190         X = B, Y = A, Z = C;
5191       
5192       if (X) {
5193         Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5194         return BinaryOperator::CreateAnd(NewOp, X);
5195       }
5196     }
5197   }
5198     
5199   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5200   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5201     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5202       return R;
5203
5204   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5205   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5206     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5207       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5208         const Type *SrcTy = Op0C->getOperand(0)->getType();
5209         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5210             // Only do this if the casts both really cause code to be generated.
5211             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5212                               I.getType(), TD) &&
5213             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5214                               I.getType(), TD)) {
5215           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5216                                             Op1C->getOperand(0), I.getName());
5217           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5218         }
5219       }
5220   }
5221
5222   return Changed ? &I : 0;
5223 }
5224
5225 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5226                                    LLVMContext *Context) {
5227   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5228 }
5229
5230 static bool HasAddOverflow(ConstantInt *Result,
5231                            ConstantInt *In1, ConstantInt *In2,
5232                            bool IsSigned) {
5233   if (IsSigned)
5234     if (In2->getValue().isNegative())
5235       return Result->getValue().sgt(In1->getValue());
5236     else
5237       return Result->getValue().slt(In1->getValue());
5238   else
5239     return Result->getValue().ult(In1->getValue());
5240 }
5241
5242 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5243 /// overflowed for this type.
5244 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5245                             Constant *In2, LLVMContext *Context,
5246                             bool IsSigned = false) {
5247   Result = ConstantExpr::getAdd(In1, In2);
5248
5249   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5250     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5251       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5252       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5253                          ExtractElement(In1, Idx, Context),
5254                          ExtractElement(In2, Idx, Context),
5255                          IsSigned))
5256         return true;
5257     }
5258     return false;
5259   }
5260
5261   return HasAddOverflow(cast<ConstantInt>(Result),
5262                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5263                         IsSigned);
5264 }
5265
5266 static bool HasSubOverflow(ConstantInt *Result,
5267                            ConstantInt *In1, ConstantInt *In2,
5268                            bool IsSigned) {
5269   if (IsSigned)
5270     if (In2->getValue().isNegative())
5271       return Result->getValue().slt(In1->getValue());
5272     else
5273       return Result->getValue().sgt(In1->getValue());
5274   else
5275     return Result->getValue().ugt(In1->getValue());
5276 }
5277
5278 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5279 /// overflowed for this type.
5280 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5281                             Constant *In2, LLVMContext *Context,
5282                             bool IsSigned = false) {
5283   Result = ConstantExpr::getSub(In1, In2);
5284
5285   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5286     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5287       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5288       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5289                          ExtractElement(In1, Idx, Context),
5290                          ExtractElement(In2, Idx, Context),
5291                          IsSigned))
5292         return true;
5293     }
5294     return false;
5295   }
5296
5297   return HasSubOverflow(cast<ConstantInt>(Result),
5298                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5299                         IsSigned);
5300 }
5301
5302 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5303 /// code necessary to compute the offset from the base pointer (without adding
5304 /// in the base pointer).  Return the result as a signed integer of intptr size.
5305 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5306   TargetData &TD = *IC.getTargetData();
5307   gep_type_iterator GTI = gep_type_begin(GEP);
5308   const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
5309   Value *Result = Constant::getNullValue(IntPtrTy);
5310
5311   // Build a mask for high order bits.
5312   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5313   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5314
5315   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5316        ++i, ++GTI) {
5317     Value *Op = *i;
5318     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5319     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5320       if (OpC->isZero()) continue;
5321       
5322       // Handle a struct index, which adds its field offset to the pointer.
5323       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5324         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5325         
5326         Result = IC.Builder->CreateAdd(Result,
5327                                        ConstantInt::get(IntPtrTy, Size),
5328                                        GEP->getName()+".offs");
5329         continue;
5330       }
5331       
5332       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5333       Constant *OC =
5334               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5335       Scale = ConstantExpr::getMul(OC, Scale);
5336       // Emit an add instruction.
5337       Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
5338       continue;
5339     }
5340     // Convert to correct type.
5341     if (Op->getType() != IntPtrTy)
5342       Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
5343     if (Size != 1) {
5344       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5345       // We'll let instcombine(mul) convert this to a shl if possible.
5346       Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
5347     }
5348
5349     // Emit an add instruction.
5350     Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
5351   }
5352   return Result;
5353 }
5354
5355
5356 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5357 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5358 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5359 /// be complex, and scales are involved.  The above expression would also be
5360 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5361 /// This later form is less amenable to optimization though, and we are allowed
5362 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5363 ///
5364 /// If we can't emit an optimized form for this expression, this returns null.
5365 /// 
5366 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5367                                           InstCombiner &IC) {
5368   TargetData &TD = *IC.getTargetData();
5369   gep_type_iterator GTI = gep_type_begin(GEP);
5370
5371   // Check to see if this gep only has a single variable index.  If so, and if
5372   // any constant indices are a multiple of its scale, then we can compute this
5373   // in terms of the scale of the variable index.  For example, if the GEP
5374   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5375   // because the expression will cross zero at the same point.
5376   unsigned i, e = GEP->getNumOperands();
5377   int64_t Offset = 0;
5378   for (i = 1; i != e; ++i, ++GTI) {
5379     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5380       // Compute the aggregate offset of constant indices.
5381       if (CI->isZero()) continue;
5382
5383       // Handle a struct index, which adds its field offset to the pointer.
5384       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5385         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5386       } else {
5387         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5388         Offset += Size*CI->getSExtValue();
5389       }
5390     } else {
5391       // Found our variable index.
5392       break;
5393     }
5394   }
5395   
5396   // If there are no variable indices, we must have a constant offset, just
5397   // evaluate it the general way.
5398   if (i == e) return 0;
5399   
5400   Value *VariableIdx = GEP->getOperand(i);
5401   // Determine the scale factor of the variable element.  For example, this is
5402   // 4 if the variable index is into an array of i32.
5403   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5404   
5405   // Verify that there are no other variable indices.  If so, emit the hard way.
5406   for (++i, ++GTI; i != e; ++i, ++GTI) {
5407     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5408     if (!CI) return 0;
5409    
5410     // Compute the aggregate offset of constant indices.
5411     if (CI->isZero()) continue;
5412     
5413     // Handle a struct index, which adds its field offset to the pointer.
5414     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5415       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5416     } else {
5417       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5418       Offset += Size*CI->getSExtValue();
5419     }
5420   }
5421   
5422   // Okay, we know we have a single variable index, which must be a
5423   // pointer/array/vector index.  If there is no offset, life is simple, return
5424   // the index.
5425   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5426   if (Offset == 0) {
5427     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5428     // we don't need to bother extending: the extension won't affect where the
5429     // computation crosses zero.
5430     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5431       VariableIdx = new TruncInst(VariableIdx, 
5432                                   TD.getIntPtrType(VariableIdx->getContext()),
5433                                   VariableIdx->getName(), &I);
5434     return VariableIdx;
5435   }
5436   
5437   // Otherwise, there is an index.  The computation we will do will be modulo
5438   // the pointer size, so get it.
5439   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5440   
5441   Offset &= PtrSizeMask;
5442   VariableScale &= PtrSizeMask;
5443
5444   // To do this transformation, any constant index must be a multiple of the
5445   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5446   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5447   // multiple of the variable scale.
5448   int64_t NewOffs = Offset / (int64_t)VariableScale;
5449   if (Offset != NewOffs*(int64_t)VariableScale)
5450     return 0;
5451
5452   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5453   const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
5454   if (VariableIdx->getType() != IntPtrTy)
5455     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5456                                               true /*SExt*/, 
5457                                               VariableIdx->getName(), &I);
5458   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5459   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5460 }
5461
5462
5463 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5464 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5465 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5466                                        ICmpInst::Predicate Cond,
5467                                        Instruction &I) {
5468   // Look through bitcasts.
5469   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5470     RHS = BCI->getOperand(0);
5471
5472   Value *PtrBase = GEPLHS->getOperand(0);
5473   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5474     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5475     // This transformation (ignoring the base and scales) is valid because we
5476     // know pointers can't overflow since the gep is inbounds.  See if we can
5477     // output an optimized form.
5478     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5479     
5480     // If not, synthesize the offset the hard way.
5481     if (Offset == 0)
5482       Offset = EmitGEPOffset(GEPLHS, I, *this);
5483     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5484                         Constant::getNullValue(Offset->getType()));
5485   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5486     // If the base pointers are different, but the indices are the same, just
5487     // compare the base pointer.
5488     if (PtrBase != GEPRHS->getOperand(0)) {
5489       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5490       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5491                         GEPRHS->getOperand(0)->getType();
5492       if (IndicesTheSame)
5493         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5494           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5495             IndicesTheSame = false;
5496             break;
5497           }
5498
5499       // If all indices are the same, just compare the base pointers.
5500       if (IndicesTheSame)
5501         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5502                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5503
5504       // Otherwise, the base pointers are different and the indices are
5505       // different, bail out.
5506       return 0;
5507     }
5508
5509     // If one of the GEPs has all zero indices, recurse.
5510     bool AllZeros = true;
5511     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5512       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5513           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5514         AllZeros = false;
5515         break;
5516       }
5517     if (AllZeros)
5518       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5519                           ICmpInst::getSwappedPredicate(Cond), I);
5520
5521     // If the other GEP has all zero indices, recurse.
5522     AllZeros = true;
5523     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5524       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5525           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5526         AllZeros = false;
5527         break;
5528       }
5529     if (AllZeros)
5530       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5531
5532     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5533       // If the GEPs only differ by one index, compare it.
5534       unsigned NumDifferences = 0;  // Keep track of # differences.
5535       unsigned DiffOperand = 0;     // The operand that differs.
5536       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5537         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5538           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5539                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5540             // Irreconcilable differences.
5541             NumDifferences = 2;
5542             break;
5543           } else {
5544             if (NumDifferences++) break;
5545             DiffOperand = i;
5546           }
5547         }
5548
5549       if (NumDifferences == 0)   // SAME GEP?
5550         return ReplaceInstUsesWith(I, // No comparison is needed here.
5551                                    ConstantInt::get(Type::getInt1Ty(*Context),
5552                                              ICmpInst::isTrueWhenEqual(Cond)));
5553
5554       else if (NumDifferences == 1) {
5555         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5556         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5557         // Make sure we do a signed comparison here.
5558         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5559       }
5560     }
5561
5562     // Only lower this if the icmp is the only user of the GEP or if we expect
5563     // the result to fold to a constant!
5564     if (TD &&
5565         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5566         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5567       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5568       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5569       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5570       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5571     }
5572   }
5573   return 0;
5574 }
5575
5576 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5577 ///
5578 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5579                                                 Instruction *LHSI,
5580                                                 Constant *RHSC) {
5581   if (!isa<ConstantFP>(RHSC)) return 0;
5582   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5583   
5584   // Get the width of the mantissa.  We don't want to hack on conversions that
5585   // might lose information from the integer, e.g. "i64 -> float"
5586   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5587   if (MantissaWidth == -1) return 0;  // Unknown.
5588   
5589   // Check to see that the input is converted from an integer type that is small
5590   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5591   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5592   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5593   
5594   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5595   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5596   if (LHSUnsigned)
5597     ++InputSize;
5598   
5599   // If the conversion would lose info, don't hack on this.
5600   if ((int)InputSize > MantissaWidth)
5601     return 0;
5602   
5603   // Otherwise, we can potentially simplify the comparison.  We know that it
5604   // will always come through as an integer value and we know the constant is
5605   // not a NAN (it would have been previously simplified).
5606   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5607   
5608   ICmpInst::Predicate Pred;
5609   switch (I.getPredicate()) {
5610   default: llvm_unreachable("Unexpected predicate!");
5611   case FCmpInst::FCMP_UEQ:
5612   case FCmpInst::FCMP_OEQ:
5613     Pred = ICmpInst::ICMP_EQ;
5614     break;
5615   case FCmpInst::FCMP_UGT:
5616   case FCmpInst::FCMP_OGT:
5617     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5618     break;
5619   case FCmpInst::FCMP_UGE:
5620   case FCmpInst::FCMP_OGE:
5621     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5622     break;
5623   case FCmpInst::FCMP_ULT:
5624   case FCmpInst::FCMP_OLT:
5625     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5626     break;
5627   case FCmpInst::FCMP_ULE:
5628   case FCmpInst::FCMP_OLE:
5629     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5630     break;
5631   case FCmpInst::FCMP_UNE:
5632   case FCmpInst::FCMP_ONE:
5633     Pred = ICmpInst::ICMP_NE;
5634     break;
5635   case FCmpInst::FCMP_ORD:
5636     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5637   case FCmpInst::FCMP_UNO:
5638     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5639   }
5640   
5641   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5642   
5643   // Now we know that the APFloat is a normal number, zero or inf.
5644   
5645   // See if the FP constant is too large for the integer.  For example,
5646   // comparing an i8 to 300.0.
5647   unsigned IntWidth = IntTy->getScalarSizeInBits();
5648   
5649   if (!LHSUnsigned) {
5650     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5651     // and large values.
5652     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5653     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5654                           APFloat::rmNearestTiesToEven);
5655     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5656       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5657           Pred == ICmpInst::ICMP_SLE)
5658         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5659       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5660     }
5661   } else {
5662     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5663     // +INF and large values.
5664     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5665     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5666                           APFloat::rmNearestTiesToEven);
5667     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5668       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5669           Pred == ICmpInst::ICMP_ULE)
5670         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5671       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5672     }
5673   }
5674   
5675   if (!LHSUnsigned) {
5676     // See if the RHS value is < SignedMin.
5677     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5678     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5679                           APFloat::rmNearestTiesToEven);
5680     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5681       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5682           Pred == ICmpInst::ICMP_SGE)
5683         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5684       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5685     }
5686   }
5687
5688   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5689   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5690   // casting the FP value to the integer value and back, checking for equality.
5691   // Don't do this for zero, because -0.0 is not fractional.
5692   Constant *RHSInt = LHSUnsigned
5693     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5694     : ConstantExpr::getFPToSI(RHSC, IntTy);
5695   if (!RHS.isZero()) {
5696     bool Equal = LHSUnsigned
5697       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5698       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5699     if (!Equal) {
5700       // If we had a comparison against a fractional value, we have to adjust
5701       // the compare predicate and sometimes the value.  RHSC is rounded towards
5702       // zero at this point.
5703       switch (Pred) {
5704       default: llvm_unreachable("Unexpected integer comparison!");
5705       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5706         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5707       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5708         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5709       case ICmpInst::ICMP_ULE:
5710         // (float)int <= 4.4   --> int <= 4
5711         // (float)int <= -4.4  --> false
5712         if (RHS.isNegative())
5713           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5714         break;
5715       case ICmpInst::ICMP_SLE:
5716         // (float)int <= 4.4   --> int <= 4
5717         // (float)int <= -4.4  --> int < -4
5718         if (RHS.isNegative())
5719           Pred = ICmpInst::ICMP_SLT;
5720         break;
5721       case ICmpInst::ICMP_ULT:
5722         // (float)int < -4.4   --> false
5723         // (float)int < 4.4    --> int <= 4
5724         if (RHS.isNegative())
5725           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5726         Pred = ICmpInst::ICMP_ULE;
5727         break;
5728       case ICmpInst::ICMP_SLT:
5729         // (float)int < -4.4   --> int < -4
5730         // (float)int < 4.4    --> int <= 4
5731         if (!RHS.isNegative())
5732           Pred = ICmpInst::ICMP_SLE;
5733         break;
5734       case ICmpInst::ICMP_UGT:
5735         // (float)int > 4.4    --> int > 4
5736         // (float)int > -4.4   --> true
5737         if (RHS.isNegative())
5738           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5739         break;
5740       case ICmpInst::ICMP_SGT:
5741         // (float)int > 4.4    --> int > 4
5742         // (float)int > -4.4   --> int >= -4
5743         if (RHS.isNegative())
5744           Pred = ICmpInst::ICMP_SGE;
5745         break;
5746       case ICmpInst::ICMP_UGE:
5747         // (float)int >= -4.4   --> true
5748         // (float)int >= 4.4    --> int > 4
5749         if (!RHS.isNegative())
5750           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5751         Pred = ICmpInst::ICMP_UGT;
5752         break;
5753       case ICmpInst::ICMP_SGE:
5754         // (float)int >= -4.4   --> int >= -4
5755         // (float)int >= 4.4    --> int > 4
5756         if (!RHS.isNegative())
5757           Pred = ICmpInst::ICMP_SGT;
5758         break;
5759       }
5760     }
5761   }
5762
5763   // Lower this FP comparison into an appropriate integer version of the
5764   // comparison.
5765   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5766 }
5767
5768 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5769   bool Changed = SimplifyCompare(I);
5770   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5771
5772   // Fold trivial predicates.
5773   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5774     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5775   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5776     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5777   
5778   // Simplify 'fcmp pred X, X'
5779   if (Op0 == Op1) {
5780     switch (I.getPredicate()) {
5781     default: llvm_unreachable("Unknown predicate!");
5782     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5783     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5784     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5785       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5786     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5787     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5788     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5789       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5790       
5791     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5792     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5793     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5794     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5795       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5796       I.setPredicate(FCmpInst::FCMP_UNO);
5797       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5798       return &I;
5799       
5800     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5801     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5802     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5803     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5804       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5805       I.setPredicate(FCmpInst::FCMP_ORD);
5806       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5807       return &I;
5808     }
5809   }
5810     
5811   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5812     return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
5813
5814   // Handle fcmp with constant RHS
5815   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5816     // If the constant is a nan, see if we can fold the comparison based on it.
5817     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5818       if (CFP->getValueAPF().isNaN()) {
5819         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5820           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5821         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5822                "Comparison must be either ordered or unordered!");
5823         // True if unordered.
5824         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5825       }
5826     }
5827     
5828     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5829       switch (LHSI->getOpcode()) {
5830       case Instruction::PHI:
5831         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5832         // block.  If in the same block, we're encouraging jump threading.  If
5833         // not, we are just pessimizing the code by making an i1 phi.
5834         if (LHSI->getParent() == I.getParent())
5835           if (Instruction *NV = FoldOpIntoPhi(I))
5836             return NV;
5837         break;
5838       case Instruction::SIToFP:
5839       case Instruction::UIToFP:
5840         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5841           return NV;
5842         break;
5843       case Instruction::Select:
5844         // If either operand of the select is a constant, we can fold the
5845         // comparison into the select arms, which will cause one to be
5846         // constant folded and the select turned into a bitwise or.
5847         Value *Op1 = 0, *Op2 = 0;
5848         if (LHSI->hasOneUse()) {
5849           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5850             // Fold the known value into the constant operand.
5851             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5852             // Insert a new FCmp of the other select operand.
5853             Op2 = Builder->CreateFCmp(I.getPredicate(),
5854                                       LHSI->getOperand(2), RHSC, I.getName());
5855           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5856             // Fold the known value into the constant operand.
5857             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5858             // Insert a new FCmp of the other select operand.
5859             Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5860                                       RHSC, I.getName());
5861           }
5862         }
5863
5864         if (Op1)
5865           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5866         break;
5867       }
5868   }
5869
5870   return Changed ? &I : 0;
5871 }
5872
5873 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5874   bool Changed = SimplifyCompare(I);
5875   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5876   const Type *Ty = Op0->getType();
5877
5878   // icmp X, X
5879   if (Op0 == Op1)
5880     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
5881                                                    I.isTrueWhenEqual()));
5882
5883   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5884     return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
5885   
5886   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5887   // addresses never equal each other!  We already know that Op0 != Op1.
5888   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5889        isa<ConstantPointerNull>(Op0)) &&
5890       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5891        isa<ConstantPointerNull>(Op1)))
5892     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
5893                                                    !I.isTrueWhenEqual()));
5894
5895   // icmp's with boolean values can always be turned into bitwise operations
5896   if (Ty == Type::getInt1Ty(*Context)) {
5897     switch (I.getPredicate()) {
5898     default: llvm_unreachable("Invalid icmp instruction!");
5899     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5900       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
5901       return BinaryOperator::CreateNot(Xor);
5902     }
5903     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5904       return BinaryOperator::CreateXor(Op0, Op1);
5905
5906     case ICmpInst::ICMP_UGT:
5907       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5908       // FALL THROUGH
5909     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5910       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
5911       return BinaryOperator::CreateAnd(Not, Op1);
5912     }
5913     case ICmpInst::ICMP_SGT:
5914       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5915       // FALL THROUGH
5916     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5917       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
5918       return BinaryOperator::CreateAnd(Not, Op0);
5919     }
5920     case ICmpInst::ICMP_UGE:
5921       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5922       // FALL THROUGH
5923     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5924       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
5925       return BinaryOperator::CreateOr(Not, Op1);
5926     }
5927     case ICmpInst::ICMP_SGE:
5928       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5929       // FALL THROUGH
5930     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5931       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
5932       return BinaryOperator::CreateOr(Not, Op0);
5933     }
5934     }
5935   }
5936
5937   unsigned BitWidth = 0;
5938   if (TD)
5939     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5940   else if (Ty->isIntOrIntVector())
5941     BitWidth = Ty->getScalarSizeInBits();
5942
5943   bool isSignBit = false;
5944
5945   // See if we are doing a comparison with a constant.
5946   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5947     Value *A = 0, *B = 0;
5948     
5949     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5950     if (I.isEquality() && CI->isNullValue() &&
5951         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5952       // (icmp cond A B) if cond is equality
5953       return new ICmpInst(I.getPredicate(), A, B);
5954     }
5955     
5956     // If we have an icmp le or icmp ge instruction, turn it into the
5957     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
5958     // them being folded in the code below.
5959     switch (I.getPredicate()) {
5960     default: break;
5961     case ICmpInst::ICMP_ULE:
5962       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5963         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5964       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
5965                           AddOne(CI));
5966     case ICmpInst::ICMP_SLE:
5967       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5968         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5969       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5970                           AddOne(CI));
5971     case ICmpInst::ICMP_UGE:
5972       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5973         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5974       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
5975                           SubOne(CI));
5976     case ICmpInst::ICMP_SGE:
5977       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5978         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5979       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5980                           SubOne(CI));
5981     }
5982     
5983     // If this comparison is a normal comparison, it demands all
5984     // bits, if it is a sign bit comparison, it only demands the sign bit.
5985     bool UnusedBit;
5986     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5987   }
5988
5989   // See if we can fold the comparison based on range information we can get
5990   // by checking whether bits are known to be zero or one in the input.
5991   if (BitWidth != 0) {
5992     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
5993     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
5994
5995     if (SimplifyDemandedBits(I.getOperandUse(0),
5996                              isSignBit ? APInt::getSignBit(BitWidth)
5997                                        : APInt::getAllOnesValue(BitWidth),
5998                              Op0KnownZero, Op0KnownOne, 0))
5999       return &I;
6000     if (SimplifyDemandedBits(I.getOperandUse(1),
6001                              APInt::getAllOnesValue(BitWidth),
6002                              Op1KnownZero, Op1KnownOne, 0))
6003       return &I;
6004
6005     // Given the known and unknown bits, compute a range that the LHS could be
6006     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6007     // EQ and NE we use unsigned values.
6008     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6009     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6010     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6011       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6012                                              Op0Min, Op0Max);
6013       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6014                                              Op1Min, Op1Max);
6015     } else {
6016       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6017                                                Op0Min, Op0Max);
6018       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6019                                                Op1Min, Op1Max);
6020     }
6021
6022     // If Min and Max are known to be the same, then SimplifyDemandedBits
6023     // figured out that the LHS is a constant.  Just constant fold this now so
6024     // that code below can assume that Min != Max.
6025     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6026       return new ICmpInst(I.getPredicate(),
6027                           ConstantInt::get(*Context, Op0Min), Op1);
6028     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6029       return new ICmpInst(I.getPredicate(), Op0,
6030                           ConstantInt::get(*Context, Op1Min));
6031
6032     // Based on the range information we know about the LHS, see if we can
6033     // simplify this comparison.  For example, (x&4) < 8  is always true.
6034     switch (I.getPredicate()) {
6035     default: llvm_unreachable("Unknown icmp opcode!");
6036     case ICmpInst::ICMP_EQ:
6037       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6038         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6039       break;
6040     case ICmpInst::ICMP_NE:
6041       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6042         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6043       break;
6044     case ICmpInst::ICMP_ULT:
6045       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6046         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6047       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6048         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6049       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6050         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6051       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6052         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6053           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6054                               SubOne(CI));
6055
6056         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6057         if (CI->isMinValue(true))
6058           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6059                            Constant::getAllOnesValue(Op0->getType()));
6060       }
6061       break;
6062     case ICmpInst::ICMP_UGT:
6063       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6064         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6065       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6066         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6067
6068       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6069         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6070       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6071         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6072           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6073                               AddOne(CI));
6074
6075         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6076         if (CI->isMaxValue(true))
6077           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6078                               Constant::getNullValue(Op0->getType()));
6079       }
6080       break;
6081     case ICmpInst::ICMP_SLT:
6082       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6083         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6084       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6085         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6086       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6087         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6088       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6089         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6090           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6091                               SubOne(CI));
6092       }
6093       break;
6094     case ICmpInst::ICMP_SGT:
6095       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6096         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6097       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6098         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6099
6100       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6101         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6102       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6103         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6104           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6105                               AddOne(CI));
6106       }
6107       break;
6108     case ICmpInst::ICMP_SGE:
6109       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6110       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6111         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6112       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6113         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6114       break;
6115     case ICmpInst::ICMP_SLE:
6116       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6117       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6118         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6119       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6120         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6121       break;
6122     case ICmpInst::ICMP_UGE:
6123       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6124       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6125         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6126       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6127         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6128       break;
6129     case ICmpInst::ICMP_ULE:
6130       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6131       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6132         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6133       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6134         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6135       break;
6136     }
6137
6138     // Turn a signed comparison into an unsigned one if both operands
6139     // are known to have the same sign.
6140     if (I.isSignedPredicate() &&
6141         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6142          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6143       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6144   }
6145
6146   // Test if the ICmpInst instruction is used exclusively by a select as
6147   // part of a minimum or maximum operation. If so, refrain from doing
6148   // any other folding. This helps out other analyses which understand
6149   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6150   // and CodeGen. And in this case, at least one of the comparison
6151   // operands has at least one user besides the compare (the select),
6152   // which would often largely negate the benefit of folding anyway.
6153   if (I.hasOneUse())
6154     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6155       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6156           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6157         return 0;
6158
6159   // See if we are doing a comparison between a constant and an instruction that
6160   // can be folded into the comparison.
6161   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6162     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6163     // instruction, see if that instruction also has constants so that the 
6164     // instruction can be folded into the icmp 
6165     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6166       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6167         return Res;
6168   }
6169
6170   // Handle icmp with constant (but not simple integer constant) RHS
6171   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6172     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6173       switch (LHSI->getOpcode()) {
6174       case Instruction::GetElementPtr:
6175         if (RHSC->isNullValue()) {
6176           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6177           bool isAllZeros = true;
6178           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6179             if (!isa<Constant>(LHSI->getOperand(i)) ||
6180                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6181               isAllZeros = false;
6182               break;
6183             }
6184           if (isAllZeros)
6185             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6186                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6187         }
6188         break;
6189
6190       case Instruction::PHI:
6191         // Only fold icmp into the PHI if the phi and fcmp are in the same
6192         // block.  If in the same block, we're encouraging jump threading.  If
6193         // not, we are just pessimizing the code by making an i1 phi.
6194         if (LHSI->getParent() == I.getParent())
6195           if (Instruction *NV = FoldOpIntoPhi(I))
6196             return NV;
6197         break;
6198       case Instruction::Select: {
6199         // If either operand of the select is a constant, we can fold the
6200         // comparison into the select arms, which will cause one to be
6201         // constant folded and the select turned into a bitwise or.
6202         Value *Op1 = 0, *Op2 = 0;
6203         if (LHSI->hasOneUse()) {
6204           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6205             // Fold the known value into the constant operand.
6206             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6207             // Insert a new ICmp of the other select operand.
6208             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6209                                       RHSC, I.getName());
6210           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6211             // Fold the known value into the constant operand.
6212             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6213             // Insert a new ICmp of the other select operand.
6214             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6215                                       RHSC, I.getName());
6216           }
6217         }
6218
6219         if (Op1)
6220           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6221         break;
6222       }
6223       case Instruction::Malloc:
6224         // If we have (malloc != null), and if the malloc has a single use, we
6225         // can assume it is successful and remove the malloc.
6226         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6227           Worklist.Add(LHSI);
6228           return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
6229                                                          !I.isTrueWhenEqual()));
6230         }
6231         break;
6232       }
6233   }
6234
6235   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6236   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6237     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6238       return NI;
6239   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6240     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6241                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6242       return NI;
6243
6244   // Test to see if the operands of the icmp are casted versions of other
6245   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6246   // now.
6247   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6248     if (isa<PointerType>(Op0->getType()) && 
6249         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6250       // We keep moving the cast from the left operand over to the right
6251       // operand, where it can often be eliminated completely.
6252       Op0 = CI->getOperand(0);
6253
6254       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6255       // so eliminate it as well.
6256       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6257         Op1 = CI2->getOperand(0);
6258
6259       // If Op1 is a constant, we can fold the cast into the constant.
6260       if (Op0->getType() != Op1->getType()) {
6261         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6262           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6263         } else {
6264           // Otherwise, cast the RHS right before the icmp
6265           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6266         }
6267       }
6268       return new ICmpInst(I.getPredicate(), Op0, Op1);
6269     }
6270   }
6271   
6272   if (isa<CastInst>(Op0)) {
6273     // Handle the special case of: icmp (cast bool to X), <cst>
6274     // This comes up when you have code like
6275     //   int X = A < B;
6276     //   if (X) ...
6277     // For generality, we handle any zero-extension of any operand comparison
6278     // with a constant or another cast from the same type.
6279     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6280       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6281         return R;
6282   }
6283   
6284   // See if it's the same type of instruction on the left and right.
6285   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6286     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6287       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6288           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6289         switch (Op0I->getOpcode()) {
6290         default: break;
6291         case Instruction::Add:
6292         case Instruction::Sub:
6293         case Instruction::Xor:
6294           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6295             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6296                                 Op1I->getOperand(0));
6297           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6298           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6299             if (CI->getValue().isSignBit()) {
6300               ICmpInst::Predicate Pred = I.isSignedPredicate()
6301                                              ? I.getUnsignedPredicate()
6302                                              : I.getSignedPredicate();
6303               return new ICmpInst(Pred, Op0I->getOperand(0),
6304                                   Op1I->getOperand(0));
6305             }
6306             
6307             if (CI->getValue().isMaxSignedValue()) {
6308               ICmpInst::Predicate Pred = I.isSignedPredicate()
6309                                              ? I.getUnsignedPredicate()
6310                                              : I.getSignedPredicate();
6311               Pred = I.getSwappedPredicate(Pred);
6312               return new ICmpInst(Pred, Op0I->getOperand(0),
6313                                   Op1I->getOperand(0));
6314             }
6315           }
6316           break;
6317         case Instruction::Mul:
6318           if (!I.isEquality())
6319             break;
6320
6321           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6322             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6323             // Mask = -1 >> count-trailing-zeros(Cst).
6324             if (!CI->isZero() && !CI->isOne()) {
6325               const APInt &AP = CI->getValue();
6326               ConstantInt *Mask = ConstantInt::get(*Context, 
6327                                       APInt::getLowBitsSet(AP.getBitWidth(),
6328                                                            AP.getBitWidth() -
6329                                                       AP.countTrailingZeros()));
6330               Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6331               Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6332               return new ICmpInst(I.getPredicate(), And1, And2);
6333             }
6334           }
6335           break;
6336         }
6337       }
6338     }
6339   }
6340   
6341   // ~x < ~y --> y < x
6342   { Value *A, *B;
6343     if (match(Op0, m_Not(m_Value(A))) &&
6344         match(Op1, m_Not(m_Value(B))))
6345       return new ICmpInst(I.getPredicate(), B, A);
6346   }
6347   
6348   if (I.isEquality()) {
6349     Value *A, *B, *C, *D;
6350     
6351     // -x == -y --> x == y
6352     if (match(Op0, m_Neg(m_Value(A))) &&
6353         match(Op1, m_Neg(m_Value(B))))
6354       return new ICmpInst(I.getPredicate(), A, B);
6355     
6356     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6357       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6358         Value *OtherVal = A == Op1 ? B : A;
6359         return new ICmpInst(I.getPredicate(), OtherVal,
6360                             Constant::getNullValue(A->getType()));
6361       }
6362
6363       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6364         // A^c1 == C^c2 --> A == C^(c1^c2)
6365         ConstantInt *C1, *C2;
6366         if (match(B, m_ConstantInt(C1)) &&
6367             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6368           Constant *NC = 
6369                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6370           Value *Xor = Builder->CreateXor(C, NC, "tmp");
6371           return new ICmpInst(I.getPredicate(), A, Xor);
6372         }
6373         
6374         // A^B == A^D -> B == D
6375         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6376         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6377         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6378         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6379       }
6380     }
6381     
6382     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6383         (A == Op0 || B == Op0)) {
6384       // A == (A^B)  ->  B == 0
6385       Value *OtherVal = A == Op0 ? B : A;
6386       return new ICmpInst(I.getPredicate(), OtherVal,
6387                           Constant::getNullValue(A->getType()));
6388     }
6389
6390     // (A-B) == A  ->  B == 0
6391     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6392       return new ICmpInst(I.getPredicate(), B, 
6393                           Constant::getNullValue(B->getType()));
6394
6395     // A == (A-B)  ->  B == 0
6396     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6397       return new ICmpInst(I.getPredicate(), B,
6398                           Constant::getNullValue(B->getType()));
6399     
6400     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6401     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6402         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6403         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6404       Value *X = 0, *Y = 0, *Z = 0;
6405       
6406       if (A == C) {
6407         X = B; Y = D; Z = A;
6408       } else if (A == D) {
6409         X = B; Y = C; Z = A;
6410       } else if (B == C) {
6411         X = A; Y = D; Z = B;
6412       } else if (B == D) {
6413         X = A; Y = C; Z = B;
6414       }
6415       
6416       if (X) {   // Build (X^Y) & Z
6417         Op1 = Builder->CreateXor(X, Y, "tmp");
6418         Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6419         I.setOperand(0, Op1);
6420         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6421         return &I;
6422       }
6423     }
6424   }
6425   return Changed ? &I : 0;
6426 }
6427
6428
6429 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6430 /// and CmpRHS are both known to be integer constants.
6431 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6432                                           ConstantInt *DivRHS) {
6433   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6434   const APInt &CmpRHSV = CmpRHS->getValue();
6435   
6436   // FIXME: If the operand types don't match the type of the divide 
6437   // then don't attempt this transform. The code below doesn't have the
6438   // logic to deal with a signed divide and an unsigned compare (and
6439   // vice versa). This is because (x /s C1) <s C2  produces different 
6440   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6441   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6442   // work. :(  The if statement below tests that condition and bails 
6443   // if it finds it. 
6444   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6445   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6446     return 0;
6447   if (DivRHS->isZero())
6448     return 0; // The ProdOV computation fails on divide by zero.
6449   if (DivIsSigned && DivRHS->isAllOnesValue())
6450     return 0; // The overflow computation also screws up here
6451   if (DivRHS->isOne())
6452     return 0; // Not worth bothering, and eliminates some funny cases
6453               // with INT_MIN.
6454
6455   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6456   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6457   // C2 (CI). By solving for X we can turn this into a range check 
6458   // instead of computing a divide. 
6459   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6460
6461   // Determine if the product overflows by seeing if the product is
6462   // not equal to the divide. Make sure we do the same kind of divide
6463   // as in the LHS instruction that we're folding. 
6464   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6465                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6466
6467   // Get the ICmp opcode
6468   ICmpInst::Predicate Pred = ICI.getPredicate();
6469
6470   // Figure out the interval that is being checked.  For example, a comparison
6471   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6472   // Compute this interval based on the constants involved and the signedness of
6473   // the compare/divide.  This computes a half-open interval, keeping track of
6474   // whether either value in the interval overflows.  After analysis each
6475   // overflow variable is set to 0 if it's corresponding bound variable is valid
6476   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6477   int LoOverflow = 0, HiOverflow = 0;
6478   Constant *LoBound = 0, *HiBound = 0;
6479   
6480   if (!DivIsSigned) {  // udiv
6481     // e.g. X/5 op 3  --> [15, 20)
6482     LoBound = Prod;
6483     HiOverflow = LoOverflow = ProdOV;
6484     if (!HiOverflow)
6485       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6486   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6487     if (CmpRHSV == 0) {       // (X / pos) op 0
6488       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6489       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6490       HiBound = DivRHS;
6491     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6492       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6493       HiOverflow = LoOverflow = ProdOV;
6494       if (!HiOverflow)
6495         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6496     } else {                       // (X / pos) op neg
6497       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6498       HiBound = AddOne(Prod);
6499       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6500       if (!LoOverflow) {
6501         ConstantInt* DivNeg =
6502                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6503         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6504                                      true) ? -1 : 0;
6505        }
6506     }
6507   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6508     if (CmpRHSV == 0) {       // (X / neg) op 0
6509       // e.g. X/-5 op 0  --> [-4, 5)
6510       LoBound = AddOne(DivRHS);
6511       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6512       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6513         HiOverflow = 1;            // [INTMIN+1, overflow)
6514         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6515       }
6516     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6517       // e.g. X/-5 op 3  --> [-19, -14)
6518       HiBound = AddOne(Prod);
6519       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6520       if (!LoOverflow)
6521         LoOverflow = AddWithOverflow(LoBound, HiBound,
6522                                      DivRHS, Context, true) ? -1 : 0;
6523     } else {                       // (X / neg) op neg
6524       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6525       LoOverflow = HiOverflow = ProdOV;
6526       if (!HiOverflow)
6527         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6528     }
6529     
6530     // Dividing by a negative swaps the condition.  LT <-> GT
6531     Pred = ICmpInst::getSwappedPredicate(Pred);
6532   }
6533
6534   Value *X = DivI->getOperand(0);
6535   switch (Pred) {
6536   default: llvm_unreachable("Unhandled icmp opcode!");
6537   case ICmpInst::ICMP_EQ:
6538     if (LoOverflow && HiOverflow)
6539       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6540     else if (HiOverflow)
6541       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6542                           ICmpInst::ICMP_UGE, X, LoBound);
6543     else if (LoOverflow)
6544       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6545                           ICmpInst::ICMP_ULT, X, HiBound);
6546     else
6547       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6548   case ICmpInst::ICMP_NE:
6549     if (LoOverflow && HiOverflow)
6550       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6551     else if (HiOverflow)
6552       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6553                           ICmpInst::ICMP_ULT, X, LoBound);
6554     else if (LoOverflow)
6555       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6556                           ICmpInst::ICMP_UGE, X, HiBound);
6557     else
6558       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6559   case ICmpInst::ICMP_ULT:
6560   case ICmpInst::ICMP_SLT:
6561     if (LoOverflow == +1)   // Low bound is greater than input range.
6562       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6563     if (LoOverflow == -1)   // Low bound is less than input range.
6564       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6565     return new ICmpInst(Pred, X, LoBound);
6566   case ICmpInst::ICMP_UGT:
6567   case ICmpInst::ICMP_SGT:
6568     if (HiOverflow == +1)       // High bound greater than input range.
6569       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6570     else if (HiOverflow == -1)  // High bound less than input range.
6571       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6572     if (Pred == ICmpInst::ICMP_UGT)
6573       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6574     else
6575       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6576   }
6577 }
6578
6579
6580 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6581 ///
6582 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6583                                                           Instruction *LHSI,
6584                                                           ConstantInt *RHS) {
6585   const APInt &RHSV = RHS->getValue();
6586   
6587   switch (LHSI->getOpcode()) {
6588   case Instruction::Trunc:
6589     if (ICI.isEquality() && LHSI->hasOneUse()) {
6590       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6591       // of the high bits truncated out of x are known.
6592       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6593              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6594       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6595       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6596       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6597       
6598       // If all the high bits are known, we can do this xform.
6599       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6600         // Pull in the high bits from known-ones set.
6601         APInt NewRHS(RHS->getValue());
6602         NewRHS.zext(SrcBits);
6603         NewRHS |= KnownOne;
6604         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6605                             ConstantInt::get(*Context, NewRHS));
6606       }
6607     }
6608     break;
6609       
6610   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6611     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6612       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6613       // fold the xor.
6614       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6615           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6616         Value *CompareVal = LHSI->getOperand(0);
6617         
6618         // If the sign bit of the XorCST is not set, there is no change to
6619         // the operation, just stop using the Xor.
6620         if (!XorCST->getValue().isNegative()) {
6621           ICI.setOperand(0, CompareVal);
6622           Worklist.Add(LHSI);
6623           return &ICI;
6624         }
6625         
6626         // Was the old condition true if the operand is positive?
6627         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6628         
6629         // If so, the new one isn't.
6630         isTrueIfPositive ^= true;
6631         
6632         if (isTrueIfPositive)
6633           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6634                               SubOne(RHS));
6635         else
6636           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6637                               AddOne(RHS));
6638       }
6639
6640       if (LHSI->hasOneUse()) {
6641         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6642         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6643           const APInt &SignBit = XorCST->getValue();
6644           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6645                                          ? ICI.getUnsignedPredicate()
6646                                          : ICI.getSignedPredicate();
6647           return new ICmpInst(Pred, LHSI->getOperand(0),
6648                               ConstantInt::get(*Context, RHSV ^ SignBit));
6649         }
6650
6651         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6652         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6653           const APInt &NotSignBit = XorCST->getValue();
6654           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6655                                          ? ICI.getUnsignedPredicate()
6656                                          : ICI.getSignedPredicate();
6657           Pred = ICI.getSwappedPredicate(Pred);
6658           return new ICmpInst(Pred, LHSI->getOperand(0),
6659                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
6660         }
6661       }
6662     }
6663     break;
6664   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6665     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6666         LHSI->getOperand(0)->hasOneUse()) {
6667       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6668       
6669       // If the LHS is an AND of a truncating cast, we can widen the
6670       // and/compare to be the input width without changing the value
6671       // produced, eliminating a cast.
6672       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6673         // We can do this transformation if either the AND constant does not
6674         // have its sign bit set or if it is an equality comparison. 
6675         // Extending a relational comparison when we're checking the sign
6676         // bit would not work.
6677         if (Cast->hasOneUse() &&
6678             (ICI.isEquality() ||
6679              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6680           uint32_t BitWidth = 
6681             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6682           APInt NewCST = AndCST->getValue();
6683           NewCST.zext(BitWidth);
6684           APInt NewCI = RHSV;
6685           NewCI.zext(BitWidth);
6686           Value *NewAnd = 
6687             Builder->CreateAnd(Cast->getOperand(0),
6688                            ConstantInt::get(*Context, NewCST), LHSI->getName());
6689           return new ICmpInst(ICI.getPredicate(), NewAnd,
6690                               ConstantInt::get(*Context, NewCI));
6691         }
6692       }
6693       
6694       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6695       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6696       // happens a LOT in code produced by the C front-end, for bitfield
6697       // access.
6698       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6699       if (Shift && !Shift->isShift())
6700         Shift = 0;
6701       
6702       ConstantInt *ShAmt;
6703       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6704       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6705       const Type *AndTy = AndCST->getType();          // Type of the and.
6706       
6707       // We can fold this as long as we can't shift unknown bits
6708       // into the mask.  This can only happen with signed shift
6709       // rights, as they sign-extend.
6710       if (ShAmt) {
6711         bool CanFold = Shift->isLogicalShift();
6712         if (!CanFold) {
6713           // To test for the bad case of the signed shr, see if any
6714           // of the bits shifted in could be tested after the mask.
6715           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6716           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6717           
6718           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6719           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6720                AndCST->getValue()) == 0)
6721             CanFold = true;
6722         }
6723         
6724         if (CanFold) {
6725           Constant *NewCst;
6726           if (Shift->getOpcode() == Instruction::Shl)
6727             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6728           else
6729             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6730           
6731           // Check to see if we are shifting out any of the bits being
6732           // compared.
6733           if (ConstantExpr::get(Shift->getOpcode(),
6734                                        NewCst, ShAmt) != RHS) {
6735             // If we shifted bits out, the fold is not going to work out.
6736             // As a special case, check to see if this means that the
6737             // result is always true or false now.
6738             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6739               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6740             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6741               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6742           } else {
6743             ICI.setOperand(1, NewCst);
6744             Constant *NewAndCST;
6745             if (Shift->getOpcode() == Instruction::Shl)
6746               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6747             else
6748               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6749             LHSI->setOperand(1, NewAndCST);
6750             LHSI->setOperand(0, Shift->getOperand(0));
6751             Worklist.Add(Shift); // Shift is dead.
6752             return &ICI;
6753           }
6754         }
6755       }
6756       
6757       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6758       // preferable because it allows the C<<Y expression to be hoisted out
6759       // of a loop if Y is invariant and X is not.
6760       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6761           ICI.isEquality() && !Shift->isArithmeticShift() &&
6762           !isa<Constant>(Shift->getOperand(0))) {
6763         // Compute C << Y.
6764         Value *NS;
6765         if (Shift->getOpcode() == Instruction::LShr) {
6766           NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
6767         } else {
6768           // Insert a logical shift.
6769           NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
6770         }
6771         
6772         // Compute X & (C << Y).
6773         Value *NewAnd = 
6774           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6775         
6776         ICI.setOperand(0, NewAnd);
6777         return &ICI;
6778       }
6779     }
6780     break;
6781     
6782   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6783     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6784     if (!ShAmt) break;
6785     
6786     uint32_t TypeBits = RHSV.getBitWidth();
6787     
6788     // Check that the shift amount is in range.  If not, don't perform
6789     // undefined shifts.  When the shift is visited it will be
6790     // simplified.
6791     if (ShAmt->uge(TypeBits))
6792       break;
6793     
6794     if (ICI.isEquality()) {
6795       // If we are comparing against bits always shifted out, the
6796       // comparison cannot succeed.
6797       Constant *Comp =
6798         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6799                                                                  ShAmt);
6800       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6801         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6802         Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6803         return ReplaceInstUsesWith(ICI, Cst);
6804       }
6805       
6806       if (LHSI->hasOneUse()) {
6807         // Otherwise strength reduce the shift into an and.
6808         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6809         Constant *Mask =
6810           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
6811                                                        TypeBits-ShAmtVal));
6812         
6813         Value *And =
6814           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
6815         return new ICmpInst(ICI.getPredicate(), And,
6816                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6817       }
6818     }
6819     
6820     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6821     bool TrueIfSigned = false;
6822     if (LHSI->hasOneUse() &&
6823         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6824       // (X << 31) <s 0  --> (X&1) != 0
6825       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6826                                            (TypeBits-ShAmt->getZExtValue()-1));
6827       Value *And =
6828         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
6829       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6830                           And, Constant::getNullValue(And->getType()));
6831     }
6832     break;
6833   }
6834     
6835   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6836   case Instruction::AShr: {
6837     // Only handle equality comparisons of shift-by-constant.
6838     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6839     if (!ShAmt || !ICI.isEquality()) break;
6840
6841     // Check that the shift amount is in range.  If not, don't perform
6842     // undefined shifts.  When the shift is visited it will be
6843     // simplified.
6844     uint32_t TypeBits = RHSV.getBitWidth();
6845     if (ShAmt->uge(TypeBits))
6846       break;
6847     
6848     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6849       
6850     // If we are comparing against bits always shifted out, the
6851     // comparison cannot succeed.
6852     APInt Comp = RHSV << ShAmtVal;
6853     if (LHSI->getOpcode() == Instruction::LShr)
6854       Comp = Comp.lshr(ShAmtVal);
6855     else
6856       Comp = Comp.ashr(ShAmtVal);
6857     
6858     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6859       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6860       Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6861       return ReplaceInstUsesWith(ICI, Cst);
6862     }
6863     
6864     // Otherwise, check to see if the bits shifted out are known to be zero.
6865     // If so, we can compare against the unshifted value:
6866     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6867     if (LHSI->hasOneUse() &&
6868         MaskedValueIsZero(LHSI->getOperand(0), 
6869                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6870       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6871                           ConstantExpr::getShl(RHS, ShAmt));
6872     }
6873       
6874     if (LHSI->hasOneUse()) {
6875       // Otherwise strength reduce the shift into an and.
6876       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6877       Constant *Mask = ConstantInt::get(*Context, Val);
6878       
6879       Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6880                                       Mask, LHSI->getName()+".mask");
6881       return new ICmpInst(ICI.getPredicate(), And,
6882                           ConstantExpr::getShl(RHS, ShAmt));
6883     }
6884     break;
6885   }
6886     
6887   case Instruction::SDiv:
6888   case Instruction::UDiv:
6889     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6890     // Fold this div into the comparison, producing a range check. 
6891     // Determine, based on the divide type, what the range is being 
6892     // checked.  If there is an overflow on the low or high side, remember 
6893     // it, otherwise compute the range [low, hi) bounding the new value.
6894     // See: InsertRangeTest above for the kinds of replacements possible.
6895     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6896       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6897                                           DivRHS))
6898         return R;
6899     break;
6900
6901   case Instruction::Add:
6902     // Fold: icmp pred (add, X, C1), C2
6903
6904     if (!ICI.isEquality()) {
6905       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6906       if (!LHSC) break;
6907       const APInt &LHSV = LHSC->getValue();
6908
6909       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6910                             .subtract(LHSV);
6911
6912       if (ICI.isSignedPredicate()) {
6913         if (CR.getLower().isSignBit()) {
6914           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6915                               ConstantInt::get(*Context, CR.getUpper()));
6916         } else if (CR.getUpper().isSignBit()) {
6917           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6918                               ConstantInt::get(*Context, CR.getLower()));
6919         }
6920       } else {
6921         if (CR.getLower().isMinValue()) {
6922           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6923                               ConstantInt::get(*Context, CR.getUpper()));
6924         } else if (CR.getUpper().isMinValue()) {
6925           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6926                               ConstantInt::get(*Context, CR.getLower()));
6927         }
6928       }
6929     }
6930     break;
6931   }
6932   
6933   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6934   if (ICI.isEquality()) {
6935     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6936     
6937     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6938     // the second operand is a constant, simplify a bit.
6939     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6940       switch (BO->getOpcode()) {
6941       case Instruction::SRem:
6942         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6943         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6944           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6945           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6946             Value *NewRem =
6947               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
6948                                   BO->getName());
6949             return new ICmpInst(ICI.getPredicate(), NewRem,
6950                                 Constant::getNullValue(BO->getType()));
6951           }
6952         }
6953         break;
6954       case Instruction::Add:
6955         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6956         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6957           if (BO->hasOneUse())
6958             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6959                                 ConstantExpr::getSub(RHS, BOp1C));
6960         } else if (RHSV == 0) {
6961           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6962           // efficiently invertible, or if the add has just this one use.
6963           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6964           
6965           if (Value *NegVal = dyn_castNegVal(BOp1))
6966             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6967           else if (Value *NegVal = dyn_castNegVal(BOp0))
6968             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6969           else if (BO->hasOneUse()) {
6970             Value *Neg = Builder->CreateNeg(BOp1);
6971             Neg->takeName(BO);
6972             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6973           }
6974         }
6975         break;
6976       case Instruction::Xor:
6977         // For the xor case, we can xor two constants together, eliminating
6978         // the explicit xor.
6979         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6980           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6981                               ConstantExpr::getXor(RHS, BOC));
6982         
6983         // FALLTHROUGH
6984       case Instruction::Sub:
6985         // Replace (([sub|xor] A, B) != 0) with (A != B)
6986         if (RHSV == 0)
6987           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6988                               BO->getOperand(1));
6989         break;
6990         
6991       case Instruction::Or:
6992         // If bits are being or'd in that are not present in the constant we
6993         // are comparing against, then the comparison could never succeed!
6994         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6995           Constant *NotCI = ConstantExpr::getNot(RHS);
6996           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6997             return ReplaceInstUsesWith(ICI,
6998                                        ConstantInt::get(Type::getInt1Ty(*Context), 
6999                                        isICMP_NE));
7000         }
7001         break;
7002         
7003       case Instruction::And:
7004         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7005           // If bits are being compared against that are and'd out, then the
7006           // comparison can never succeed!
7007           if ((RHSV & ~BOC->getValue()) != 0)
7008             return ReplaceInstUsesWith(ICI,
7009                                        ConstantInt::get(Type::getInt1Ty(*Context),
7010                                        isICMP_NE));
7011           
7012           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7013           if (RHS == BOC && RHSV.isPowerOf2())
7014             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7015                                 ICmpInst::ICMP_NE, LHSI,
7016                                 Constant::getNullValue(RHS->getType()));
7017           
7018           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7019           if (BOC->getValue().isSignBit()) {
7020             Value *X = BO->getOperand(0);
7021             Constant *Zero = Constant::getNullValue(X->getType());
7022             ICmpInst::Predicate pred = isICMP_NE ? 
7023               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7024             return new ICmpInst(pred, X, Zero);
7025           }
7026           
7027           // ((X & ~7) == 0) --> X < 8
7028           if (RHSV == 0 && isHighOnes(BOC)) {
7029             Value *X = BO->getOperand(0);
7030             Constant *NegX = ConstantExpr::getNeg(BOC);
7031             ICmpInst::Predicate pred = isICMP_NE ? 
7032               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7033             return new ICmpInst(pred, X, NegX);
7034           }
7035         }
7036       default: break;
7037       }
7038     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7039       // Handle icmp {eq|ne} <intrinsic>, intcst.
7040       if (II->getIntrinsicID() == Intrinsic::bswap) {
7041         Worklist.Add(II);
7042         ICI.setOperand(0, II->getOperand(1));
7043         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7044         return &ICI;
7045       }
7046     }
7047   }
7048   return 0;
7049 }
7050
7051 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7052 /// We only handle extending casts so far.
7053 ///
7054 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7055   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7056   Value *LHSCIOp        = LHSCI->getOperand(0);
7057   const Type *SrcTy     = LHSCIOp->getType();
7058   const Type *DestTy    = LHSCI->getType();
7059   Value *RHSCIOp;
7060
7061   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7062   // integer type is the same size as the pointer type.
7063   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7064       TD->getPointerSizeInBits() ==
7065          cast<IntegerType>(DestTy)->getBitWidth()) {
7066     Value *RHSOp = 0;
7067     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7068       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7069     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7070       RHSOp = RHSC->getOperand(0);
7071       // If the pointer types don't match, insert a bitcast.
7072       if (LHSCIOp->getType() != RHSOp->getType())
7073         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7074     }
7075
7076     if (RHSOp)
7077       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7078   }
7079   
7080   // The code below only handles extension cast instructions, so far.
7081   // Enforce this.
7082   if (LHSCI->getOpcode() != Instruction::ZExt &&
7083       LHSCI->getOpcode() != Instruction::SExt)
7084     return 0;
7085
7086   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7087   bool isSignedCmp = ICI.isSignedPredicate();
7088
7089   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7090     // Not an extension from the same type?
7091     RHSCIOp = CI->getOperand(0);
7092     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7093       return 0;
7094     
7095     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7096     // and the other is a zext), then we can't handle this.
7097     if (CI->getOpcode() != LHSCI->getOpcode())
7098       return 0;
7099
7100     // Deal with equality cases early.
7101     if (ICI.isEquality())
7102       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7103
7104     // A signed comparison of sign extended values simplifies into a
7105     // signed comparison.
7106     if (isSignedCmp && isSignedExt)
7107       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7108
7109     // The other three cases all fold into an unsigned comparison.
7110     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7111   }
7112
7113   // If we aren't dealing with a constant on the RHS, exit early
7114   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7115   if (!CI)
7116     return 0;
7117
7118   // Compute the constant that would happen if we truncated to SrcTy then
7119   // reextended to DestTy.
7120   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7121   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7122                                                 Res1, DestTy);
7123
7124   // If the re-extended constant didn't change...
7125   if (Res2 == CI) {
7126     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7127     // For example, we might have:
7128     //    %A = sext i16 %X to i32
7129     //    %B = icmp ugt i32 %A, 1330
7130     // It is incorrect to transform this into 
7131     //    %B = icmp ugt i16 %X, 1330
7132     // because %A may have negative value. 
7133     //
7134     // However, we allow this when the compare is EQ/NE, because they are
7135     // signless.
7136     if (isSignedExt == isSignedCmp || ICI.isEquality())
7137       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7138     return 0;
7139   }
7140
7141   // The re-extended constant changed so the constant cannot be represented 
7142   // in the shorter type. Consequently, we cannot emit a simple comparison.
7143
7144   // First, handle some easy cases. We know the result cannot be equal at this
7145   // point so handle the ICI.isEquality() cases
7146   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7147     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7148   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7149     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7150
7151   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7152   // should have been folded away previously and not enter in here.
7153   Value *Result;
7154   if (isSignedCmp) {
7155     // We're performing a signed comparison.
7156     if (cast<ConstantInt>(CI)->getValue().isNegative())
7157       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7158     else
7159       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7160   } else {
7161     // We're performing an unsigned comparison.
7162     if (isSignedExt) {
7163       // We're performing an unsigned comp with a sign extended value.
7164       // This is true if the input is >= 0. [aka >s -1]
7165       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7166       Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7167     } else {
7168       // Unsigned extend & unsigned compare -> always true.
7169       Result = ConstantInt::getTrue(*Context);
7170     }
7171   }
7172
7173   // Finally, return the value computed.
7174   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7175       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7176     return ReplaceInstUsesWith(ICI, Result);
7177
7178   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7179           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7180          "ICmp should be folded!");
7181   if (Constant *CI = dyn_cast<Constant>(Result))
7182     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7183   return BinaryOperator::CreateNot(Result);
7184 }
7185
7186 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7187   return commonShiftTransforms(I);
7188 }
7189
7190 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7191   return commonShiftTransforms(I);
7192 }
7193
7194 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7195   if (Instruction *R = commonShiftTransforms(I))
7196     return R;
7197   
7198   Value *Op0 = I.getOperand(0);
7199   
7200   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7201   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7202     if (CSI->isAllOnesValue())
7203       return ReplaceInstUsesWith(I, CSI);
7204
7205   // See if we can turn a signed shr into an unsigned shr.
7206   if (MaskedValueIsZero(Op0,
7207                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7208     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7209
7210   // Arithmetic shifting an all-sign-bit value is a no-op.
7211   unsigned NumSignBits = ComputeNumSignBits(Op0);
7212   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7213     return ReplaceInstUsesWith(I, Op0);
7214
7215   return 0;
7216 }
7217
7218 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7219   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7220   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7221
7222   // shl X, 0 == X and shr X, 0 == X
7223   // shl 0, X == 0 and shr 0, X == 0
7224   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7225       Op0 == Constant::getNullValue(Op0->getType()))
7226     return ReplaceInstUsesWith(I, Op0);
7227   
7228   if (isa<UndefValue>(Op0)) {            
7229     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7230       return ReplaceInstUsesWith(I, Op0);
7231     else                                    // undef << X -> 0, undef >>u X -> 0
7232       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7233   }
7234   if (isa<UndefValue>(Op1)) {
7235     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7236       return ReplaceInstUsesWith(I, Op0);          
7237     else                                     // X << undef, X >>u undef -> 0
7238       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7239   }
7240
7241   // See if we can fold away this shift.
7242   if (SimplifyDemandedInstructionBits(I))
7243     return &I;
7244
7245   // Try to fold constant and into select arguments.
7246   if (isa<Constant>(Op0))
7247     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7248       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7249         return R;
7250
7251   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7252     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7253       return Res;
7254   return 0;
7255 }
7256
7257 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7258                                                BinaryOperator &I) {
7259   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7260
7261   // See if we can simplify any instructions used by the instruction whose sole 
7262   // purpose is to compute bits we don't care about.
7263   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7264   
7265   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7266   // a signed shift.
7267   //
7268   if (Op1->uge(TypeBits)) {
7269     if (I.getOpcode() != Instruction::AShr)
7270       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7271     else {
7272       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7273       return &I;
7274     }
7275   }
7276   
7277   // ((X*C1) << C2) == (X * (C1 << C2))
7278   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7279     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7280       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7281         return BinaryOperator::CreateMul(BO->getOperand(0),
7282                                         ConstantExpr::getShl(BOOp, Op1));
7283   
7284   // Try to fold constant and into select arguments.
7285   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7286     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7287       return R;
7288   if (isa<PHINode>(Op0))
7289     if (Instruction *NV = FoldOpIntoPhi(I))
7290       return NV;
7291   
7292   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7293   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7294     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7295     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7296     // place.  Don't try to do this transformation in this case.  Also, we
7297     // require that the input operand is a shift-by-constant so that we have
7298     // confidence that the shifts will get folded together.  We could do this
7299     // xform in more cases, but it is unlikely to be profitable.
7300     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7301         isa<ConstantInt>(TrOp->getOperand(1))) {
7302       // Okay, we'll do this xform.  Make the shift of shift.
7303       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7304       // (shift2 (shift1 & 0x00FF), c2)
7305       Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7306
7307       // For logical shifts, the truncation has the effect of making the high
7308       // part of the register be zeros.  Emulate this by inserting an AND to
7309       // clear the top bits as needed.  This 'and' will usually be zapped by
7310       // other xforms later if dead.
7311       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7312       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7313       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7314       
7315       // The mask we constructed says what the trunc would do if occurring
7316       // between the shifts.  We want to know the effect *after* the second
7317       // shift.  We know that it is a logical shift by a constant, so adjust the
7318       // mask as appropriate.
7319       if (I.getOpcode() == Instruction::Shl)
7320         MaskV <<= Op1->getZExtValue();
7321       else {
7322         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7323         MaskV = MaskV.lshr(Op1->getZExtValue());
7324       }
7325
7326       // shift1 & 0x00FF
7327       Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7328                                       TI->getName());
7329
7330       // Return the value truncated to the interesting size.
7331       return new TruncInst(And, I.getType());
7332     }
7333   }
7334   
7335   if (Op0->hasOneUse()) {
7336     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7337       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7338       Value *V1, *V2;
7339       ConstantInt *CC;
7340       switch (Op0BO->getOpcode()) {
7341         default: break;
7342         case Instruction::Add:
7343         case Instruction::And:
7344         case Instruction::Or:
7345         case Instruction::Xor: {
7346           // These operators commute.
7347           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7348           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7349               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7350                     m_Specific(Op1)))) {
7351             Value *YS =         // (Y << C)
7352               Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7353             // (X + (Y << C))
7354             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7355                                             Op0BO->getOperand(1)->getName());
7356             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7357             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7358                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7359           }
7360           
7361           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7362           Value *Op0BOOp1 = Op0BO->getOperand(1);
7363           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7364               match(Op0BOOp1, 
7365                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7366                           m_ConstantInt(CC))) &&
7367               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7368             Value *YS =   // (Y << C)
7369               Builder->CreateShl(Op0BO->getOperand(0), Op1,
7370                                            Op0BO->getName());
7371             // X & (CC << C)
7372             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7373                                            V1->getName()+".mask");
7374             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7375           }
7376         }
7377           
7378         // FALL THROUGH.
7379         case Instruction::Sub: {
7380           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7381           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7382               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7383                     m_Specific(Op1)))) {
7384             Value *YS =  // (Y << C)
7385               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7386             // (X + (Y << C))
7387             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7388                                             Op0BO->getOperand(0)->getName());
7389             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7390             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7391                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7392           }
7393           
7394           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7395           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7396               match(Op0BO->getOperand(0),
7397                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7398                           m_ConstantInt(CC))) && V2 == Op1 &&
7399               cast<BinaryOperator>(Op0BO->getOperand(0))
7400                   ->getOperand(0)->hasOneUse()) {
7401             Value *YS = // (Y << C)
7402               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7403             // X & (CC << C)
7404             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7405                                            V1->getName()+".mask");
7406             
7407             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7408           }
7409           
7410           break;
7411         }
7412       }
7413       
7414       
7415       // If the operand is an bitwise operator with a constant RHS, and the
7416       // shift is the only use, we can pull it out of the shift.
7417       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7418         bool isValid = true;     // Valid only for And, Or, Xor
7419         bool highBitSet = false; // Transform if high bit of constant set?
7420         
7421         switch (Op0BO->getOpcode()) {
7422           default: isValid = false; break;   // Do not perform transform!
7423           case Instruction::Add:
7424             isValid = isLeftShift;
7425             break;
7426           case Instruction::Or:
7427           case Instruction::Xor:
7428             highBitSet = false;
7429             break;
7430           case Instruction::And:
7431             highBitSet = true;
7432             break;
7433         }
7434         
7435         // If this is a signed shift right, and the high bit is modified
7436         // by the logical operation, do not perform the transformation.
7437         // The highBitSet boolean indicates the value of the high bit of
7438         // the constant which would cause it to be modified for this
7439         // operation.
7440         //
7441         if (isValid && I.getOpcode() == Instruction::AShr)
7442           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7443         
7444         if (isValid) {
7445           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7446           
7447           Value *NewShift =
7448             Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7449           NewShift->takeName(Op0BO);
7450           
7451           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7452                                         NewRHS);
7453         }
7454       }
7455     }
7456   }
7457   
7458   // Find out if this is a shift of a shift by a constant.
7459   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7460   if (ShiftOp && !ShiftOp->isShift())
7461     ShiftOp = 0;
7462   
7463   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7464     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7465     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7466     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7467     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7468     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7469     Value *X = ShiftOp->getOperand(0);
7470     
7471     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7472     
7473     const IntegerType *Ty = cast<IntegerType>(I.getType());
7474     
7475     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7476     if (I.getOpcode() == ShiftOp->getOpcode()) {
7477       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7478       // saturates.
7479       if (AmtSum >= TypeBits) {
7480         if (I.getOpcode() != Instruction::AShr)
7481           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7482         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7483       }
7484       
7485       return BinaryOperator::Create(I.getOpcode(), X,
7486                                     ConstantInt::get(Ty, AmtSum));
7487     }
7488     
7489     if (ShiftOp->getOpcode() == Instruction::LShr &&
7490         I.getOpcode() == Instruction::AShr) {
7491       if (AmtSum >= TypeBits)
7492         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7493       
7494       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7495       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7496     }
7497     
7498     if (ShiftOp->getOpcode() == Instruction::AShr &&
7499         I.getOpcode() == Instruction::LShr) {
7500       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7501       if (AmtSum >= TypeBits)
7502         AmtSum = TypeBits-1;
7503       
7504       Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7505
7506       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7507       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7508     }
7509     
7510     // Okay, if we get here, one shift must be left, and the other shift must be
7511     // right.  See if the amounts are equal.
7512     if (ShiftAmt1 == ShiftAmt2) {
7513       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7514       if (I.getOpcode() == Instruction::Shl) {
7515         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7516         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7517       }
7518       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7519       if (I.getOpcode() == Instruction::LShr) {
7520         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7521         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7522       }
7523       // We can simplify ((X << C) >>s C) into a trunc + sext.
7524       // NOTE: we could do this for any C, but that would make 'unusual' integer
7525       // types.  For now, just stick to ones well-supported by the code
7526       // generators.
7527       const Type *SExtType = 0;
7528       switch (Ty->getBitWidth() - ShiftAmt1) {
7529       case 1  :
7530       case 8  :
7531       case 16 :
7532       case 32 :
7533       case 64 :
7534       case 128:
7535         SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7536         break;
7537       default: break;
7538       }
7539       if (SExtType)
7540         return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
7541       // Otherwise, we can't handle it yet.
7542     } else if (ShiftAmt1 < ShiftAmt2) {
7543       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7544       
7545       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7546       if (I.getOpcode() == Instruction::Shl) {
7547         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7548                ShiftOp->getOpcode() == Instruction::AShr);
7549         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7550         
7551         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7552         return BinaryOperator::CreateAnd(Shift,
7553                                          ConstantInt::get(*Context, Mask));
7554       }
7555       
7556       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7557       if (I.getOpcode() == Instruction::LShr) {
7558         assert(ShiftOp->getOpcode() == Instruction::Shl);
7559         Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7560         
7561         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7562         return BinaryOperator::CreateAnd(Shift,
7563                                          ConstantInt::get(*Context, Mask));
7564       }
7565       
7566       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7567     } else {
7568       assert(ShiftAmt2 < ShiftAmt1);
7569       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7570
7571       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7572       if (I.getOpcode() == Instruction::Shl) {
7573         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7574                ShiftOp->getOpcode() == Instruction::AShr);
7575         Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7576                                             ConstantInt::get(Ty, ShiftDiff));
7577         
7578         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7579         return BinaryOperator::CreateAnd(Shift,
7580                                          ConstantInt::get(*Context, Mask));
7581       }
7582       
7583       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7584       if (I.getOpcode() == Instruction::LShr) {
7585         assert(ShiftOp->getOpcode() == Instruction::Shl);
7586         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7587         
7588         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7589         return BinaryOperator::CreateAnd(Shift,
7590                                          ConstantInt::get(*Context, Mask));
7591       }
7592       
7593       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7594     }
7595   }
7596   return 0;
7597 }
7598
7599
7600 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7601 /// expression.  If so, decompose it, returning some value X, such that Val is
7602 /// X*Scale+Offset.
7603 ///
7604 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7605                                         int &Offset, LLVMContext *Context) {
7606   assert(Val->getType() == Type::getInt32Ty(*Context) && 
7607          "Unexpected allocation size type!");
7608   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7609     Offset = CI->getZExtValue();
7610     Scale  = 0;
7611     return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7612   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7613     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7614       if (I->getOpcode() == Instruction::Shl) {
7615         // This is a value scaled by '1 << the shift amt'.
7616         Scale = 1U << RHS->getZExtValue();
7617         Offset = 0;
7618         return I->getOperand(0);
7619       } else if (I->getOpcode() == Instruction::Mul) {
7620         // This value is scaled by 'RHS'.
7621         Scale = RHS->getZExtValue();
7622         Offset = 0;
7623         return I->getOperand(0);
7624       } else if (I->getOpcode() == Instruction::Add) {
7625         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7626         // where C1 is divisible by C2.
7627         unsigned SubScale;
7628         Value *SubVal = 
7629           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7630                                     Offset, Context);
7631         Offset += RHS->getZExtValue();
7632         Scale = SubScale;
7633         return SubVal;
7634       }
7635     }
7636   }
7637
7638   // Otherwise, we can't look past this.
7639   Scale = 1;
7640   Offset = 0;
7641   return Val;
7642 }
7643
7644
7645 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7646 /// try to eliminate the cast by moving the type information into the alloc.
7647 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7648                                                    AllocationInst &AI) {
7649   const PointerType *PTy = cast<PointerType>(CI.getType());
7650   
7651   BuilderTy AllocaBuilder(*Builder);
7652   AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7653   
7654   // Remove any uses of AI that are dead.
7655   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7656   
7657   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7658     Instruction *User = cast<Instruction>(*UI++);
7659     if (isInstructionTriviallyDead(User)) {
7660       while (UI != E && *UI == User)
7661         ++UI; // If this instruction uses AI more than once, don't break UI.
7662       
7663       ++NumDeadInst;
7664       DEBUG(errs() << "IC: DCE: " << *User << '\n');
7665       EraseInstFromFunction(*User);
7666     }
7667   }
7668
7669   // This requires TargetData to get the alloca alignment and size information.
7670   if (!TD) return 0;
7671
7672   // Get the type really allocated and the type casted to.
7673   const Type *AllocElTy = AI.getAllocatedType();
7674   const Type *CastElTy = PTy->getElementType();
7675   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7676
7677   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7678   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7679   if (CastElTyAlign < AllocElTyAlign) return 0;
7680
7681   // If the allocation has multiple uses, only promote it if we are strictly
7682   // increasing the alignment of the resultant allocation.  If we keep it the
7683   // same, we open the door to infinite loops of various kinds.  (A reference
7684   // from a dbg.declare doesn't count as a use for this purpose.)
7685   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7686       CastElTyAlign == AllocElTyAlign) return 0;
7687
7688   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7689   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7690   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7691
7692   // See if we can satisfy the modulus by pulling a scale out of the array
7693   // size argument.
7694   unsigned ArraySizeScale;
7695   int ArrayOffset;
7696   Value *NumElements = // See if the array size is a decomposable linear expr.
7697     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7698                               ArrayOffset, Context);
7699  
7700   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7701   // do the xform.
7702   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7703       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7704
7705   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7706   Value *Amt = 0;
7707   if (Scale == 1) {
7708     Amt = NumElements;
7709   } else {
7710     Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7711     // Insert before the alloca, not before the cast.
7712     Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
7713   }
7714   
7715   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7716     Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7717     Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
7718   }
7719   
7720   AllocationInst *New;
7721   if (isa<MallocInst>(AI))
7722     New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
7723   else
7724     New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7725   New->setAlignment(AI.getAlignment());
7726   New->takeName(&AI);
7727   
7728   // If the allocation has one real use plus a dbg.declare, just remove the
7729   // declare.
7730   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7731     EraseInstFromFunction(*DI);
7732   }
7733   // If the allocation has multiple real uses, insert a cast and change all
7734   // things that used it to use the new cast.  This will also hack on CI, but it
7735   // will die soon.
7736   else if (!AI.hasOneUse()) {
7737     // New is the allocation instruction, pointer typed. AI is the original
7738     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7739     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
7740     AI.replaceAllUsesWith(NewCast);
7741   }
7742   return ReplaceInstUsesWith(CI, New);
7743 }
7744
7745 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7746 /// and return it as type Ty without inserting any new casts and without
7747 /// changing the computed value.  This is used by code that tries to decide
7748 /// whether promoting or shrinking integer operations to wider or smaller types
7749 /// will allow us to eliminate a truncate or extend.
7750 ///
7751 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7752 /// extension operation if Ty is larger.
7753 ///
7754 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7755 /// should return true if trunc(V) can be computed by computing V in the smaller
7756 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7757 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7758 /// efficiently truncated.
7759 ///
7760 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7761 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7762 /// the final result.
7763 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7764                                               unsigned CastOpc,
7765                                               int &NumCastsRemoved){
7766   // We can always evaluate constants in another type.
7767   if (isa<Constant>(V))
7768     return true;
7769   
7770   Instruction *I = dyn_cast<Instruction>(V);
7771   if (!I) return false;
7772   
7773   const Type *OrigTy = V->getType();
7774   
7775   // If this is an extension or truncate, we can often eliminate it.
7776   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7777     // If this is a cast from the destination type, we can trivially eliminate
7778     // it, and this will remove a cast overall.
7779     if (I->getOperand(0)->getType() == Ty) {
7780       // If the first operand is itself a cast, and is eliminable, do not count
7781       // this as an eliminable cast.  We would prefer to eliminate those two
7782       // casts first.
7783       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7784         ++NumCastsRemoved;
7785       return true;
7786     }
7787   }
7788
7789   // We can't extend or shrink something that has multiple uses: doing so would
7790   // require duplicating the instruction in general, which isn't profitable.
7791   if (!I->hasOneUse()) return false;
7792
7793   unsigned Opc = I->getOpcode();
7794   switch (Opc) {
7795   case Instruction::Add:
7796   case Instruction::Sub:
7797   case Instruction::Mul:
7798   case Instruction::And:
7799   case Instruction::Or:
7800   case Instruction::Xor:
7801     // These operators can all arbitrarily be extended or truncated.
7802     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7803                                       NumCastsRemoved) &&
7804            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7805                                       NumCastsRemoved);
7806
7807   case Instruction::UDiv:
7808   case Instruction::URem: {
7809     // UDiv and URem can be truncated if all the truncated bits are zero.
7810     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7811     uint32_t BitWidth = Ty->getScalarSizeInBits();
7812     if (BitWidth < OrigBitWidth) {
7813       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7814       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7815           MaskedValueIsZero(I->getOperand(1), Mask)) {
7816         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7817                                           NumCastsRemoved) &&
7818                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7819                                           NumCastsRemoved);
7820       }
7821     }
7822     break;
7823   }
7824   case Instruction::Shl:
7825     // If we are truncating the result of this SHL, and if it's a shift of a
7826     // constant amount, we can always perform a SHL in a smaller type.
7827     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7828       uint32_t BitWidth = Ty->getScalarSizeInBits();
7829       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7830           CI->getLimitedValue(BitWidth) < BitWidth)
7831         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7832                                           NumCastsRemoved);
7833     }
7834     break;
7835   case Instruction::LShr:
7836     // If this is a truncate of a logical shr, we can truncate it to a smaller
7837     // lshr iff we know that the bits we would otherwise be shifting in are
7838     // already zeros.
7839     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7840       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7841       uint32_t BitWidth = Ty->getScalarSizeInBits();
7842       if (BitWidth < OrigBitWidth &&
7843           MaskedValueIsZero(I->getOperand(0),
7844             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7845           CI->getLimitedValue(BitWidth) < BitWidth) {
7846         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7847                                           NumCastsRemoved);
7848       }
7849     }
7850     break;
7851   case Instruction::ZExt:
7852   case Instruction::SExt:
7853   case Instruction::Trunc:
7854     // If this is the same kind of case as our original (e.g. zext+zext), we
7855     // can safely replace it.  Note that replacing it does not reduce the number
7856     // of casts in the input.
7857     if (Opc == CastOpc)
7858       return true;
7859
7860     // sext (zext ty1), ty2 -> zext ty2
7861     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7862       return true;
7863     break;
7864   case Instruction::Select: {
7865     SelectInst *SI = cast<SelectInst>(I);
7866     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7867                                       NumCastsRemoved) &&
7868            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7869                                       NumCastsRemoved);
7870   }
7871   case Instruction::PHI: {
7872     // We can change a phi if we can change all operands.
7873     PHINode *PN = cast<PHINode>(I);
7874     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7875       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7876                                       NumCastsRemoved))
7877         return false;
7878     return true;
7879   }
7880   default:
7881     // TODO: Can handle more cases here.
7882     break;
7883   }
7884   
7885   return false;
7886 }
7887
7888 /// EvaluateInDifferentType - Given an expression that 
7889 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7890 /// evaluate the expression.
7891 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7892                                              bool isSigned) {
7893   if (Constant *C = dyn_cast<Constant>(V))
7894     return ConstantExpr::getIntegerCast(C, Ty,
7895                                                isSigned /*Sext or ZExt*/);
7896
7897   // Otherwise, it must be an instruction.
7898   Instruction *I = cast<Instruction>(V);
7899   Instruction *Res = 0;
7900   unsigned Opc = I->getOpcode();
7901   switch (Opc) {
7902   case Instruction::Add:
7903   case Instruction::Sub:
7904   case Instruction::Mul:
7905   case Instruction::And:
7906   case Instruction::Or:
7907   case Instruction::Xor:
7908   case Instruction::AShr:
7909   case Instruction::LShr:
7910   case Instruction::Shl:
7911   case Instruction::UDiv:
7912   case Instruction::URem: {
7913     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7914     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7915     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7916     break;
7917   }    
7918   case Instruction::Trunc:
7919   case Instruction::ZExt:
7920   case Instruction::SExt:
7921     // If the source type of the cast is the type we're trying for then we can
7922     // just return the source.  There's no need to insert it because it is not
7923     // new.
7924     if (I->getOperand(0)->getType() == Ty)
7925       return I->getOperand(0);
7926     
7927     // Otherwise, must be the same type of cast, so just reinsert a new one.
7928     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7929                            Ty);
7930     break;
7931   case Instruction::Select: {
7932     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7933     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7934     Res = SelectInst::Create(I->getOperand(0), True, False);
7935     break;
7936   }
7937   case Instruction::PHI: {
7938     PHINode *OPN = cast<PHINode>(I);
7939     PHINode *NPN = PHINode::Create(Ty);
7940     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7941       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7942       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7943     }
7944     Res = NPN;
7945     break;
7946   }
7947   default: 
7948     // TODO: Can handle more cases here.
7949     llvm_unreachable("Unreachable!");
7950     break;
7951   }
7952   
7953   Res->takeName(I);
7954   return InsertNewInstBefore(Res, *I);
7955 }
7956
7957 /// @brief Implement the transforms common to all CastInst visitors.
7958 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7959   Value *Src = CI.getOperand(0);
7960
7961   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7962   // eliminate it now.
7963   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7964     if (Instruction::CastOps opc = 
7965         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7966       // The first cast (CSrc) is eliminable so we need to fix up or replace
7967       // the second cast (CI). CSrc will then have a good chance of being dead.
7968       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7969     }
7970   }
7971
7972   // If we are casting a select then fold the cast into the select
7973   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7974     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7975       return NV;
7976
7977   // If we are casting a PHI then fold the cast into the PHI
7978   if (isa<PHINode>(Src))
7979     if (Instruction *NV = FoldOpIntoPhi(CI))
7980       return NV;
7981   
7982   return 0;
7983 }
7984
7985 /// FindElementAtOffset - Given a type and a constant offset, determine whether
7986 /// or not there is a sequence of GEP indices into the type that will land us at
7987 /// the specified offset.  If so, fill them into NewIndices and return the
7988 /// resultant element type, otherwise return null.
7989 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
7990                                        SmallVectorImpl<Value*> &NewIndices,
7991                                        const TargetData *TD,
7992                                        LLVMContext *Context) {
7993   if (!TD) return 0;
7994   if (!Ty->isSized()) return 0;
7995   
7996   // Start with the index over the outer type.  Note that the type size
7997   // might be zero (even if the offset isn't zero) if the indexed type
7998   // is something like [0 x {int, int}]
7999   const Type *IntPtrTy = TD->getIntPtrType(*Context);
8000   int64_t FirstIdx = 0;
8001   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8002     FirstIdx = Offset/TySize;
8003     Offset -= FirstIdx*TySize;
8004     
8005     // Handle hosts where % returns negative instead of values [0..TySize).
8006     if (Offset < 0) {
8007       --FirstIdx;
8008       Offset += TySize;
8009       assert(Offset >= 0);
8010     }
8011     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8012   }
8013   
8014   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8015     
8016   // Index into the types.  If we fail, set OrigBase to null.
8017   while (Offset) {
8018     // Indexing into tail padding between struct/array elements.
8019     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8020       return 0;
8021     
8022     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8023       const StructLayout *SL = TD->getStructLayout(STy);
8024       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8025              "Offset must stay within the indexed type");
8026       
8027       unsigned Elt = SL->getElementContainingOffset(Offset);
8028       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8029       
8030       Offset -= SL->getElementOffset(Elt);
8031       Ty = STy->getElementType(Elt);
8032     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8033       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8034       assert(EltSize && "Cannot index into a zero-sized array");
8035       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8036       Offset %= EltSize;
8037       Ty = AT->getElementType();
8038     } else {
8039       // Otherwise, we can't index into the middle of this atomic type, bail.
8040       return 0;
8041     }
8042   }
8043   
8044   return Ty;
8045 }
8046
8047 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8048 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8049   Value *Src = CI.getOperand(0);
8050   
8051   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8052     // If casting the result of a getelementptr instruction with no offset, turn
8053     // this into a cast of the original pointer!
8054     if (GEP->hasAllZeroIndices()) {
8055       // Changing the cast operand is usually not a good idea but it is safe
8056       // here because the pointer operand is being replaced with another 
8057       // pointer operand so the opcode doesn't need to change.
8058       Worklist.Add(GEP);
8059       CI.setOperand(0, GEP->getOperand(0));
8060       return &CI;
8061     }
8062     
8063     // If the GEP has a single use, and the base pointer is a bitcast, and the
8064     // GEP computes a constant offset, see if we can convert these three
8065     // instructions into fewer.  This typically happens with unions and other
8066     // non-type-safe code.
8067     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8068       if (GEP->hasAllConstantIndices()) {
8069         // We are guaranteed to get a constant from EmitGEPOffset.
8070         ConstantInt *OffsetV =
8071                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8072         int64_t Offset = OffsetV->getSExtValue();
8073         
8074         // Get the base pointer input of the bitcast, and the type it points to.
8075         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8076         const Type *GEPIdxTy =
8077           cast<PointerType>(OrigBase->getType())->getElementType();
8078         SmallVector<Value*, 8> NewIndices;
8079         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8080           // If we were able to index down into an element, create the GEP
8081           // and bitcast the result.  This eliminates one bitcast, potentially
8082           // two.
8083           Value *NGEP = Builder->CreateGEP(OrigBase, NewIndices.begin(),
8084                                            NewIndices.end());
8085           NGEP->takeName(GEP);
8086           if (isa<Instruction>(NGEP) && cast<GEPOperator>(GEP)->isInBounds())
8087             cast<GEPOperator>(NGEP)->setIsInBounds(true);
8088           
8089           if (isa<BitCastInst>(CI))
8090             return new BitCastInst(NGEP, CI.getType());
8091           assert(isa<PtrToIntInst>(CI));
8092           return new PtrToIntInst(NGEP, CI.getType());
8093         }
8094       }      
8095     }
8096   }
8097     
8098   return commonCastTransforms(CI);
8099 }
8100
8101 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8102 /// type like i42.  We don't want to introduce operations on random non-legal
8103 /// integer types where they don't already exist in the code.  In the future,
8104 /// we should consider making this based off target-data, so that 32-bit targets
8105 /// won't get i64 operations etc.
8106 static bool isSafeIntegerType(const Type *Ty) {
8107   switch (Ty->getPrimitiveSizeInBits()) {
8108   case 8:
8109   case 16:
8110   case 32:
8111   case 64:
8112     return true;
8113   default: 
8114     return false;
8115   }
8116 }
8117
8118 /// commonIntCastTransforms - This function implements the common transforms
8119 /// for trunc, zext, and sext.
8120 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8121   if (Instruction *Result = commonCastTransforms(CI))
8122     return Result;
8123
8124   Value *Src = CI.getOperand(0);
8125   const Type *SrcTy = Src->getType();
8126   const Type *DestTy = CI.getType();
8127   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8128   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8129
8130   // See if we can simplify any instructions used by the LHS whose sole 
8131   // purpose is to compute bits we don't care about.
8132   if (SimplifyDemandedInstructionBits(CI))
8133     return &CI;
8134
8135   // If the source isn't an instruction or has more than one use then we
8136   // can't do anything more. 
8137   Instruction *SrcI = dyn_cast<Instruction>(Src);
8138   if (!SrcI || !Src->hasOneUse())
8139     return 0;
8140
8141   // Attempt to propagate the cast into the instruction for int->int casts.
8142   int NumCastsRemoved = 0;
8143   // Only do this if the dest type is a simple type, don't convert the
8144   // expression tree to something weird like i93 unless the source is also
8145   // strange.
8146   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8147        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8148       CanEvaluateInDifferentType(SrcI, DestTy,
8149                                  CI.getOpcode(), NumCastsRemoved)) {
8150     // If this cast is a truncate, evaluting in a different type always
8151     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8152     // we need to do an AND to maintain the clear top-part of the computation,
8153     // so we require that the input have eliminated at least one cast.  If this
8154     // is a sign extension, we insert two new casts (to do the extension) so we
8155     // require that two casts have been eliminated.
8156     bool DoXForm = false;
8157     bool JustReplace = false;
8158     switch (CI.getOpcode()) {
8159     default:
8160       // All the others use floating point so we shouldn't actually 
8161       // get here because of the check above.
8162       llvm_unreachable("Unknown cast type");
8163     case Instruction::Trunc:
8164       DoXForm = true;
8165       break;
8166     case Instruction::ZExt: {
8167       DoXForm = NumCastsRemoved >= 1;
8168       if (!DoXForm && 0) {
8169         // If it's unnecessary to issue an AND to clear the high bits, it's
8170         // always profitable to do this xform.
8171         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8172         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8173         if (MaskedValueIsZero(TryRes, Mask))
8174           return ReplaceInstUsesWith(CI, TryRes);
8175         
8176         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8177           if (TryI->use_empty())
8178             EraseInstFromFunction(*TryI);
8179       }
8180       break;
8181     }
8182     case Instruction::SExt: {
8183       DoXForm = NumCastsRemoved >= 2;
8184       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8185         // If we do not have to emit the truncate + sext pair, then it's always
8186         // profitable to do this xform.
8187         //
8188         // It's not safe to eliminate the trunc + sext pair if one of the
8189         // eliminated cast is a truncate. e.g.
8190         // t2 = trunc i32 t1 to i16
8191         // t3 = sext i16 t2 to i32
8192         // !=
8193         // i32 t1
8194         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8195         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8196         if (NumSignBits > (DestBitSize - SrcBitSize))
8197           return ReplaceInstUsesWith(CI, TryRes);
8198         
8199         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8200           if (TryI->use_empty())
8201             EraseInstFromFunction(*TryI);
8202       }
8203       break;
8204     }
8205     }
8206     
8207     if (DoXForm) {
8208       DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8209             " to avoid cast: " << CI);
8210       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8211                                            CI.getOpcode() == Instruction::SExt);
8212       if (JustReplace)
8213         // Just replace this cast with the result.
8214         return ReplaceInstUsesWith(CI, Res);
8215
8216       assert(Res->getType() == DestTy);
8217       switch (CI.getOpcode()) {
8218       default: llvm_unreachable("Unknown cast type!");
8219       case Instruction::Trunc:
8220         // Just replace this cast with the result.
8221         return ReplaceInstUsesWith(CI, Res);
8222       case Instruction::ZExt: {
8223         assert(SrcBitSize < DestBitSize && "Not a zext?");
8224
8225         // If the high bits are already zero, just replace this cast with the
8226         // result.
8227         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8228         if (MaskedValueIsZero(Res, Mask))
8229           return ReplaceInstUsesWith(CI, Res);
8230
8231         // We need to emit an AND to clear the high bits.
8232         Constant *C = ConstantInt::get(*Context, 
8233                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8234         return BinaryOperator::CreateAnd(Res, C);
8235       }
8236       case Instruction::SExt: {
8237         // If the high bits are already filled with sign bit, just replace this
8238         // cast with the result.
8239         unsigned NumSignBits = ComputeNumSignBits(Res);
8240         if (NumSignBits > (DestBitSize - SrcBitSize))
8241           return ReplaceInstUsesWith(CI, Res);
8242
8243         // We need to emit a cast to truncate, then a cast to sext.
8244         return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8245       }
8246       }
8247     }
8248   }
8249   
8250   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8251   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8252
8253   switch (SrcI->getOpcode()) {
8254   case Instruction::Add:
8255   case Instruction::Mul:
8256   case Instruction::And:
8257   case Instruction::Or:
8258   case Instruction::Xor:
8259     // If we are discarding information, rewrite.
8260     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8261       // Don't insert two casts unless at least one can be eliminated.
8262       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8263           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8264         Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8265         Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8266         return BinaryOperator::Create(
8267             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8268       }
8269     }
8270
8271     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8272     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8273         SrcI->getOpcode() == Instruction::Xor &&
8274         Op1 == ConstantInt::getTrue(*Context) &&
8275         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8276       Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8277       return BinaryOperator::CreateXor(New,
8278                                       ConstantInt::get(CI.getType(), 1));
8279     }
8280     break;
8281
8282   case Instruction::Shl: {
8283     // Canonicalize trunc inside shl, if we can.
8284     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8285     if (CI && DestBitSize < SrcBitSize &&
8286         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8287       Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8288       Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8289       return BinaryOperator::CreateShl(Op0c, Op1c);
8290     }
8291     break;
8292   }
8293   }
8294   return 0;
8295 }
8296
8297 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8298   if (Instruction *Result = commonIntCastTransforms(CI))
8299     return Result;
8300   
8301   Value *Src = CI.getOperand(0);
8302   const Type *Ty = CI.getType();
8303   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8304   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8305
8306   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8307   if (DestBitWidth == 1) {
8308     Constant *One = ConstantInt::get(Src->getType(), 1);
8309     Src = Builder->CreateAnd(Src, One, "tmp");
8310     Value *Zero = Constant::getNullValue(Src->getType());
8311     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8312   }
8313
8314   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8315   ConstantInt *ShAmtV = 0;
8316   Value *ShiftOp = 0;
8317   if (Src->hasOneUse() &&
8318       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8319     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8320     
8321     // Get a mask for the bits shifting in.
8322     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8323     if (MaskedValueIsZero(ShiftOp, Mask)) {
8324       if (ShAmt >= DestBitWidth)        // All zeros.
8325         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8326       
8327       // Okay, we can shrink this.  Truncate the input, then return a new
8328       // shift.
8329       Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8330       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8331       return BinaryOperator::CreateLShr(V1, V2);
8332     }
8333   }
8334   
8335   return 0;
8336 }
8337
8338 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8339 /// in order to eliminate the icmp.
8340 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8341                                              bool DoXform) {
8342   // If we are just checking for a icmp eq of a single bit and zext'ing it
8343   // to an integer, then shift the bit to the appropriate place and then
8344   // cast to integer to avoid the comparison.
8345   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8346     const APInt &Op1CV = Op1C->getValue();
8347       
8348     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8349     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8350     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8351         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8352       if (!DoXform) return ICI;
8353
8354       Value *In = ICI->getOperand(0);
8355       Value *Sh = ConstantInt::get(In->getType(),
8356                                    In->getType()->getScalarSizeInBits()-1);
8357       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8358       if (In->getType() != CI.getType())
8359         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8360
8361       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8362         Constant *One = ConstantInt::get(In->getType(), 1);
8363         In = Builder->CreateXor(In, One, In->getName()+".not");
8364       }
8365
8366       return ReplaceInstUsesWith(CI, In);
8367     }
8368       
8369       
8370       
8371     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8372     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8373     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8374     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8375     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8376     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8377     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8378     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8379     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8380         // This only works for EQ and NE
8381         ICI->isEquality()) {
8382       // If Op1C some other power of two, convert:
8383       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8384       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8385       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8386       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8387         
8388       APInt KnownZeroMask(~KnownZero);
8389       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8390         if (!DoXform) return ICI;
8391
8392         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8393         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8394           // (X&4) == 2 --> false
8395           // (X&4) != 2 --> true
8396           Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8397           Res = ConstantExpr::getZExt(Res, CI.getType());
8398           return ReplaceInstUsesWith(CI, Res);
8399         }
8400           
8401         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8402         Value *In = ICI->getOperand(0);
8403         if (ShiftAmt) {
8404           // Perform a logical shr by shiftamt.
8405           // Insert the shift to put the result in the low bit.
8406           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8407                                    In->getName()+".lobit");
8408         }
8409           
8410         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8411           Constant *One = ConstantInt::get(In->getType(), 1);
8412           In = Builder->CreateXor(In, One, "tmp");
8413         }
8414           
8415         if (CI.getType() == In->getType())
8416           return ReplaceInstUsesWith(CI, In);
8417         else
8418           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8419       }
8420     }
8421   }
8422
8423   return 0;
8424 }
8425
8426 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8427   // If one of the common conversion will work ..
8428   if (Instruction *Result = commonIntCastTransforms(CI))
8429     return Result;
8430
8431   Value *Src = CI.getOperand(0);
8432
8433   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8434   // types and if the sizes are just right we can convert this into a logical
8435   // 'and' which will be much cheaper than the pair of casts.
8436   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8437     // Get the sizes of the types involved.  We know that the intermediate type
8438     // will be smaller than A or C, but don't know the relation between A and C.
8439     Value *A = CSrc->getOperand(0);
8440     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8441     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8442     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8443     // If we're actually extending zero bits, then if
8444     // SrcSize <  DstSize: zext(a & mask)
8445     // SrcSize == DstSize: a & mask
8446     // SrcSize  > DstSize: trunc(a) & mask
8447     if (SrcSize < DstSize) {
8448       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8449       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8450       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8451       return new ZExtInst(And, CI.getType());
8452     }
8453     
8454     if (SrcSize == DstSize) {
8455       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8456       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8457                                                            AndValue));
8458     }
8459     if (SrcSize > DstSize) {
8460       Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8461       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8462       return BinaryOperator::CreateAnd(Trunc, 
8463                                        ConstantInt::get(Trunc->getType(),
8464                                                                AndValue));
8465     }
8466   }
8467
8468   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8469     return transformZExtICmp(ICI, CI);
8470
8471   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8472   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8473     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8474     // of the (zext icmp) will be transformed.
8475     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8476     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8477     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8478         (transformZExtICmp(LHS, CI, false) ||
8479          transformZExtICmp(RHS, CI, false))) {
8480       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8481       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
8482       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8483     }
8484   }
8485
8486   // zext(trunc(t) & C) -> (t & zext(C)).
8487   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8488     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8489       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8490         Value *TI0 = TI->getOperand(0);
8491         if (TI0->getType() == CI.getType())
8492           return
8493             BinaryOperator::CreateAnd(TI0,
8494                                 ConstantExpr::getZExt(C, CI.getType()));
8495       }
8496
8497   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8498   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8499     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8500       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8501         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8502             And->getOperand(1) == C)
8503           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8504             Value *TI0 = TI->getOperand(0);
8505             if (TI0->getType() == CI.getType()) {
8506               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8507               Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8508               return BinaryOperator::CreateXor(NewAnd, ZC);
8509             }
8510           }
8511
8512   return 0;
8513 }
8514
8515 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8516   if (Instruction *I = commonIntCastTransforms(CI))
8517     return I;
8518   
8519   Value *Src = CI.getOperand(0);
8520   
8521   // Canonicalize sign-extend from i1 to a select.
8522   if (Src->getType() == Type::getInt1Ty(*Context))
8523     return SelectInst::Create(Src,
8524                               Constant::getAllOnesValue(CI.getType()),
8525                               Constant::getNullValue(CI.getType()));
8526
8527   // See if the value being truncated is already sign extended.  If so, just
8528   // eliminate the trunc/sext pair.
8529   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8530     Value *Op = cast<User>(Src)->getOperand(0);
8531     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8532     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8533     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8534     unsigned NumSignBits = ComputeNumSignBits(Op);
8535
8536     if (OpBits == DestBits) {
8537       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8538       // bits, it is already ready.
8539       if (NumSignBits > DestBits-MidBits)
8540         return ReplaceInstUsesWith(CI, Op);
8541     } else if (OpBits < DestBits) {
8542       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8543       // bits, just sext from i32.
8544       if (NumSignBits > OpBits-MidBits)
8545         return new SExtInst(Op, CI.getType(), "tmp");
8546     } else {
8547       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8548       // bits, just truncate to i32.
8549       if (NumSignBits > OpBits-MidBits)
8550         return new TruncInst(Op, CI.getType(), "tmp");
8551     }
8552   }
8553
8554   // If the input is a shl/ashr pair of a same constant, then this is a sign
8555   // extension from a smaller value.  If we could trust arbitrary bitwidth
8556   // integers, we could turn this into a truncate to the smaller bit and then
8557   // use a sext for the whole extension.  Since we don't, look deeper and check
8558   // for a truncate.  If the source and dest are the same type, eliminate the
8559   // trunc and extend and just do shifts.  For example, turn:
8560   //   %a = trunc i32 %i to i8
8561   //   %b = shl i8 %a, 6
8562   //   %c = ashr i8 %b, 6
8563   //   %d = sext i8 %c to i32
8564   // into:
8565   //   %a = shl i32 %i, 30
8566   //   %d = ashr i32 %a, 30
8567   Value *A = 0;
8568   ConstantInt *BA = 0, *CA = 0;
8569   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8570                         m_ConstantInt(CA))) &&
8571       BA == CA && isa<TruncInst>(A)) {
8572     Value *I = cast<TruncInst>(A)->getOperand(0);
8573     if (I->getType() == CI.getType()) {
8574       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8575       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8576       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8577       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8578       I = Builder->CreateShl(I, ShAmtV, CI.getName());
8579       return BinaryOperator::CreateAShr(I, ShAmtV);
8580     }
8581   }
8582   
8583   return 0;
8584 }
8585
8586 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8587 /// in the specified FP type without changing its value.
8588 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8589                               LLVMContext *Context) {
8590   bool losesInfo;
8591   APFloat F = CFP->getValueAPF();
8592   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8593   if (!losesInfo)
8594     return ConstantFP::get(*Context, F);
8595   return 0;
8596 }
8597
8598 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8599 /// through it until we get the source value.
8600 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8601   if (Instruction *I = dyn_cast<Instruction>(V))
8602     if (I->getOpcode() == Instruction::FPExt)
8603       return LookThroughFPExtensions(I->getOperand(0), Context);
8604   
8605   // If this value is a constant, return the constant in the smallest FP type
8606   // that can accurately represent it.  This allows us to turn
8607   // (float)((double)X+2.0) into x+2.0f.
8608   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8609     if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8610       return V;  // No constant folding of this.
8611     // See if the value can be truncated to float and then reextended.
8612     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8613       return V;
8614     if (CFP->getType() == Type::getDoubleTy(*Context))
8615       return V;  // Won't shrink.
8616     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8617       return V;
8618     // Don't try to shrink to various long double types.
8619   }
8620   
8621   return V;
8622 }
8623
8624 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8625   if (Instruction *I = commonCastTransforms(CI))
8626     return I;
8627   
8628   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8629   // smaller than the destination type, we can eliminate the truncate by doing
8630   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8631   // many builtins (sqrt, etc).
8632   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8633   if (OpI && OpI->hasOneUse()) {
8634     switch (OpI->getOpcode()) {
8635     default: break;
8636     case Instruction::FAdd:
8637     case Instruction::FSub:
8638     case Instruction::FMul:
8639     case Instruction::FDiv:
8640     case Instruction::FRem:
8641       const Type *SrcTy = OpI->getType();
8642       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8643       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8644       if (LHSTrunc->getType() != SrcTy && 
8645           RHSTrunc->getType() != SrcTy) {
8646         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8647         // If the source types were both smaller than the destination type of
8648         // the cast, do this xform.
8649         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8650             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8651           LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8652           RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
8653           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8654         }
8655       }
8656       break;  
8657     }
8658   }
8659   return 0;
8660 }
8661
8662 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8663   return commonCastTransforms(CI);
8664 }
8665
8666 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8667   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8668   if (OpI == 0)
8669     return commonCastTransforms(FI);
8670
8671   // fptoui(uitofp(X)) --> X
8672   // fptoui(sitofp(X)) --> X
8673   // This is safe if the intermediate type has enough bits in its mantissa to
8674   // accurately represent all values of X.  For example, do not do this with
8675   // i64->float->i64.  This is also safe for sitofp case, because any negative
8676   // 'X' value would cause an undefined result for the fptoui. 
8677   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8678       OpI->getOperand(0)->getType() == FI.getType() &&
8679       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8680                     OpI->getType()->getFPMantissaWidth())
8681     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8682
8683   return commonCastTransforms(FI);
8684 }
8685
8686 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8687   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8688   if (OpI == 0)
8689     return commonCastTransforms(FI);
8690   
8691   // fptosi(sitofp(X)) --> X
8692   // fptosi(uitofp(X)) --> X
8693   // This is safe if the intermediate type has enough bits in its mantissa to
8694   // accurately represent all values of X.  For example, do not do this with
8695   // i64->float->i64.  This is also safe for sitofp case, because any negative
8696   // 'X' value would cause an undefined result for the fptoui. 
8697   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8698       OpI->getOperand(0)->getType() == FI.getType() &&
8699       (int)FI.getType()->getScalarSizeInBits() <=
8700                     OpI->getType()->getFPMantissaWidth())
8701     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8702   
8703   return commonCastTransforms(FI);
8704 }
8705
8706 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8707   return commonCastTransforms(CI);
8708 }
8709
8710 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8711   return commonCastTransforms(CI);
8712 }
8713
8714 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8715   // If the destination integer type is smaller than the intptr_t type for
8716   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8717   // trunc to be exposed to other transforms.  Don't do this for extending
8718   // ptrtoint's, because we don't know if the target sign or zero extends its
8719   // pointers.
8720   if (TD &&
8721       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8722     Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8723                                        TD->getIntPtrType(CI.getContext()),
8724                                        "tmp");
8725     return new TruncInst(P, CI.getType());
8726   }
8727   
8728   return commonPointerCastTransforms(CI);
8729 }
8730
8731 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8732   // If the source integer type is larger than the intptr_t type for
8733   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8734   // allows the trunc to be exposed to other transforms.  Don't do this for
8735   // extending inttoptr's, because we don't know if the target sign or zero
8736   // extends to pointers.
8737   if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
8738       TD->getPointerSizeInBits()) {
8739     Value *P = Builder->CreateTrunc(CI.getOperand(0),
8740                                     TD->getIntPtrType(CI.getContext()), "tmp");
8741     return new IntToPtrInst(P, CI.getType());
8742   }
8743   
8744   if (Instruction *I = commonCastTransforms(CI))
8745     return I;
8746
8747   return 0;
8748 }
8749
8750 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8751   // If the operands are integer typed then apply the integer transforms,
8752   // otherwise just apply the common ones.
8753   Value *Src = CI.getOperand(0);
8754   const Type *SrcTy = Src->getType();
8755   const Type *DestTy = CI.getType();
8756
8757   if (isa<PointerType>(SrcTy)) {
8758     if (Instruction *I = commonPointerCastTransforms(CI))
8759       return I;
8760   } else {
8761     if (Instruction *Result = commonCastTransforms(CI))
8762       return Result;
8763   }
8764
8765
8766   // Get rid of casts from one type to the same type. These are useless and can
8767   // be replaced by the operand.
8768   if (DestTy == Src->getType())
8769     return ReplaceInstUsesWith(CI, Src);
8770
8771   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8772     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8773     const Type *DstElTy = DstPTy->getElementType();
8774     const Type *SrcElTy = SrcPTy->getElementType();
8775     
8776     // If the address spaces don't match, don't eliminate the bitcast, which is
8777     // required for changing types.
8778     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8779       return 0;
8780     
8781     // If we are casting a malloc or alloca to a pointer to a type of the same
8782     // size, rewrite the allocation instruction to allocate the "right" type.
8783     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8784       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8785         return V;
8786     
8787     // If the source and destination are pointers, and this cast is equivalent
8788     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8789     // This can enhance SROA and other transforms that want type-safe pointers.
8790     Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8791     unsigned NumZeros = 0;
8792     while (SrcElTy != DstElTy && 
8793            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8794            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8795       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8796       ++NumZeros;
8797     }
8798
8799     // If we found a path from the src to dest, create the getelementptr now.
8800     if (SrcElTy == DstElTy) {
8801       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8802       Instruction *GEP = GetElementPtrInst::Create(Src,
8803                                                    Idxs.begin(), Idxs.end(), "",
8804                                                    ((Instruction*) NULL));
8805       cast<GEPOperator>(GEP)->setIsInBounds(true);
8806       return GEP;
8807     }
8808   }
8809
8810   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8811     if (DestVTy->getNumElements() == 1) {
8812       if (!isa<VectorType>(SrcTy)) {
8813         Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
8814         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
8815                             Constant::getNullValue(Type::getInt32Ty(*Context)));
8816       }
8817       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8818     }
8819   }
8820
8821   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8822     if (SrcVTy->getNumElements() == 1) {
8823       if (!isa<VectorType>(DestTy)) {
8824         Value *Elem = 
8825           Builder->CreateExtractElement(Src,
8826                             Constant::getNullValue(Type::getInt32Ty(*Context)));
8827         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8828       }
8829     }
8830   }
8831
8832   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8833     if (SVI->hasOneUse()) {
8834       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8835       // a bitconvert to a vector with the same # elts.
8836       if (isa<VectorType>(DestTy) && 
8837           cast<VectorType>(DestTy)->getNumElements() ==
8838                 SVI->getType()->getNumElements() &&
8839           SVI->getType()->getNumElements() ==
8840             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8841         CastInst *Tmp;
8842         // If either of the operands is a cast from CI.getType(), then
8843         // evaluating the shuffle in the casted destination's type will allow
8844         // us to eliminate at least one cast.
8845         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8846              Tmp->getOperand(0)->getType() == DestTy) ||
8847             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8848              Tmp->getOperand(0)->getType() == DestTy)) {
8849           Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8850           Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
8851           // Return a new shuffle vector.  Use the same element ID's, as we
8852           // know the vector types match #elts.
8853           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8854         }
8855       }
8856     }
8857   }
8858   return 0;
8859 }
8860
8861 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8862 ///   %C = or %A, %B
8863 ///   %D = select %cond, %C, %A
8864 /// into:
8865 ///   %C = select %cond, %B, 0
8866 ///   %D = or %A, %C
8867 ///
8868 /// Assuming that the specified instruction is an operand to the select, return
8869 /// a bitmask indicating which operands of this instruction are foldable if they
8870 /// equal the other incoming value of the select.
8871 ///
8872 static unsigned GetSelectFoldableOperands(Instruction *I) {
8873   switch (I->getOpcode()) {
8874   case Instruction::Add:
8875   case Instruction::Mul:
8876   case Instruction::And:
8877   case Instruction::Or:
8878   case Instruction::Xor:
8879     return 3;              // Can fold through either operand.
8880   case Instruction::Sub:   // Can only fold on the amount subtracted.
8881   case Instruction::Shl:   // Can only fold on the shift amount.
8882   case Instruction::LShr:
8883   case Instruction::AShr:
8884     return 1;
8885   default:
8886     return 0;              // Cannot fold
8887   }
8888 }
8889
8890 /// GetSelectFoldableConstant - For the same transformation as the previous
8891 /// function, return the identity constant that goes into the select.
8892 static Constant *GetSelectFoldableConstant(Instruction *I,
8893                                            LLVMContext *Context) {
8894   switch (I->getOpcode()) {
8895   default: llvm_unreachable("This cannot happen!");
8896   case Instruction::Add:
8897   case Instruction::Sub:
8898   case Instruction::Or:
8899   case Instruction::Xor:
8900   case Instruction::Shl:
8901   case Instruction::LShr:
8902   case Instruction::AShr:
8903     return Constant::getNullValue(I->getType());
8904   case Instruction::And:
8905     return Constant::getAllOnesValue(I->getType());
8906   case Instruction::Mul:
8907     return ConstantInt::get(I->getType(), 1);
8908   }
8909 }
8910
8911 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8912 /// have the same opcode and only one use each.  Try to simplify this.
8913 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8914                                           Instruction *FI) {
8915   if (TI->getNumOperands() == 1) {
8916     // If this is a non-volatile load or a cast from the same type,
8917     // merge.
8918     if (TI->isCast()) {
8919       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8920         return 0;
8921     } else {
8922       return 0;  // unknown unary op.
8923     }
8924
8925     // Fold this by inserting a select from the input values.
8926     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8927                                           FI->getOperand(0), SI.getName()+".v");
8928     InsertNewInstBefore(NewSI, SI);
8929     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8930                             TI->getType());
8931   }
8932
8933   // Only handle binary operators here.
8934   if (!isa<BinaryOperator>(TI))
8935     return 0;
8936
8937   // Figure out if the operations have any operands in common.
8938   Value *MatchOp, *OtherOpT, *OtherOpF;
8939   bool MatchIsOpZero;
8940   if (TI->getOperand(0) == FI->getOperand(0)) {
8941     MatchOp  = TI->getOperand(0);
8942     OtherOpT = TI->getOperand(1);
8943     OtherOpF = FI->getOperand(1);
8944     MatchIsOpZero = true;
8945   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8946     MatchOp  = TI->getOperand(1);
8947     OtherOpT = TI->getOperand(0);
8948     OtherOpF = FI->getOperand(0);
8949     MatchIsOpZero = false;
8950   } else if (!TI->isCommutative()) {
8951     return 0;
8952   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8953     MatchOp  = TI->getOperand(0);
8954     OtherOpT = TI->getOperand(1);
8955     OtherOpF = FI->getOperand(0);
8956     MatchIsOpZero = true;
8957   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8958     MatchOp  = TI->getOperand(1);
8959     OtherOpT = TI->getOperand(0);
8960     OtherOpF = FI->getOperand(1);
8961     MatchIsOpZero = true;
8962   } else {
8963     return 0;
8964   }
8965
8966   // If we reach here, they do have operations in common.
8967   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8968                                          OtherOpF, SI.getName()+".v");
8969   InsertNewInstBefore(NewSI, SI);
8970
8971   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8972     if (MatchIsOpZero)
8973       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8974     else
8975       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8976   }
8977   llvm_unreachable("Shouldn't get here");
8978   return 0;
8979 }
8980
8981 static bool isSelect01(Constant *C1, Constant *C2) {
8982   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
8983   if (!C1I)
8984     return false;
8985   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
8986   if (!C2I)
8987     return false;
8988   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
8989 }
8990
8991 /// FoldSelectIntoOp - Try fold the select into one of the operands to
8992 /// facilitate further optimization.
8993 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
8994                                             Value *FalseVal) {
8995   // See the comment above GetSelectFoldableOperands for a description of the
8996   // transformation we are doing here.
8997   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
8998     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8999         !isa<Constant>(FalseVal)) {
9000       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9001         unsigned OpToFold = 0;
9002         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9003           OpToFold = 1;
9004         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9005           OpToFold = 2;
9006         }
9007
9008         if (OpToFold) {
9009           Constant *C = GetSelectFoldableConstant(TVI, Context);
9010           Value *OOp = TVI->getOperand(2-OpToFold);
9011           // Avoid creating select between 2 constants unless it's selecting
9012           // between 0 and 1.
9013           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9014             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9015             InsertNewInstBefore(NewSel, SI);
9016             NewSel->takeName(TVI);
9017             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9018               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9019             llvm_unreachable("Unknown instruction!!");
9020           }
9021         }
9022       }
9023     }
9024   }
9025
9026   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9027     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9028         !isa<Constant>(TrueVal)) {
9029       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9030         unsigned OpToFold = 0;
9031         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9032           OpToFold = 1;
9033         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9034           OpToFold = 2;
9035         }
9036
9037         if (OpToFold) {
9038           Constant *C = GetSelectFoldableConstant(FVI, Context);
9039           Value *OOp = FVI->getOperand(2-OpToFold);
9040           // Avoid creating select between 2 constants unless it's selecting
9041           // between 0 and 1.
9042           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9043             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9044             InsertNewInstBefore(NewSel, SI);
9045             NewSel->takeName(FVI);
9046             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9047               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9048             llvm_unreachable("Unknown instruction!!");
9049           }
9050         }
9051       }
9052     }
9053   }
9054
9055   return 0;
9056 }
9057
9058 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9059 /// ICmpInst as its first operand.
9060 ///
9061 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9062                                                    ICmpInst *ICI) {
9063   bool Changed = false;
9064   ICmpInst::Predicate Pred = ICI->getPredicate();
9065   Value *CmpLHS = ICI->getOperand(0);
9066   Value *CmpRHS = ICI->getOperand(1);
9067   Value *TrueVal = SI.getTrueValue();
9068   Value *FalseVal = SI.getFalseValue();
9069
9070   // Check cases where the comparison is with a constant that
9071   // can be adjusted to fit the min/max idiom. We may edit ICI in
9072   // place here, so make sure the select is the only user.
9073   if (ICI->hasOneUse())
9074     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9075       switch (Pred) {
9076       default: break;
9077       case ICmpInst::ICMP_ULT:
9078       case ICmpInst::ICMP_SLT: {
9079         // X < MIN ? T : F  -->  F
9080         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9081           return ReplaceInstUsesWith(SI, FalseVal);
9082         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9083         Constant *AdjustedRHS = SubOne(CI);
9084         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9085             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9086           Pred = ICmpInst::getSwappedPredicate(Pred);
9087           CmpRHS = AdjustedRHS;
9088           std::swap(FalseVal, TrueVal);
9089           ICI->setPredicate(Pred);
9090           ICI->setOperand(1, CmpRHS);
9091           SI.setOperand(1, TrueVal);
9092           SI.setOperand(2, FalseVal);
9093           Changed = true;
9094         }
9095         break;
9096       }
9097       case ICmpInst::ICMP_UGT:
9098       case ICmpInst::ICMP_SGT: {
9099         // X > MAX ? T : F  -->  F
9100         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9101           return ReplaceInstUsesWith(SI, FalseVal);
9102         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9103         Constant *AdjustedRHS = AddOne(CI);
9104         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9105             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9106           Pred = ICmpInst::getSwappedPredicate(Pred);
9107           CmpRHS = AdjustedRHS;
9108           std::swap(FalseVal, TrueVal);
9109           ICI->setPredicate(Pred);
9110           ICI->setOperand(1, CmpRHS);
9111           SI.setOperand(1, TrueVal);
9112           SI.setOperand(2, FalseVal);
9113           Changed = true;
9114         }
9115         break;
9116       }
9117       }
9118
9119       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9120       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9121       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9122       if (match(TrueVal, m_ConstantInt<-1>()) &&
9123           match(FalseVal, m_ConstantInt<0>()))
9124         Pred = ICI->getPredicate();
9125       else if (match(TrueVal, m_ConstantInt<0>()) &&
9126                match(FalseVal, m_ConstantInt<-1>()))
9127         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9128       
9129       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9130         // If we are just checking for a icmp eq of a single bit and zext'ing it
9131         // to an integer, then shift the bit to the appropriate place and then
9132         // cast to integer to avoid the comparison.
9133         const APInt &Op1CV = CI->getValue();
9134     
9135         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9136         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9137         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9138             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9139           Value *In = ICI->getOperand(0);
9140           Value *Sh = ConstantInt::get(In->getType(),
9141                                        In->getType()->getScalarSizeInBits()-1);
9142           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9143                                                         In->getName()+".lobit"),
9144                                    *ICI);
9145           if (In->getType() != SI.getType())
9146             In = CastInst::CreateIntegerCast(In, SI.getType(),
9147                                              true/*SExt*/, "tmp", ICI);
9148     
9149           if (Pred == ICmpInst::ICMP_SGT)
9150             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9151                                        In->getName()+".not"), *ICI);
9152     
9153           return ReplaceInstUsesWith(SI, In);
9154         }
9155       }
9156     }
9157
9158   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9159     // Transform (X == Y) ? X : Y  -> Y
9160     if (Pred == ICmpInst::ICMP_EQ)
9161       return ReplaceInstUsesWith(SI, FalseVal);
9162     // Transform (X != Y) ? X : Y  -> X
9163     if (Pred == ICmpInst::ICMP_NE)
9164       return ReplaceInstUsesWith(SI, TrueVal);
9165     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9166
9167   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9168     // Transform (X == Y) ? Y : X  -> X
9169     if (Pred == ICmpInst::ICMP_EQ)
9170       return ReplaceInstUsesWith(SI, FalseVal);
9171     // Transform (X != Y) ? Y : X  -> Y
9172     if (Pred == ICmpInst::ICMP_NE)
9173       return ReplaceInstUsesWith(SI, TrueVal);
9174     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9175   }
9176
9177   /// NOTE: if we wanted to, this is where to detect integer ABS
9178
9179   return Changed ? &SI : 0;
9180 }
9181
9182 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9183   Value *CondVal = SI.getCondition();
9184   Value *TrueVal = SI.getTrueValue();
9185   Value *FalseVal = SI.getFalseValue();
9186
9187   // select true, X, Y  -> X
9188   // select false, X, Y -> Y
9189   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9190     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9191
9192   // select C, X, X -> X
9193   if (TrueVal == FalseVal)
9194     return ReplaceInstUsesWith(SI, TrueVal);
9195
9196   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9197     return ReplaceInstUsesWith(SI, FalseVal);
9198   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9199     return ReplaceInstUsesWith(SI, TrueVal);
9200   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9201     if (isa<Constant>(TrueVal))
9202       return ReplaceInstUsesWith(SI, TrueVal);
9203     else
9204       return ReplaceInstUsesWith(SI, FalseVal);
9205   }
9206
9207   if (SI.getType() == Type::getInt1Ty(*Context)) {
9208     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9209       if (C->getZExtValue()) {
9210         // Change: A = select B, true, C --> A = or B, C
9211         return BinaryOperator::CreateOr(CondVal, FalseVal);
9212       } else {
9213         // Change: A = select B, false, C --> A = and !B, C
9214         Value *NotCond =
9215           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9216                                              "not."+CondVal->getName()), SI);
9217         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9218       }
9219     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9220       if (C->getZExtValue() == false) {
9221         // Change: A = select B, C, false --> A = and B, C
9222         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9223       } else {
9224         // Change: A = select B, C, true --> A = or !B, C
9225         Value *NotCond =
9226           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9227                                              "not."+CondVal->getName()), SI);
9228         return BinaryOperator::CreateOr(NotCond, TrueVal);
9229       }
9230     }
9231     
9232     // select a, b, a  -> a&b
9233     // select a, a, b  -> a|b
9234     if (CondVal == TrueVal)
9235       return BinaryOperator::CreateOr(CondVal, FalseVal);
9236     else if (CondVal == FalseVal)
9237       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9238   }
9239
9240   // Selecting between two integer constants?
9241   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9242     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9243       // select C, 1, 0 -> zext C to int
9244       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9245         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9246       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9247         // select C, 0, 1 -> zext !C to int
9248         Value *NotCond =
9249           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9250                                                "not."+CondVal->getName()), SI);
9251         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9252       }
9253
9254       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9255         // If one of the constants is zero (we know they can't both be) and we
9256         // have an icmp instruction with zero, and we have an 'and' with the
9257         // non-constant value, eliminate this whole mess.  This corresponds to
9258         // cases like this: ((X & 27) ? 27 : 0)
9259         if (TrueValC->isZero() || FalseValC->isZero())
9260           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9261               cast<Constant>(IC->getOperand(1))->isNullValue())
9262             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9263               if (ICA->getOpcode() == Instruction::And &&
9264                   isa<ConstantInt>(ICA->getOperand(1)) &&
9265                   (ICA->getOperand(1) == TrueValC ||
9266                    ICA->getOperand(1) == FalseValC) &&
9267                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9268                 // Okay, now we know that everything is set up, we just don't
9269                 // know whether we have a icmp_ne or icmp_eq and whether the 
9270                 // true or false val is the zero.
9271                 bool ShouldNotVal = !TrueValC->isZero();
9272                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9273                 Value *V = ICA;
9274                 if (ShouldNotVal)
9275                   V = InsertNewInstBefore(BinaryOperator::Create(
9276                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9277                 return ReplaceInstUsesWith(SI, V);
9278               }
9279       }
9280     }
9281
9282   // See if we are selecting two values based on a comparison of the two values.
9283   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9284     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9285       // Transform (X == Y) ? X : Y  -> Y
9286       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9287         // This is not safe in general for floating point:  
9288         // consider X== -0, Y== +0.
9289         // It becomes safe if either operand is a nonzero constant.
9290         ConstantFP *CFPt, *CFPf;
9291         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9292               !CFPt->getValueAPF().isZero()) ||
9293             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9294              !CFPf->getValueAPF().isZero()))
9295         return ReplaceInstUsesWith(SI, FalseVal);
9296       }
9297       // Transform (X != Y) ? X : Y  -> X
9298       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9299         return ReplaceInstUsesWith(SI, TrueVal);
9300       // NOTE: if we wanted to, this is where to detect MIN/MAX
9301
9302     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9303       // Transform (X == Y) ? Y : X  -> X
9304       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9305         // This is not safe in general for floating point:  
9306         // consider X== -0, Y== +0.
9307         // It becomes safe if either operand is a nonzero constant.
9308         ConstantFP *CFPt, *CFPf;
9309         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9310               !CFPt->getValueAPF().isZero()) ||
9311             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9312              !CFPf->getValueAPF().isZero()))
9313           return ReplaceInstUsesWith(SI, FalseVal);
9314       }
9315       // Transform (X != Y) ? Y : X  -> Y
9316       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9317         return ReplaceInstUsesWith(SI, TrueVal);
9318       // NOTE: if we wanted to, this is where to detect MIN/MAX
9319     }
9320     // NOTE: if we wanted to, this is where to detect ABS
9321   }
9322
9323   // See if we are selecting two values based on a comparison of the two values.
9324   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9325     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9326       return Result;
9327
9328   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9329     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9330       if (TI->hasOneUse() && FI->hasOneUse()) {
9331         Instruction *AddOp = 0, *SubOp = 0;
9332
9333         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9334         if (TI->getOpcode() == FI->getOpcode())
9335           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9336             return IV;
9337
9338         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9339         // even legal for FP.
9340         if ((TI->getOpcode() == Instruction::Sub &&
9341              FI->getOpcode() == Instruction::Add) ||
9342             (TI->getOpcode() == Instruction::FSub &&
9343              FI->getOpcode() == Instruction::FAdd)) {
9344           AddOp = FI; SubOp = TI;
9345         } else if ((FI->getOpcode() == Instruction::Sub &&
9346                     TI->getOpcode() == Instruction::Add) ||
9347                    (FI->getOpcode() == Instruction::FSub &&
9348                     TI->getOpcode() == Instruction::FAdd)) {
9349           AddOp = TI; SubOp = FI;
9350         }
9351
9352         if (AddOp) {
9353           Value *OtherAddOp = 0;
9354           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9355             OtherAddOp = AddOp->getOperand(1);
9356           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9357             OtherAddOp = AddOp->getOperand(0);
9358           }
9359
9360           if (OtherAddOp) {
9361             // So at this point we know we have (Y -> OtherAddOp):
9362             //        select C, (add X, Y), (sub X, Z)
9363             Value *NegVal;  // Compute -Z
9364             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9365               NegVal = ConstantExpr::getNeg(C);
9366             } else {
9367               NegVal = InsertNewInstBefore(
9368                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
9369                                               "tmp"), SI);
9370             }
9371
9372             Value *NewTrueOp = OtherAddOp;
9373             Value *NewFalseOp = NegVal;
9374             if (AddOp != TI)
9375               std::swap(NewTrueOp, NewFalseOp);
9376             Instruction *NewSel =
9377               SelectInst::Create(CondVal, NewTrueOp,
9378                                  NewFalseOp, SI.getName() + ".p");
9379
9380             NewSel = InsertNewInstBefore(NewSel, SI);
9381             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9382           }
9383         }
9384       }
9385
9386   // See if we can fold the select into one of our operands.
9387   if (SI.getType()->isInteger()) {
9388     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9389     if (FoldI)
9390       return FoldI;
9391   }
9392
9393   if (BinaryOperator::isNot(CondVal)) {
9394     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9395     SI.setOperand(1, FalseVal);
9396     SI.setOperand(2, TrueVal);
9397     return &SI;
9398   }
9399
9400   return 0;
9401 }
9402
9403 /// EnforceKnownAlignment - If the specified pointer points to an object that
9404 /// we control, modify the object's alignment to PrefAlign. This isn't
9405 /// often possible though. If alignment is important, a more reliable approach
9406 /// is to simply align all global variables and allocation instructions to
9407 /// their preferred alignment from the beginning.
9408 ///
9409 static unsigned EnforceKnownAlignment(Value *V,
9410                                       unsigned Align, unsigned PrefAlign) {
9411
9412   User *U = dyn_cast<User>(V);
9413   if (!U) return Align;
9414
9415   switch (Operator::getOpcode(U)) {
9416   default: break;
9417   case Instruction::BitCast:
9418     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9419   case Instruction::GetElementPtr: {
9420     // If all indexes are zero, it is just the alignment of the base pointer.
9421     bool AllZeroOperands = true;
9422     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9423       if (!isa<Constant>(*i) ||
9424           !cast<Constant>(*i)->isNullValue()) {
9425         AllZeroOperands = false;
9426         break;
9427       }
9428
9429     if (AllZeroOperands) {
9430       // Treat this like a bitcast.
9431       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9432     }
9433     break;
9434   }
9435   }
9436
9437   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9438     // If there is a large requested alignment and we can, bump up the alignment
9439     // of the global.
9440     if (!GV->isDeclaration()) {
9441       if (GV->getAlignment() >= PrefAlign)
9442         Align = GV->getAlignment();
9443       else {
9444         GV->setAlignment(PrefAlign);
9445         Align = PrefAlign;
9446       }
9447     }
9448   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9449     // If there is a requested alignment and if this is an alloca, round up.  We
9450     // don't do this for malloc, because some systems can't respect the request.
9451     if (isa<AllocaInst>(AI)) {
9452       if (AI->getAlignment() >= PrefAlign)
9453         Align = AI->getAlignment();
9454       else {
9455         AI->setAlignment(PrefAlign);
9456         Align = PrefAlign;
9457       }
9458     }
9459   }
9460
9461   return Align;
9462 }
9463
9464 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9465 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9466 /// and it is more than the alignment of the ultimate object, see if we can
9467 /// increase the alignment of the ultimate object, making this check succeed.
9468 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9469                                                   unsigned PrefAlign) {
9470   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9471                       sizeof(PrefAlign) * CHAR_BIT;
9472   APInt Mask = APInt::getAllOnesValue(BitWidth);
9473   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9474   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9475   unsigned TrailZ = KnownZero.countTrailingOnes();
9476   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9477
9478   if (PrefAlign > Align)
9479     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9480   
9481     // We don't need to make any adjustment.
9482   return Align;
9483 }
9484
9485 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9486   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9487   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9488   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9489   unsigned CopyAlign = MI->getAlignment();
9490
9491   if (CopyAlign < MinAlign) {
9492     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9493                                              MinAlign, false));
9494     return MI;
9495   }
9496   
9497   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9498   // load/store.
9499   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9500   if (MemOpLength == 0) return 0;
9501   
9502   // Source and destination pointer types are always "i8*" for intrinsic.  See
9503   // if the size is something we can handle with a single primitive load/store.
9504   // A single load+store correctly handles overlapping memory in the memmove
9505   // case.
9506   unsigned Size = MemOpLength->getZExtValue();
9507   if (Size == 0) return MI;  // Delete this mem transfer.
9508   
9509   if (Size > 8 || (Size&(Size-1)))
9510     return 0;  // If not 1/2/4/8 bytes, exit.
9511   
9512   // Use an integer load+store unless we can find something better.
9513   Type *NewPtrTy =
9514                 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9515   
9516   // Memcpy forces the use of i8* for the source and destination.  That means
9517   // that if you're using memcpy to move one double around, you'll get a cast
9518   // from double* to i8*.  We'd much rather use a double load+store rather than
9519   // an i64 load+store, here because this improves the odds that the source or
9520   // dest address will be promotable.  See if we can find a better type than the
9521   // integer datatype.
9522   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9523     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9524     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9525       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9526       // down through these levels if so.
9527       while (!SrcETy->isSingleValueType()) {
9528         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9529           if (STy->getNumElements() == 1)
9530             SrcETy = STy->getElementType(0);
9531           else
9532             break;
9533         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9534           if (ATy->getNumElements() == 1)
9535             SrcETy = ATy->getElementType();
9536           else
9537             break;
9538         } else
9539           break;
9540       }
9541       
9542       if (SrcETy->isSingleValueType())
9543         NewPtrTy = PointerType::getUnqual(SrcETy);
9544     }
9545   }
9546   
9547   
9548   // If the memcpy/memmove provides better alignment info than we can
9549   // infer, use it.
9550   SrcAlign = std::max(SrcAlign, CopyAlign);
9551   DstAlign = std::max(DstAlign, CopyAlign);
9552   
9553   Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9554   Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
9555   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9556   InsertNewInstBefore(L, *MI);
9557   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9558
9559   // Set the size of the copy to 0, it will be deleted on the next iteration.
9560   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9561   return MI;
9562 }
9563
9564 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9565   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9566   if (MI->getAlignment() < Alignment) {
9567     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9568                                              Alignment, false));
9569     return MI;
9570   }
9571   
9572   // Extract the length and alignment and fill if they are constant.
9573   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9574   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9575   if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9576     return 0;
9577   uint64_t Len = LenC->getZExtValue();
9578   Alignment = MI->getAlignment();
9579   
9580   // If the length is zero, this is a no-op
9581   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9582   
9583   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9584   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9585     const Type *ITy = IntegerType::get(*Context, Len*8);  // n=1 -> i8.
9586     
9587     Value *Dest = MI->getDest();
9588     Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
9589
9590     // Alignment 0 is identity for alignment 1 for memset, but not store.
9591     if (Alignment == 0) Alignment = 1;
9592     
9593     // Extract the fill value and store.
9594     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9595     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9596                                       Dest, false, Alignment), *MI);
9597     
9598     // Set the size of the copy to 0, it will be deleted on the next iteration.
9599     MI->setLength(Constant::getNullValue(LenC->getType()));
9600     return MI;
9601   }
9602
9603   return 0;
9604 }
9605
9606
9607 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9608 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9609 /// the heavy lifting.
9610 ///
9611 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9612   // If the caller function is nounwind, mark the call as nounwind, even if the
9613   // callee isn't.
9614   if (CI.getParent()->getParent()->doesNotThrow() &&
9615       !CI.doesNotThrow()) {
9616     CI.setDoesNotThrow();
9617     return &CI;
9618   }
9619   
9620   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9621   if (!II) return visitCallSite(&CI);
9622   
9623   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9624   // visitCallSite.
9625   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9626     bool Changed = false;
9627
9628     // memmove/cpy/set of zero bytes is a noop.
9629     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9630       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9631
9632       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9633         if (CI->getZExtValue() == 1) {
9634           // Replace the instruction with just byte operations.  We would
9635           // transform other cases to loads/stores, but we don't know if
9636           // alignment is sufficient.
9637         }
9638     }
9639
9640     // If we have a memmove and the source operation is a constant global,
9641     // then the source and dest pointers can't alias, so we can change this
9642     // into a call to memcpy.
9643     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9644       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9645         if (GVSrc->isConstant()) {
9646           Module *M = CI.getParent()->getParent()->getParent();
9647           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9648           const Type *Tys[1];
9649           Tys[0] = CI.getOperand(3)->getType();
9650           CI.setOperand(0, 
9651                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9652           Changed = true;
9653         }
9654
9655       // memmove(x,x,size) -> noop.
9656       if (MMI->getSource() == MMI->getDest())
9657         return EraseInstFromFunction(CI);
9658     }
9659
9660     // If we can determine a pointer alignment that is bigger than currently
9661     // set, update the alignment.
9662     if (isa<MemTransferInst>(MI)) {
9663       if (Instruction *I = SimplifyMemTransfer(MI))
9664         return I;
9665     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9666       if (Instruction *I = SimplifyMemSet(MSI))
9667         return I;
9668     }
9669           
9670     if (Changed) return II;
9671   }
9672   
9673   switch (II->getIntrinsicID()) {
9674   default: break;
9675   case Intrinsic::bswap:
9676     // bswap(bswap(x)) -> x
9677     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9678       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9679         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9680     break;
9681   case Intrinsic::ppc_altivec_lvx:
9682   case Intrinsic::ppc_altivec_lvxl:
9683   case Intrinsic::x86_sse_loadu_ps:
9684   case Intrinsic::x86_sse2_loadu_pd:
9685   case Intrinsic::x86_sse2_loadu_dq:
9686     // Turn PPC lvx     -> load if the pointer is known aligned.
9687     // Turn X86 loadups -> load if the pointer is known aligned.
9688     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9689       Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9690                                          PointerType::getUnqual(II->getType()));
9691       return new LoadInst(Ptr);
9692     }
9693     break;
9694   case Intrinsic::ppc_altivec_stvx:
9695   case Intrinsic::ppc_altivec_stvxl:
9696     // Turn stvx -> store if the pointer is known aligned.
9697     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9698       const Type *OpPtrTy = 
9699         PointerType::getUnqual(II->getOperand(1)->getType());
9700       Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
9701       return new StoreInst(II->getOperand(1), Ptr);
9702     }
9703     break;
9704   case Intrinsic::x86_sse_storeu_ps:
9705   case Intrinsic::x86_sse2_storeu_pd:
9706   case Intrinsic::x86_sse2_storeu_dq:
9707     // Turn X86 storeu -> store if the pointer is known aligned.
9708     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9709       const Type *OpPtrTy = 
9710         PointerType::getUnqual(II->getOperand(2)->getType());
9711       Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
9712       return new StoreInst(II->getOperand(2), Ptr);
9713     }
9714     break;
9715     
9716   case Intrinsic::x86_sse_cvttss2si: {
9717     // These intrinsics only demands the 0th element of its input vector.  If
9718     // we can simplify the input based on that, do so now.
9719     unsigned VWidth =
9720       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9721     APInt DemandedElts(VWidth, 1);
9722     APInt UndefElts(VWidth, 0);
9723     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9724                                               UndefElts)) {
9725       II->setOperand(1, V);
9726       return II;
9727     }
9728     break;
9729   }
9730     
9731   case Intrinsic::ppc_altivec_vperm:
9732     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9733     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9734       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9735       
9736       // Check that all of the elements are integer constants or undefs.
9737       bool AllEltsOk = true;
9738       for (unsigned i = 0; i != 16; ++i) {
9739         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9740             !isa<UndefValue>(Mask->getOperand(i))) {
9741           AllEltsOk = false;
9742           break;
9743         }
9744       }
9745       
9746       if (AllEltsOk) {
9747         // Cast the input vectors to byte vectors.
9748         Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9749         Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
9750         Value *Result = UndefValue::get(Op0->getType());
9751         
9752         // Only extract each element once.
9753         Value *ExtractedElts[32];
9754         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9755         
9756         for (unsigned i = 0; i != 16; ++i) {
9757           if (isa<UndefValue>(Mask->getOperand(i)))
9758             continue;
9759           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9760           Idx &= 31;  // Match the hardware behavior.
9761           
9762           if (ExtractedElts[Idx] == 0) {
9763             ExtractedElts[Idx] = 
9764               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1, 
9765                   ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9766                                             "tmp");
9767           }
9768         
9769           // Insert this value into the result vector.
9770           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9771                          ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9772                                                 "tmp");
9773         }
9774         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9775       }
9776     }
9777     break;
9778
9779   case Intrinsic::stackrestore: {
9780     // If the save is right next to the restore, remove the restore.  This can
9781     // happen when variable allocas are DCE'd.
9782     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9783       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9784         BasicBlock::iterator BI = SS;
9785         if (&*++BI == II)
9786           return EraseInstFromFunction(CI);
9787       }
9788     }
9789     
9790     // Scan down this block to see if there is another stack restore in the
9791     // same block without an intervening call/alloca.
9792     BasicBlock::iterator BI = II;
9793     TerminatorInst *TI = II->getParent()->getTerminator();
9794     bool CannotRemove = false;
9795     for (++BI; &*BI != TI; ++BI) {
9796       if (isa<AllocaInst>(BI)) {
9797         CannotRemove = true;
9798         break;
9799       }
9800       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9801         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9802           // If there is a stackrestore below this one, remove this one.
9803           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9804             return EraseInstFromFunction(CI);
9805           // Otherwise, ignore the intrinsic.
9806         } else {
9807           // If we found a non-intrinsic call, we can't remove the stack
9808           // restore.
9809           CannotRemove = true;
9810           break;
9811         }
9812       }
9813     }
9814     
9815     // If the stack restore is in a return/unwind block and if there are no
9816     // allocas or calls between the restore and the return, nuke the restore.
9817     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9818       return EraseInstFromFunction(CI);
9819     break;
9820   }
9821   }
9822
9823   return visitCallSite(II);
9824 }
9825
9826 // InvokeInst simplification
9827 //
9828 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9829   return visitCallSite(&II);
9830 }
9831
9832 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9833 /// passed through the varargs area, we can eliminate the use of the cast.
9834 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9835                                          const CastInst * const CI,
9836                                          const TargetData * const TD,
9837                                          const int ix) {
9838   if (!CI->isLosslessCast())
9839     return false;
9840
9841   // The size of ByVal arguments is derived from the type, so we
9842   // can't change to a type with a different size.  If the size were
9843   // passed explicitly we could avoid this check.
9844   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9845     return true;
9846
9847   const Type* SrcTy = 
9848             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9849   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9850   if (!SrcTy->isSized() || !DstTy->isSized())
9851     return false;
9852   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
9853     return false;
9854   return true;
9855 }
9856
9857 // visitCallSite - Improvements for call and invoke instructions.
9858 //
9859 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9860   bool Changed = false;
9861
9862   // If the callee is a constexpr cast of a function, attempt to move the cast
9863   // to the arguments of the call/invoke.
9864   if (transformConstExprCastCall(CS)) return 0;
9865
9866   Value *Callee = CS.getCalledValue();
9867
9868   if (Function *CalleeF = dyn_cast<Function>(Callee))
9869     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9870       Instruction *OldCall = CS.getInstruction();
9871       // If the call and callee calling conventions don't match, this call must
9872       // be unreachable, as the call is undefined.
9873       new StoreInst(ConstantInt::getTrue(*Context),
9874                 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), 
9875                                   OldCall);
9876       if (!OldCall->use_empty())
9877         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9878       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9879         return EraseInstFromFunction(*OldCall);
9880       return 0;
9881     }
9882
9883   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9884     // This instruction is not reachable, just remove it.  We insert a store to
9885     // undef so that we know that this code is not reachable, despite the fact
9886     // that we can't modify the CFG here.
9887     new StoreInst(ConstantInt::getTrue(*Context),
9888                UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
9889                   CS.getInstruction());
9890
9891     if (!CS.getInstruction()->use_empty())
9892       CS.getInstruction()->
9893         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9894
9895     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9896       // Don't break the CFG, insert a dummy cond branch.
9897       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9898                          ConstantInt::getTrue(*Context), II);
9899     }
9900     return EraseInstFromFunction(*CS.getInstruction());
9901   }
9902
9903   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9904     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9905       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9906         return transformCallThroughTrampoline(CS);
9907
9908   const PointerType *PTy = cast<PointerType>(Callee->getType());
9909   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9910   if (FTy->isVarArg()) {
9911     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9912     // See if we can optimize any arguments passed through the varargs area of
9913     // the call.
9914     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9915            E = CS.arg_end(); I != E; ++I, ++ix) {
9916       CastInst *CI = dyn_cast<CastInst>(*I);
9917       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9918         *I = CI->getOperand(0);
9919         Changed = true;
9920       }
9921     }
9922   }
9923
9924   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9925     // Inline asm calls cannot throw - mark them 'nounwind'.
9926     CS.setDoesNotThrow();
9927     Changed = true;
9928   }
9929
9930   return Changed ? CS.getInstruction() : 0;
9931 }
9932
9933 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9934 // attempt to move the cast to the arguments of the call/invoke.
9935 //
9936 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9937   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9938   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9939   if (CE->getOpcode() != Instruction::BitCast || 
9940       !isa<Function>(CE->getOperand(0)))
9941     return false;
9942   Function *Callee = cast<Function>(CE->getOperand(0));
9943   Instruction *Caller = CS.getInstruction();
9944   const AttrListPtr &CallerPAL = CS.getAttributes();
9945
9946   // Okay, this is a cast from a function to a different type.  Unless doing so
9947   // would cause a type conversion of one of our arguments, change this call to
9948   // be a direct call with arguments casted to the appropriate types.
9949   //
9950   const FunctionType *FT = Callee->getFunctionType();
9951   const Type *OldRetTy = Caller->getType();
9952   const Type *NewRetTy = FT->getReturnType();
9953
9954   if (isa<StructType>(NewRetTy))
9955     return false; // TODO: Handle multiple return values.
9956
9957   // Check to see if we are changing the return type...
9958   if (OldRetTy != NewRetTy) {
9959     if (Callee->isDeclaration() &&
9960         // Conversion is ok if changing from one pointer type to another or from
9961         // a pointer to an integer of the same size.
9962         !((isa<PointerType>(OldRetTy) || !TD ||
9963            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
9964           (isa<PointerType>(NewRetTy) || !TD ||
9965            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
9966       return false;   // Cannot transform this return value.
9967
9968     if (!Caller->use_empty() &&
9969         // void -> non-void is handled specially
9970         NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
9971       return false;   // Cannot transform this return value.
9972
9973     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9974       Attributes RAttrs = CallerPAL.getRetAttributes();
9975       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9976         return false;   // Attribute not compatible with transformed value.
9977     }
9978
9979     // If the callsite is an invoke instruction, and the return value is used by
9980     // a PHI node in a successor, we cannot change the return type of the call
9981     // because there is no place to put the cast instruction (without breaking
9982     // the critical edge).  Bail out in this case.
9983     if (!Caller->use_empty())
9984       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9985         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9986              UI != E; ++UI)
9987           if (PHINode *PN = dyn_cast<PHINode>(*UI))
9988             if (PN->getParent() == II->getNormalDest() ||
9989                 PN->getParent() == II->getUnwindDest())
9990               return false;
9991   }
9992
9993   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9994   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9995
9996   CallSite::arg_iterator AI = CS.arg_begin();
9997   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9998     const Type *ParamTy = FT->getParamType(i);
9999     const Type *ActTy = (*AI)->getType();
10000
10001     if (!CastInst::isCastable(ActTy, ParamTy))
10002       return false;   // Cannot transform this parameter value.
10003
10004     if (CallerPAL.getParamAttributes(i + 1) 
10005         & Attribute::typeIncompatible(ParamTy))
10006       return false;   // Attribute not compatible with transformed value.
10007
10008     // Converting from one pointer type to another or between a pointer and an
10009     // integer of the same size is safe even if we do not have a body.
10010     bool isConvertible = ActTy == ParamTy ||
10011       (TD && ((isa<PointerType>(ParamTy) ||
10012       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10013               (isa<PointerType>(ActTy) ||
10014               ActTy == TD->getIntPtrType(Caller->getContext()))));
10015     if (Callee->isDeclaration() && !isConvertible) return false;
10016   }
10017
10018   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10019       Callee->isDeclaration())
10020     return false;   // Do not delete arguments unless we have a function body.
10021
10022   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10023       !CallerPAL.isEmpty())
10024     // In this case we have more arguments than the new function type, but we
10025     // won't be dropping them.  Check that these extra arguments have attributes
10026     // that are compatible with being a vararg call argument.
10027     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10028       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10029         break;
10030       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10031       if (PAttrs & Attribute::VarArgsIncompatible)
10032         return false;
10033     }
10034
10035   // Okay, we decided that this is a safe thing to do: go ahead and start
10036   // inserting cast instructions as necessary...
10037   std::vector<Value*> Args;
10038   Args.reserve(NumActualArgs);
10039   SmallVector<AttributeWithIndex, 8> attrVec;
10040   attrVec.reserve(NumCommonArgs);
10041
10042   // Get any return attributes.
10043   Attributes RAttrs = CallerPAL.getRetAttributes();
10044
10045   // If the return value is not being used, the type may not be compatible
10046   // with the existing attributes.  Wipe out any problematic attributes.
10047   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10048
10049   // Add the new return attributes.
10050   if (RAttrs)
10051     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10052
10053   AI = CS.arg_begin();
10054   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10055     const Type *ParamTy = FT->getParamType(i);
10056     if ((*AI)->getType() == ParamTy) {
10057       Args.push_back(*AI);
10058     } else {
10059       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10060           false, ParamTy, false);
10061       Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10062     }
10063
10064     // Add any parameter attributes.
10065     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10066       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10067   }
10068
10069   // If the function takes more arguments than the call was taking, add them
10070   // now.
10071   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10072     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10073
10074   // If we are removing arguments to the function, emit an obnoxious warning.
10075   if (FT->getNumParams() < NumActualArgs) {
10076     if (!FT->isVarArg()) {
10077       errs() << "WARNING: While resolving call to function '"
10078              << Callee->getName() << "' arguments were dropped!\n";
10079     } else {
10080       // Add all of the arguments in their promoted form to the arg list.
10081       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10082         const Type *PTy = getPromotedType((*AI)->getType());
10083         if (PTy != (*AI)->getType()) {
10084           // Must promote to pass through va_arg area!
10085           Instruction::CastOps opcode =
10086             CastInst::getCastOpcode(*AI, false, PTy, false);
10087           Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10088         } else {
10089           Args.push_back(*AI);
10090         }
10091
10092         // Add any parameter attributes.
10093         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10094           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10095       }
10096     }
10097   }
10098
10099   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10100     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10101
10102   if (NewRetTy == Type::getVoidTy(*Context))
10103     Caller->setName("");   // Void type should not have a name.
10104
10105   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10106                                                      attrVec.end());
10107
10108   Instruction *NC;
10109   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10110     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10111                             Args.begin(), Args.end(),
10112                             Caller->getName(), Caller);
10113     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10114     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10115   } else {
10116     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10117                           Caller->getName(), Caller);
10118     CallInst *CI = cast<CallInst>(Caller);
10119     if (CI->isTailCall())
10120       cast<CallInst>(NC)->setTailCall();
10121     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10122     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10123   }
10124
10125   // Insert a cast of the return type as necessary.
10126   Value *NV = NC;
10127   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10128     if (NV->getType() != Type::getVoidTy(*Context)) {
10129       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10130                                                             OldRetTy, false);
10131       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10132
10133       // If this is an invoke instruction, we should insert it after the first
10134       // non-phi, instruction in the normal successor block.
10135       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10136         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10137         InsertNewInstBefore(NC, *I);
10138       } else {
10139         // Otherwise, it's a call, just insert cast right after the call instr
10140         InsertNewInstBefore(NC, *Caller);
10141       }
10142       Worklist.AddUsersToWorkList(*Caller);
10143     } else {
10144       NV = UndefValue::get(Caller->getType());
10145     }
10146   }
10147
10148   if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10149     Caller->replaceAllUsesWith(NV);
10150   Caller->eraseFromParent();
10151   Worklist.Remove(Caller);
10152   return true;
10153 }
10154
10155 // transformCallThroughTrampoline - Turn a call to a function created by the
10156 // init_trampoline intrinsic into a direct call to the underlying function.
10157 //
10158 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10159   Value *Callee = CS.getCalledValue();
10160   const PointerType *PTy = cast<PointerType>(Callee->getType());
10161   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10162   const AttrListPtr &Attrs = CS.getAttributes();
10163
10164   // If the call already has the 'nest' attribute somewhere then give up -
10165   // otherwise 'nest' would occur twice after splicing in the chain.
10166   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10167     return 0;
10168
10169   IntrinsicInst *Tramp =
10170     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10171
10172   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10173   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10174   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10175
10176   const AttrListPtr &NestAttrs = NestF->getAttributes();
10177   if (!NestAttrs.isEmpty()) {
10178     unsigned NestIdx = 1;
10179     const Type *NestTy = 0;
10180     Attributes NestAttr = Attribute::None;
10181
10182     // Look for a parameter marked with the 'nest' attribute.
10183     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10184          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10185       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10186         // Record the parameter type and any other attributes.
10187         NestTy = *I;
10188         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10189         break;
10190       }
10191
10192     if (NestTy) {
10193       Instruction *Caller = CS.getInstruction();
10194       std::vector<Value*> NewArgs;
10195       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10196
10197       SmallVector<AttributeWithIndex, 8> NewAttrs;
10198       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10199
10200       // Insert the nest argument into the call argument list, which may
10201       // mean appending it.  Likewise for attributes.
10202
10203       // Add any result attributes.
10204       if (Attributes Attr = Attrs.getRetAttributes())
10205         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10206
10207       {
10208         unsigned Idx = 1;
10209         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10210         do {
10211           if (Idx == NestIdx) {
10212             // Add the chain argument and attributes.
10213             Value *NestVal = Tramp->getOperand(3);
10214             if (NestVal->getType() != NestTy)
10215               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10216             NewArgs.push_back(NestVal);
10217             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10218           }
10219
10220           if (I == E)
10221             break;
10222
10223           // Add the original argument and attributes.
10224           NewArgs.push_back(*I);
10225           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10226             NewAttrs.push_back
10227               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10228
10229           ++Idx, ++I;
10230         } while (1);
10231       }
10232
10233       // Add any function attributes.
10234       if (Attributes Attr = Attrs.getFnAttributes())
10235         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10236
10237       // The trampoline may have been bitcast to a bogus type (FTy).
10238       // Handle this by synthesizing a new function type, equal to FTy
10239       // with the chain parameter inserted.
10240
10241       std::vector<const Type*> NewTypes;
10242       NewTypes.reserve(FTy->getNumParams()+1);
10243
10244       // Insert the chain's type into the list of parameter types, which may
10245       // mean appending it.
10246       {
10247         unsigned Idx = 1;
10248         FunctionType::param_iterator I = FTy->param_begin(),
10249           E = FTy->param_end();
10250
10251         do {
10252           if (Idx == NestIdx)
10253             // Add the chain's type.
10254             NewTypes.push_back(NestTy);
10255
10256           if (I == E)
10257             break;
10258
10259           // Add the original type.
10260           NewTypes.push_back(*I);
10261
10262           ++Idx, ++I;
10263         } while (1);
10264       }
10265
10266       // Replace the trampoline call with a direct call.  Let the generic
10267       // code sort out any function type mismatches.
10268       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10269                                                 FTy->isVarArg());
10270       Constant *NewCallee =
10271         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10272         NestF : ConstantExpr::getBitCast(NestF, 
10273                                          PointerType::getUnqual(NewFTy));
10274       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10275                                                    NewAttrs.end());
10276
10277       Instruction *NewCaller;
10278       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10279         NewCaller = InvokeInst::Create(NewCallee,
10280                                        II->getNormalDest(), II->getUnwindDest(),
10281                                        NewArgs.begin(), NewArgs.end(),
10282                                        Caller->getName(), Caller);
10283         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10284         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10285       } else {
10286         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10287                                      Caller->getName(), Caller);
10288         if (cast<CallInst>(Caller)->isTailCall())
10289           cast<CallInst>(NewCaller)->setTailCall();
10290         cast<CallInst>(NewCaller)->
10291           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10292         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10293       }
10294       if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10295         Caller->replaceAllUsesWith(NewCaller);
10296       Caller->eraseFromParent();
10297       Worklist.Remove(Caller);
10298       return 0;
10299     }
10300   }
10301
10302   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10303   // parameter, there is no need to adjust the argument list.  Let the generic
10304   // code sort out any function type mismatches.
10305   Constant *NewCallee =
10306     NestF->getType() == PTy ? NestF : 
10307                               ConstantExpr::getBitCast(NestF, PTy);
10308   CS.setCalledFunction(NewCallee);
10309   return CS.getInstruction();
10310 }
10311
10312 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10313 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10314 /// and a single binop.
10315 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10316   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10317   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10318   unsigned Opc = FirstInst->getOpcode();
10319   Value *LHSVal = FirstInst->getOperand(0);
10320   Value *RHSVal = FirstInst->getOperand(1);
10321     
10322   const Type *LHSType = LHSVal->getType();
10323   const Type *RHSType = RHSVal->getType();
10324   
10325   // Scan to see if all operands are the same opcode, all have one use, and all
10326   // kill their operands (i.e. the operands have one use).
10327   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10328     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10329     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10330         // Verify type of the LHS matches so we don't fold cmp's of different
10331         // types or GEP's with different index types.
10332         I->getOperand(0)->getType() != LHSType ||
10333         I->getOperand(1)->getType() != RHSType)
10334       return 0;
10335
10336     // If they are CmpInst instructions, check their predicates
10337     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10338       if (cast<CmpInst>(I)->getPredicate() !=
10339           cast<CmpInst>(FirstInst)->getPredicate())
10340         return 0;
10341     
10342     // Keep track of which operand needs a phi node.
10343     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10344     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10345   }
10346   
10347   // Otherwise, this is safe to transform!
10348   
10349   Value *InLHS = FirstInst->getOperand(0);
10350   Value *InRHS = FirstInst->getOperand(1);
10351   PHINode *NewLHS = 0, *NewRHS = 0;
10352   if (LHSVal == 0) {
10353     NewLHS = PHINode::Create(LHSType,
10354                              FirstInst->getOperand(0)->getName() + ".pn");
10355     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10356     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10357     InsertNewInstBefore(NewLHS, PN);
10358     LHSVal = NewLHS;
10359   }
10360   
10361   if (RHSVal == 0) {
10362     NewRHS = PHINode::Create(RHSType,
10363                              FirstInst->getOperand(1)->getName() + ".pn");
10364     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10365     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10366     InsertNewInstBefore(NewRHS, PN);
10367     RHSVal = NewRHS;
10368   }
10369   
10370   // Add all operands to the new PHIs.
10371   if (NewLHS || NewRHS) {
10372     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10373       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10374       if (NewLHS) {
10375         Value *NewInLHS = InInst->getOperand(0);
10376         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10377       }
10378       if (NewRHS) {
10379         Value *NewInRHS = InInst->getOperand(1);
10380         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10381       }
10382     }
10383   }
10384     
10385   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10386     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10387   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10388   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10389                          LHSVal, RHSVal);
10390 }
10391
10392 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10393   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10394   
10395   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10396                                         FirstInst->op_end());
10397   // This is true if all GEP bases are allocas and if all indices into them are
10398   // constants.
10399   bool AllBasePointersAreAllocas = true;
10400   
10401   // Scan to see if all operands are the same opcode, all have one use, and all
10402   // kill their operands (i.e. the operands have one use).
10403   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10404     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10405     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10406       GEP->getNumOperands() != FirstInst->getNumOperands())
10407       return 0;
10408
10409     // Keep track of whether or not all GEPs are of alloca pointers.
10410     if (AllBasePointersAreAllocas &&
10411         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10412          !GEP->hasAllConstantIndices()))
10413       AllBasePointersAreAllocas = false;
10414     
10415     // Compare the operand lists.
10416     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10417       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10418         continue;
10419       
10420       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10421       // if one of the PHIs has a constant for the index.  The index may be
10422       // substantially cheaper to compute for the constants, so making it a
10423       // variable index could pessimize the path.  This also handles the case
10424       // for struct indices, which must always be constant.
10425       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10426           isa<ConstantInt>(GEP->getOperand(op)))
10427         return 0;
10428       
10429       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10430         return 0;
10431       FixedOperands[op] = 0;  // Needs a PHI.
10432     }
10433   }
10434   
10435   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10436   // bother doing this transformation.  At best, this will just save a bit of
10437   // offset calculation, but all the predecessors will have to materialize the
10438   // stack address into a register anyway.  We'd actually rather *clone* the
10439   // load up into the predecessors so that we have a load of a gep of an alloca,
10440   // which can usually all be folded into the load.
10441   if (AllBasePointersAreAllocas)
10442     return 0;
10443   
10444   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10445   // that is variable.
10446   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10447   
10448   bool HasAnyPHIs = false;
10449   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10450     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10451     Value *FirstOp = FirstInst->getOperand(i);
10452     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10453                                      FirstOp->getName()+".pn");
10454     InsertNewInstBefore(NewPN, PN);
10455     
10456     NewPN->reserveOperandSpace(e);
10457     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10458     OperandPhis[i] = NewPN;
10459     FixedOperands[i] = NewPN;
10460     HasAnyPHIs = true;
10461   }
10462
10463   
10464   // Add all operands to the new PHIs.
10465   if (HasAnyPHIs) {
10466     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10467       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10468       BasicBlock *InBB = PN.getIncomingBlock(i);
10469       
10470       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10471         if (PHINode *OpPhi = OperandPhis[op])
10472           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10473     }
10474   }
10475   
10476   Value *Base = FixedOperands[0];
10477   GetElementPtrInst *GEP =
10478     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10479                               FixedOperands.end());
10480   if (cast<GEPOperator>(FirstInst)->isInBounds())
10481     cast<GEPOperator>(GEP)->setIsInBounds(true);
10482   return GEP;
10483 }
10484
10485
10486 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10487 /// sink the load out of the block that defines it.  This means that it must be
10488 /// obvious the value of the load is not changed from the point of the load to
10489 /// the end of the block it is in.
10490 ///
10491 /// Finally, it is safe, but not profitable, to sink a load targetting a
10492 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10493 /// to a register.
10494 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10495   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10496   
10497   for (++BBI; BBI != E; ++BBI)
10498     if (BBI->mayWriteToMemory())
10499       return false;
10500   
10501   // Check for non-address taken alloca.  If not address-taken already, it isn't
10502   // profitable to do this xform.
10503   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10504     bool isAddressTaken = false;
10505     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10506          UI != E; ++UI) {
10507       if (isa<LoadInst>(UI)) continue;
10508       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10509         // If storing TO the alloca, then the address isn't taken.
10510         if (SI->getOperand(1) == AI) continue;
10511       }
10512       isAddressTaken = true;
10513       break;
10514     }
10515     
10516     if (!isAddressTaken && AI->isStaticAlloca())
10517       return false;
10518   }
10519   
10520   // If this load is a load from a GEP with a constant offset from an alloca,
10521   // then we don't want to sink it.  In its present form, it will be
10522   // load [constant stack offset].  Sinking it will cause us to have to
10523   // materialize the stack addresses in each predecessor in a register only to
10524   // do a shared load from register in the successor.
10525   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10526     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10527       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10528         return false;
10529   
10530   return true;
10531 }
10532
10533
10534 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10535 // operator and they all are only used by the PHI, PHI together their
10536 // inputs, and do the operation once, to the result of the PHI.
10537 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10538   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10539
10540   // Scan the instruction, looking for input operations that can be folded away.
10541   // If all input operands to the phi are the same instruction (e.g. a cast from
10542   // the same type or "+42") we can pull the operation through the PHI, reducing
10543   // code size and simplifying code.
10544   Constant *ConstantOp = 0;
10545   const Type *CastSrcTy = 0;
10546   bool isVolatile = false;
10547   if (isa<CastInst>(FirstInst)) {
10548     CastSrcTy = FirstInst->getOperand(0)->getType();
10549   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10550     // Can fold binop, compare or shift here if the RHS is a constant, 
10551     // otherwise call FoldPHIArgBinOpIntoPHI.
10552     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10553     if (ConstantOp == 0)
10554       return FoldPHIArgBinOpIntoPHI(PN);
10555   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10556     isVolatile = LI->isVolatile();
10557     // We can't sink the load if the loaded value could be modified between the
10558     // load and the PHI.
10559     if (LI->getParent() != PN.getIncomingBlock(0) ||
10560         !isSafeAndProfitableToSinkLoad(LI))
10561       return 0;
10562     
10563     // If the PHI is of volatile loads and the load block has multiple
10564     // successors, sinking it would remove a load of the volatile value from
10565     // the path through the other successor.
10566     if (isVolatile &&
10567         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10568       return 0;
10569     
10570   } else if (isa<GetElementPtrInst>(FirstInst)) {
10571     return FoldPHIArgGEPIntoPHI(PN);
10572   } else {
10573     return 0;  // Cannot fold this operation.
10574   }
10575
10576   // Check to see if all arguments are the same operation.
10577   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10578     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10579     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10580     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10581       return 0;
10582     if (CastSrcTy) {
10583       if (I->getOperand(0)->getType() != CastSrcTy)
10584         return 0;  // Cast operation must match.
10585     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10586       // We can't sink the load if the loaded value could be modified between 
10587       // the load and the PHI.
10588       if (LI->isVolatile() != isVolatile ||
10589           LI->getParent() != PN.getIncomingBlock(i) ||
10590           !isSafeAndProfitableToSinkLoad(LI))
10591         return 0;
10592       
10593       // If the PHI is of volatile loads and the load block has multiple
10594       // successors, sinking it would remove a load of the volatile value from
10595       // the path through the other successor.
10596       if (isVolatile &&
10597           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10598         return 0;
10599       
10600     } else if (I->getOperand(1) != ConstantOp) {
10601       return 0;
10602     }
10603   }
10604
10605   // Okay, they are all the same operation.  Create a new PHI node of the
10606   // correct type, and PHI together all of the LHS's of the instructions.
10607   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10608                                    PN.getName()+".in");
10609   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10610
10611   Value *InVal = FirstInst->getOperand(0);
10612   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10613
10614   // Add all operands to the new PHI.
10615   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10616     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10617     if (NewInVal != InVal)
10618       InVal = 0;
10619     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10620   }
10621
10622   Value *PhiVal;
10623   if (InVal) {
10624     // The new PHI unions all of the same values together.  This is really
10625     // common, so we handle it intelligently here for compile-time speed.
10626     PhiVal = InVal;
10627     delete NewPN;
10628   } else {
10629     InsertNewInstBefore(NewPN, PN);
10630     PhiVal = NewPN;
10631   }
10632
10633   // Insert and return the new operation.
10634   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10635     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10636   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10637     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10638   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10639     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10640                            PhiVal, ConstantOp);
10641   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10642   
10643   // If this was a volatile load that we are merging, make sure to loop through
10644   // and mark all the input loads as non-volatile.  If we don't do this, we will
10645   // insert a new volatile load and the old ones will not be deletable.
10646   if (isVolatile)
10647     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10648       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10649   
10650   return new LoadInst(PhiVal, "", isVolatile);
10651 }
10652
10653 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10654 /// that is dead.
10655 static bool DeadPHICycle(PHINode *PN,
10656                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10657   if (PN->use_empty()) return true;
10658   if (!PN->hasOneUse()) return false;
10659
10660   // Remember this node, and if we find the cycle, return.
10661   if (!PotentiallyDeadPHIs.insert(PN))
10662     return true;
10663   
10664   // Don't scan crazily complex things.
10665   if (PotentiallyDeadPHIs.size() == 16)
10666     return false;
10667
10668   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10669     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10670
10671   return false;
10672 }
10673
10674 /// PHIsEqualValue - Return true if this phi node is always equal to
10675 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10676 ///   z = some value; x = phi (y, z); y = phi (x, z)
10677 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10678                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10679   // See if we already saw this PHI node.
10680   if (!ValueEqualPHIs.insert(PN))
10681     return true;
10682   
10683   // Don't scan crazily complex things.
10684   if (ValueEqualPHIs.size() == 16)
10685     return false;
10686  
10687   // Scan the operands to see if they are either phi nodes or are equal to
10688   // the value.
10689   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10690     Value *Op = PN->getIncomingValue(i);
10691     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10692       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10693         return false;
10694     } else if (Op != NonPhiInVal)
10695       return false;
10696   }
10697   
10698   return true;
10699 }
10700
10701
10702 // PHINode simplification
10703 //
10704 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10705   // If LCSSA is around, don't mess with Phi nodes
10706   if (MustPreserveLCSSA) return 0;
10707   
10708   if (Value *V = PN.hasConstantValue())
10709     return ReplaceInstUsesWith(PN, V);
10710
10711   // If all PHI operands are the same operation, pull them through the PHI,
10712   // reducing code size.
10713   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10714       isa<Instruction>(PN.getIncomingValue(1)) &&
10715       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10716       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10717       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10718       // than themselves more than once.
10719       PN.getIncomingValue(0)->hasOneUse())
10720     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10721       return Result;
10722
10723   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10724   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10725   // PHI)... break the cycle.
10726   if (PN.hasOneUse()) {
10727     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10728     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10729       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10730       PotentiallyDeadPHIs.insert(&PN);
10731       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10732         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10733     }
10734    
10735     // If this phi has a single use, and if that use just computes a value for
10736     // the next iteration of a loop, delete the phi.  This occurs with unused
10737     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10738     // common case here is good because the only other things that catch this
10739     // are induction variable analysis (sometimes) and ADCE, which is only run
10740     // late.
10741     if (PHIUser->hasOneUse() &&
10742         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10743         PHIUser->use_back() == &PN) {
10744       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10745     }
10746   }
10747
10748   // We sometimes end up with phi cycles that non-obviously end up being the
10749   // same value, for example:
10750   //   z = some value; x = phi (y, z); y = phi (x, z)
10751   // where the phi nodes don't necessarily need to be in the same block.  Do a
10752   // quick check to see if the PHI node only contains a single non-phi value, if
10753   // so, scan to see if the phi cycle is actually equal to that value.
10754   {
10755     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10756     // Scan for the first non-phi operand.
10757     while (InValNo != NumOperandVals && 
10758            isa<PHINode>(PN.getIncomingValue(InValNo)))
10759       ++InValNo;
10760
10761     if (InValNo != NumOperandVals) {
10762       Value *NonPhiInVal = PN.getOperand(InValNo);
10763       
10764       // Scan the rest of the operands to see if there are any conflicts, if so
10765       // there is no need to recursively scan other phis.
10766       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10767         Value *OpVal = PN.getIncomingValue(InValNo);
10768         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10769           break;
10770       }
10771       
10772       // If we scanned over all operands, then we have one unique value plus
10773       // phi values.  Scan PHI nodes to see if they all merge in each other or
10774       // the value.
10775       if (InValNo == NumOperandVals) {
10776         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10777         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10778           return ReplaceInstUsesWith(PN, NonPhiInVal);
10779       }
10780     }
10781   }
10782   return 0;
10783 }
10784
10785 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10786   Value *PtrOp = GEP.getOperand(0);
10787   // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
10788   if (GEP.getNumOperands() == 1)
10789     return ReplaceInstUsesWith(GEP, PtrOp);
10790
10791   if (isa<UndefValue>(GEP.getOperand(0)))
10792     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10793
10794   bool HasZeroPointerIndex = false;
10795   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10796     HasZeroPointerIndex = C->isNullValue();
10797
10798   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10799     return ReplaceInstUsesWith(GEP, PtrOp);
10800
10801   // Eliminate unneeded casts for indices.
10802   if (TD) {
10803     bool MadeChange = false;
10804     unsigned PtrSize = TD->getPointerSizeInBits();
10805     
10806     gep_type_iterator GTI = gep_type_begin(GEP);
10807     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10808          I != E; ++I, ++GTI) {
10809       if (!isa<SequentialType>(*GTI)) continue;
10810       
10811       // If we are using a wider index than needed for this platform, shrink it
10812       // to what we need.  If narrower, sign-extend it to what we need.  This
10813       // explicit cast can make subsequent optimizations more obvious.
10814       unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
10815       if (OpBits == PtrSize)
10816         continue;
10817       
10818       *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
10819       MadeChange = true;
10820     }
10821     if (MadeChange) return &GEP;
10822   }
10823
10824   // Combine Indices - If the source pointer to this getelementptr instruction
10825   // is a getelementptr instruction, combine the indices of the two
10826   // getelementptr instructions into a single instruction.
10827   //
10828   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
10829     // Note that if our source is a gep chain itself that we wait for that
10830     // chain to be resolved before we perform this transformation.  This
10831     // avoids us creating a TON of code in some cases.
10832     //
10833     if (GetElementPtrInst *SrcGEP =
10834           dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10835       if (SrcGEP->getNumOperands() == 2)
10836         return 0;   // Wait until our source is folded to completion.
10837
10838     SmallVector<Value*, 8> Indices;
10839
10840     // Find out whether the last index in the source GEP is a sequential idx.
10841     bool EndsWithSequential = false;
10842     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10843          I != E; ++I)
10844       EndsWithSequential = !isa<StructType>(*I);
10845
10846     // Can we combine the two pointer arithmetics offsets?
10847     if (EndsWithSequential) {
10848       // Replace: gep (gep %P, long B), long A, ...
10849       // With:    T = long A+B; gep %P, T, ...
10850       //
10851       Value *Sum;
10852       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10853       Value *GO1 = GEP.getOperand(1);
10854       if (SO1 == Constant::getNullValue(SO1->getType())) {
10855         Sum = GO1;
10856       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10857         Sum = SO1;
10858       } else {
10859         // If they aren't the same type, then the input hasn't been processed
10860         // by the loop above yet (which canonicalizes sequential index types to
10861         // intptr_t).  Just avoid transforming this until the input has been
10862         // normalized.
10863         if (SO1->getType() != GO1->getType())
10864           return 0;
10865         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10866       }
10867
10868       // Update the GEP in place if possible.
10869       if (Src->getNumOperands() == 2) {
10870         GEP.setOperand(0, Src->getOperand(0));
10871         GEP.setOperand(1, Sum);
10872         return &GEP;
10873       }
10874       Indices.append(Src->op_begin()+1, Src->op_end()-1);
10875       Indices.push_back(Sum);
10876       Indices.append(GEP.op_begin()+2, GEP.op_end());
10877     } else if (isa<Constant>(*GEP.idx_begin()) &&
10878                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10879                Src->getNumOperands() != 1) {
10880       // Otherwise we can do the fold if the first index of the GEP is a zero
10881       Indices.append(Src->op_begin()+1, Src->op_end());
10882       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
10883     }
10884
10885     if (!Indices.empty()) {
10886       GetElementPtrInst *NewGEP =
10887         GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
10888                                   Indices.end(), GEP.getName());
10889       if (cast<GEPOperator>(&GEP)->isInBounds() && Src->isInBounds())
10890         cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10891       return NewGEP;
10892     }
10893   }
10894   
10895   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10896   if (Value *X = getBitCastOperand(PtrOp)) {
10897     assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
10898
10899     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10900     // into     : GEP [10 x i8]* X, i32 0, ...
10901     //
10902     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10903     //           into     : GEP i8* X, ...
10904     // 
10905     // This occurs when the program declares an array extern like "int X[];"
10906     if (HasZeroPointerIndex) {
10907       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10908       const PointerType *XTy = cast<PointerType>(X->getType());
10909       if (const ArrayType *CATy =
10910           dyn_cast<ArrayType>(CPTy->getElementType())) {
10911         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10912         if (CATy->getElementType() == XTy->getElementType()) {
10913           // -> GEP i8* X, ...
10914           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
10915           GetElementPtrInst *NewGEP =
10916             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10917                                       GEP.getName());
10918           if (cast<GEPOperator>(&GEP)->isInBounds())
10919             cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10920           return NewGEP;
10921         }
10922         
10923         if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
10924           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
10925           if (CATy->getElementType() == XATy->getElementType()) {
10926             // -> GEP [10 x i8]* X, i32 0, ...
10927             // At this point, we know that the cast source type is a pointer
10928             // to an array of the same type as the destination pointer
10929             // array.  Because the array type is never stepped over (there
10930             // is a leading zero) we can fold the cast into this GEP.
10931             GEP.setOperand(0, X);
10932             return &GEP;
10933           }
10934         }
10935       }
10936     } else if (GEP.getNumOperands() == 2) {
10937       // Transform things like:
10938       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10939       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10940       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10941       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10942       if (TD && isa<ArrayType>(SrcElTy) &&
10943           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10944           TD->getTypeAllocSize(ResElTy)) {
10945         Value *Idx[2];
10946         Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
10947         Idx[1] = GEP.getOperand(1);
10948         Value *NewGEP =
10949           Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
10950         if (cast<GEPOperator>(&GEP)->isInBounds())
10951           cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10952         // V and GEP are both pointer types --> BitCast
10953         return new BitCastInst(NewGEP, GEP.getType());
10954       }
10955       
10956       // Transform things like:
10957       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10958       //   (where tmp = 8*tmp2) into:
10959       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10960       
10961       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
10962         uint64_t ArrayEltSize =
10963             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
10964         
10965         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
10966         // allow either a mul, shift, or constant here.
10967         Value *NewIdx = 0;
10968         ConstantInt *Scale = 0;
10969         if (ArrayEltSize == 1) {
10970           NewIdx = GEP.getOperand(1);
10971           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
10972         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10973           NewIdx = ConstantInt::get(CI->getType(), 1);
10974           Scale = CI;
10975         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10976           if (Inst->getOpcode() == Instruction::Shl &&
10977               isa<ConstantInt>(Inst->getOperand(1))) {
10978             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10979             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10980             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
10981                                      1ULL << ShAmtVal);
10982             NewIdx = Inst->getOperand(0);
10983           } else if (Inst->getOpcode() == Instruction::Mul &&
10984                      isa<ConstantInt>(Inst->getOperand(1))) {
10985             Scale = cast<ConstantInt>(Inst->getOperand(1));
10986             NewIdx = Inst->getOperand(0);
10987           }
10988         }
10989         
10990         // If the index will be to exactly the right offset with the scale taken
10991         // out, perform the transformation. Note, we don't know whether Scale is
10992         // signed or not. We'll use unsigned version of division/modulo
10993         // operation after making sure Scale doesn't have the sign bit set.
10994         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
10995             Scale->getZExtValue() % ArrayEltSize == 0) {
10996           Scale = ConstantInt::get(Scale->getType(),
10997                                    Scale->getZExtValue() / ArrayEltSize);
10998           if (Scale->getZExtValue() != 1) {
10999             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11000                                                        false /*ZExt*/);
11001             NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11002           }
11003
11004           // Insert the new GEP instruction.
11005           Value *Idx[2];
11006           Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11007           Idx[1] = NewIdx;
11008           Value *NewGEP = Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11009           if (cast<GEPOperator>(&GEP)->isInBounds())
11010             cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11011           // The NewGEP must be pointer typed, so must the old one -> BitCast
11012           return new BitCastInst(NewGEP, GEP.getType());
11013         }
11014       }
11015     }
11016   }
11017   
11018   /// See if we can simplify:
11019   ///   X = bitcast A* to B*
11020   ///   Y = gep X, <...constant indices...>
11021   /// into a gep of the original struct.  This is important for SROA and alias
11022   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11023   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11024     if (TD &&
11025         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11026       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11027       // a constant back from EmitGEPOffset.
11028       ConstantInt *OffsetV =
11029                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11030       int64_t Offset = OffsetV->getSExtValue();
11031       
11032       // If this GEP instruction doesn't move the pointer, just replace the GEP
11033       // with a bitcast of the real input to the dest type.
11034       if (Offset == 0) {
11035         // If the bitcast is of an allocation, and the allocation will be
11036         // converted to match the type of the cast, don't touch this.
11037         if (isa<AllocationInst>(BCI->getOperand(0))) {
11038           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11039           if (Instruction *I = visitBitCast(*BCI)) {
11040             if (I != BCI) {
11041               I->takeName(BCI);
11042               BCI->getParent()->getInstList().insert(BCI, I);
11043               ReplaceInstUsesWith(*BCI, I);
11044             }
11045             return &GEP;
11046           }
11047         }
11048         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11049       }
11050       
11051       // Otherwise, if the offset is non-zero, we need to find out if there is a
11052       // field at Offset in 'A's type.  If so, we can pull the cast through the
11053       // GEP.
11054       SmallVector<Value*, 8> NewIndices;
11055       const Type *InTy =
11056         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11057       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11058         Value *NGEP = Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11059                                          NewIndices.end());
11060         if (cast<GEPOperator>(&GEP)->isInBounds())
11061           cast<GEPOperator>(NGEP)->setIsInBounds(true);
11062         
11063         if (NGEP->getType() == GEP.getType())
11064           return ReplaceInstUsesWith(GEP, NGEP);
11065         NGEP->takeName(&GEP);
11066         return new BitCastInst(NGEP, GEP.getType());
11067       }
11068     }
11069   }    
11070     
11071   return 0;
11072 }
11073
11074 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11075   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11076   if (AI.isArrayAllocation()) {  // Check C != 1
11077     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11078       const Type *NewTy = 
11079         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11080       AllocationInst *New = 0;
11081
11082       // Create and insert the replacement instruction...
11083       if (isa<MallocInst>(AI))
11084         New = Builder->CreateMalloc(NewTy, 0, AI.getName());
11085       else {
11086         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11087         New = Builder->CreateAlloca(NewTy, 0, AI.getName());
11088       }
11089       New->setAlignment(AI.getAlignment());
11090
11091       // Scan to the end of the allocation instructions, to skip over a block of
11092       // allocas if possible...also skip interleaved debug info
11093       //
11094       BasicBlock::iterator It = New;
11095       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11096
11097       // Now that I is pointing to the first non-allocation-inst in the block,
11098       // insert our getelementptr instruction...
11099       //
11100       Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11101       Value *Idx[2];
11102       Idx[0] = NullIdx;
11103       Idx[1] = NullIdx;
11104       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11105                                            New->getName()+".sub", It);
11106       cast<GEPOperator>(V)->setIsInBounds(true);
11107
11108       // Now make everything use the getelementptr instead of the original
11109       // allocation.
11110       return ReplaceInstUsesWith(AI, V);
11111     } else if (isa<UndefValue>(AI.getArraySize())) {
11112       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11113     }
11114   }
11115
11116   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11117     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11118     // Note that we only do this for alloca's, because malloc should allocate
11119     // and return a unique pointer, even for a zero byte allocation.
11120     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11121       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11122
11123     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11124     if (AI.getAlignment() == 0)
11125       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11126   }
11127
11128   return 0;
11129 }
11130
11131 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11132   Value *Op = FI.getOperand(0);
11133
11134   // free undef -> unreachable.
11135   if (isa<UndefValue>(Op)) {
11136     // Insert a new store to null because we cannot modify the CFG here.
11137     new StoreInst(ConstantInt::getTrue(*Context),
11138            UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
11139     return EraseInstFromFunction(FI);
11140   }
11141   
11142   // If we have 'free null' delete the instruction.  This can happen in stl code
11143   // when lots of inlining happens.
11144   if (isa<ConstantPointerNull>(Op))
11145     return EraseInstFromFunction(FI);
11146   
11147   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11148   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11149     FI.setOperand(0, CI->getOperand(0));
11150     return &FI;
11151   }
11152   
11153   // Change free (gep X, 0,0,0,0) into free(X)
11154   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11155     if (GEPI->hasAllZeroIndices()) {
11156       Worklist.Add(GEPI);
11157       FI.setOperand(0, GEPI->getOperand(0));
11158       return &FI;
11159     }
11160   }
11161   
11162   // Change free(malloc) into nothing, if the malloc has a single use.
11163   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11164     if (MI->hasOneUse()) {
11165       EraseInstFromFunction(FI);
11166       return EraseInstFromFunction(*MI);
11167     }
11168
11169   return 0;
11170 }
11171
11172
11173 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11174 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11175                                         const TargetData *TD) {
11176   User *CI = cast<User>(LI.getOperand(0));
11177   Value *CastOp = CI->getOperand(0);
11178   LLVMContext *Context = IC.getContext();
11179
11180   if (TD) {
11181     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11182       // Instead of loading constant c string, use corresponding integer value
11183       // directly if string length is small enough.
11184       std::string Str;
11185       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11186         unsigned len = Str.length();
11187         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11188         unsigned numBits = Ty->getPrimitiveSizeInBits();
11189         // Replace LI with immediate integer store.
11190         if ((numBits >> 3) == len + 1) {
11191           APInt StrVal(numBits, 0);
11192           APInt SingleChar(numBits, 0);
11193           if (TD->isLittleEndian()) {
11194             for (signed i = len-1; i >= 0; i--) {
11195               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11196               StrVal = (StrVal << 8) | SingleChar;
11197             }
11198           } else {
11199             for (unsigned i = 0; i < len; i++) {
11200               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11201               StrVal = (StrVal << 8) | SingleChar;
11202             }
11203             // Append NULL at the end.
11204             SingleChar = 0;
11205             StrVal = (StrVal << 8) | SingleChar;
11206           }
11207           Value *NL = ConstantInt::get(*Context, StrVal);
11208           return IC.ReplaceInstUsesWith(LI, NL);
11209         }
11210       }
11211     }
11212   }
11213
11214   const PointerType *DestTy = cast<PointerType>(CI->getType());
11215   const Type *DestPTy = DestTy->getElementType();
11216   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11217
11218     // If the address spaces don't match, don't eliminate the cast.
11219     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11220       return 0;
11221
11222     const Type *SrcPTy = SrcTy->getElementType();
11223
11224     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11225          isa<VectorType>(DestPTy)) {
11226       // If the source is an array, the code below will not succeed.  Check to
11227       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11228       // constants.
11229       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11230         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11231           if (ASrcTy->getNumElements() != 0) {
11232             Value *Idxs[2];
11233             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
11234             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11235             SrcTy = cast<PointerType>(CastOp->getType());
11236             SrcPTy = SrcTy->getElementType();
11237           }
11238
11239       if (IC.getTargetData() &&
11240           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11241             isa<VectorType>(SrcPTy)) &&
11242           // Do not allow turning this into a load of an integer, which is then
11243           // casted to a pointer, this pessimizes pointer analysis a lot.
11244           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11245           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11246                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11247
11248         // Okay, we are casting from one integer or pointer type to another of
11249         // the same size.  Instead of casting the pointer before the load, cast
11250         // the result of the loaded value.
11251         Value *NewLoad = 
11252           IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
11253         // Now cast the result of the load.
11254         return new BitCastInst(NewLoad, LI.getType());
11255       }
11256     }
11257   }
11258   return 0;
11259 }
11260
11261 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11262   Value *Op = LI.getOperand(0);
11263
11264   // Attempt to improve the alignment.
11265   if (TD) {
11266     unsigned KnownAlign =
11267       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11268     if (KnownAlign >
11269         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11270                                   LI.getAlignment()))
11271       LI.setAlignment(KnownAlign);
11272   }
11273
11274   // load (cast X) --> cast (load X) iff safe.
11275   if (isa<CastInst>(Op))
11276     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11277       return Res;
11278
11279   // None of the following transforms are legal for volatile loads.
11280   if (LI.isVolatile()) return 0;
11281   
11282   // Do really simple store-to-load forwarding and load CSE, to catch cases
11283   // where there are several consequtive memory accesses to the same location,
11284   // separated by a few arithmetic operations.
11285   BasicBlock::iterator BBI = &LI;
11286   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11287     return ReplaceInstUsesWith(LI, AvailableVal);
11288
11289   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11290     const Value *GEPI0 = GEPI->getOperand(0);
11291     // TODO: Consider a target hook for valid address spaces for this xform.
11292     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
11293       // Insert a new store to null instruction before the load to indicate
11294       // that this code is not reachable.  We do this instead of inserting
11295       // an unreachable instruction directly because we cannot modify the
11296       // CFG.
11297       new StoreInst(UndefValue::get(LI.getType()),
11298                     Constant::getNullValue(Op->getType()), &LI);
11299       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11300     }
11301   } 
11302
11303   if (Constant *C = dyn_cast<Constant>(Op)) {
11304     // load null/undef -> undef
11305     // TODO: Consider a target hook for valid address spaces for this xform.
11306     if (isa<UndefValue>(C) ||
11307         (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
11308       // Insert a new store to null instruction before the load to indicate that
11309       // this code is not reachable.  We do this instead of inserting an
11310       // unreachable instruction directly because we cannot modify the CFG.
11311       new StoreInst(UndefValue::get(LI.getType()),
11312                     Constant::getNullValue(Op->getType()), &LI);
11313       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11314     }
11315
11316     // Instcombine load (constant global) into the value loaded.
11317     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11318       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11319         return ReplaceInstUsesWith(LI, GV->getInitializer());
11320
11321     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11322     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11323       if (CE->getOpcode() == Instruction::GetElementPtr) {
11324         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11325           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11326             if (Constant *V = 
11327                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11328                                                       *Context))
11329               return ReplaceInstUsesWith(LI, V);
11330         if (CE->getOperand(0)->isNullValue()) {
11331           // Insert a new store to null instruction before the load to indicate
11332           // that this code is not reachable.  We do this instead of inserting
11333           // an unreachable instruction directly because we cannot modify the
11334           // CFG.
11335           new StoreInst(UndefValue::get(LI.getType()),
11336                         Constant::getNullValue(Op->getType()), &LI);
11337           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11338         }
11339
11340       } else if (CE->isCast()) {
11341         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11342           return Res;
11343       }
11344     }
11345   }
11346     
11347   // If this load comes from anywhere in a constant global, and if the global
11348   // is all undef or zero, we know what it loads.
11349   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11350     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11351       if (GV->getInitializer()->isNullValue())
11352         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11353       else if (isa<UndefValue>(GV->getInitializer()))
11354         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11355     }
11356   }
11357
11358   if (Op->hasOneUse()) {
11359     // Change select and PHI nodes to select values instead of addresses: this
11360     // helps alias analysis out a lot, allows many others simplifications, and
11361     // exposes redundancy in the code.
11362     //
11363     // Note that we cannot do the transformation unless we know that the
11364     // introduced loads cannot trap!  Something like this is valid as long as
11365     // the condition is always false: load (select bool %C, int* null, int* %G),
11366     // but it would not be valid if we transformed it to load from null
11367     // unconditionally.
11368     //
11369     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11370       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11371       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11372           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11373         Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11374                                         SI->getOperand(1)->getName()+".val");
11375         Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11376                                         SI->getOperand(2)->getName()+".val");
11377         return SelectInst::Create(SI->getCondition(), V1, V2);
11378       }
11379
11380       // load (select (cond, null, P)) -> load P
11381       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11382         if (C->isNullValue()) {
11383           LI.setOperand(0, SI->getOperand(2));
11384           return &LI;
11385         }
11386
11387       // load (select (cond, P, null)) -> load P
11388       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11389         if (C->isNullValue()) {
11390           LI.setOperand(0, SI->getOperand(1));
11391           return &LI;
11392         }
11393     }
11394   }
11395   return 0;
11396 }
11397
11398 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11399 /// when possible.  This makes it generally easy to do alias analysis and/or
11400 /// SROA/mem2reg of the memory object.
11401 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11402   User *CI = cast<User>(SI.getOperand(1));
11403   Value *CastOp = CI->getOperand(0);
11404
11405   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11406   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11407   if (SrcTy == 0) return 0;
11408   
11409   const Type *SrcPTy = SrcTy->getElementType();
11410
11411   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11412     return 0;
11413   
11414   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11415   /// to its first element.  This allows us to handle things like:
11416   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11417   /// on 32-bit hosts.
11418   SmallVector<Value*, 4> NewGEPIndices;
11419   
11420   // If the source is an array, the code below will not succeed.  Check to
11421   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11422   // constants.
11423   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11424     // Index through pointer.
11425     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11426     NewGEPIndices.push_back(Zero);
11427     
11428     while (1) {
11429       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11430         if (!STy->getNumElements()) /* Struct can be empty {} */
11431           break;
11432         NewGEPIndices.push_back(Zero);
11433         SrcPTy = STy->getElementType(0);
11434       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11435         NewGEPIndices.push_back(Zero);
11436         SrcPTy = ATy->getElementType();
11437       } else {
11438         break;
11439       }
11440     }
11441     
11442     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11443   }
11444
11445   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11446     return 0;
11447   
11448   // If the pointers point into different address spaces or if they point to
11449   // values with different sizes, we can't do the transformation.
11450   if (!IC.getTargetData() ||
11451       SrcTy->getAddressSpace() != 
11452         cast<PointerType>(CI->getType())->getAddressSpace() ||
11453       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11454       IC.getTargetData()->getTypeSizeInBits(DestPTy))
11455     return 0;
11456
11457   // Okay, we are casting from one integer or pointer type to another of
11458   // the same size.  Instead of casting the pointer before 
11459   // the store, cast the value to be stored.
11460   Value *NewCast;
11461   Value *SIOp0 = SI.getOperand(0);
11462   Instruction::CastOps opcode = Instruction::BitCast;
11463   const Type* CastSrcTy = SIOp0->getType();
11464   const Type* CastDstTy = SrcPTy;
11465   if (isa<PointerType>(CastDstTy)) {
11466     if (CastSrcTy->isInteger())
11467       opcode = Instruction::IntToPtr;
11468   } else if (isa<IntegerType>(CastDstTy)) {
11469     if (isa<PointerType>(SIOp0->getType()))
11470       opcode = Instruction::PtrToInt;
11471   }
11472   
11473   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11474   // emit a GEP to index into its first field.
11475   if (!NewGEPIndices.empty()) {
11476     CastOp = IC.Builder->CreateGEP(CastOp, NewGEPIndices.begin(),
11477                                    NewGEPIndices.end());
11478     cast<GEPOperator>(CastOp)->setIsInBounds(true);
11479   }
11480   
11481   NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11482                                    SIOp0->getName()+".c");
11483   return new StoreInst(NewCast, CastOp);
11484 }
11485
11486 /// equivalentAddressValues - Test if A and B will obviously have the same
11487 /// value. This includes recognizing that %t0 and %t1 will have the same
11488 /// value in code like this:
11489 ///   %t0 = getelementptr \@a, 0, 3
11490 ///   store i32 0, i32* %t0
11491 ///   %t1 = getelementptr \@a, 0, 3
11492 ///   %t2 = load i32* %t1
11493 ///
11494 static bool equivalentAddressValues(Value *A, Value *B) {
11495   // Test if the values are trivially equivalent.
11496   if (A == B) return true;
11497   
11498   // Test if the values come form identical arithmetic instructions.
11499   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11500   // its only used to compare two uses within the same basic block, which
11501   // means that they'll always either have the same value or one of them
11502   // will have an undefined value.
11503   if (isa<BinaryOperator>(A) ||
11504       isa<CastInst>(A) ||
11505       isa<PHINode>(A) ||
11506       isa<GetElementPtrInst>(A))
11507     if (Instruction *BI = dyn_cast<Instruction>(B))
11508       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
11509         return true;
11510   
11511   // Otherwise they may not be equivalent.
11512   return false;
11513 }
11514
11515 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11516 // return the llvm.dbg.declare.
11517 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11518   if (!V->hasNUses(2))
11519     return 0;
11520   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11521        UI != E; ++UI) {
11522     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11523       return DI;
11524     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11525       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11526         return DI;
11527       }
11528   }
11529   return 0;
11530 }
11531
11532 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11533   Value *Val = SI.getOperand(0);
11534   Value *Ptr = SI.getOperand(1);
11535
11536   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11537     EraseInstFromFunction(SI);
11538     ++NumCombined;
11539     return 0;
11540   }
11541   
11542   // If the RHS is an alloca with a single use, zapify the store, making the
11543   // alloca dead.
11544   // If the RHS is an alloca with a two uses, the other one being a 
11545   // llvm.dbg.declare, zapify the store and the declare, making the
11546   // alloca dead.  We must do this to prevent declare's from affecting
11547   // codegen.
11548   if (!SI.isVolatile()) {
11549     if (Ptr->hasOneUse()) {
11550       if (isa<AllocaInst>(Ptr)) {
11551         EraseInstFromFunction(SI);
11552         ++NumCombined;
11553         return 0;
11554       }
11555       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11556         if (isa<AllocaInst>(GEP->getOperand(0))) {
11557           if (GEP->getOperand(0)->hasOneUse()) {
11558             EraseInstFromFunction(SI);
11559             ++NumCombined;
11560             return 0;
11561           }
11562           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11563             EraseInstFromFunction(*DI);
11564             EraseInstFromFunction(SI);
11565             ++NumCombined;
11566             return 0;
11567           }
11568         }
11569       }
11570     }
11571     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11572       EraseInstFromFunction(*DI);
11573       EraseInstFromFunction(SI);
11574       ++NumCombined;
11575       return 0;
11576     }
11577   }
11578
11579   // Attempt to improve the alignment.
11580   if (TD) {
11581     unsigned KnownAlign =
11582       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11583     if (KnownAlign >
11584         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11585                                   SI.getAlignment()))
11586       SI.setAlignment(KnownAlign);
11587   }
11588
11589   // Do really simple DSE, to catch cases where there are several consecutive
11590   // stores to the same location, separated by a few arithmetic operations. This
11591   // situation often occurs with bitfield accesses.
11592   BasicBlock::iterator BBI = &SI;
11593   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11594        --ScanInsts) {
11595     --BBI;
11596     // Don't count debug info directives, lest they affect codegen,
11597     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11598     // It is necessary for correctness to skip those that feed into a
11599     // llvm.dbg.declare, as these are not present when debugging is off.
11600     if (isa<DbgInfoIntrinsic>(BBI) ||
11601         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11602       ScanInsts++;
11603       continue;
11604     }    
11605     
11606     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11607       // Prev store isn't volatile, and stores to the same location?
11608       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11609                                                           SI.getOperand(1))) {
11610         ++NumDeadStore;
11611         ++BBI;
11612         EraseInstFromFunction(*PrevSI);
11613         continue;
11614       }
11615       break;
11616     }
11617     
11618     // If this is a load, we have to stop.  However, if the loaded value is from
11619     // the pointer we're loading and is producing the pointer we're storing,
11620     // then *this* store is dead (X = load P; store X -> P).
11621     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11622       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11623           !SI.isVolatile()) {
11624         EraseInstFromFunction(SI);
11625         ++NumCombined;
11626         return 0;
11627       }
11628       // Otherwise, this is a load from some other location.  Stores before it
11629       // may not be dead.
11630       break;
11631     }
11632     
11633     // Don't skip over loads or things that can modify memory.
11634     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11635       break;
11636   }
11637   
11638   
11639   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11640
11641   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11642   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
11643     if (!isa<UndefValue>(Val)) {
11644       SI.setOperand(0, UndefValue::get(Val->getType()));
11645       if (Instruction *U = dyn_cast<Instruction>(Val))
11646         Worklist.Add(U);  // Dropped a use.
11647       ++NumCombined;
11648     }
11649     return 0;  // Do not modify these!
11650   }
11651
11652   // store undef, Ptr -> noop
11653   if (isa<UndefValue>(Val)) {
11654     EraseInstFromFunction(SI);
11655     ++NumCombined;
11656     return 0;
11657   }
11658
11659   // If the pointer destination is a cast, see if we can fold the cast into the
11660   // source instead.
11661   if (isa<CastInst>(Ptr))
11662     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11663       return Res;
11664   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11665     if (CE->isCast())
11666       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11667         return Res;
11668
11669   
11670   // If this store is the last instruction in the basic block (possibly
11671   // excepting debug info instructions and the pointer bitcasts that feed
11672   // into them), and if the block ends with an unconditional branch, try
11673   // to move it to the successor block.
11674   BBI = &SI; 
11675   do {
11676     ++BBI;
11677   } while (isa<DbgInfoIntrinsic>(BBI) ||
11678            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11679   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11680     if (BI->isUnconditional())
11681       if (SimplifyStoreAtEndOfBlock(SI))
11682         return 0;  // xform done!
11683   
11684   return 0;
11685 }
11686
11687 /// SimplifyStoreAtEndOfBlock - Turn things like:
11688 ///   if () { *P = v1; } else { *P = v2 }
11689 /// into a phi node with a store in the successor.
11690 ///
11691 /// Simplify things like:
11692 ///   *P = v1; if () { *P = v2; }
11693 /// into a phi node with a store in the successor.
11694 ///
11695 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11696   BasicBlock *StoreBB = SI.getParent();
11697   
11698   // Check to see if the successor block has exactly two incoming edges.  If
11699   // so, see if the other predecessor contains a store to the same location.
11700   // if so, insert a PHI node (if needed) and move the stores down.
11701   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11702   
11703   // Determine whether Dest has exactly two predecessors and, if so, compute
11704   // the other predecessor.
11705   pred_iterator PI = pred_begin(DestBB);
11706   BasicBlock *OtherBB = 0;
11707   if (*PI != StoreBB)
11708     OtherBB = *PI;
11709   ++PI;
11710   if (PI == pred_end(DestBB))
11711     return false;
11712   
11713   if (*PI != StoreBB) {
11714     if (OtherBB)
11715       return false;
11716     OtherBB = *PI;
11717   }
11718   if (++PI != pred_end(DestBB))
11719     return false;
11720
11721   // Bail out if all the relevant blocks aren't distinct (this can happen,
11722   // for example, if SI is in an infinite loop)
11723   if (StoreBB == DestBB || OtherBB == DestBB)
11724     return false;
11725
11726   // Verify that the other block ends in a branch and is not otherwise empty.
11727   BasicBlock::iterator BBI = OtherBB->getTerminator();
11728   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11729   if (!OtherBr || BBI == OtherBB->begin())
11730     return false;
11731   
11732   // If the other block ends in an unconditional branch, check for the 'if then
11733   // else' case.  there is an instruction before the branch.
11734   StoreInst *OtherStore = 0;
11735   if (OtherBr->isUnconditional()) {
11736     --BBI;
11737     // Skip over debugging info.
11738     while (isa<DbgInfoIntrinsic>(BBI) ||
11739            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11740       if (BBI==OtherBB->begin())
11741         return false;
11742       --BBI;
11743     }
11744     // If this isn't a store, or isn't a store to the same location, bail out.
11745     OtherStore = dyn_cast<StoreInst>(BBI);
11746     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11747       return false;
11748   } else {
11749     // Otherwise, the other block ended with a conditional branch. If one of the
11750     // destinations is StoreBB, then we have the if/then case.
11751     if (OtherBr->getSuccessor(0) != StoreBB && 
11752         OtherBr->getSuccessor(1) != StoreBB)
11753       return false;
11754     
11755     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11756     // if/then triangle.  See if there is a store to the same ptr as SI that
11757     // lives in OtherBB.
11758     for (;; --BBI) {
11759       // Check to see if we find the matching store.
11760       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11761         if (OtherStore->getOperand(1) != SI.getOperand(1))
11762           return false;
11763         break;
11764       }
11765       // If we find something that may be using or overwriting the stored
11766       // value, or if we run out of instructions, we can't do the xform.
11767       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11768           BBI == OtherBB->begin())
11769         return false;
11770     }
11771     
11772     // In order to eliminate the store in OtherBr, we have to
11773     // make sure nothing reads or overwrites the stored value in
11774     // StoreBB.
11775     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11776       // FIXME: This should really be AA driven.
11777       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11778         return false;
11779     }
11780   }
11781   
11782   // Insert a PHI node now if we need it.
11783   Value *MergedVal = OtherStore->getOperand(0);
11784   if (MergedVal != SI.getOperand(0)) {
11785     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11786     PN->reserveOperandSpace(2);
11787     PN->addIncoming(SI.getOperand(0), SI.getParent());
11788     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11789     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11790   }
11791   
11792   // Advance to a place where it is safe to insert the new store and
11793   // insert it.
11794   BBI = DestBB->getFirstNonPHI();
11795   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11796                                     OtherStore->isVolatile()), *BBI);
11797   
11798   // Nuke the old stores.
11799   EraseInstFromFunction(SI);
11800   EraseInstFromFunction(*OtherStore);
11801   ++NumCombined;
11802   return true;
11803 }
11804
11805
11806 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11807   // Change br (not X), label True, label False to: br X, label False, True
11808   Value *X = 0;
11809   BasicBlock *TrueDest;
11810   BasicBlock *FalseDest;
11811   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11812       !isa<Constant>(X)) {
11813     // Swap Destinations and condition...
11814     BI.setCondition(X);
11815     BI.setSuccessor(0, FalseDest);
11816     BI.setSuccessor(1, TrueDest);
11817     return &BI;
11818   }
11819
11820   // Cannonicalize fcmp_one -> fcmp_oeq
11821   FCmpInst::Predicate FPred; Value *Y;
11822   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11823                              TrueDest, FalseDest)) &&
11824       BI.getCondition()->hasOneUse())
11825     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11826         FPred == FCmpInst::FCMP_OGE) {
11827       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11828       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11829       
11830       // Swap Destinations and condition.
11831       BI.setSuccessor(0, FalseDest);
11832       BI.setSuccessor(1, TrueDest);
11833       Worklist.Add(Cond);
11834       return &BI;
11835     }
11836
11837   // Cannonicalize icmp_ne -> icmp_eq
11838   ICmpInst::Predicate IPred;
11839   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11840                       TrueDest, FalseDest)) &&
11841       BI.getCondition()->hasOneUse())
11842     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11843         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11844         IPred == ICmpInst::ICMP_SGE) {
11845       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11846       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11847       // Swap Destinations and condition.
11848       BI.setSuccessor(0, FalseDest);
11849       BI.setSuccessor(1, TrueDest);
11850       Worklist.Add(Cond);
11851       return &BI;
11852     }
11853
11854   return 0;
11855 }
11856
11857 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11858   Value *Cond = SI.getCondition();
11859   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11860     if (I->getOpcode() == Instruction::Add)
11861       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11862         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11863         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11864           SI.setOperand(i,
11865                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11866                                                 AddRHS));
11867         SI.setOperand(0, I->getOperand(0));
11868         Worklist.Add(I);
11869         return &SI;
11870       }
11871   }
11872   return 0;
11873 }
11874
11875 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11876   Value *Agg = EV.getAggregateOperand();
11877
11878   if (!EV.hasIndices())
11879     return ReplaceInstUsesWith(EV, Agg);
11880
11881   if (Constant *C = dyn_cast<Constant>(Agg)) {
11882     if (isa<UndefValue>(C))
11883       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11884       
11885     if (isa<ConstantAggregateZero>(C))
11886       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11887
11888     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11889       // Extract the element indexed by the first index out of the constant
11890       Value *V = C->getOperand(*EV.idx_begin());
11891       if (EV.getNumIndices() > 1)
11892         // Extract the remaining indices out of the constant indexed by the
11893         // first index
11894         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11895       else
11896         return ReplaceInstUsesWith(EV, V);
11897     }
11898     return 0; // Can't handle other constants
11899   } 
11900   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11901     // We're extracting from an insertvalue instruction, compare the indices
11902     const unsigned *exti, *exte, *insi, *inse;
11903     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11904          exte = EV.idx_end(), inse = IV->idx_end();
11905          exti != exte && insi != inse;
11906          ++exti, ++insi) {
11907       if (*insi != *exti)
11908         // The insert and extract both reference distinctly different elements.
11909         // This means the extract is not influenced by the insert, and we can
11910         // replace the aggregate operand of the extract with the aggregate
11911         // operand of the insert. i.e., replace
11912         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11913         // %E = extractvalue { i32, { i32 } } %I, 0
11914         // with
11915         // %E = extractvalue { i32, { i32 } } %A, 0
11916         return ExtractValueInst::Create(IV->getAggregateOperand(),
11917                                         EV.idx_begin(), EV.idx_end());
11918     }
11919     if (exti == exte && insi == inse)
11920       // Both iterators are at the end: Index lists are identical. Replace
11921       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11922       // %C = extractvalue { i32, { i32 } } %B, 1, 0
11923       // with "i32 42"
11924       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11925     if (exti == exte) {
11926       // The extract list is a prefix of the insert list. i.e. replace
11927       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11928       // %E = extractvalue { i32, { i32 } } %I, 1
11929       // with
11930       // %X = extractvalue { i32, { i32 } } %A, 1
11931       // %E = insertvalue { i32 } %X, i32 42, 0
11932       // by switching the order of the insert and extract (though the
11933       // insertvalue should be left in, since it may have other uses).
11934       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
11935                                                  EV.idx_begin(), EV.idx_end());
11936       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11937                                      insi, inse);
11938     }
11939     if (insi == inse)
11940       // The insert list is a prefix of the extract list
11941       // We can simply remove the common indices from the extract and make it
11942       // operate on the inserted value instead of the insertvalue result.
11943       // i.e., replace
11944       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11945       // %E = extractvalue { i32, { i32 } } %I, 1, 0
11946       // with
11947       // %E extractvalue { i32 } { i32 42 }, 0
11948       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
11949                                       exti, exte);
11950   }
11951   // Can't simplify extracts from other values. Note that nested extracts are
11952   // already simplified implicitely by the above (extract ( extract (insert) )
11953   // will be translated into extract ( insert ( extract ) ) first and then just
11954   // the value inserted, if appropriate).
11955   return 0;
11956 }
11957
11958 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11959 /// is to leave as a vector operation.
11960 static bool CheapToScalarize(Value *V, bool isConstant) {
11961   if (isa<ConstantAggregateZero>(V)) 
11962     return true;
11963   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11964     if (isConstant) return true;
11965     // If all elts are the same, we can extract.
11966     Constant *Op0 = C->getOperand(0);
11967     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11968       if (C->getOperand(i) != Op0)
11969         return false;
11970     return true;
11971   }
11972   Instruction *I = dyn_cast<Instruction>(V);
11973   if (!I) return false;
11974   
11975   // Insert element gets simplified to the inserted element or is deleted if
11976   // this is constant idx extract element and its a constant idx insertelt.
11977   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11978       isa<ConstantInt>(I->getOperand(2)))
11979     return true;
11980   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11981     return true;
11982   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11983     if (BO->hasOneUse() &&
11984         (CheapToScalarize(BO->getOperand(0), isConstant) ||
11985          CheapToScalarize(BO->getOperand(1), isConstant)))
11986       return true;
11987   if (CmpInst *CI = dyn_cast<CmpInst>(I))
11988     if (CI->hasOneUse() &&
11989         (CheapToScalarize(CI->getOperand(0), isConstant) ||
11990          CheapToScalarize(CI->getOperand(1), isConstant)))
11991       return true;
11992   
11993   return false;
11994 }
11995
11996 /// Read and decode a shufflevector mask.
11997 ///
11998 /// It turns undef elements into values that are larger than the number of
11999 /// elements in the input.
12000 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12001   unsigned NElts = SVI->getType()->getNumElements();
12002   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12003     return std::vector<unsigned>(NElts, 0);
12004   if (isa<UndefValue>(SVI->getOperand(2)))
12005     return std::vector<unsigned>(NElts, 2*NElts);
12006
12007   std::vector<unsigned> Result;
12008   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12009   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12010     if (isa<UndefValue>(*i))
12011       Result.push_back(NElts*2);  // undef -> 8
12012     else
12013       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12014   return Result;
12015 }
12016
12017 /// FindScalarElement - Given a vector and an element number, see if the scalar
12018 /// value is already around as a register, for example if it were inserted then
12019 /// extracted from the vector.
12020 static Value *FindScalarElement(Value *V, unsigned EltNo,
12021                                 LLVMContext *Context) {
12022   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12023   const VectorType *PTy = cast<VectorType>(V->getType());
12024   unsigned Width = PTy->getNumElements();
12025   if (EltNo >= Width)  // Out of range access.
12026     return UndefValue::get(PTy->getElementType());
12027   
12028   if (isa<UndefValue>(V))
12029     return UndefValue::get(PTy->getElementType());
12030   else if (isa<ConstantAggregateZero>(V))
12031     return Constant::getNullValue(PTy->getElementType());
12032   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12033     return CP->getOperand(EltNo);
12034   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12035     // If this is an insert to a variable element, we don't know what it is.
12036     if (!isa<ConstantInt>(III->getOperand(2))) 
12037       return 0;
12038     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12039     
12040     // If this is an insert to the element we are looking for, return the
12041     // inserted value.
12042     if (EltNo == IIElt) 
12043       return III->getOperand(1);
12044     
12045     // Otherwise, the insertelement doesn't modify the value, recurse on its
12046     // vector input.
12047     return FindScalarElement(III->getOperand(0), EltNo, Context);
12048   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12049     unsigned LHSWidth =
12050       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12051     unsigned InEl = getShuffleMask(SVI)[EltNo];
12052     if (InEl < LHSWidth)
12053       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12054     else if (InEl < LHSWidth*2)
12055       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12056     else
12057       return UndefValue::get(PTy->getElementType());
12058   }
12059   
12060   // Otherwise, we don't know.
12061   return 0;
12062 }
12063
12064 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12065   // If vector val is undef, replace extract with scalar undef.
12066   if (isa<UndefValue>(EI.getOperand(0)))
12067     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12068
12069   // If vector val is constant 0, replace extract with scalar 0.
12070   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12071     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12072   
12073   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12074     // If vector val is constant with all elements the same, replace EI with
12075     // that element. When the elements are not identical, we cannot replace yet
12076     // (we do that below, but only when the index is constant).
12077     Constant *op0 = C->getOperand(0);
12078     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12079       if (C->getOperand(i) != op0) {
12080         op0 = 0; 
12081         break;
12082       }
12083     if (op0)
12084       return ReplaceInstUsesWith(EI, op0);
12085   }
12086   
12087   // If extracting a specified index from the vector, see if we can recursively
12088   // find a previously computed scalar that was inserted into the vector.
12089   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12090     unsigned IndexVal = IdxC->getZExtValue();
12091     unsigned VectorWidth = 
12092       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12093       
12094     // If this is extracting an invalid index, turn this into undef, to avoid
12095     // crashing the code below.
12096     if (IndexVal >= VectorWidth)
12097       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12098     
12099     // This instruction only demands the single element from the input vector.
12100     // If the input vector has a single use, simplify it based on this use
12101     // property.
12102     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12103       APInt UndefElts(VectorWidth, 0);
12104       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12105       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12106                                                 DemandedMask, UndefElts)) {
12107         EI.setOperand(0, V);
12108         return &EI;
12109       }
12110     }
12111     
12112     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12113       return ReplaceInstUsesWith(EI, Elt);
12114     
12115     // If the this extractelement is directly using a bitcast from a vector of
12116     // the same number of elements, see if we can find the source element from
12117     // it.  In this case, we will end up needing to bitcast the scalars.
12118     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12119       if (const VectorType *VT = 
12120               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12121         if (VT->getNumElements() == VectorWidth)
12122           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12123                                              IndexVal, Context))
12124             return new BitCastInst(Elt, EI.getType());
12125     }
12126   }
12127   
12128   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12129     if (I->hasOneUse()) {
12130       // Push extractelement into predecessor operation if legal and
12131       // profitable to do so
12132       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12133         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12134         if (CheapToScalarize(BO, isConstantElt)) {
12135           Value *newEI0 =
12136             Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12137                                           EI.getName()+".lhs");
12138           Value *newEI1 =
12139             Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12140                                           EI.getName()+".rhs");
12141           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12142         }
12143       } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
12144         unsigned AS = LI->getPointerAddressSpace();
12145         Value *Ptr = Builder->CreateBitCast(I->getOperand(0),
12146                                             PointerType::get(EI.getType(), AS),
12147                                             I->getOperand(0)->getName());
12148         Value *GEP =
12149           Builder->CreateGEP(Ptr, EI.getOperand(1), I->getName()+".gep");
12150         cast<GEPOperator>(GEP)->setIsInBounds(true);
12151         
12152         LoadInst *Load = Builder->CreateLoad(GEP, "tmp");
12153
12154         // Make sure the Load goes before the load instruction in the source,
12155         // not wherever the extract happens to be.
12156         if (Instruction *P = dyn_cast<Instruction>(Ptr))
12157           P->moveBefore(I);
12158         if (Instruction *G = dyn_cast<Instruction>(GEP))
12159           G->moveBefore(I);
12160         Load->moveBefore(I);
12161         
12162         return ReplaceInstUsesWith(EI, Load);
12163       }
12164     }
12165     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12166       // Extracting the inserted element?
12167       if (IE->getOperand(2) == EI.getOperand(1))
12168         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12169       // If the inserted and extracted elements are constants, they must not
12170       // be the same value, extract from the pre-inserted value instead.
12171       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
12172         Worklist.AddValue(EI.getOperand(0));
12173         EI.setOperand(0, IE->getOperand(0));
12174         return &EI;
12175       }
12176     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12177       // If this is extracting an element from a shufflevector, figure out where
12178       // it came from and extract from the appropriate input element instead.
12179       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12180         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12181         Value *Src;
12182         unsigned LHSWidth =
12183           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12184
12185         if (SrcIdx < LHSWidth)
12186           Src = SVI->getOperand(0);
12187         else if (SrcIdx < LHSWidth*2) {
12188           SrcIdx -= LHSWidth;
12189           Src = SVI->getOperand(1);
12190         } else {
12191           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12192         }
12193         return ExtractElementInst::Create(Src,
12194                          ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12195                                           false));
12196       }
12197     }
12198     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12199   }
12200   return 0;
12201 }
12202
12203 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12204 /// elements from either LHS or RHS, return the shuffle mask and true. 
12205 /// Otherwise, return false.
12206 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12207                                          std::vector<Constant*> &Mask,
12208                                          LLVMContext *Context) {
12209   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12210          "Invalid CollectSingleShuffleElements");
12211   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12212
12213   if (isa<UndefValue>(V)) {
12214     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12215     return true;
12216   } else if (V == LHS) {
12217     for (unsigned i = 0; i != NumElts; ++i)
12218       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12219     return true;
12220   } else if (V == RHS) {
12221     for (unsigned i = 0; i != NumElts; ++i)
12222       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12223     return true;
12224   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12225     // If this is an insert of an extract from some other vector, include it.
12226     Value *VecOp    = IEI->getOperand(0);
12227     Value *ScalarOp = IEI->getOperand(1);
12228     Value *IdxOp    = IEI->getOperand(2);
12229     
12230     if (!isa<ConstantInt>(IdxOp))
12231       return false;
12232     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12233     
12234     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12235       // Okay, we can handle this if the vector we are insertinting into is
12236       // transitively ok.
12237       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12238         // If so, update the mask to reflect the inserted undef.
12239         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12240         return true;
12241       }      
12242     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12243       if (isa<ConstantInt>(EI->getOperand(1)) &&
12244           EI->getOperand(0)->getType() == V->getType()) {
12245         unsigned ExtractedIdx =
12246           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12247         
12248         // This must be extracting from either LHS or RHS.
12249         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12250           // Okay, we can handle this if the vector we are insertinting into is
12251           // transitively ok.
12252           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12253             // If so, update the mask to reflect the inserted value.
12254             if (EI->getOperand(0) == LHS) {
12255               Mask[InsertedIdx % NumElts] = 
12256                  ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12257             } else {
12258               assert(EI->getOperand(0) == RHS);
12259               Mask[InsertedIdx % NumElts] = 
12260                 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12261               
12262             }
12263             return true;
12264           }
12265         }
12266       }
12267     }
12268   }
12269   // TODO: Handle shufflevector here!
12270   
12271   return false;
12272 }
12273
12274 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12275 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12276 /// that computes V and the LHS value of the shuffle.
12277 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12278                                      Value *&RHS, LLVMContext *Context) {
12279   assert(isa<VectorType>(V->getType()) && 
12280          (RHS == 0 || V->getType() == RHS->getType()) &&
12281          "Invalid shuffle!");
12282   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12283
12284   if (isa<UndefValue>(V)) {
12285     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12286     return V;
12287   } else if (isa<ConstantAggregateZero>(V)) {
12288     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12289     return V;
12290   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12291     // If this is an insert of an extract from some other vector, include it.
12292     Value *VecOp    = IEI->getOperand(0);
12293     Value *ScalarOp = IEI->getOperand(1);
12294     Value *IdxOp    = IEI->getOperand(2);
12295     
12296     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12297       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12298           EI->getOperand(0)->getType() == V->getType()) {
12299         unsigned ExtractedIdx =
12300           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12301         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12302         
12303         // Either the extracted from or inserted into vector must be RHSVec,
12304         // otherwise we'd end up with a shuffle of three inputs.
12305         if (EI->getOperand(0) == RHS || RHS == 0) {
12306           RHS = EI->getOperand(0);
12307           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12308           Mask[InsertedIdx % NumElts] = 
12309             ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12310           return V;
12311         }
12312         
12313         if (VecOp == RHS) {
12314           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12315                                             RHS, Context);
12316           // Everything but the extracted element is replaced with the RHS.
12317           for (unsigned i = 0; i != NumElts; ++i) {
12318             if (i != InsertedIdx)
12319               Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12320           }
12321           return V;
12322         }
12323         
12324         // If this insertelement is a chain that comes from exactly these two
12325         // vectors, return the vector and the effective shuffle.
12326         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12327                                          Context))
12328           return EI->getOperand(0);
12329         
12330       }
12331     }
12332   }
12333   // TODO: Handle shufflevector here!
12334   
12335   // Otherwise, can't do anything fancy.  Return an identity vector.
12336   for (unsigned i = 0; i != NumElts; ++i)
12337     Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12338   return V;
12339 }
12340
12341 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12342   Value *VecOp    = IE.getOperand(0);
12343   Value *ScalarOp = IE.getOperand(1);
12344   Value *IdxOp    = IE.getOperand(2);
12345   
12346   // Inserting an undef or into an undefined place, remove this.
12347   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12348     ReplaceInstUsesWith(IE, VecOp);
12349   
12350   // If the inserted element was extracted from some other vector, and if the 
12351   // indexes are constant, try to turn this into a shufflevector operation.
12352   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12353     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12354         EI->getOperand(0)->getType() == IE.getType()) {
12355       unsigned NumVectorElts = IE.getType()->getNumElements();
12356       unsigned ExtractedIdx =
12357         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12358       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12359       
12360       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12361         return ReplaceInstUsesWith(IE, VecOp);
12362       
12363       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12364         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12365       
12366       // If we are extracting a value from a vector, then inserting it right
12367       // back into the same place, just use the input vector.
12368       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12369         return ReplaceInstUsesWith(IE, VecOp);      
12370       
12371       // We could theoretically do this for ANY input.  However, doing so could
12372       // turn chains of insertelement instructions into a chain of shufflevector
12373       // instructions, and right now we do not merge shufflevectors.  As such,
12374       // only do this in a situation where it is clear that there is benefit.
12375       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12376         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12377         // the values of VecOp, except then one read from EIOp0.
12378         // Build a new shuffle mask.
12379         std::vector<Constant*> Mask;
12380         if (isa<UndefValue>(VecOp))
12381           Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
12382         else {
12383           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12384           Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
12385                                                        NumVectorElts));
12386         } 
12387         Mask[InsertedIdx] = 
12388                            ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12389         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12390                                      ConstantVector::get(Mask));
12391       }
12392       
12393       // If this insertelement isn't used by some other insertelement, turn it
12394       // (and any insertelements it points to), into one big shuffle.
12395       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12396         std::vector<Constant*> Mask;
12397         Value *RHS = 0;
12398         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12399         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12400         // We now have a shuffle of LHS, RHS, Mask.
12401         return new ShuffleVectorInst(LHS, RHS,
12402                                      ConstantVector::get(Mask));
12403       }
12404     }
12405   }
12406
12407   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12408   APInt UndefElts(VWidth, 0);
12409   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12410   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12411     return &IE;
12412
12413   return 0;
12414 }
12415
12416
12417 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12418   Value *LHS = SVI.getOperand(0);
12419   Value *RHS = SVI.getOperand(1);
12420   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12421
12422   bool MadeChange = false;
12423
12424   // Undefined shuffle mask -> undefined value.
12425   if (isa<UndefValue>(SVI.getOperand(2)))
12426     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12427
12428   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12429
12430   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12431     return 0;
12432
12433   APInt UndefElts(VWidth, 0);
12434   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12435   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12436     LHS = SVI.getOperand(0);
12437     RHS = SVI.getOperand(1);
12438     MadeChange = true;
12439   }
12440   
12441   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12442   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12443   if (LHS == RHS || isa<UndefValue>(LHS)) {
12444     if (isa<UndefValue>(LHS) && LHS == RHS) {
12445       // shuffle(undef,undef,mask) -> undef.
12446       return ReplaceInstUsesWith(SVI, LHS);
12447     }
12448     
12449     // Remap any references to RHS to use LHS.
12450     std::vector<Constant*> Elts;
12451     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12452       if (Mask[i] >= 2*e)
12453         Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12454       else {
12455         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12456             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12457           Mask[i] = 2*e;     // Turn into undef.
12458           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12459         } else {
12460           Mask[i] = Mask[i] % e;  // Force to LHS.
12461           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12462         }
12463       }
12464     }
12465     SVI.setOperand(0, SVI.getOperand(1));
12466     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12467     SVI.setOperand(2, ConstantVector::get(Elts));
12468     LHS = SVI.getOperand(0);
12469     RHS = SVI.getOperand(1);
12470     MadeChange = true;
12471   }
12472   
12473   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12474   bool isLHSID = true, isRHSID = true;
12475     
12476   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12477     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12478     // Is this an identity shuffle of the LHS value?
12479     isLHSID &= (Mask[i] == i);
12480       
12481     // Is this an identity shuffle of the RHS value?
12482     isRHSID &= (Mask[i]-e == i);
12483   }
12484
12485   // Eliminate identity shuffles.
12486   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12487   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12488   
12489   // If the LHS is a shufflevector itself, see if we can combine it with this
12490   // one without producing an unusual shuffle.  Here we are really conservative:
12491   // we are absolutely afraid of producing a shuffle mask not in the input
12492   // program, because the code gen may not be smart enough to turn a merged
12493   // shuffle into two specific shuffles: it may produce worse code.  As such,
12494   // we only merge two shuffles if the result is one of the two input shuffle
12495   // masks.  In this case, merging the shuffles just removes one instruction,
12496   // which we know is safe.  This is good for things like turning:
12497   // (splat(splat)) -> splat.
12498   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12499     if (isa<UndefValue>(RHS)) {
12500       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12501
12502       std::vector<unsigned> NewMask;
12503       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12504         if (Mask[i] >= 2*e)
12505           NewMask.push_back(2*e);
12506         else
12507           NewMask.push_back(LHSMask[Mask[i]]);
12508       
12509       // If the result mask is equal to the src shuffle or this shuffle mask, do
12510       // the replacement.
12511       if (NewMask == LHSMask || NewMask == Mask) {
12512         unsigned LHSInNElts =
12513           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12514         std::vector<Constant*> Elts;
12515         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12516           if (NewMask[i] >= LHSInNElts*2) {
12517             Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12518           } else {
12519             Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12520           }
12521         }
12522         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12523                                      LHSSVI->getOperand(1),
12524                                      ConstantVector::get(Elts));
12525       }
12526     }
12527   }
12528
12529   return MadeChange ? &SVI : 0;
12530 }
12531
12532
12533
12534
12535 /// TryToSinkInstruction - Try to move the specified instruction from its
12536 /// current block into the beginning of DestBlock, which can only happen if it's
12537 /// safe to move the instruction past all of the instructions between it and the
12538 /// end of its block.
12539 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12540   assert(I->hasOneUse() && "Invariants didn't hold!");
12541
12542   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12543   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12544     return false;
12545
12546   // Do not sink alloca instructions out of the entry block.
12547   if (isa<AllocaInst>(I) && I->getParent() ==
12548         &DestBlock->getParent()->getEntryBlock())
12549     return false;
12550
12551   // We can only sink load instructions if there is nothing between the load and
12552   // the end of block that could change the value.
12553   if (I->mayReadFromMemory()) {
12554     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12555          Scan != E; ++Scan)
12556       if (Scan->mayWriteToMemory())
12557         return false;
12558   }
12559
12560   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12561
12562   CopyPrecedingStopPoint(I, InsertPos);
12563   I->moveBefore(InsertPos);
12564   ++NumSunkInst;
12565   return true;
12566 }
12567
12568
12569 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12570 /// all reachable code to the worklist.
12571 ///
12572 /// This has a couple of tricks to make the code faster and more powerful.  In
12573 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12574 /// them to the worklist (this significantly speeds up instcombine on code where
12575 /// many instructions are dead or constant).  Additionally, if we find a branch
12576 /// whose condition is a known constant, we only visit the reachable successors.
12577 ///
12578 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12579                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12580                                        InstCombiner &IC,
12581                                        const TargetData *TD) {
12582   SmallVector<BasicBlock*, 256> Worklist;
12583   Worklist.push_back(BB);
12584
12585   while (!Worklist.empty()) {
12586     BB = Worklist.back();
12587     Worklist.pop_back();
12588     
12589     // We have now visited this block!  If we've already been here, ignore it.
12590     if (!Visited.insert(BB)) continue;
12591
12592     DbgInfoIntrinsic *DBI_Prev = NULL;
12593     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12594       Instruction *Inst = BBI++;
12595       
12596       // DCE instruction if trivially dead.
12597       if (isInstructionTriviallyDead(Inst)) {
12598         ++NumDeadInst;
12599         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
12600         Inst->eraseFromParent();
12601         continue;
12602       }
12603       
12604       // ConstantProp instruction if trivially constant.
12605       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12606         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12607                      << *Inst << '\n');
12608         Inst->replaceAllUsesWith(C);
12609         ++NumConstProp;
12610         Inst->eraseFromParent();
12611         continue;
12612       }
12613      
12614       // If there are two consecutive llvm.dbg.stoppoint calls then
12615       // it is likely that the optimizer deleted code in between these
12616       // two intrinsics. 
12617       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12618       if (DBI_Next) {
12619         if (DBI_Prev
12620             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12621             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12622           IC.Worklist.Remove(DBI_Prev);
12623           DBI_Prev->eraseFromParent();
12624         }
12625         DBI_Prev = DBI_Next;
12626       } else {
12627         DBI_Prev = 0;
12628       }
12629
12630       IC.Worklist.Add(Inst);
12631     }
12632
12633     // Recursively visit successors.  If this is a branch or switch on a
12634     // constant, only visit the reachable successor.
12635     TerminatorInst *TI = BB->getTerminator();
12636     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12637       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12638         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12639         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12640         Worklist.push_back(ReachableBB);
12641         continue;
12642       }
12643     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12644       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12645         // See if this is an explicit destination.
12646         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12647           if (SI->getCaseValue(i) == Cond) {
12648             BasicBlock *ReachableBB = SI->getSuccessor(i);
12649             Worklist.push_back(ReachableBB);
12650             continue;
12651           }
12652         
12653         // Otherwise it is the default destination.
12654         Worklist.push_back(SI->getSuccessor(0));
12655         continue;
12656       }
12657     }
12658     
12659     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12660       Worklist.push_back(TI->getSuccessor(i));
12661   }
12662 }
12663
12664 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12665   bool Changed = false;
12666   TD = getAnalysisIfAvailable<TargetData>();
12667   
12668   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12669         << F.getNameStr() << "\n");
12670
12671   {
12672     // Do a depth-first traversal of the function, populate the worklist with
12673     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12674     // track of which blocks we visit.
12675     SmallPtrSet<BasicBlock*, 64> Visited;
12676     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12677
12678     // Do a quick scan over the function.  If we find any blocks that are
12679     // unreachable, remove any instructions inside of them.  This prevents
12680     // the instcombine code from having to deal with some bad special cases.
12681     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12682       if (!Visited.count(BB)) {
12683         Instruction *Term = BB->getTerminator();
12684         while (Term != BB->begin()) {   // Remove instrs bottom-up
12685           BasicBlock::iterator I = Term; --I;
12686
12687           DEBUG(errs() << "IC: DCE: " << *I << '\n');
12688           // A debug intrinsic shouldn't force another iteration if we weren't
12689           // going to do one without it.
12690           if (!isa<DbgInfoIntrinsic>(I)) {
12691             ++NumDeadInst;
12692             Changed = true;
12693           }
12694           if (!I->use_empty())
12695             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12696           I->eraseFromParent();
12697         }
12698       }
12699   }
12700
12701   while (!Worklist.isEmpty()) {
12702     Instruction *I = Worklist.RemoveOne();
12703     if (I == 0) continue;  // skip null values.
12704
12705     // Check to see if we can DCE the instruction.
12706     if (isInstructionTriviallyDead(I)) {
12707       DEBUG(errs() << "IC: DCE: " << *I << '\n');
12708       EraseInstFromFunction(*I);
12709       ++NumDeadInst;
12710       Changed = true;
12711       continue;
12712     }
12713
12714     // Instruction isn't dead, see if we can constant propagate it.
12715     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12716       DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
12717
12718       // Add operands to the worklist.
12719       ReplaceInstUsesWith(*I, C);
12720       ++NumConstProp;
12721       EraseInstFromFunction(*I);
12722       Changed = true;
12723       continue;
12724     }
12725
12726     if (TD) {
12727       // See if we can constant fold its operands.
12728       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12729         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12730           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
12731                                   F.getContext(), TD))
12732             if (NewC != CE) {
12733               i->set(NewC);
12734               Changed = true;
12735             }
12736     }
12737
12738     // See if we can trivially sink this instruction to a successor basic block.
12739     if (I->hasOneUse()) {
12740       BasicBlock *BB = I->getParent();
12741       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12742       if (UserParent != BB) {
12743         bool UserIsSuccessor = false;
12744         // See if the user is one of our successors.
12745         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12746           if (*SI == UserParent) {
12747             UserIsSuccessor = true;
12748             break;
12749           }
12750
12751         // If the user is one of our immediate successors, and if that successor
12752         // only has us as a predecessors (we'd have to split the critical edge
12753         // otherwise), we can keep going.
12754         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12755             next(pred_begin(UserParent)) == pred_end(UserParent))
12756           // Okay, the CFG is simple enough, try to sink this instruction.
12757           Changed |= TryToSinkInstruction(I, UserParent);
12758       }
12759     }
12760
12761     // Now that we have an instruction, try combining it to simplify it.
12762     Builder->SetInsertPoint(I->getParent(), I);
12763     
12764 #ifndef NDEBUG
12765     std::string OrigI;
12766 #endif
12767     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
12768     
12769     if (Instruction *Result = visit(*I)) {
12770       ++NumCombined;
12771       // Should we replace the old instruction with a new one?
12772       if (Result != I) {
12773         DEBUG(errs() << "IC: Old = " << *I << '\n'
12774                      << "    New = " << *Result << '\n');
12775
12776         // Everything uses the new instruction now.
12777         I->replaceAllUsesWith(Result);
12778
12779         // Push the new instruction and any users onto the worklist.
12780         Worklist.Add(Result);
12781         Worklist.AddUsersToWorkList(*Result);
12782
12783         // Move the name to the new instruction first.
12784         Result->takeName(I);
12785
12786         // Insert the new instruction into the basic block...
12787         BasicBlock *InstParent = I->getParent();
12788         BasicBlock::iterator InsertPos = I;
12789
12790         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12791           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12792             ++InsertPos;
12793
12794         InstParent->getInstList().insert(InsertPos, Result);
12795
12796         EraseInstFromFunction(*I);
12797       } else {
12798 #ifndef NDEBUG
12799         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12800                      << "    New = " << *I << '\n');
12801 #endif
12802
12803         // If the instruction was modified, it's possible that it is now dead.
12804         // if so, remove it.
12805         if (isInstructionTriviallyDead(I)) {
12806           EraseInstFromFunction(*I);
12807         } else {
12808           Worklist.Add(I);
12809           Worklist.AddUsersToWorkList(*I);
12810         }
12811       }
12812       Changed = true;
12813     }
12814   }
12815
12816   Worklist.Zap();
12817   return Changed;
12818 }
12819
12820
12821 bool InstCombiner::runOnFunction(Function &F) {
12822   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12823   Context = &F.getContext();
12824   
12825   
12826   /// Builder - This is an IRBuilder that automatically inserts new
12827   /// instructions into the worklist when they are created.
12828   IRBuilder<true, ConstantFolder, InstCombineIRInserter> 
12829     TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12830                InstCombineIRInserter(Worklist));
12831   Builder = &TheBuilder;
12832   
12833   bool EverMadeChange = false;
12834
12835   // Iterate while there is work to do.
12836   unsigned Iteration = 0;
12837   while (DoOneIteration(F, Iteration++))
12838     EverMadeChange = true;
12839   
12840   Builder = 0;
12841   return EverMadeChange;
12842 }
12843
12844 FunctionPass *llvm::createInstructionCombiningPass() {
12845   return new InstCombiner();
12846 }