5fe8ee876c345a42671c05ff232b949fbf9f9ee7
[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/MathExtras.h"
56 #include "llvm/Support/PatternMatch.h"
57 #include "llvm/Support/Compiler.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include "llvm/ADT/DenseMap.h"
60 #include "llvm/ADT/SmallVector.h"
61 #include "llvm/ADT/SmallPtrSet.h"
62 #include "llvm/ADT/Statistic.h"
63 #include "llvm/ADT/STLExtras.h"
64 #include <algorithm>
65 #include <climits>
66 #include <sstream>
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   class VISIBILITY_HIDDEN InstCombiner
78     : public FunctionPass,
79       public InstVisitor<InstCombiner, Instruction*> {
80     // Worklist of all of the instructions that need to be simplified.
81     SmallVector<Instruction*, 256> Worklist;
82     DenseMap<Instruction*, unsigned> WorklistMap;
83     TargetData *TD;
84     bool MustPreserveLCSSA;
85   public:
86     static char ID; // Pass identification, replacement for typeid
87     InstCombiner() : FunctionPass(&ID) {}
88
89     LLVMContext *Context;
90     LLVMContext *getContext() const { return Context; }
91
92     /// AddToWorkList - Add the specified instruction to the worklist if it
93     /// isn't already in it.
94     void AddToWorkList(Instruction *I) {
95       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
96         Worklist.push_back(I);
97     }
98     
99     // RemoveFromWorkList - remove I from the worklist if it exists.
100     void RemoveFromWorkList(Instruction *I) {
101       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
102       if (It == WorklistMap.end()) return; // Not in worklist.
103       
104       // Don't bother moving everything down, just null out the slot.
105       Worklist[It->second] = 0;
106       
107       WorklistMap.erase(It);
108     }
109     
110     Instruction *RemoveOneFromWorkList() {
111       Instruction *I = Worklist.back();
112       Worklist.pop_back();
113       WorklistMap.erase(I);
114       return I;
115     }
116
117     
118     /// AddUsersToWorkList - When an instruction is simplified, add all users of
119     /// the instruction to the work lists because they might get more simplified
120     /// now.
121     ///
122     void AddUsersToWorkList(Value &I) {
123       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
124            UI != UE; ++UI)
125         AddToWorkList(cast<Instruction>(*UI));
126     }
127
128     /// AddUsesToWorkList - When an instruction is simplified, add operands to
129     /// the work lists because they might get more simplified now.
130     ///
131     void AddUsesToWorkList(Instruction &I) {
132       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
133         if (Instruction *Op = dyn_cast<Instruction>(*i))
134           AddToWorkList(Op);
135     }
136     
137     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
138     /// dead.  Add all of its operands to the worklist, turning them into
139     /// undef's to reduce the number of uses of those instructions.
140     ///
141     /// Return the specified operand before it is turned into an undef.
142     ///
143     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
144       Value *R = I.getOperand(op);
145       
146       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
147         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
148           AddToWorkList(Op);
149           // Set the operand to undef to drop the use.
150           *i = UndefValue::get(Op->getType());
151         }
152       
153       return R;
154     }
155
156   public:
157     virtual bool runOnFunction(Function &F);
158     
159     bool DoOneIteration(Function &F, unsigned ItNum);
160
161     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
162       AU.addPreservedID(LCSSAID);
163       AU.setPreservesCFG();
164     }
165
166     TargetData *getTargetData() const { return TD; }
167
168     // Visitation implementation - Implement instruction combining for different
169     // instruction types.  The semantics are as follows:
170     // Return Value:
171     //    null        - No change was made
172     //     I          - Change was made, I is still valid, I may be dead though
173     //   otherwise    - Change was made, replace I with returned instruction
174     //
175     Instruction *visitAdd(BinaryOperator &I);
176     Instruction *visitFAdd(BinaryOperator &I);
177     Instruction *visitSub(BinaryOperator &I);
178     Instruction *visitFSub(BinaryOperator &I);
179     Instruction *visitMul(BinaryOperator &I);
180     Instruction *visitFMul(BinaryOperator &I);
181     Instruction *visitURem(BinaryOperator &I);
182     Instruction *visitSRem(BinaryOperator &I);
183     Instruction *visitFRem(BinaryOperator &I);
184     bool SimplifyDivRemOfSelect(BinaryOperator &I);
185     Instruction *commonRemTransforms(BinaryOperator &I);
186     Instruction *commonIRemTransforms(BinaryOperator &I);
187     Instruction *commonDivTransforms(BinaryOperator &I);
188     Instruction *commonIDivTransforms(BinaryOperator &I);
189     Instruction *visitUDiv(BinaryOperator &I);
190     Instruction *visitSDiv(BinaryOperator &I);
191     Instruction *visitFDiv(BinaryOperator &I);
192     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
193     Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
194     Instruction *visitAnd(BinaryOperator &I);
195     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
196     Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
197     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
198                                      Value *A, Value *B, Value *C);
199     Instruction *visitOr (BinaryOperator &I);
200     Instruction *visitXor(BinaryOperator &I);
201     Instruction *visitShl(BinaryOperator &I);
202     Instruction *visitAShr(BinaryOperator &I);
203     Instruction *visitLShr(BinaryOperator &I);
204     Instruction *commonShiftTransforms(BinaryOperator &I);
205     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
206                                       Constant *RHSC);
207     Instruction *visitFCmpInst(FCmpInst &I);
208     Instruction *visitICmpInst(ICmpInst &I);
209     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
210     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
211                                                 Instruction *LHS,
212                                                 ConstantInt *RHS);
213     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
214                                 ConstantInt *DivRHS);
215
216     Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
217                              ICmpInst::Predicate Cond, Instruction &I);
218     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
219                                      BinaryOperator &I);
220     Instruction *commonCastTransforms(CastInst &CI);
221     Instruction *commonIntCastTransforms(CastInst &CI);
222     Instruction *commonPointerCastTransforms(CastInst &CI);
223     Instruction *visitTrunc(TruncInst &CI);
224     Instruction *visitZExt(ZExtInst &CI);
225     Instruction *visitSExt(SExtInst &CI);
226     Instruction *visitFPTrunc(FPTruncInst &CI);
227     Instruction *visitFPExt(CastInst &CI);
228     Instruction *visitFPToUI(FPToUIInst &FI);
229     Instruction *visitFPToSI(FPToSIInst &FI);
230     Instruction *visitUIToFP(CastInst &CI);
231     Instruction *visitSIToFP(CastInst &CI);
232     Instruction *visitPtrToInt(PtrToIntInst &CI);
233     Instruction *visitIntToPtr(IntToPtrInst &CI);
234     Instruction *visitBitCast(BitCastInst &CI);
235     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
236                                 Instruction *FI);
237     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
238     Instruction *visitSelectInst(SelectInst &SI);
239     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
240     Instruction *visitCallInst(CallInst &CI);
241     Instruction *visitInvokeInst(InvokeInst &II);
242     Instruction *visitPHINode(PHINode &PN);
243     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
244     Instruction *visitAllocationInst(AllocationInst &AI);
245     Instruction *visitFreeInst(FreeInst &FI);
246     Instruction *visitLoadInst(LoadInst &LI);
247     Instruction *visitStoreInst(StoreInst &SI);
248     Instruction *visitBranchInst(BranchInst &BI);
249     Instruction *visitSwitchInst(SwitchInst &SI);
250     Instruction *visitInsertElementInst(InsertElementInst &IE);
251     Instruction *visitExtractElementInst(ExtractElementInst &EI);
252     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
253     Instruction *visitExtractValueInst(ExtractValueInst &EV);
254
255     // visitInstruction - Specify what to return for unhandled instructions...
256     Instruction *visitInstruction(Instruction &I) { return 0; }
257
258   private:
259     Instruction *visitCallSite(CallSite CS);
260     bool transformConstExprCastCall(CallSite CS);
261     Instruction *transformCallThroughTrampoline(CallSite CS);
262     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
263                                    bool DoXform = true);
264     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
265     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
266
267
268   public:
269     // InsertNewInstBefore - insert an instruction New before instruction Old
270     // in the program.  Add the new instruction to the worklist.
271     //
272     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
273       assert(New && New->getParent() == 0 &&
274              "New instruction already inserted into a basic block!");
275       BasicBlock *BB = Old.getParent();
276       BB->getInstList().insert(&Old, New);  // Insert inst
277       AddToWorkList(New);
278       return New;
279     }
280
281     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
282     /// This also adds the cast to the worklist.  Finally, this returns the
283     /// cast.
284     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
285                             Instruction &Pos) {
286       if (V->getType() == Ty) return V;
287
288       if (Constant *CV = dyn_cast<Constant>(V))
289         return ConstantExpr::getCast(opc, CV, Ty);
290       
291       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
292       AddToWorkList(C);
293       return C;
294     }
295         
296     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
297       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
298     }
299
300
301     // ReplaceInstUsesWith - This method is to be used when an instruction is
302     // found to be dead, replacable with another preexisting expression.  Here
303     // we add all uses of I to the worklist, replace all uses of I with the new
304     // value, then return I, so that the inst combiner will know that I was
305     // modified.
306     //
307     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
308       AddUsersToWorkList(I);         // Add all modified instrs to worklist
309       if (&I != V) {
310         I.replaceAllUsesWith(V);
311         return &I;
312       } else {
313         // If we are replacing the instruction with itself, this must be in a
314         // segment of unreachable code, so just clobber the instruction.
315         I.replaceAllUsesWith(UndefValue::get(I.getType()));
316         return &I;
317       }
318     }
319
320     // EraseInstFromFunction - When dealing with an instruction that has side
321     // effects or produces a void value, we can't rely on DCE to delete the
322     // instruction.  Instead, visit methods should return the value returned by
323     // this function.
324     Instruction *EraseInstFromFunction(Instruction &I) {
325       assert(I.use_empty() && "Cannot erase instruction that is used!");
326       AddUsesToWorkList(I);
327       RemoveFromWorkList(&I);
328       I.eraseFromParent();
329       return 0;  // Don't do anything with FI
330     }
331         
332     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
333                            APInt &KnownOne, unsigned Depth = 0) const {
334       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
335     }
336     
337     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
338                            unsigned Depth = 0) const {
339       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
340     }
341     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
342       return llvm::ComputeNumSignBits(Op, TD, Depth);
343     }
344
345   private:
346
347     /// SimplifyCommutative - This performs a few simplifications for 
348     /// commutative operators.
349     bool SimplifyCommutative(BinaryOperator &I);
350
351     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
352     /// most-complex to least-complex order.
353     bool SimplifyCompare(CmpInst &I);
354
355     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
356     /// based on the demanded bits.
357     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
358                                    APInt& KnownZero, APInt& KnownOne,
359                                    unsigned Depth);
360     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
361                               APInt& KnownZero, APInt& KnownOne,
362                               unsigned Depth=0);
363         
364     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
365     /// SimplifyDemandedBits knows about.  See if the instruction has any
366     /// properties that allow us to simplify its operands.
367     bool SimplifyDemandedInstructionBits(Instruction &Inst);
368         
369     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
370                                       APInt& UndefElts, unsigned Depth = 0);
371       
372     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
373     // PHI node as operand #0, see if we can fold the instruction into the PHI
374     // (which is only possible if all operands to the PHI are constants).
375     Instruction *FoldOpIntoPhi(Instruction &I);
376
377     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
378     // operator and they all are only used by the PHI, PHI together their
379     // inputs, and do the operation once, to the result of the PHI.
380     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
381     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
382     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
383
384     
385     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
386                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
387     
388     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
389                               bool isSub, Instruction &I);
390     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
391                                  bool isSigned, bool Inside, Instruction &IB);
392     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
393     Instruction *MatchBSwap(BinaryOperator &I);
394     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
395     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
396     Instruction *SimplifyMemSet(MemSetInst *MI);
397
398
399     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
400
401     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
402                                     unsigned CastOpc, int &NumCastsRemoved);
403     unsigned GetOrEnforceKnownAlignment(Value *V,
404                                         unsigned PrefAlign = 0);
405
406   };
407 }
408
409 char InstCombiner::ID = 0;
410 static RegisterPass<InstCombiner>
411 X("instcombine", "Combine redundant instructions");
412
413 // getComplexity:  Assign a complexity or rank value to LLVM Values...
414 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
415 static unsigned getComplexity(LLVMContext *Context, Value *V) {
416   if (isa<Instruction>(V)) {
417     if (BinaryOperator::isNeg(V) ||
418         BinaryOperator::isFNeg(V) ||
419         BinaryOperator::isNot(V))
420       return 3;
421     return 4;
422   }
423   if (isa<Argument>(V)) return 3;
424   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
425 }
426
427 // isOnlyUse - Return true if this instruction will be deleted if we stop using
428 // it.
429 static bool isOnlyUse(Value *V) {
430   return V->hasOneUse() || isa<Constant>(V);
431 }
432
433 // getPromotedType - Return the specified type promoted as it would be to pass
434 // though a va_arg area...
435 static const Type *getPromotedType(const Type *Ty) {
436   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
437     if (ITy->getBitWidth() < 32)
438       return Type::getInt32Ty(Ty->getContext());
439   }
440   return Ty;
441 }
442
443 /// getBitCastOperand - If the specified operand is a CastInst, a constant
444 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
445 /// operand value, otherwise return null.
446 static Value *getBitCastOperand(Value *V) {
447   if (Operator *O = dyn_cast<Operator>(V)) {
448     if (O->getOpcode() == Instruction::BitCast)
449       return O->getOperand(0);
450     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
451       if (GEP->hasAllZeroIndices())
452         return GEP->getPointerOperand();
453   }
454   return 0;
455 }
456
457 /// This function is a wrapper around CastInst::isEliminableCastPair. It
458 /// simply extracts arguments and returns what that function returns.
459 static Instruction::CastOps 
460 isEliminableCastPair(
461   const CastInst *CI, ///< The first cast instruction
462   unsigned opcode,       ///< The opcode of the second cast instruction
463   const Type *DstTy,     ///< The target type for the second cast instruction
464   TargetData *TD         ///< The target data for pointer size
465 ) {
466
467   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
468   const Type *MidTy = CI->getType();                  // B from above
469
470   // Get the opcodes of the two Cast instructions
471   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
472   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
473
474   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
475                                                 DstTy,
476                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
477   
478   // We don't want to form an inttoptr or ptrtoint that converts to an integer
479   // type that differs from the pointer size.
480   if ((Res == Instruction::IntToPtr &&
481           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
482       (Res == Instruction::PtrToInt &&
483           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
484     Res = 0;
485   
486   return Instruction::CastOps(Res);
487 }
488
489 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
490 /// in any code being generated.  It does not require codegen if V is simple
491 /// enough or if the cast can be folded into other casts.
492 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
493                               const Type *Ty, TargetData *TD) {
494   if (V->getType() == Ty || isa<Constant>(V)) return false;
495   
496   // If this is another cast that can be eliminated, it isn't codegen either.
497   if (const CastInst *CI = dyn_cast<CastInst>(V))
498     if (isEliminableCastPair(CI, opcode, Ty, TD))
499       return false;
500   return true;
501 }
502
503 // SimplifyCommutative - This performs a few simplifications for commutative
504 // operators:
505 //
506 //  1. Order operands such that they are listed from right (least complex) to
507 //     left (most complex).  This puts constants before unary operators before
508 //     binary operators.
509 //
510 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
511 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
512 //
513 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
514   bool Changed = false;
515   if (getComplexity(Context, I.getOperand(0)) < 
516       getComplexity(Context, I.getOperand(1)))
517     Changed = !I.swapOperands();
518
519   if (!I.isAssociative()) return Changed;
520   Instruction::BinaryOps Opcode = I.getOpcode();
521   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
522     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
523       if (isa<Constant>(I.getOperand(1))) {
524         Constant *Folded = ConstantExpr::get(I.getOpcode(),
525                                              cast<Constant>(I.getOperand(1)),
526                                              cast<Constant>(Op->getOperand(1)));
527         I.setOperand(0, Op->getOperand(0));
528         I.setOperand(1, Folded);
529         return true;
530       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
531         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
532             isOnlyUse(Op) && isOnlyUse(Op1)) {
533           Constant *C1 = cast<Constant>(Op->getOperand(1));
534           Constant *C2 = cast<Constant>(Op1->getOperand(1));
535
536           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
537           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
538           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
539                                                     Op1->getOperand(0),
540                                                     Op1->getName(), &I);
541           AddToWorkList(New);
542           I.setOperand(0, New);
543           I.setOperand(1, Folded);
544           return true;
545         }
546     }
547   return Changed;
548 }
549
550 /// SimplifyCompare - For a CmpInst this function just orders the operands
551 /// so that theyare listed from right (least complex) to left (most complex).
552 /// This puts constants before unary operators before binary operators.
553 bool InstCombiner::SimplifyCompare(CmpInst &I) {
554   if (getComplexity(Context, I.getOperand(0)) >=
555       getComplexity(Context, I.getOperand(1)))
556     return false;
557   I.swapOperands();
558   // Compare instructions are not associative so there's nothing else we can do.
559   return true;
560 }
561
562 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
563 // if the LHS is a constant zero (which is the 'negate' form).
564 //
565 static inline Value *dyn_castNegVal(Value *V) {
566   if (BinaryOperator::isNeg(V))
567     return BinaryOperator::getNegArgument(V);
568
569   // Constants can be considered to be negated values if they can be folded.
570   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
571     return ConstantExpr::getNeg(C);
572
573   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
574     if (C->getType()->getElementType()->isInteger())
575       return ConstantExpr::getNeg(C);
576
577   return 0;
578 }
579
580 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
581 // instruction if the LHS is a constant negative zero (which is the 'negate'
582 // form).
583 //
584 static inline Value *dyn_castFNegVal(Value *V) {
585   if (BinaryOperator::isFNeg(V))
586     return BinaryOperator::getFNegArgument(V);
587
588   // Constants can be considered to be negated values if they can be folded.
589   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
590     return ConstantExpr::getFNeg(C);
591
592   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
593     if (C->getType()->getElementType()->isFloatingPoint())
594       return ConstantExpr::getFNeg(C);
595
596   return 0;
597 }
598
599 static inline Value *dyn_castNotVal(Value *V) {
600   if (BinaryOperator::isNot(V))
601     return BinaryOperator::getNotArgument(V);
602
603   // Constants can be considered to be not'ed values...
604   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
605     return ConstantInt::get(C->getType(), ~C->getValue());
606   return 0;
607 }
608
609 // dyn_castFoldableMul - If this value is a multiply that can be folded into
610 // other computations (because it has a constant operand), return the
611 // non-constant operand of the multiply, and set CST to point to the multiplier.
612 // Otherwise, return null.
613 //
614 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
615   if (V->hasOneUse() && V->getType()->isInteger())
616     if (Instruction *I = dyn_cast<Instruction>(V)) {
617       if (I->getOpcode() == Instruction::Mul)
618         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
619           return I->getOperand(0);
620       if (I->getOpcode() == Instruction::Shl)
621         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
622           // The multiplier is really 1 << CST.
623           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
624           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
625           CST = ConstantInt::get(V->getType()->getContext(),
626                                  APInt(BitWidth, 1).shl(CSTVal));
627           return I->getOperand(0);
628         }
629     }
630   return 0;
631 }
632
633 /// AddOne - Add one to a ConstantInt
634 static Constant *AddOne(Constant *C) {
635   return ConstantExpr::getAdd(C, 
636     ConstantInt::get(C->getType(), 1));
637 }
638 /// SubOne - Subtract one from a ConstantInt
639 static Constant *SubOne(ConstantInt *C) {
640   return ConstantExpr::getSub(C, 
641     ConstantInt::get(C->getType(), 1));
642 }
643 /// MultiplyOverflows - True if the multiply can not be expressed in an int
644 /// this size.
645 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
646   uint32_t W = C1->getBitWidth();
647   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
648   if (sign) {
649     LHSExt.sext(W * 2);
650     RHSExt.sext(W * 2);
651   } else {
652     LHSExt.zext(W * 2);
653     RHSExt.zext(W * 2);
654   }
655
656   APInt MulExt = LHSExt * RHSExt;
657
658   if (sign) {
659     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
660     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
661     return MulExt.slt(Min) || MulExt.sgt(Max);
662   } else 
663     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
664 }
665
666
667 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
668 /// specified instruction is a constant integer.  If so, check to see if there
669 /// are any bits set in the constant that are not demanded.  If so, shrink the
670 /// constant and return true.
671 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
672                                    APInt Demanded) {
673   assert(I && "No instruction?");
674   assert(OpNo < I->getNumOperands() && "Operand index too large");
675
676   // If the operand is not a constant integer, nothing to do.
677   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
678   if (!OpC) return false;
679
680   // If there are no bits set that aren't demanded, nothing to do.
681   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
682   if ((~Demanded & OpC->getValue()) == 0)
683     return false;
684
685   // This instruction is producing bits that are not demanded. Shrink the RHS.
686   Demanded &= OpC->getValue();
687   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
688   return true;
689 }
690
691 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
692 // set of known zero and one bits, compute the maximum and minimum values that
693 // could have the specified known zero and known one bits, returning them in
694 // min/max.
695 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
696                                                    const APInt& KnownOne,
697                                                    APInt& Min, APInt& Max) {
698   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
699          KnownZero.getBitWidth() == Min.getBitWidth() &&
700          KnownZero.getBitWidth() == Max.getBitWidth() &&
701          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
702   APInt UnknownBits = ~(KnownZero|KnownOne);
703
704   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
705   // bit if it is unknown.
706   Min = KnownOne;
707   Max = KnownOne|UnknownBits;
708   
709   if (UnknownBits.isNegative()) { // Sign bit is unknown
710     Min.set(Min.getBitWidth()-1);
711     Max.clear(Max.getBitWidth()-1);
712   }
713 }
714
715 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
716 // a set of known zero and one bits, compute the maximum and minimum values that
717 // could have the specified known zero and known one bits, returning them in
718 // min/max.
719 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
720                                                      const APInt &KnownOne,
721                                                      APInt &Min, APInt &Max) {
722   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
723          KnownZero.getBitWidth() == Min.getBitWidth() &&
724          KnownZero.getBitWidth() == Max.getBitWidth() &&
725          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
726   APInt UnknownBits = ~(KnownZero|KnownOne);
727   
728   // The minimum value is when the unknown bits are all zeros.
729   Min = KnownOne;
730   // The maximum value is when the unknown bits are all ones.
731   Max = KnownOne|UnknownBits;
732 }
733
734 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
735 /// SimplifyDemandedBits knows about.  See if the instruction has any
736 /// properties that allow us to simplify its operands.
737 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
738   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
739   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
740   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
741   
742   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
743                                      KnownZero, KnownOne, 0);
744   if (V == 0) return false;
745   if (V == &Inst) return true;
746   ReplaceInstUsesWith(Inst, V);
747   return true;
748 }
749
750 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
751 /// specified instruction operand if possible, updating it in place.  It returns
752 /// true if it made any change and false otherwise.
753 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
754                                         APInt &KnownZero, APInt &KnownOne,
755                                         unsigned Depth) {
756   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
757                                           KnownZero, KnownOne, Depth);
758   if (NewVal == 0) return false;
759   U.set(NewVal);
760   return true;
761 }
762
763
764 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
765 /// value based on the demanded bits.  When this function is called, it is known
766 /// that only the bits set in DemandedMask of the result of V are ever used
767 /// downstream. Consequently, depending on the mask and V, it may be possible
768 /// to replace V with a constant or one of its operands. In such cases, this
769 /// function does the replacement and returns true. In all other cases, it
770 /// returns false after analyzing the expression and setting KnownOne and known
771 /// to be one in the expression.  KnownZero contains all the bits that are known
772 /// to be zero in the expression. These are provided to potentially allow the
773 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
774 /// the expression. KnownOne and KnownZero always follow the invariant that 
775 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
776 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
777 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
778 /// and KnownOne must all be the same.
779 ///
780 /// This returns null if it did not change anything and it permits no
781 /// simplification.  This returns V itself if it did some simplification of V's
782 /// operands based on the information about what bits are demanded. This returns
783 /// some other non-null value if it found out that V is equal to another value
784 /// in the context where the specified bits are demanded, but not for all users.
785 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
786                                              APInt &KnownZero, APInt &KnownOne,
787                                              unsigned Depth) {
788   assert(V != 0 && "Null pointer of Value???");
789   assert(Depth <= 6 && "Limit Search Depth");
790   uint32_t BitWidth = DemandedMask.getBitWidth();
791   const Type *VTy = V->getType();
792   assert((TD || !isa<PointerType>(VTy)) &&
793          "SimplifyDemandedBits needs to know bit widths!");
794   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
795          (!VTy->isIntOrIntVector() ||
796           VTy->getScalarSizeInBits() == BitWidth) &&
797          KnownZero.getBitWidth() == BitWidth &&
798          KnownOne.getBitWidth() == BitWidth &&
799          "Value *V, DemandedMask, KnownZero and KnownOne "
800          "must have same BitWidth");
801   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
802     // We know all of the bits for a constant!
803     KnownOne = CI->getValue() & DemandedMask;
804     KnownZero = ~KnownOne & DemandedMask;
805     return 0;
806   }
807   if (isa<ConstantPointerNull>(V)) {
808     // We know all of the bits for a constant!
809     KnownOne.clear();
810     KnownZero = DemandedMask;
811     return 0;
812   }
813
814   KnownZero.clear();
815   KnownOne.clear();
816   if (DemandedMask == 0) {   // Not demanding any bits from V.
817     if (isa<UndefValue>(V))
818       return 0;
819     return UndefValue::get(VTy);
820   }
821   
822   if (Depth == 6)        // Limit search depth.
823     return 0;
824   
825   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
826   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
827
828   Instruction *I = dyn_cast<Instruction>(V);
829   if (!I) {
830     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
831     return 0;        // Only analyze instructions.
832   }
833
834   // If there are multiple uses of this value and we aren't at the root, then
835   // we can't do any simplifications of the operands, because DemandedMask
836   // only reflects the bits demanded by *one* of the users.
837   if (Depth != 0 && !I->hasOneUse()) {
838     // Despite the fact that we can't simplify this instruction in all User's
839     // context, we can at least compute the knownzero/knownone bits, and we can
840     // do simplifications that apply to *just* the one user if we know that
841     // this instruction has a simpler value in that context.
842     if (I->getOpcode() == Instruction::And) {
843       // If either the LHS or the RHS are Zero, the result is zero.
844       ComputeMaskedBits(I->getOperand(1), DemandedMask,
845                         RHSKnownZero, RHSKnownOne, Depth+1);
846       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
847                         LHSKnownZero, LHSKnownOne, Depth+1);
848       
849       // If all of the demanded bits are known 1 on one side, return the other.
850       // These bits cannot contribute to the result of the 'and' in this
851       // context.
852       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
853           (DemandedMask & ~LHSKnownZero))
854         return I->getOperand(0);
855       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
856           (DemandedMask & ~RHSKnownZero))
857         return I->getOperand(1);
858       
859       // If all of the demanded bits in the inputs are known zeros, return zero.
860       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
861         return Constant::getNullValue(VTy);
862       
863     } else if (I->getOpcode() == Instruction::Or) {
864       // We can simplify (X|Y) -> X or Y in the user's context if we know that
865       // only bits from X or Y are demanded.
866       
867       // If either the LHS or the RHS are One, the result is One.
868       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
869                         RHSKnownZero, RHSKnownOne, Depth+1);
870       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
871                         LHSKnownZero, LHSKnownOne, Depth+1);
872       
873       // If all of the demanded bits are known zero on one side, return the
874       // other.  These bits cannot contribute to the result of the 'or' in this
875       // context.
876       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
877           (DemandedMask & ~LHSKnownOne))
878         return I->getOperand(0);
879       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
880           (DemandedMask & ~RHSKnownOne))
881         return I->getOperand(1);
882       
883       // If all of the potentially set bits on one side are known to be set on
884       // the other side, just use the 'other' side.
885       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
886           (DemandedMask & (~RHSKnownZero)))
887         return I->getOperand(0);
888       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
889           (DemandedMask & (~LHSKnownZero)))
890         return I->getOperand(1);
891     }
892     
893     // Compute the KnownZero/KnownOne bits to simplify things downstream.
894     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
895     return 0;
896   }
897   
898   // If this is the root being simplified, allow it to have multiple uses,
899   // just set the DemandedMask to all bits so that we can try to simplify the
900   // operands.  This allows visitTruncInst (for example) to simplify the
901   // operand of a trunc without duplicating all the logic below.
902   if (Depth == 0 && !V->hasOneUse())
903     DemandedMask = APInt::getAllOnesValue(BitWidth);
904   
905   switch (I->getOpcode()) {
906   default:
907     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
908     break;
909   case Instruction::And:
910     // If either the LHS or the RHS are Zero, the result is zero.
911     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
912                              RHSKnownZero, RHSKnownOne, Depth+1) ||
913         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
914                              LHSKnownZero, LHSKnownOne, Depth+1))
915       return I;
916     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
917     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
918
919     // If all of the demanded bits are known 1 on one side, return the other.
920     // These bits cannot contribute to the result of the 'and'.
921     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
922         (DemandedMask & ~LHSKnownZero))
923       return I->getOperand(0);
924     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
925         (DemandedMask & ~RHSKnownZero))
926       return I->getOperand(1);
927     
928     // If all of the demanded bits in the inputs are known zeros, return zero.
929     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
930       return Constant::getNullValue(VTy);
931       
932     // If the RHS is a constant, see if we can simplify it.
933     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
934       return I;
935       
936     // Output known-1 bits are only known if set in both the LHS & RHS.
937     RHSKnownOne &= LHSKnownOne;
938     // Output known-0 are known to be clear if zero in either the LHS | RHS.
939     RHSKnownZero |= LHSKnownZero;
940     break;
941   case Instruction::Or:
942     // If either the LHS or the RHS are One, the result is One.
943     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
944                              RHSKnownZero, RHSKnownOne, Depth+1) ||
945         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
946                              LHSKnownZero, LHSKnownOne, Depth+1))
947       return I;
948     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
949     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
950     
951     // If all of the demanded bits are known zero on one side, return the other.
952     // These bits cannot contribute to the result of the 'or'.
953     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
954         (DemandedMask & ~LHSKnownOne))
955       return I->getOperand(0);
956     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
957         (DemandedMask & ~RHSKnownOne))
958       return I->getOperand(1);
959
960     // If all of the potentially set bits on one side are known to be set on
961     // the other side, just use the 'other' side.
962     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
963         (DemandedMask & (~RHSKnownZero)))
964       return I->getOperand(0);
965     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
966         (DemandedMask & (~LHSKnownZero)))
967       return I->getOperand(1);
968         
969     // If the RHS is a constant, see if we can simplify it.
970     if (ShrinkDemandedConstant(I, 1, DemandedMask))
971       return I;
972           
973     // Output known-0 bits are only known if clear in both the LHS & RHS.
974     RHSKnownZero &= LHSKnownZero;
975     // Output known-1 are known to be set if set in either the LHS | RHS.
976     RHSKnownOne |= LHSKnownOne;
977     break;
978   case Instruction::Xor: {
979     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
980                              RHSKnownZero, RHSKnownOne, Depth+1) ||
981         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
982                              LHSKnownZero, LHSKnownOne, Depth+1))
983       return I;
984     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
985     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
986     
987     // If all of the demanded bits are known zero on one side, return the other.
988     // These bits cannot contribute to the result of the 'xor'.
989     if ((DemandedMask & RHSKnownZero) == DemandedMask)
990       return I->getOperand(0);
991     if ((DemandedMask & LHSKnownZero) == DemandedMask)
992       return I->getOperand(1);
993     
994     // Output known-0 bits are known if clear or set in both the LHS & RHS.
995     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
996                          (RHSKnownOne & LHSKnownOne);
997     // Output known-1 are known to be set if set in only one of the LHS, RHS.
998     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
999                         (RHSKnownOne & LHSKnownZero);
1000     
1001     // If all of the demanded bits are known to be zero on one side or the
1002     // other, turn this into an *inclusive* or.
1003     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1004     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1005       Instruction *Or =
1006         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1007                                  I->getName());
1008       return InsertNewInstBefore(Or, *I);
1009     }
1010     
1011     // If all of the demanded bits on one side are known, and all of the set
1012     // bits on that side are also known to be set on the other side, turn this
1013     // into an AND, as we know the bits will be cleared.
1014     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1015     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1016       // all known
1017       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1018         Constant *AndC = Constant::getIntegerValue(VTy,
1019                                                    ~RHSKnownOne & DemandedMask);
1020         Instruction *And = 
1021           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1022         return InsertNewInstBefore(And, *I);
1023       }
1024     }
1025     
1026     // If the RHS is a constant, see if we can simplify it.
1027     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1028     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1029       return I;
1030     
1031     RHSKnownZero = KnownZeroOut;
1032     RHSKnownOne  = KnownOneOut;
1033     break;
1034   }
1035   case Instruction::Select:
1036     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1037                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1038         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1039                              LHSKnownZero, LHSKnownOne, Depth+1))
1040       return I;
1041     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1042     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1043     
1044     // If the operands are constants, see if we can simplify them.
1045     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1046         ShrinkDemandedConstant(I, 2, DemandedMask))
1047       return I;
1048     
1049     // Only known if known in both the LHS and RHS.
1050     RHSKnownOne &= LHSKnownOne;
1051     RHSKnownZero &= LHSKnownZero;
1052     break;
1053   case Instruction::Trunc: {
1054     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1055     DemandedMask.zext(truncBf);
1056     RHSKnownZero.zext(truncBf);
1057     RHSKnownOne.zext(truncBf);
1058     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1059                              RHSKnownZero, RHSKnownOne, Depth+1))
1060       return I;
1061     DemandedMask.trunc(BitWidth);
1062     RHSKnownZero.trunc(BitWidth);
1063     RHSKnownOne.trunc(BitWidth);
1064     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1065     break;
1066   }
1067   case Instruction::BitCast:
1068     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1069       return false;  // vector->int or fp->int?
1070
1071     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1072       if (const VectorType *SrcVTy =
1073             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1074         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1075           // Don't touch a bitcast between vectors of different element counts.
1076           return false;
1077       } else
1078         // Don't touch a scalar-to-vector bitcast.
1079         return false;
1080     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1081       // Don't touch a vector-to-scalar bitcast.
1082       return false;
1083
1084     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1085                              RHSKnownZero, RHSKnownOne, Depth+1))
1086       return I;
1087     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1088     break;
1089   case Instruction::ZExt: {
1090     // Compute the bits in the result that are not present in the input.
1091     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1092     
1093     DemandedMask.trunc(SrcBitWidth);
1094     RHSKnownZero.trunc(SrcBitWidth);
1095     RHSKnownOne.trunc(SrcBitWidth);
1096     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1097                              RHSKnownZero, RHSKnownOne, Depth+1))
1098       return I;
1099     DemandedMask.zext(BitWidth);
1100     RHSKnownZero.zext(BitWidth);
1101     RHSKnownOne.zext(BitWidth);
1102     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1103     // The top bits are known to be zero.
1104     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1105     break;
1106   }
1107   case Instruction::SExt: {
1108     // Compute the bits in the result that are not present in the input.
1109     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1110     
1111     APInt InputDemandedBits = DemandedMask & 
1112                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1113
1114     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1115     // If any of the sign extended bits are demanded, we know that the sign
1116     // bit is demanded.
1117     if ((NewBits & DemandedMask) != 0)
1118       InputDemandedBits.set(SrcBitWidth-1);
1119       
1120     InputDemandedBits.trunc(SrcBitWidth);
1121     RHSKnownZero.trunc(SrcBitWidth);
1122     RHSKnownOne.trunc(SrcBitWidth);
1123     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1124                              RHSKnownZero, RHSKnownOne, Depth+1))
1125       return I;
1126     InputDemandedBits.zext(BitWidth);
1127     RHSKnownZero.zext(BitWidth);
1128     RHSKnownOne.zext(BitWidth);
1129     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1130       
1131     // If the sign bit of the input is known set or clear, then we know the
1132     // top bits of the result.
1133
1134     // If the input sign bit is known zero, or if the NewBits are not demanded
1135     // convert this into a zero extension.
1136     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1137       // Convert to ZExt cast
1138       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1139       return InsertNewInstBefore(NewCast, *I);
1140     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1141       RHSKnownOne |= NewBits;
1142     }
1143     break;
1144   }
1145   case Instruction::Add: {
1146     // Figure out what the input bits are.  If the top bits of the and result
1147     // are not demanded, then the add doesn't demand them from its input
1148     // either.
1149     unsigned NLZ = DemandedMask.countLeadingZeros();
1150       
1151     // If there is a constant on the RHS, there are a variety of xformations
1152     // we can do.
1153     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1154       // If null, this should be simplified elsewhere.  Some of the xforms here
1155       // won't work if the RHS is zero.
1156       if (RHS->isZero())
1157         break;
1158       
1159       // If the top bit of the output is demanded, demand everything from the
1160       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1161       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1162
1163       // Find information about known zero/one bits in the input.
1164       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1165                                LHSKnownZero, LHSKnownOne, Depth+1))
1166         return I;
1167
1168       // If the RHS of the add has bits set that can't affect the input, reduce
1169       // the constant.
1170       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1171         return I;
1172       
1173       // Avoid excess work.
1174       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1175         break;
1176       
1177       // Turn it into OR if input bits are zero.
1178       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1179         Instruction *Or =
1180           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1181                                    I->getName());
1182         return InsertNewInstBefore(Or, *I);
1183       }
1184       
1185       // We can say something about the output known-zero and known-one bits,
1186       // depending on potential carries from the input constant and the
1187       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1188       // bits set and the RHS constant is 0x01001, then we know we have a known
1189       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1190       
1191       // To compute this, we first compute the potential carry bits.  These are
1192       // the bits which may be modified.  I'm not aware of a better way to do
1193       // this scan.
1194       const APInt &RHSVal = RHS->getValue();
1195       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1196       
1197       // Now that we know which bits have carries, compute the known-1/0 sets.
1198       
1199       // Bits are known one if they are known zero in one operand and one in the
1200       // other, and there is no input carry.
1201       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1202                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1203       
1204       // Bits are known zero if they are known zero in both operands and there
1205       // is no input carry.
1206       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1207     } else {
1208       // If the high-bits of this ADD are not demanded, then it does not demand
1209       // the high bits of its LHS or RHS.
1210       if (DemandedMask[BitWidth-1] == 0) {
1211         // Right fill the mask of bits for this ADD to demand the most
1212         // significant bit and all those below it.
1213         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1214         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1215                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1216             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1217                                  LHSKnownZero, LHSKnownOne, Depth+1))
1218           return I;
1219       }
1220     }
1221     break;
1222   }
1223   case Instruction::Sub:
1224     // If the high-bits of this SUB are not demanded, then it does not demand
1225     // the high bits of its LHS or RHS.
1226     if (DemandedMask[BitWidth-1] == 0) {
1227       // Right fill the mask of bits for this SUB to demand the most
1228       // significant bit and all those below it.
1229       uint32_t NLZ = DemandedMask.countLeadingZeros();
1230       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1231       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1232                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1233           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1234                                LHSKnownZero, LHSKnownOne, Depth+1))
1235         return I;
1236     }
1237     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1238     // the known zeros and ones.
1239     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1240     break;
1241   case Instruction::Shl:
1242     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1243       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1244       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1245       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1246                                RHSKnownZero, RHSKnownOne, Depth+1))
1247         return I;
1248       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1249       RHSKnownZero <<= ShiftAmt;
1250       RHSKnownOne  <<= ShiftAmt;
1251       // low bits known zero.
1252       if (ShiftAmt)
1253         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1254     }
1255     break;
1256   case Instruction::LShr:
1257     // For a logical shift right
1258     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1259       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1260       
1261       // Unsigned shift right.
1262       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1263       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1264                                RHSKnownZero, RHSKnownOne, Depth+1))
1265         return I;
1266       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1267       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1268       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1269       if (ShiftAmt) {
1270         // Compute the new bits that are at the top now.
1271         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1272         RHSKnownZero |= HighBits;  // high bits known zero.
1273       }
1274     }
1275     break;
1276   case Instruction::AShr:
1277     // If this is an arithmetic shift right and only the low-bit is set, we can
1278     // always convert this into a logical shr, even if the shift amount is
1279     // variable.  The low bit of the shift cannot be an input sign bit unless
1280     // the shift amount is >= the size of the datatype, which is undefined.
1281     if (DemandedMask == 1) {
1282       // Perform the logical shift right.
1283       Instruction *NewVal = BinaryOperator::CreateLShr(
1284                         I->getOperand(0), I->getOperand(1), I->getName());
1285       return InsertNewInstBefore(NewVal, *I);
1286     }    
1287
1288     // If the sign bit is the only bit demanded by this ashr, then there is no
1289     // need to do it, the shift doesn't change the high bit.
1290     if (DemandedMask.isSignBit())
1291       return I->getOperand(0);
1292     
1293     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1294       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1295       
1296       // Signed shift right.
1297       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1298       // If any of the "high bits" are demanded, we should set the sign bit as
1299       // demanded.
1300       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1301         DemandedMaskIn.set(BitWidth-1);
1302       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1303                                RHSKnownZero, RHSKnownOne, Depth+1))
1304         return I;
1305       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1306       // Compute the new bits that are at the top now.
1307       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1308       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1309       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1310         
1311       // Handle the sign bits.
1312       APInt SignBit(APInt::getSignBit(BitWidth));
1313       // Adjust to where it is now in the mask.
1314       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1315         
1316       // If the input sign bit is known to be zero, or if none of the top bits
1317       // are demanded, turn this into an unsigned shift right.
1318       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1319           (HighBits & ~DemandedMask) == HighBits) {
1320         // Perform the logical shift right.
1321         Instruction *NewVal = BinaryOperator::CreateLShr(
1322                           I->getOperand(0), SA, I->getName());
1323         return InsertNewInstBefore(NewVal, *I);
1324       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1325         RHSKnownOne |= HighBits;
1326       }
1327     }
1328     break;
1329   case Instruction::SRem:
1330     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1331       APInt RA = Rem->getValue().abs();
1332       if (RA.isPowerOf2()) {
1333         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1334           return I->getOperand(0);
1335
1336         APInt LowBits = RA - 1;
1337         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1338         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1339                                  LHSKnownZero, LHSKnownOne, Depth+1))
1340           return I;
1341
1342         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1343           LHSKnownZero |= ~LowBits;
1344
1345         KnownZero |= LHSKnownZero & DemandedMask;
1346
1347         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1348       }
1349     }
1350     break;
1351   case Instruction::URem: {
1352     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1353     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1354     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1355                              KnownZero2, KnownOne2, Depth+1) ||
1356         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1357                              KnownZero2, KnownOne2, Depth+1))
1358       return I;
1359
1360     unsigned Leaders = KnownZero2.countLeadingOnes();
1361     Leaders = std::max(Leaders,
1362                        KnownZero2.countLeadingOnes());
1363     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1364     break;
1365   }
1366   case Instruction::Call:
1367     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1368       switch (II->getIntrinsicID()) {
1369       default: break;
1370       case Intrinsic::bswap: {
1371         // If the only bits demanded come from one byte of the bswap result,
1372         // just shift the input byte into position to eliminate the bswap.
1373         unsigned NLZ = DemandedMask.countLeadingZeros();
1374         unsigned NTZ = DemandedMask.countTrailingZeros();
1375           
1376         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1377         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1378         // have 14 leading zeros, round to 8.
1379         NLZ &= ~7;
1380         NTZ &= ~7;
1381         // If we need exactly one byte, we can do this transformation.
1382         if (BitWidth-NLZ-NTZ == 8) {
1383           unsigned ResultBit = NTZ;
1384           unsigned InputBit = BitWidth-NTZ-8;
1385           
1386           // Replace this with either a left or right shift to get the byte into
1387           // the right place.
1388           Instruction *NewVal;
1389           if (InputBit > ResultBit)
1390             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1391                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1392           else
1393             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1394                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1395           NewVal->takeName(I);
1396           return InsertNewInstBefore(NewVal, *I);
1397         }
1398           
1399         // TODO: Could compute known zero/one bits based on the input.
1400         break;
1401       }
1402       }
1403     }
1404     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1405     break;
1406   }
1407   
1408   // If the client is only demanding bits that we know, return the known
1409   // constant.
1410   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1411     return Constant::getIntegerValue(VTy, RHSKnownOne);
1412   return false;
1413 }
1414
1415
1416 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1417 /// any number of elements. DemandedElts contains the set of elements that are
1418 /// actually used by the caller.  This method analyzes which elements of the
1419 /// operand are undef and returns that information in UndefElts.
1420 ///
1421 /// If the information about demanded elements can be used to simplify the
1422 /// operation, the operation is simplified, then the resultant value is
1423 /// returned.  This returns null if no change was made.
1424 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1425                                                 APInt& UndefElts,
1426                                                 unsigned Depth) {
1427   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1428   APInt EltMask(APInt::getAllOnesValue(VWidth));
1429   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1430
1431   if (isa<UndefValue>(V)) {
1432     // If the entire vector is undefined, just return this info.
1433     UndefElts = EltMask;
1434     return 0;
1435   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1436     UndefElts = EltMask;
1437     return UndefValue::get(V->getType());
1438   }
1439
1440   UndefElts = 0;
1441   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1442     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1443     Constant *Undef = UndefValue::get(EltTy);
1444
1445     std::vector<Constant*> Elts;
1446     for (unsigned i = 0; i != VWidth; ++i)
1447       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1448         Elts.push_back(Undef);
1449         UndefElts.set(i);
1450       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1451         Elts.push_back(Undef);
1452         UndefElts.set(i);
1453       } else {                               // Otherwise, defined.
1454         Elts.push_back(CP->getOperand(i));
1455       }
1456
1457     // If we changed the constant, return it.
1458     Constant *NewCP = ConstantVector::get(Elts);
1459     return NewCP != CP ? NewCP : 0;
1460   } else if (isa<ConstantAggregateZero>(V)) {
1461     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1462     // set to undef.
1463     
1464     // Check if this is identity. If so, return 0 since we are not simplifying
1465     // anything.
1466     if (DemandedElts == ((1ULL << VWidth) -1))
1467       return 0;
1468     
1469     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1470     Constant *Zero = Constant::getNullValue(EltTy);
1471     Constant *Undef = UndefValue::get(EltTy);
1472     std::vector<Constant*> Elts;
1473     for (unsigned i = 0; i != VWidth; ++i) {
1474       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1475       Elts.push_back(Elt);
1476     }
1477     UndefElts = DemandedElts ^ EltMask;
1478     return ConstantVector::get(Elts);
1479   }
1480   
1481   // Limit search depth.
1482   if (Depth == 10)
1483     return 0;
1484
1485   // If multiple users are using the root value, procede with
1486   // simplification conservatively assuming that all elements
1487   // are needed.
1488   if (!V->hasOneUse()) {
1489     // Quit if we find multiple users of a non-root value though.
1490     // They'll be handled when it's their turn to be visited by
1491     // the main instcombine process.
1492     if (Depth != 0)
1493       // TODO: Just compute the UndefElts information recursively.
1494       return 0;
1495
1496     // Conservatively assume that all elements are needed.
1497     DemandedElts = EltMask;
1498   }
1499   
1500   Instruction *I = dyn_cast<Instruction>(V);
1501   if (!I) return 0;        // Only analyze instructions.
1502   
1503   bool MadeChange = false;
1504   APInt UndefElts2(VWidth, 0);
1505   Value *TmpV;
1506   switch (I->getOpcode()) {
1507   default: break;
1508     
1509   case Instruction::InsertElement: {
1510     // If this is a variable index, we don't know which element it overwrites.
1511     // demand exactly the same input as we produce.
1512     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1513     if (Idx == 0) {
1514       // Note that we can't propagate undef elt info, because we don't know
1515       // which elt is getting updated.
1516       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1517                                         UndefElts2, Depth+1);
1518       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1519       break;
1520     }
1521     
1522     // If this is inserting an element that isn't demanded, remove this
1523     // insertelement.
1524     unsigned IdxNo = Idx->getZExtValue();
1525     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1526       return AddSoonDeadInstToWorklist(*I, 0);
1527     
1528     // Otherwise, the element inserted overwrites whatever was there, so the
1529     // input demanded set is simpler than the output set.
1530     APInt DemandedElts2 = DemandedElts;
1531     DemandedElts2.clear(IdxNo);
1532     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1533                                       UndefElts, Depth+1);
1534     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1535
1536     // The inserted element is defined.
1537     UndefElts.clear(IdxNo);
1538     break;
1539   }
1540   case Instruction::ShuffleVector: {
1541     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1542     uint64_t LHSVWidth =
1543       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1544     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1545     for (unsigned i = 0; i < VWidth; i++) {
1546       if (DemandedElts[i]) {
1547         unsigned MaskVal = Shuffle->getMaskValue(i);
1548         if (MaskVal != -1u) {
1549           assert(MaskVal < LHSVWidth * 2 &&
1550                  "shufflevector mask index out of range!");
1551           if (MaskVal < LHSVWidth)
1552             LeftDemanded.set(MaskVal);
1553           else
1554             RightDemanded.set(MaskVal - LHSVWidth);
1555         }
1556       }
1557     }
1558
1559     APInt UndefElts4(LHSVWidth, 0);
1560     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1561                                       UndefElts4, Depth+1);
1562     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1563
1564     APInt UndefElts3(LHSVWidth, 0);
1565     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1566                                       UndefElts3, Depth+1);
1567     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1568
1569     bool NewUndefElts = false;
1570     for (unsigned i = 0; i < VWidth; i++) {
1571       unsigned MaskVal = Shuffle->getMaskValue(i);
1572       if (MaskVal == -1u) {
1573         UndefElts.set(i);
1574       } else if (MaskVal < LHSVWidth) {
1575         if (UndefElts4[MaskVal]) {
1576           NewUndefElts = true;
1577           UndefElts.set(i);
1578         }
1579       } else {
1580         if (UndefElts3[MaskVal - LHSVWidth]) {
1581           NewUndefElts = true;
1582           UndefElts.set(i);
1583         }
1584       }
1585     }
1586
1587     if (NewUndefElts) {
1588       // Add additional discovered undefs.
1589       std::vector<Constant*> Elts;
1590       for (unsigned i = 0; i < VWidth; ++i) {
1591         if (UndefElts[i])
1592           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1593         else
1594           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1595                                           Shuffle->getMaskValue(i)));
1596       }
1597       I->setOperand(2, ConstantVector::get(Elts));
1598       MadeChange = true;
1599     }
1600     break;
1601   }
1602   case Instruction::BitCast: {
1603     // Vector->vector casts only.
1604     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1605     if (!VTy) break;
1606     unsigned InVWidth = VTy->getNumElements();
1607     APInt InputDemandedElts(InVWidth, 0);
1608     unsigned Ratio;
1609
1610     if (VWidth == InVWidth) {
1611       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1612       // elements as are demanded of us.
1613       Ratio = 1;
1614       InputDemandedElts = DemandedElts;
1615     } else if (VWidth > InVWidth) {
1616       // Untested so far.
1617       break;
1618       
1619       // If there are more elements in the result than there are in the source,
1620       // then an input element is live if any of the corresponding output
1621       // elements are live.
1622       Ratio = VWidth/InVWidth;
1623       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1624         if (DemandedElts[OutIdx])
1625           InputDemandedElts.set(OutIdx/Ratio);
1626       }
1627     } else {
1628       // Untested so far.
1629       break;
1630       
1631       // If there are more elements in the source than there are in the result,
1632       // then an input element is live if the corresponding output element is
1633       // live.
1634       Ratio = InVWidth/VWidth;
1635       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1636         if (DemandedElts[InIdx/Ratio])
1637           InputDemandedElts.set(InIdx);
1638     }
1639     
1640     // div/rem demand all inputs, because they don't want divide by zero.
1641     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1642                                       UndefElts2, Depth+1);
1643     if (TmpV) {
1644       I->setOperand(0, TmpV);
1645       MadeChange = true;
1646     }
1647     
1648     UndefElts = UndefElts2;
1649     if (VWidth > InVWidth) {
1650       llvm_unreachable("Unimp");
1651       // If there are more elements in the result than there are in the source,
1652       // then an output element is undef if the corresponding input element is
1653       // undef.
1654       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1655         if (UndefElts2[OutIdx/Ratio])
1656           UndefElts.set(OutIdx);
1657     } else if (VWidth < InVWidth) {
1658       llvm_unreachable("Unimp");
1659       // If there are more elements in the source than there are in the result,
1660       // then a result element is undef if all of the corresponding input
1661       // elements are undef.
1662       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1663       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1664         if (!UndefElts2[InIdx])            // Not undef?
1665           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1666     }
1667     break;
1668   }
1669   case Instruction::And:
1670   case Instruction::Or:
1671   case Instruction::Xor:
1672   case Instruction::Add:
1673   case Instruction::Sub:
1674   case Instruction::Mul:
1675     // div/rem demand all inputs, because they don't want divide by zero.
1676     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1677                                       UndefElts, Depth+1);
1678     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1679     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1680                                       UndefElts2, Depth+1);
1681     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1682       
1683     // Output elements are undefined if both are undefined.  Consider things
1684     // like undef&0.  The result is known zero, not undef.
1685     UndefElts &= UndefElts2;
1686     break;
1687     
1688   case Instruction::Call: {
1689     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1690     if (!II) break;
1691     switch (II->getIntrinsicID()) {
1692     default: break;
1693       
1694     // Binary vector operations that work column-wise.  A dest element is a
1695     // function of the corresponding input elements from the two inputs.
1696     case Intrinsic::x86_sse_sub_ss:
1697     case Intrinsic::x86_sse_mul_ss:
1698     case Intrinsic::x86_sse_min_ss:
1699     case Intrinsic::x86_sse_max_ss:
1700     case Intrinsic::x86_sse2_sub_sd:
1701     case Intrinsic::x86_sse2_mul_sd:
1702     case Intrinsic::x86_sse2_min_sd:
1703     case Intrinsic::x86_sse2_max_sd:
1704       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1705                                         UndefElts, Depth+1);
1706       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1707       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1708                                         UndefElts2, Depth+1);
1709       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1710
1711       // If only the low elt is demanded and this is a scalarizable intrinsic,
1712       // scalarize it now.
1713       if (DemandedElts == 1) {
1714         switch (II->getIntrinsicID()) {
1715         default: break;
1716         case Intrinsic::x86_sse_sub_ss:
1717         case Intrinsic::x86_sse_mul_ss:
1718         case Intrinsic::x86_sse2_sub_sd:
1719         case Intrinsic::x86_sse2_mul_sd:
1720           // TODO: Lower MIN/MAX/ABS/etc
1721           Value *LHS = II->getOperand(1);
1722           Value *RHS = II->getOperand(2);
1723           // Extract the element as scalars.
1724           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1725             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1726           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1727             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1728           
1729           switch (II->getIntrinsicID()) {
1730           default: llvm_unreachable("Case stmts out of sync!");
1731           case Intrinsic::x86_sse_sub_ss:
1732           case Intrinsic::x86_sse2_sub_sd:
1733             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1734                                                         II->getName()), *II);
1735             break;
1736           case Intrinsic::x86_sse_mul_ss:
1737           case Intrinsic::x86_sse2_mul_sd:
1738             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1739                                                          II->getName()), *II);
1740             break;
1741           }
1742           
1743           Instruction *New =
1744             InsertElementInst::Create(
1745               UndefValue::get(II->getType()), TmpV,
1746               ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1747           InsertNewInstBefore(New, *II);
1748           AddSoonDeadInstToWorklist(*II, 0);
1749           return New;
1750         }            
1751       }
1752         
1753       // Output elements are undefined if both are undefined.  Consider things
1754       // like undef&0.  The result is known zero, not undef.
1755       UndefElts &= UndefElts2;
1756       break;
1757     }
1758     break;
1759   }
1760   }
1761   return MadeChange ? I : 0;
1762 }
1763
1764
1765 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1766 /// function is designed to check a chain of associative operators for a
1767 /// potential to apply a certain optimization.  Since the optimization may be
1768 /// applicable if the expression was reassociated, this checks the chain, then
1769 /// reassociates the expression as necessary to expose the optimization
1770 /// opportunity.  This makes use of a special Functor, which must define
1771 /// 'shouldApply' and 'apply' methods.
1772 ///
1773 template<typename Functor>
1774 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1775   unsigned Opcode = Root.getOpcode();
1776   Value *LHS = Root.getOperand(0);
1777
1778   // Quick check, see if the immediate LHS matches...
1779   if (F.shouldApply(LHS))
1780     return F.apply(Root);
1781
1782   // Otherwise, if the LHS is not of the same opcode as the root, return.
1783   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1784   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1785     // Should we apply this transform to the RHS?
1786     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1787
1788     // If not to the RHS, check to see if we should apply to the LHS...
1789     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1790       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1791       ShouldApply = true;
1792     }
1793
1794     // If the functor wants to apply the optimization to the RHS of LHSI,
1795     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1796     if (ShouldApply) {
1797       // Now all of the instructions are in the current basic block, go ahead
1798       // and perform the reassociation.
1799       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1800
1801       // First move the selected RHS to the LHS of the root...
1802       Root.setOperand(0, LHSI->getOperand(1));
1803
1804       // Make what used to be the LHS of the root be the user of the root...
1805       Value *ExtraOperand = TmpLHSI->getOperand(1);
1806       if (&Root == TmpLHSI) {
1807         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1808         return 0;
1809       }
1810       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1811       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1812       BasicBlock::iterator ARI = &Root; ++ARI;
1813       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1814       ARI = Root;
1815
1816       // Now propagate the ExtraOperand down the chain of instructions until we
1817       // get to LHSI.
1818       while (TmpLHSI != LHSI) {
1819         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1820         // Move the instruction to immediately before the chain we are
1821         // constructing to avoid breaking dominance properties.
1822         NextLHSI->moveBefore(ARI);
1823         ARI = NextLHSI;
1824
1825         Value *NextOp = NextLHSI->getOperand(1);
1826         NextLHSI->setOperand(1, ExtraOperand);
1827         TmpLHSI = NextLHSI;
1828         ExtraOperand = NextOp;
1829       }
1830
1831       // Now that the instructions are reassociated, have the functor perform
1832       // the transformation...
1833       return F.apply(Root);
1834     }
1835
1836     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1837   }
1838   return 0;
1839 }
1840
1841 namespace {
1842
1843 // AddRHS - Implements: X + X --> X << 1
1844 struct AddRHS {
1845   Value *RHS;
1846   explicit AddRHS(Value *rhs) : RHS(rhs) {}
1847   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1848   Instruction *apply(BinaryOperator &Add) const {
1849     return BinaryOperator::CreateShl(Add.getOperand(0),
1850                                      ConstantInt::get(Add.getType(), 1));
1851   }
1852 };
1853
1854 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1855 //                 iff C1&C2 == 0
1856 struct AddMaskingAnd {
1857   Constant *C2;
1858   explicit AddMaskingAnd(Constant *c) : C2(c) {}
1859   bool shouldApply(Value *LHS) const {
1860     ConstantInt *C1;
1861     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1862            ConstantExpr::getAnd(C1, C2)->isNullValue();
1863   }
1864   Instruction *apply(BinaryOperator &Add) const {
1865     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1866   }
1867 };
1868
1869 }
1870
1871 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1872                                              InstCombiner *IC) {
1873   LLVMContext *Context = IC->getContext();
1874   
1875   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1876     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1877   }
1878
1879   // Figure out if the constant is the left or the right argument.
1880   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1881   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1882
1883   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1884     if (ConstIsRHS)
1885       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1886     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1887   }
1888
1889   Value *Op0 = SO, *Op1 = ConstOperand;
1890   if (!ConstIsRHS)
1891     std::swap(Op0, Op1);
1892   Instruction *New;
1893   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1894     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1895   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1896     New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1897                           Op0, Op1, SO->getName()+".cmp");
1898   else {
1899     llvm_unreachable("Unknown binary instruction type!");
1900   }
1901   return IC->InsertNewInstBefore(New, I);
1902 }
1903
1904 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1905 // constant as the other operand, try to fold the binary operator into the
1906 // select arguments.  This also works for Cast instructions, which obviously do
1907 // not have a second operand.
1908 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1909                                      InstCombiner *IC) {
1910   // Don't modify shared select instructions
1911   if (!SI->hasOneUse()) return 0;
1912   Value *TV = SI->getOperand(1);
1913   Value *FV = SI->getOperand(2);
1914
1915   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1916     // Bool selects with constant operands can be folded to logical ops.
1917     if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
1918
1919     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1920     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1921
1922     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1923                               SelectFalseVal);
1924   }
1925   return 0;
1926 }
1927
1928
1929 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1930 /// node as operand #0, see if we can fold the instruction into the PHI (which
1931 /// is only possible if all operands to the PHI are constants).
1932 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1933   PHINode *PN = cast<PHINode>(I.getOperand(0));
1934   unsigned NumPHIValues = PN->getNumIncomingValues();
1935   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1936
1937   // Check to see if all of the operands of the PHI are constants.  If there is
1938   // one non-constant value, remember the BB it is.  If there is more than one
1939   // or if *it* is a PHI, bail out.
1940   BasicBlock *NonConstBB = 0;
1941   for (unsigned i = 0; i != NumPHIValues; ++i)
1942     if (!isa<Constant>(PN->getIncomingValue(i))) {
1943       if (NonConstBB) return 0;  // More than one non-const value.
1944       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1945       NonConstBB = PN->getIncomingBlock(i);
1946       
1947       // If the incoming non-constant value is in I's block, we have an infinite
1948       // loop.
1949       if (NonConstBB == I.getParent())
1950         return 0;
1951     }
1952   
1953   // If there is exactly one non-constant value, we can insert a copy of the
1954   // operation in that block.  However, if this is a critical edge, we would be
1955   // inserting the computation one some other paths (e.g. inside a loop).  Only
1956   // do this if the pred block is unconditionally branching into the phi block.
1957   if (NonConstBB) {
1958     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1959     if (!BI || !BI->isUnconditional()) return 0;
1960   }
1961
1962   // Okay, we can do the transformation: create the new PHI node.
1963   PHINode *NewPN = PHINode::Create(I.getType(), "");
1964   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1965   InsertNewInstBefore(NewPN, *PN);
1966   NewPN->takeName(PN);
1967
1968   // Next, add all of the operands to the PHI.
1969   if (I.getNumOperands() == 2) {
1970     Constant *C = cast<Constant>(I.getOperand(1));
1971     for (unsigned i = 0; i != NumPHIValues; ++i) {
1972       Value *InV = 0;
1973       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1974         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1975           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1976         else
1977           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1978       } else {
1979         assert(PN->getIncomingBlock(i) == NonConstBB);
1980         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1981           InV = BinaryOperator::Create(BO->getOpcode(),
1982                                        PN->getIncomingValue(i), C, "phitmp",
1983                                        NonConstBB->getTerminator());
1984         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1985           InV = CmpInst::Create(*Context, CI->getOpcode(), 
1986                                 CI->getPredicate(),
1987                                 PN->getIncomingValue(i), C, "phitmp",
1988                                 NonConstBB->getTerminator());
1989         else
1990           llvm_unreachable("Unknown binop!");
1991         
1992         AddToWorkList(cast<Instruction>(InV));
1993       }
1994       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1995     }
1996   } else { 
1997     CastInst *CI = cast<CastInst>(&I);
1998     const Type *RetTy = CI->getType();
1999     for (unsigned i = 0; i != NumPHIValues; ++i) {
2000       Value *InV;
2001       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2002         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2003       } else {
2004         assert(PN->getIncomingBlock(i) == NonConstBB);
2005         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2006                                I.getType(), "phitmp", 
2007                                NonConstBB->getTerminator());
2008         AddToWorkList(cast<Instruction>(InV));
2009       }
2010       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2011     }
2012   }
2013   return ReplaceInstUsesWith(I, NewPN);
2014 }
2015
2016
2017 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2018 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2019 /// This basically requires proving that the add in the original type would not
2020 /// overflow to change the sign bit or have a carry out.
2021 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2022   // There are different heuristics we can use for this.  Here are some simple
2023   // ones.
2024   
2025   // Add has the property that adding any two 2's complement numbers can only 
2026   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2027   // have at least two sign bits, we know that the addition of the two values will
2028   // sign extend fine.
2029   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2030     return true;
2031   
2032   
2033   // If one of the operands only has one non-zero bit, and if the other operand
2034   // has a known-zero bit in a more significant place than it (not including the
2035   // sign bit) the ripple may go up to and fill the zero, but won't change the
2036   // sign.  For example, (X & ~4) + 1.
2037   
2038   // TODO: Implement.
2039   
2040   return false;
2041 }
2042
2043
2044 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2045   bool Changed = SimplifyCommutative(I);
2046   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2047
2048   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2049     // X + undef -> undef
2050     if (isa<UndefValue>(RHS))
2051       return ReplaceInstUsesWith(I, RHS);
2052
2053     // X + 0 --> X
2054     if (RHSC->isNullValue())
2055       return ReplaceInstUsesWith(I, LHS);
2056
2057     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2058       // X + (signbit) --> X ^ signbit
2059       const APInt& Val = CI->getValue();
2060       uint32_t BitWidth = Val.getBitWidth();
2061       if (Val == APInt::getSignBit(BitWidth))
2062         return BinaryOperator::CreateXor(LHS, RHS);
2063       
2064       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2065       // (X & 254)+1 -> (X&254)|1
2066       if (SimplifyDemandedInstructionBits(I))
2067         return &I;
2068
2069       // zext(bool) + C -> bool ? C + 1 : C
2070       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2071         if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2072           return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2073     }
2074
2075     if (isa<PHINode>(LHS))
2076       if (Instruction *NV = FoldOpIntoPhi(I))
2077         return NV;
2078     
2079     ConstantInt *XorRHS = 0;
2080     Value *XorLHS = 0;
2081     if (isa<ConstantInt>(RHSC) &&
2082         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2083       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2084       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2085       
2086       uint32_t Size = TySizeBits / 2;
2087       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2088       APInt CFF80Val(-C0080Val);
2089       do {
2090         if (TySizeBits > Size) {
2091           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2092           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2093           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2094               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2095             // This is a sign extend if the top bits are known zero.
2096             if (!MaskedValueIsZero(XorLHS, 
2097                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2098               Size = 0;  // Not a sign ext, but can't be any others either.
2099             break;
2100           }
2101         }
2102         Size >>= 1;
2103         C0080Val = APIntOps::lshr(C0080Val, Size);
2104         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2105       } while (Size >= 1);
2106       
2107       // FIXME: This shouldn't be necessary. When the backends can handle types
2108       // with funny bit widths then this switch statement should be removed. It
2109       // is just here to get the size of the "middle" type back up to something
2110       // that the back ends can handle.
2111       const Type *MiddleType = 0;
2112       switch (Size) {
2113         default: break;
2114         case 32: MiddleType = Type::getInt32Ty(*Context); break;
2115         case 16: MiddleType = Type::getInt16Ty(*Context); break;
2116         case  8: MiddleType = Type::getInt8Ty(*Context); break;
2117       }
2118       if (MiddleType) {
2119         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2120         InsertNewInstBefore(NewTrunc, I);
2121         return new SExtInst(NewTrunc, I.getType(), I.getName());
2122       }
2123     }
2124   }
2125
2126   if (I.getType() == Type::getInt1Ty(*Context))
2127     return BinaryOperator::CreateXor(LHS, RHS);
2128
2129   // X + X --> X << 1
2130   if (I.getType()->isInteger()) {
2131     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2132       return Result;
2133
2134     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2135       if (RHSI->getOpcode() == Instruction::Sub)
2136         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2137           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2138     }
2139     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2140       if (LHSI->getOpcode() == Instruction::Sub)
2141         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2142           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2143     }
2144   }
2145
2146   // -A + B  -->  B - A
2147   // -A + -B  -->  -(A + B)
2148   if (Value *LHSV = dyn_castNegVal(LHS)) {
2149     if (LHS->getType()->isIntOrIntVector()) {
2150       if (Value *RHSV = dyn_castNegVal(RHS)) {
2151         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2152         InsertNewInstBefore(NewAdd, I);
2153         return BinaryOperator::CreateNeg(NewAdd);
2154       }
2155     }
2156     
2157     return BinaryOperator::CreateSub(RHS, LHSV);
2158   }
2159
2160   // A + -B  -->  A - B
2161   if (!isa<Constant>(RHS))
2162     if (Value *V = dyn_castNegVal(RHS))
2163       return BinaryOperator::CreateSub(LHS, V);
2164
2165
2166   ConstantInt *C2;
2167   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2168     if (X == RHS)   // X*C + X --> X * (C+1)
2169       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2170
2171     // X*C1 + X*C2 --> X * (C1+C2)
2172     ConstantInt *C1;
2173     if (X == dyn_castFoldableMul(RHS, C1))
2174       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2175   }
2176
2177   // X + X*C --> X * (C+1)
2178   if (dyn_castFoldableMul(RHS, C2) == LHS)
2179     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2180
2181   // X + ~X --> -1   since   ~X = -X-1
2182   if (dyn_castNotVal(LHS) == RHS ||
2183       dyn_castNotVal(RHS) == LHS)
2184     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2185   
2186
2187   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2188   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2189     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2190       return R;
2191   
2192   // A+B --> A|B iff A and B have no bits set in common.
2193   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2194     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2195     APInt LHSKnownOne(IT->getBitWidth(), 0);
2196     APInt LHSKnownZero(IT->getBitWidth(), 0);
2197     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2198     if (LHSKnownZero != 0) {
2199       APInt RHSKnownOne(IT->getBitWidth(), 0);
2200       APInt RHSKnownZero(IT->getBitWidth(), 0);
2201       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2202       
2203       // No bits in common -> bitwise or.
2204       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2205         return BinaryOperator::CreateOr(LHS, RHS);
2206     }
2207   }
2208
2209   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2210   if (I.getType()->isIntOrIntVector()) {
2211     Value *W, *X, *Y, *Z;
2212     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2213         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2214       if (W != Y) {
2215         if (W == Z) {
2216           std::swap(Y, Z);
2217         } else if (Y == X) {
2218           std::swap(W, X);
2219         } else if (X == Z) {
2220           std::swap(Y, Z);
2221           std::swap(W, X);
2222         }
2223       }
2224
2225       if (W == Y) {
2226         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2227                                                             LHS->getName()), I);
2228         return BinaryOperator::CreateMul(W, NewAdd);
2229       }
2230     }
2231   }
2232
2233   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2234     Value *X = 0;
2235     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2236       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2237
2238     // (X & FF00) + xx00  -> (X+xx00) & FF00
2239     if (LHS->hasOneUse() &&
2240         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2241       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2242       if (Anded == CRHS) {
2243         // See if all bits from the first bit set in the Add RHS up are included
2244         // in the mask.  First, get the rightmost bit.
2245         const APInt& AddRHSV = CRHS->getValue();
2246
2247         // Form a mask of all bits from the lowest bit added through the top.
2248         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2249
2250         // See if the and mask includes all of these bits.
2251         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2252
2253         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2254           // Okay, the xform is safe.  Insert the new add pronto.
2255           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2256                                                             LHS->getName()), I);
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         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2306                                                         CI, "addconv");
2307         InsertNewInstBefore(NewAdd, I);
2308         return new SExtInst(NewAdd, I.getType());
2309       }
2310     }
2311     
2312     // (add (sext x), (sext y)) --> (sext (add int x, y))
2313     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2314       // Only do this if x/y have the same type, if at last one of them has a
2315       // single use (so we don't increase the number of sexts), and if the
2316       // integer add will not overflow.
2317       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2318           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2319           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2320                                    RHSConv->getOperand(0))) {
2321         // Insert the new integer add.
2322         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2323                                                         RHSConv->getOperand(0),
2324                                                         "addconv");
2325         InsertNewInstBefore(NewAdd, I);
2326         return new SExtInst(NewAdd, I.getType());
2327       }
2328     }
2329   }
2330
2331   return Changed ? &I : 0;
2332 }
2333
2334 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2335   bool Changed = SimplifyCommutative(I);
2336   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2337
2338   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2339     // X + 0 --> X
2340     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2341       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2342                               (I.getType())->getValueAPF()))
2343         return ReplaceInstUsesWith(I, LHS);
2344     }
2345
2346     if (isa<PHINode>(LHS))
2347       if (Instruction *NV = FoldOpIntoPhi(I))
2348         return NV;
2349   }
2350
2351   // -A + B  -->  B - A
2352   // -A + -B  -->  -(A + B)
2353   if (Value *LHSV = dyn_castFNegVal(LHS))
2354     return BinaryOperator::CreateFSub(RHS, LHSV);
2355
2356   // A + -B  -->  A - B
2357   if (!isa<Constant>(RHS))
2358     if (Value *V = dyn_castFNegVal(RHS))
2359       return BinaryOperator::CreateFSub(LHS, V);
2360
2361   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2362   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2363     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2364       return ReplaceInstUsesWith(I, LHS);
2365
2366   // Check for (add double (sitofp x), y), see if we can merge this into an
2367   // integer add followed by a promotion.
2368   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2369     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2370     // ... if the constant fits in the integer value.  This is useful for things
2371     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2372     // requires a constant pool load, and generally allows the add to be better
2373     // instcombined.
2374     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2375       Constant *CI = 
2376       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2377       if (LHSConv->hasOneUse() &&
2378           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2379           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2380         // Insert the new integer add.
2381         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2382                                                         CI, "addconv");
2383         InsertNewInstBefore(NewAdd, I);
2384         return new SIToFPInst(NewAdd, I.getType());
2385       }
2386     }
2387     
2388     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2389     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2390       // Only do this if x/y have the same type, if at last one of them has a
2391       // single use (so we don't increase the number of int->fp conversions),
2392       // and if the integer add will not overflow.
2393       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2394           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2395           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2396                                    RHSConv->getOperand(0))) {
2397         // Insert the new integer add.
2398         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2399                                                         RHSConv->getOperand(0),
2400                                                         "addconv");
2401         InsertNewInstBefore(NewAdd, I);
2402         return new SIToFPInst(NewAdd, I.getType());
2403       }
2404     }
2405   }
2406   
2407   return Changed ? &I : 0;
2408 }
2409
2410 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2411   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2412
2413   if (Op0 == Op1)                        // sub X, X  -> 0
2414     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2415
2416   // If this is a 'B = x-(-A)', change to B = x+A...
2417   if (Value *V = dyn_castNegVal(Op1))
2418     return BinaryOperator::CreateAdd(Op0, V);
2419
2420   if (isa<UndefValue>(Op0))
2421     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2422   if (isa<UndefValue>(Op1))
2423     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2424
2425   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2426     // Replace (-1 - A) with (~A)...
2427     if (C->isAllOnesValue())
2428       return BinaryOperator::CreateNot(Op1);
2429
2430     // C - ~X == X + (1+C)
2431     Value *X = 0;
2432     if (match(Op1, m_Not(m_Value(X))))
2433       return BinaryOperator::CreateAdd(X, AddOne(C));
2434
2435     // -(X >>u 31) -> (X >>s 31)
2436     // -(X >>s 31) -> (X >>u 31)
2437     if (C->isZero()) {
2438       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2439         if (SI->getOpcode() == Instruction::LShr) {
2440           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2441             // Check to see if we are shifting out everything but the sign bit.
2442             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2443                 SI->getType()->getPrimitiveSizeInBits()-1) {
2444               // Ok, the transformation is safe.  Insert AShr.
2445               return BinaryOperator::Create(Instruction::AShr, 
2446                                           SI->getOperand(0), CU, SI->getName());
2447             }
2448           }
2449         }
2450         else if (SI->getOpcode() == Instruction::AShr) {
2451           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2452             // Check to see if we are shifting out everything but the sign bit.
2453             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2454                 SI->getType()->getPrimitiveSizeInBits()-1) {
2455               // Ok, the transformation is safe.  Insert LShr. 
2456               return BinaryOperator::CreateLShr(
2457                                           SI->getOperand(0), CU, SI->getName());
2458             }
2459           }
2460         }
2461       }
2462     }
2463
2464     // Try to fold constant sub into select arguments.
2465     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2466       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2467         return R;
2468
2469     // C - zext(bool) -> bool ? C - 1 : C
2470     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2471       if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2472         return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2473   }
2474
2475   if (I.getType() == Type::getInt1Ty(*Context))
2476     return BinaryOperator::CreateXor(Op0, Op1);
2477
2478   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2479     if (Op1I->getOpcode() == Instruction::Add) {
2480       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2481         return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2482                                          I.getName());
2483       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2484         return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2485                                          I.getName());
2486       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2487         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2488           // C1-(X+C2) --> (C1-C2)-X
2489           return BinaryOperator::CreateSub(
2490             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2491       }
2492     }
2493
2494     if (Op1I->hasOneUse()) {
2495       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2496       // is not used by anyone else...
2497       //
2498       if (Op1I->getOpcode() == Instruction::Sub) {
2499         // Swap the two operands of the subexpr...
2500         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2501         Op1I->setOperand(0, IIOp1);
2502         Op1I->setOperand(1, IIOp0);
2503
2504         // Create the new top level add instruction...
2505         return BinaryOperator::CreateAdd(Op0, Op1);
2506       }
2507
2508       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2509       //
2510       if (Op1I->getOpcode() == Instruction::And &&
2511           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2512         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2513
2514         Value *NewNot =
2515           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2516         return BinaryOperator::CreateAnd(Op0, NewNot);
2517       }
2518
2519       // 0 - (X sdiv C)  -> (X sdiv -C)
2520       if (Op1I->getOpcode() == Instruction::SDiv)
2521         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2522           if (CSI->isZero())
2523             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2524               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2525                                           ConstantExpr::getNeg(DivRHS));
2526
2527       // X - X*C --> X * (1-C)
2528       ConstantInt *C2 = 0;
2529       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2530         Constant *CP1 = 
2531           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2532                                              C2);
2533         return BinaryOperator::CreateMul(Op0, CP1);
2534       }
2535     }
2536   }
2537
2538   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2539     if (Op0I->getOpcode() == Instruction::Add) {
2540       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2541         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2542       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2543         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2544     } else if (Op0I->getOpcode() == Instruction::Sub) {
2545       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2546         return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2547                                          I.getName());
2548     }
2549   }
2550
2551   ConstantInt *C1;
2552   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2553     if (X == Op1)  // X*C - X --> X * (C-1)
2554       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2555
2556     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2557     if (X == dyn_castFoldableMul(Op1, C2))
2558       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2559   }
2560   return 0;
2561 }
2562
2563 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2564   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2565
2566   // If this is a 'B = x-(-A)', change to B = x+A...
2567   if (Value *V = dyn_castFNegVal(Op1))
2568     return BinaryOperator::CreateFAdd(Op0, V);
2569
2570   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2571     if (Op1I->getOpcode() == Instruction::FAdd) {
2572       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2573         return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2574                                           I.getName());
2575       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2576         return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2577                                           I.getName());
2578     }
2579   }
2580
2581   return 0;
2582 }
2583
2584 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2585 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2586 /// TrueIfSigned if the result of the comparison is true when the input value is
2587 /// signed.
2588 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2589                            bool &TrueIfSigned) {
2590   switch (pred) {
2591   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2592     TrueIfSigned = true;
2593     return RHS->isZero();
2594   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2595     TrueIfSigned = true;
2596     return RHS->isAllOnesValue();
2597   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2598     TrueIfSigned = false;
2599     return RHS->isAllOnesValue();
2600   case ICmpInst::ICMP_UGT:
2601     // True if LHS u> RHS and RHS == high-bit-mask - 1
2602     TrueIfSigned = true;
2603     return RHS->getValue() ==
2604       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2605   case ICmpInst::ICMP_UGE: 
2606     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2607     TrueIfSigned = true;
2608     return RHS->getValue().isSignBit();
2609   default:
2610     return false;
2611   }
2612 }
2613
2614 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2615   bool Changed = SimplifyCommutative(I);
2616   Value *Op0 = I.getOperand(0);
2617
2618   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2619     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2620
2621   // Simplify mul instructions with a constant RHS...
2622   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2623     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2624
2625       // ((X << C1)*C2) == (X * (C2 << C1))
2626       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2627         if (SI->getOpcode() == Instruction::Shl)
2628           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2629             return BinaryOperator::CreateMul(SI->getOperand(0),
2630                                         ConstantExpr::getShl(CI, ShOp));
2631
2632       if (CI->isZero())
2633         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2634       if (CI->equalsInt(1))                  // X * 1  == X
2635         return ReplaceInstUsesWith(I, Op0);
2636       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2637         return BinaryOperator::CreateNeg(Op0, I.getName());
2638
2639       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2640       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2641         return BinaryOperator::CreateShl(Op0,
2642                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2643       }
2644     } else if (isa<VectorType>(Op1->getType())) {
2645       if (Op1->isNullValue())
2646         return ReplaceInstUsesWith(I, Op1);
2647
2648       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2649         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2650           return BinaryOperator::CreateNeg(Op0, I.getName());
2651
2652         // As above, vector X*splat(1.0) -> X in all defined cases.
2653         if (Constant *Splat = Op1V->getSplatValue()) {
2654           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2655             if (CI->equalsInt(1))
2656               return ReplaceInstUsesWith(I, Op0);
2657         }
2658       }
2659     }
2660     
2661     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2662       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2663           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2664         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2665         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2666                                                      Op1, "tmp");
2667         InsertNewInstBefore(Add, I);
2668         Value *C1C2 = ConstantExpr::getMul(Op1, 
2669                                            cast<Constant>(Op0I->getOperand(1)));
2670         return BinaryOperator::CreateAdd(Add, C1C2);
2671         
2672       }
2673
2674     // Try to fold constant mul into select arguments.
2675     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2676       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2677         return R;
2678
2679     if (isa<PHINode>(Op0))
2680       if (Instruction *NV = FoldOpIntoPhi(I))
2681         return NV;
2682   }
2683
2684   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2685     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2686       return BinaryOperator::CreateMul(Op0v, Op1v);
2687
2688   // (X / Y) *  Y = X - (X % Y)
2689   // (X / Y) * -Y = (X % Y) - X
2690   {
2691     Value *Op1 = I.getOperand(1);
2692     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2693     if (!BO ||
2694         (BO->getOpcode() != Instruction::UDiv && 
2695          BO->getOpcode() != Instruction::SDiv)) {
2696       Op1 = Op0;
2697       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2698     }
2699     Value *Neg = dyn_castNegVal(Op1);
2700     if (BO && BO->hasOneUse() &&
2701         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2702         (BO->getOpcode() == Instruction::UDiv ||
2703          BO->getOpcode() == Instruction::SDiv)) {
2704       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2705
2706       // If the division is exact, X % Y is zero.
2707       if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2708         if (SDiv->isExact()) {
2709           if (Op1BO == Op1)
2710             return ReplaceInstUsesWith(I, Op0BO);
2711           else
2712             return BinaryOperator::CreateNeg(Op0BO);
2713         }
2714
2715       Instruction *Rem;
2716       if (BO->getOpcode() == Instruction::UDiv)
2717         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2718       else
2719         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2720
2721       InsertNewInstBefore(Rem, I);
2722       Rem->takeName(BO);
2723
2724       if (Op1BO == Op1)
2725         return BinaryOperator::CreateSub(Op0BO, Rem);
2726       else
2727         return BinaryOperator::CreateSub(Rem, Op0BO);
2728     }
2729   }
2730
2731   if (I.getType() == Type::getInt1Ty(*Context))
2732     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2733
2734   // If one of the operands of the multiply is a cast from a boolean value, then
2735   // we know the bool is either zero or one, so this is a 'masking' multiply.
2736   // See if we can simplify things based on how the boolean was originally
2737   // formed.
2738   CastInst *BoolCast = 0;
2739   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2740     if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2741       BoolCast = CI;
2742   if (!BoolCast)
2743     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2744       if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2745         BoolCast = CI;
2746   if (BoolCast) {
2747     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2748       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2749       const Type *SCOpTy = SCIOp0->getType();
2750       bool TIS = false;
2751       
2752       // If the icmp is true iff the sign bit of X is set, then convert this
2753       // multiply into a shift/and combination.
2754       if (isa<ConstantInt>(SCIOp1) &&
2755           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2756           TIS) {
2757         // Shift the X value right to turn it into "all signbits".
2758         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2759                                           SCOpTy->getPrimitiveSizeInBits()-1);
2760         Value *V =
2761           InsertNewInstBefore(
2762             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2763                                             BoolCast->getOperand(0)->getName()+
2764                                             ".mask"), I);
2765
2766         // If the multiply type is not the same as the source type, sign extend
2767         // or truncate to the multiply type.
2768         if (I.getType() != V->getType()) {
2769           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2770           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2771           Instruction::CastOps opcode = 
2772             (SrcBits == DstBits ? Instruction::BitCast : 
2773              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2774           V = InsertCastBefore(opcode, V, I.getType(), I);
2775         }
2776
2777         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2778         return BinaryOperator::CreateAnd(V, OtherOp);
2779       }
2780     }
2781   }
2782
2783   return Changed ? &I : 0;
2784 }
2785
2786 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2787   bool Changed = SimplifyCommutative(I);
2788   Value *Op0 = I.getOperand(0);
2789
2790   // Simplify mul instructions with a constant RHS...
2791   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2792     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2793       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2794       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2795       if (Op1F->isExactlyValue(1.0))
2796         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2797     } else if (isa<VectorType>(Op1->getType())) {
2798       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2799         // As above, vector X*splat(1.0) -> X in all defined cases.
2800         if (Constant *Splat = Op1V->getSplatValue()) {
2801           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2802             if (F->isExactlyValue(1.0))
2803               return ReplaceInstUsesWith(I, Op0);
2804         }
2805       }
2806     }
2807
2808     // Try to fold constant mul into select arguments.
2809     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2810       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2811         return R;
2812
2813     if (isa<PHINode>(Op0))
2814       if (Instruction *NV = FoldOpIntoPhi(I))
2815         return NV;
2816   }
2817
2818   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
2819     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2820       return BinaryOperator::CreateFMul(Op0v, Op1v);
2821
2822   return Changed ? &I : 0;
2823 }
2824
2825 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2826 /// instruction.
2827 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2828   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2829   
2830   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2831   int NonNullOperand = -1;
2832   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2833     if (ST->isNullValue())
2834       NonNullOperand = 2;
2835   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2836   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2837     if (ST->isNullValue())
2838       NonNullOperand = 1;
2839   
2840   if (NonNullOperand == -1)
2841     return false;
2842   
2843   Value *SelectCond = SI->getOperand(0);
2844   
2845   // Change the div/rem to use 'Y' instead of the select.
2846   I.setOperand(1, SI->getOperand(NonNullOperand));
2847   
2848   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2849   // problem.  However, the select, or the condition of the select may have
2850   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2851   // propagate the known value for the select into other uses of it, and
2852   // propagate a known value of the condition into its other users.
2853   
2854   // If the select and condition only have a single use, don't bother with this,
2855   // early exit.
2856   if (SI->use_empty() && SelectCond->hasOneUse())
2857     return true;
2858   
2859   // Scan the current block backward, looking for other uses of SI.
2860   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2861   
2862   while (BBI != BBFront) {
2863     --BBI;
2864     // If we found a call to a function, we can't assume it will return, so
2865     // information from below it cannot be propagated above it.
2866     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2867       break;
2868     
2869     // Replace uses of the select or its condition with the known values.
2870     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2871          I != E; ++I) {
2872       if (*I == SI) {
2873         *I = SI->getOperand(NonNullOperand);
2874         AddToWorkList(BBI);
2875       } else if (*I == SelectCond) {
2876         *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2877                                    ConstantInt::getFalse(*Context);
2878         AddToWorkList(BBI);
2879       }
2880     }
2881     
2882     // If we past the instruction, quit looking for it.
2883     if (&*BBI == SI)
2884       SI = 0;
2885     if (&*BBI == SelectCond)
2886       SelectCond = 0;
2887     
2888     // If we ran out of things to eliminate, break out of the loop.
2889     if (SelectCond == 0 && SI == 0)
2890       break;
2891     
2892   }
2893   return true;
2894 }
2895
2896
2897 /// This function implements the transforms on div instructions that work
2898 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2899 /// used by the visitors to those instructions.
2900 /// @brief Transforms common to all three div instructions
2901 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2902   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2903
2904   // undef / X -> 0        for integer.
2905   // undef / X -> undef    for FP (the undef could be a snan).
2906   if (isa<UndefValue>(Op0)) {
2907     if (Op0->getType()->isFPOrFPVector())
2908       return ReplaceInstUsesWith(I, Op0);
2909     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2910   }
2911
2912   // X / undef -> undef
2913   if (isa<UndefValue>(Op1))
2914     return ReplaceInstUsesWith(I, Op1);
2915
2916   return 0;
2917 }
2918
2919 /// This function implements the transforms common to both integer division
2920 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2921 /// division instructions.
2922 /// @brief Common integer divide transforms
2923 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2924   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2925
2926   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2927   if (Op0 == Op1) {
2928     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2929       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2930       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2931       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2932     }
2933
2934     Constant *CI = ConstantInt::get(I.getType(), 1);
2935     return ReplaceInstUsesWith(I, CI);
2936   }
2937   
2938   if (Instruction *Common = commonDivTransforms(I))
2939     return Common;
2940   
2941   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2942   // This does not apply for fdiv.
2943   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2944     return &I;
2945
2946   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2947     // div X, 1 == X
2948     if (RHS->equalsInt(1))
2949       return ReplaceInstUsesWith(I, Op0);
2950
2951     // (X / C1) / C2  -> X / (C1*C2)
2952     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2953       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2954         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2955           if (MultiplyOverflows(RHS, LHSRHS,
2956                                 I.getOpcode()==Instruction::SDiv))
2957             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2958           else 
2959             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2960                                       ConstantExpr::getMul(RHS, LHSRHS));
2961         }
2962
2963     if (!RHS->isZero()) { // avoid X udiv 0
2964       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2965         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2966           return R;
2967       if (isa<PHINode>(Op0))
2968         if (Instruction *NV = FoldOpIntoPhi(I))
2969           return NV;
2970     }
2971   }
2972
2973   // 0 / X == 0, we don't need to preserve faults!
2974   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2975     if (LHS->equalsInt(0))
2976       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2977
2978   // It can't be division by zero, hence it must be division by one.
2979   if (I.getType() == Type::getInt1Ty(*Context))
2980     return ReplaceInstUsesWith(I, Op0);
2981
2982   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2983     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2984       // div X, 1 == X
2985       if (X->isOne())
2986         return ReplaceInstUsesWith(I, Op0);
2987   }
2988
2989   return 0;
2990 }
2991
2992 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2993   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2994
2995   // Handle the integer div common cases
2996   if (Instruction *Common = commonIDivTransforms(I))
2997     return Common;
2998
2999   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3000     // X udiv C^2 -> X >> C
3001     // Check to see if this is an unsigned division with an exact power of 2,
3002     // if so, convert to a right shift.
3003     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3004       return BinaryOperator::CreateLShr(Op0, 
3005             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3006
3007     // X udiv C, where C >= signbit
3008     if (C->getValue().isNegative()) {
3009       Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3010                                                     ICmpInst::ICMP_ULT, Op0, C),
3011                                       I);
3012       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3013                                 ConstantInt::get(I.getType(), 1));
3014     }
3015   }
3016
3017   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3018   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3019     if (RHSI->getOpcode() == Instruction::Shl &&
3020         isa<ConstantInt>(RHSI->getOperand(0))) {
3021       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3022       if (C1.isPowerOf2()) {
3023         Value *N = RHSI->getOperand(1);
3024         const Type *NTy = N->getType();
3025         if (uint32_t C2 = C1.logBase2()) {
3026           Constant *C2V = ConstantInt::get(NTy, C2);
3027           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3028         }
3029         return BinaryOperator::CreateLShr(Op0, N);
3030       }
3031     }
3032   }
3033   
3034   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3035   // where C1&C2 are powers of two.
3036   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3037     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3038       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3039         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3040         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3041           // Compute the shift amounts
3042           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3043           // Construct the "on true" case of the select
3044           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3045           Instruction *TSI = BinaryOperator::CreateLShr(
3046                                                  Op0, TC, SI->getName()+".t");
3047           TSI = InsertNewInstBefore(TSI, I);
3048   
3049           // Construct the "on false" case of the select
3050           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3051           Instruction *FSI = BinaryOperator::CreateLShr(
3052                                                  Op0, FC, SI->getName()+".f");
3053           FSI = InsertNewInstBefore(FSI, I);
3054
3055           // construct the select instruction and return it.
3056           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3057         }
3058       }
3059   return 0;
3060 }
3061
3062 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3063   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3064
3065   // Handle the integer div common cases
3066   if (Instruction *Common = commonIDivTransforms(I))
3067     return Common;
3068
3069   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3070     // sdiv X, -1 == -X
3071     if (RHS->isAllOnesValue())
3072       return BinaryOperator::CreateNeg(Op0);
3073
3074     // sdiv X, C  -->  ashr X, log2(C)
3075     if (cast<SDivOperator>(&I)->isExact() &&
3076         RHS->getValue().isNonNegative() &&
3077         RHS->getValue().isPowerOf2()) {
3078       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3079                                             RHS->getValue().exactLogBase2());
3080       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3081     }
3082
3083     // -X/C  -->  X/-C  provided the negation doesn't overflow.
3084     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3085       if (isa<Constant>(Sub->getOperand(0)) &&
3086           cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3087           Sub->hasNoSignedOverflow())
3088         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3089                                           ConstantExpr::getNeg(RHS));
3090   }
3091
3092   // If the sign bits of both operands are zero (i.e. we can prove they are
3093   // unsigned inputs), turn this into a udiv.
3094   if (I.getType()->isInteger()) {
3095     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3096     if (MaskedValueIsZero(Op0, Mask)) {
3097       if (MaskedValueIsZero(Op1, Mask)) {
3098         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3099         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3100       }
3101       ConstantInt *ShiftedInt;
3102       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3103           ShiftedInt->getValue().isPowerOf2()) {
3104         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3105         // Safe because the only negative value (1 << Y) can take on is
3106         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3107         // the sign bit set.
3108         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3109       }
3110     }
3111   }
3112   
3113   return 0;
3114 }
3115
3116 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3117   return commonDivTransforms(I);
3118 }
3119
3120 /// This function implements the transforms on rem instructions that work
3121 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3122 /// is used by the visitors to those instructions.
3123 /// @brief Transforms common to all three rem instructions
3124 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3125   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3126
3127   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3128     if (I.getType()->isFPOrFPVector())
3129       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3130     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3131   }
3132   if (isa<UndefValue>(Op1))
3133     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3134
3135   // Handle cases involving: rem X, (select Cond, Y, Z)
3136   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3137     return &I;
3138
3139   return 0;
3140 }
3141
3142 /// This function implements the transforms common to both integer remainder
3143 /// instructions (urem and srem). It is called by the visitors to those integer
3144 /// remainder instructions.
3145 /// @brief Common integer remainder transforms
3146 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3147   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3148
3149   if (Instruction *common = commonRemTransforms(I))
3150     return common;
3151
3152   // 0 % X == 0 for integer, we don't need to preserve faults!
3153   if (Constant *LHS = dyn_cast<Constant>(Op0))
3154     if (LHS->isNullValue())
3155       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3156
3157   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3158     // X % 0 == undef, we don't need to preserve faults!
3159     if (RHS->equalsInt(0))
3160       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3161     
3162     if (RHS->equalsInt(1))  // X % 1 == 0
3163       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3164
3165     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3166       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3167         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3168           return R;
3169       } else if (isa<PHINode>(Op0I)) {
3170         if (Instruction *NV = FoldOpIntoPhi(I))
3171           return NV;
3172       }
3173
3174       // See if we can fold away this rem instruction.
3175       if (SimplifyDemandedInstructionBits(I))
3176         return &I;
3177     }
3178   }
3179
3180   return 0;
3181 }
3182
3183 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3184   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3185
3186   if (Instruction *common = commonIRemTransforms(I))
3187     return common;
3188   
3189   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3190     // X urem C^2 -> X and C
3191     // Check to see if this is an unsigned remainder with an exact power of 2,
3192     // if so, convert to a bitwise and.
3193     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3194       if (C->getValue().isPowerOf2())
3195         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3196   }
3197
3198   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3199     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3200     if (RHSI->getOpcode() == Instruction::Shl &&
3201         isa<ConstantInt>(RHSI->getOperand(0))) {
3202       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3203         Constant *N1 = Constant::getAllOnesValue(I.getType());
3204         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3205                                                                    "tmp"), I);
3206         return BinaryOperator::CreateAnd(Op0, Add);
3207       }
3208     }
3209   }
3210
3211   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3212   // where C1&C2 are powers of two.
3213   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3214     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3215       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3216         // STO == 0 and SFO == 0 handled above.
3217         if ((STO->getValue().isPowerOf2()) && 
3218             (SFO->getValue().isPowerOf2())) {
3219           Value *TrueAnd = InsertNewInstBefore(
3220             BinaryOperator::CreateAnd(Op0, SubOne(STO),
3221                                       SI->getName()+".t"), I);
3222           Value *FalseAnd = InsertNewInstBefore(
3223             BinaryOperator::CreateAnd(Op0, SubOne(SFO),
3224                                       SI->getName()+".f"), I);
3225           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3226         }
3227       }
3228   }
3229   
3230   return 0;
3231 }
3232
3233 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3234   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3235
3236   // Handle the integer rem common cases
3237   if (Instruction *common = commonIRemTransforms(I))
3238     return common;
3239   
3240   if (Value *RHSNeg = dyn_castNegVal(Op1))
3241     if (!isa<Constant>(RHSNeg) ||
3242         (isa<ConstantInt>(RHSNeg) &&
3243          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3244       // X % -Y -> X % Y
3245       AddUsesToWorkList(I);
3246       I.setOperand(1, RHSNeg);
3247       return &I;
3248     }
3249
3250   // If the sign bits of both operands are zero (i.e. we can prove they are
3251   // unsigned inputs), turn this into a urem.
3252   if (I.getType()->isInteger()) {
3253     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3254     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3255       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3256       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3257     }
3258   }
3259
3260   // If it's a constant vector, flip any negative values positive.
3261   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3262     unsigned VWidth = RHSV->getNumOperands();
3263
3264     bool hasNegative = false;
3265     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3266       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3267         if (RHS->getValue().isNegative())
3268           hasNegative = true;
3269
3270     if (hasNegative) {
3271       std::vector<Constant *> Elts(VWidth);
3272       for (unsigned i = 0; i != VWidth; ++i) {
3273         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3274           if (RHS->getValue().isNegative())
3275             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3276           else
3277             Elts[i] = RHS;
3278         }
3279       }
3280
3281       Constant *NewRHSV = ConstantVector::get(Elts);
3282       if (NewRHSV != RHSV) {
3283         AddUsesToWorkList(I);
3284         I.setOperand(1, NewRHSV);
3285         return &I;
3286       }
3287     }
3288   }
3289
3290   return 0;
3291 }
3292
3293 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3294   return commonRemTransforms(I);
3295 }
3296
3297 // isOneBitSet - Return true if there is exactly one bit set in the specified
3298 // constant.
3299 static bool isOneBitSet(const ConstantInt *CI) {
3300   return CI->getValue().isPowerOf2();
3301 }
3302
3303 // isHighOnes - Return true if the constant is of the form 1+0+.
3304 // This is the same as lowones(~X).
3305 static bool isHighOnes(const ConstantInt *CI) {
3306   return (~CI->getValue() + 1).isPowerOf2();
3307 }
3308
3309 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3310 /// are carefully arranged to allow folding of expressions such as:
3311 ///
3312 ///      (A < B) | (A > B) --> (A != B)
3313 ///
3314 /// Note that this is only valid if the first and second predicates have the
3315 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3316 ///
3317 /// Three bits are used to represent the condition, as follows:
3318 ///   0  A > B
3319 ///   1  A == B
3320 ///   2  A < B
3321 ///
3322 /// <=>  Value  Definition
3323 /// 000     0   Always false
3324 /// 001     1   A >  B
3325 /// 010     2   A == B
3326 /// 011     3   A >= B
3327 /// 100     4   A <  B
3328 /// 101     5   A != B
3329 /// 110     6   A <= B
3330 /// 111     7   Always true
3331 ///  
3332 static unsigned getICmpCode(const ICmpInst *ICI) {
3333   switch (ICI->getPredicate()) {
3334     // False -> 0
3335   case ICmpInst::ICMP_UGT: return 1;  // 001
3336   case ICmpInst::ICMP_SGT: return 1;  // 001
3337   case ICmpInst::ICMP_EQ:  return 2;  // 010
3338   case ICmpInst::ICMP_UGE: return 3;  // 011
3339   case ICmpInst::ICMP_SGE: return 3;  // 011
3340   case ICmpInst::ICMP_ULT: return 4;  // 100
3341   case ICmpInst::ICMP_SLT: return 4;  // 100
3342   case ICmpInst::ICMP_NE:  return 5;  // 101
3343   case ICmpInst::ICMP_ULE: return 6;  // 110
3344   case ICmpInst::ICMP_SLE: return 6;  // 110
3345     // True -> 7
3346   default:
3347     llvm_unreachable("Invalid ICmp predicate!");
3348     return 0;
3349   }
3350 }
3351
3352 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3353 /// predicate into a three bit mask. It also returns whether it is an ordered
3354 /// predicate by reference.
3355 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3356   isOrdered = false;
3357   switch (CC) {
3358   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3359   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3360   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3361   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3362   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3363   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3364   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3365   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3366   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3367   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3368   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3369   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3370   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3371   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3372     // True -> 7
3373   default:
3374     // Not expecting FCMP_FALSE and FCMP_TRUE;
3375     llvm_unreachable("Unexpected FCmp predicate!");
3376     return 0;
3377   }
3378 }
3379
3380 /// getICmpValue - This is the complement of getICmpCode, which turns an
3381 /// opcode and two operands into either a constant true or false, or a brand 
3382 /// new ICmp instruction. The sign is passed in to determine which kind
3383 /// of predicate to use in the new icmp instruction.
3384 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3385                            LLVMContext *Context) {
3386   switch (code) {
3387   default: llvm_unreachable("Illegal ICmp code!");
3388   case  0: return ConstantInt::getFalse(*Context);
3389   case  1: 
3390     if (sign)
3391       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
3392     else
3393       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3394   case  2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ,  LHS, RHS);
3395   case  3: 
3396     if (sign)
3397       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
3398     else
3399       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
3400   case  4: 
3401     if (sign)
3402       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
3403     else
3404       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3405   case  5: return new ICmpInst(*Context, ICmpInst::ICMP_NE,  LHS, RHS);
3406   case  6: 
3407     if (sign)
3408       return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
3409     else
3410       return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
3411   case  7: return ConstantInt::getTrue(*Context);
3412   }
3413 }
3414
3415 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3416 /// opcode and two operands into either a FCmp instruction. isordered is passed
3417 /// in to determine which kind of predicate to use in the new fcmp instruction.
3418 static Value *getFCmpValue(bool isordered, unsigned code,
3419                            Value *LHS, Value *RHS, LLVMContext *Context) {
3420   switch (code) {
3421   default: llvm_unreachable("Illegal FCmp code!");
3422   case  0:
3423     if (isordered)
3424       return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
3425     else
3426       return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
3427   case  1: 
3428     if (isordered)
3429       return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
3430     else
3431       return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
3432   case  2: 
3433     if (isordered)
3434       return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
3435     else
3436       return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
3437   case  3: 
3438     if (isordered)
3439       return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
3440     else
3441       return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
3442   case  4: 
3443     if (isordered)
3444       return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
3445     else
3446       return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
3447   case  5: 
3448     if (isordered)
3449       return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
3450     else
3451       return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
3452   case  6: 
3453     if (isordered)
3454       return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
3455     else
3456       return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
3457   case  7: return ConstantInt::getTrue(*Context);
3458   }
3459 }
3460
3461 /// PredicatesFoldable - Return true if both predicates match sign or if at
3462 /// least one of them is an equality comparison (which is signless).
3463 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3464   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3465          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3466          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3467 }
3468
3469 namespace { 
3470 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3471 struct FoldICmpLogical {
3472   InstCombiner &IC;
3473   Value *LHS, *RHS;
3474   ICmpInst::Predicate pred;
3475   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3476     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3477       pred(ICI->getPredicate()) {}
3478   bool shouldApply(Value *V) const {
3479     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3480       if (PredicatesFoldable(pred, ICI->getPredicate()))
3481         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3482                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3483     return false;
3484   }
3485   Instruction *apply(Instruction &Log) const {
3486     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3487     if (ICI->getOperand(0) != LHS) {
3488       assert(ICI->getOperand(1) == LHS);
3489       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3490     }
3491
3492     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3493     unsigned LHSCode = getICmpCode(ICI);
3494     unsigned RHSCode = getICmpCode(RHSICI);
3495     unsigned Code;
3496     switch (Log.getOpcode()) {
3497     case Instruction::And: Code = LHSCode & RHSCode; break;
3498     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3499     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3500     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3501     }
3502
3503     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3504                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3505       
3506     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3507     if (Instruction *I = dyn_cast<Instruction>(RV))
3508       return I;
3509     // Otherwise, it's a constant boolean value...
3510     return IC.ReplaceInstUsesWith(Log, RV);
3511   }
3512 };
3513 } // end anonymous namespace
3514
3515 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3516 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3517 // guaranteed to be a binary operator.
3518 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3519                                     ConstantInt *OpRHS,
3520                                     ConstantInt *AndRHS,
3521                                     BinaryOperator &TheAnd) {
3522   Value *X = Op->getOperand(0);
3523   Constant *Together = 0;
3524   if (!Op->isShift())
3525     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3526
3527   switch (Op->getOpcode()) {
3528   case Instruction::Xor:
3529     if (Op->hasOneUse()) {
3530       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3531       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3532       InsertNewInstBefore(And, TheAnd);
3533       And->takeName(Op);
3534       return BinaryOperator::CreateXor(And, Together);
3535     }
3536     break;
3537   case Instruction::Or:
3538     if (Together == AndRHS) // (X | C) & C --> C
3539       return ReplaceInstUsesWith(TheAnd, AndRHS);
3540
3541     if (Op->hasOneUse() && Together != OpRHS) {
3542       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3543       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3544       InsertNewInstBefore(Or, TheAnd);
3545       Or->takeName(Op);
3546       return BinaryOperator::CreateAnd(Or, AndRHS);
3547     }
3548     break;
3549   case Instruction::Add:
3550     if (Op->hasOneUse()) {
3551       // Adding a one to a single bit bit-field should be turned into an XOR
3552       // of the bit.  First thing to check is to see if this AND is with a
3553       // single bit constant.
3554       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3555
3556       // If there is only one bit set...
3557       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3558         // Ok, at this point, we know that we are masking the result of the
3559         // ADD down to exactly one bit.  If the constant we are adding has
3560         // no bits set below this bit, then we can eliminate the ADD.
3561         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3562
3563         // Check to see if any bits below the one bit set in AndRHSV are set.
3564         if ((AddRHS & (AndRHSV-1)) == 0) {
3565           // If not, the only thing that can effect the output of the AND is
3566           // the bit specified by AndRHSV.  If that bit is set, the effect of
3567           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3568           // no effect.
3569           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3570             TheAnd.setOperand(0, X);
3571             return &TheAnd;
3572           } else {
3573             // Pull the XOR out of the AND.
3574             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3575             InsertNewInstBefore(NewAnd, TheAnd);
3576             NewAnd->takeName(Op);
3577             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3578           }
3579         }
3580       }
3581     }
3582     break;
3583
3584   case Instruction::Shl: {
3585     // We know that the AND will not produce any of the bits shifted in, so if
3586     // the anded constant includes them, clear them now!
3587     //
3588     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3589     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3590     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3591     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3592
3593     if (CI->getValue() == ShlMask) { 
3594     // Masking out bits that the shift already masks
3595       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3596     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3597       TheAnd.setOperand(1, CI);
3598       return &TheAnd;
3599     }
3600     break;
3601   }
3602   case Instruction::LShr:
3603   {
3604     // We know that the AND will not produce any of the bits shifted in, so if
3605     // the anded constant includes them, clear them now!  This only applies to
3606     // unsigned shifts, because a signed shr may bring in set bits!
3607     //
3608     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3609     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3610     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3611     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3612
3613     if (CI->getValue() == ShrMask) {   
3614     // Masking out bits that the shift already masks.
3615       return ReplaceInstUsesWith(TheAnd, Op);
3616     } else if (CI != AndRHS) {
3617       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3618       return &TheAnd;
3619     }
3620     break;
3621   }
3622   case Instruction::AShr:
3623     // Signed shr.
3624     // See if this is shifting in some sign extension, then masking it out
3625     // with an and.
3626     if (Op->hasOneUse()) {
3627       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3628       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3629       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3630       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3631       if (C == AndRHS) {          // Masking out bits shifted in.
3632         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3633         // Make the argument unsigned.
3634         Value *ShVal = Op->getOperand(0);
3635         ShVal = InsertNewInstBefore(
3636             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3637                                    Op->getName()), TheAnd);
3638         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3639       }
3640     }
3641     break;
3642   }
3643   return 0;
3644 }
3645
3646
3647 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3648 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3649 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3650 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3651 /// insert new instructions.
3652 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3653                                            bool isSigned, bool Inside, 
3654                                            Instruction &IB) {
3655   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3656             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3657          "Lo is not <= Hi in range emission code!");
3658     
3659   if (Inside) {
3660     if (Lo == Hi)  // Trivially false.
3661       return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
3662
3663     // V >= Min && V < Hi --> V < Hi
3664     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3665       ICmpInst::Predicate pred = (isSigned ? 
3666         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3667       return new ICmpInst(*Context, pred, V, Hi);
3668     }
3669
3670     // Emit V-Lo <u Hi-Lo
3671     Constant *NegLo = ConstantExpr::getNeg(Lo);
3672     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3673     InsertNewInstBefore(Add, IB);
3674     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3675     return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
3676   }
3677
3678   if (Lo == Hi)  // Trivially true.
3679     return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
3680
3681   // V < Min || V >= Hi -> V > Hi-1
3682   Hi = SubOne(cast<ConstantInt>(Hi));
3683   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3684     ICmpInst::Predicate pred = (isSigned ? 
3685         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3686     return new ICmpInst(*Context, pred, V, Hi);
3687   }
3688
3689   // Emit V-Lo >u Hi-1-Lo
3690   // Note that Hi has already had one subtracted from it, above.
3691   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3692   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3693   InsertNewInstBefore(Add, IB);
3694   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3695   return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
3696 }
3697
3698 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3699 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3700 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3701 // not, since all 1s are not contiguous.
3702 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3703   const APInt& V = Val->getValue();
3704   uint32_t BitWidth = Val->getType()->getBitWidth();
3705   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3706
3707   // look for the first zero bit after the run of ones
3708   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3709   // look for the first non-zero bit
3710   ME = V.getActiveBits(); 
3711   return true;
3712 }
3713
3714 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3715 /// where isSub determines whether the operator is a sub.  If we can fold one of
3716 /// the following xforms:
3717 /// 
3718 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3719 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3720 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3721 ///
3722 /// return (A +/- B).
3723 ///
3724 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3725                                         ConstantInt *Mask, bool isSub,
3726                                         Instruction &I) {
3727   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3728   if (!LHSI || LHSI->getNumOperands() != 2 ||
3729       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3730
3731   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3732
3733   switch (LHSI->getOpcode()) {
3734   default: return 0;
3735   case Instruction::And:
3736     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3737       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3738       if ((Mask->getValue().countLeadingZeros() + 
3739            Mask->getValue().countPopulation()) == 
3740           Mask->getValue().getBitWidth())
3741         break;
3742
3743       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3744       // part, we don't need any explicit masks to take them out of A.  If that
3745       // is all N is, ignore it.
3746       uint32_t MB = 0, ME = 0;
3747       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3748         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3749         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3750         if (MaskedValueIsZero(RHS, Mask))
3751           break;
3752       }
3753     }
3754     return 0;
3755   case Instruction::Or:
3756   case Instruction::Xor:
3757     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3758     if ((Mask->getValue().countLeadingZeros() + 
3759          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3760         && ConstantExpr::getAnd(N, Mask)->isNullValue())
3761       break;
3762     return 0;
3763   }
3764   
3765   Instruction *New;
3766   if (isSub)
3767     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3768   else
3769     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3770   return InsertNewInstBefore(New, I);
3771 }
3772
3773 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3774 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3775                                           ICmpInst *LHS, ICmpInst *RHS) {
3776   Value *Val, *Val2;
3777   ConstantInt *LHSCst, *RHSCst;
3778   ICmpInst::Predicate LHSCC, RHSCC;
3779   
3780   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3781   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3782                          m_ConstantInt(LHSCst))) ||
3783       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3784                          m_ConstantInt(RHSCst))))
3785     return 0;
3786   
3787   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3788   // where C is a power of 2
3789   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3790       LHSCst->getValue().isPowerOf2()) {
3791     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3792     InsertNewInstBefore(NewOr, I);
3793     return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
3794   }
3795   
3796   // From here on, we only handle:
3797   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3798   if (Val != Val2) return 0;
3799   
3800   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3801   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3802       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3803       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3804       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3805     return 0;
3806   
3807   // We can't fold (ugt x, C) & (sgt x, C2).
3808   if (!PredicatesFoldable(LHSCC, RHSCC))
3809     return 0;
3810     
3811   // Ensure that the larger constant is on the RHS.
3812   bool ShouldSwap;
3813   if (ICmpInst::isSignedPredicate(LHSCC) ||
3814       (ICmpInst::isEquality(LHSCC) && 
3815        ICmpInst::isSignedPredicate(RHSCC)))
3816     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3817   else
3818     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3819     
3820   if (ShouldSwap) {
3821     std::swap(LHS, RHS);
3822     std::swap(LHSCst, RHSCst);
3823     std::swap(LHSCC, RHSCC);
3824   }
3825
3826   // At this point, we know we have have two icmp instructions
3827   // comparing a value against two constants and and'ing the result
3828   // together.  Because of the above check, we know that we only have
3829   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3830   // (from the FoldICmpLogical check above), that the two constants 
3831   // are not equal and that the larger constant is on the RHS
3832   assert(LHSCst != RHSCst && "Compares not folded above?");
3833
3834   switch (LHSCC) {
3835   default: llvm_unreachable("Unknown integer condition code!");
3836   case ICmpInst::ICMP_EQ:
3837     switch (RHSCC) {
3838     default: llvm_unreachable("Unknown integer condition code!");
3839     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3840     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3841     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3842       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3843     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3844     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3845     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3846       return ReplaceInstUsesWith(I, LHS);
3847     }
3848   case ICmpInst::ICMP_NE:
3849     switch (RHSCC) {
3850     default: llvm_unreachable("Unknown integer condition code!");
3851     case ICmpInst::ICMP_ULT:
3852       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3853         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
3854       break;                        // (X != 13 & X u< 15) -> no change
3855     case ICmpInst::ICMP_SLT:
3856       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3857         return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
3858       break;                        // (X != 13 & X s< 15) -> no change
3859     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3860     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3861     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3862       return ReplaceInstUsesWith(I, RHS);
3863     case ICmpInst::ICMP_NE:
3864       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3865         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3866         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3867                                                      Val->getName()+".off");
3868         InsertNewInstBefore(Add, I);
3869         return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
3870                             ConstantInt::get(Add->getType(), 1));
3871       }
3872       break;                        // (X != 13 & X != 15) -> no change
3873     }
3874     break;
3875   case ICmpInst::ICMP_ULT:
3876     switch (RHSCC) {
3877     default: llvm_unreachable("Unknown integer condition code!");
3878     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3879     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3880       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3881     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3882       break;
3883     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3884     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3885       return ReplaceInstUsesWith(I, LHS);
3886     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3887       break;
3888     }
3889     break;
3890   case ICmpInst::ICMP_SLT:
3891     switch (RHSCC) {
3892     default: llvm_unreachable("Unknown integer condition code!");
3893     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3894     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3895       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3896     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3897       break;
3898     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3899     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3900       return ReplaceInstUsesWith(I, LHS);
3901     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3902       break;
3903     }
3904     break;
3905   case ICmpInst::ICMP_UGT:
3906     switch (RHSCC) {
3907     default: llvm_unreachable("Unknown integer condition code!");
3908     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3909     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3910       return ReplaceInstUsesWith(I, RHS);
3911     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3912       break;
3913     case ICmpInst::ICMP_NE:
3914       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3915         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3916       break;                        // (X u> 13 & X != 15) -> no change
3917     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3918       return InsertRangeTest(Val, AddOne(LHSCst),
3919                              RHSCst, false, true, I);
3920     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3921       break;
3922     }
3923     break;
3924   case ICmpInst::ICMP_SGT:
3925     switch (RHSCC) {
3926     default: llvm_unreachable("Unknown integer condition code!");
3927     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3928     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3929       return ReplaceInstUsesWith(I, RHS);
3930     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3931       break;
3932     case ICmpInst::ICMP_NE:
3933       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3934         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3935       break;                        // (X s> 13 & X != 15) -> no change
3936     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3937       return InsertRangeTest(Val, AddOne(LHSCst),
3938                              RHSCst, true, true, I);
3939     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3940       break;
3941     }
3942     break;
3943   }
3944  
3945   return 0;
3946 }
3947
3948 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3949                                           FCmpInst *RHS) {
3950   
3951   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3952       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3953     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3954     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3955       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3956         // If either of the constants are nans, then the whole thing returns
3957         // false.
3958         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3959           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3960         return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 
3961                             LHS->getOperand(0), RHS->getOperand(0));
3962       }
3963     
3964     // Handle vector zeros.  This occurs because the canonical form of
3965     // "fcmp ord x,x" is "fcmp ord x, 0".
3966     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3967         isa<ConstantAggregateZero>(RHS->getOperand(1)))
3968       return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 
3969                           LHS->getOperand(0), RHS->getOperand(0));
3970     return 0;
3971   }
3972   
3973   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3974   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3975   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3976   
3977   
3978   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3979     // Swap RHS operands to match LHS.
3980     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3981     std::swap(Op1LHS, Op1RHS);
3982   }
3983   
3984   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3985     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3986     if (Op0CC == Op1CC)
3987       return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3988     
3989     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
3990       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3991     if (Op0CC == FCmpInst::FCMP_TRUE)
3992       return ReplaceInstUsesWith(I, RHS);
3993     if (Op1CC == FCmpInst::FCMP_TRUE)
3994       return ReplaceInstUsesWith(I, LHS);
3995     
3996     bool Op0Ordered;
3997     bool Op1Ordered;
3998     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3999     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4000     if (Op1Pred == 0) {
4001       std::swap(LHS, RHS);
4002       std::swap(Op0Pred, Op1Pred);
4003       std::swap(Op0Ordered, Op1Ordered);
4004     }
4005     if (Op0Pred == 0) {
4006       // uno && ueq -> uno && (uno || eq) -> ueq
4007       // ord && olt -> ord && (ord && lt) -> olt
4008       if (Op0Ordered == Op1Ordered)
4009         return ReplaceInstUsesWith(I, RHS);
4010       
4011       // uno && oeq -> uno && (ord && eq) -> false
4012       // uno && ord -> false
4013       if (!Op0Ordered)
4014         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4015       // ord && ueq -> ord && (uno || eq) -> oeq
4016       return cast<Instruction>(getFCmpValue(true, Op1Pred,
4017                                             Op0LHS, Op0RHS, Context));
4018     }
4019   }
4020
4021   return 0;
4022 }
4023
4024
4025 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4026   bool Changed = SimplifyCommutative(I);
4027   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4028
4029   if (isa<UndefValue>(Op1))                         // X & undef -> 0
4030     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4031
4032   // and X, X = X
4033   if (Op0 == Op1)
4034     return ReplaceInstUsesWith(I, Op1);
4035
4036   // See if we can simplify any instructions used by the instruction whose sole 
4037   // purpose is to compute bits we don't care about.
4038   if (SimplifyDemandedInstructionBits(I))
4039     return &I;
4040   if (isa<VectorType>(I.getType())) {
4041     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4042       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
4043         return ReplaceInstUsesWith(I, I.getOperand(0));
4044     } else if (isa<ConstantAggregateZero>(Op1)) {
4045       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4046     }
4047   }
4048
4049   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4050     const APInt& AndRHSMask = AndRHS->getValue();
4051     APInt NotAndRHS(~AndRHSMask);
4052
4053     // Optimize a variety of ((val OP C1) & C2) combinations...
4054     if (isa<BinaryOperator>(Op0)) {
4055       Instruction *Op0I = cast<Instruction>(Op0);
4056       Value *Op0LHS = Op0I->getOperand(0);
4057       Value *Op0RHS = Op0I->getOperand(1);
4058       switch (Op0I->getOpcode()) {
4059       case Instruction::Xor:
4060       case Instruction::Or:
4061         // If the mask is only needed on one incoming arm, push it up.
4062         if (Op0I->hasOneUse()) {
4063           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4064             // Not masking anything out for the LHS, move to RHS.
4065             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4066                                                    Op0RHS->getName()+".masked");
4067             InsertNewInstBefore(NewRHS, I);
4068             return BinaryOperator::Create(
4069                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4070           }
4071           if (!isa<Constant>(Op0RHS) &&
4072               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4073             // Not masking anything out for the RHS, move to LHS.
4074             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4075                                                    Op0LHS->getName()+".masked");
4076             InsertNewInstBefore(NewLHS, I);
4077             return BinaryOperator::Create(
4078                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4079           }
4080         }
4081
4082         break;
4083       case Instruction::Add:
4084         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4085         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4086         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4087         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4088           return BinaryOperator::CreateAnd(V, AndRHS);
4089         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4090           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4091         break;
4092
4093       case Instruction::Sub:
4094         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4095         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4096         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4097         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4098           return BinaryOperator::CreateAnd(V, AndRHS);
4099
4100         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4101         // has 1's for all bits that the subtraction with A might affect.
4102         if (Op0I->hasOneUse()) {
4103           uint32_t BitWidth = AndRHSMask.getBitWidth();
4104           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4105           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4106
4107           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4108           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4109               MaskedValueIsZero(Op0LHS, Mask)) {
4110             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4111             InsertNewInstBefore(NewNeg, I);
4112             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4113           }
4114         }
4115         break;
4116
4117       case Instruction::Shl:
4118       case Instruction::LShr:
4119         // (1 << x) & 1 --> zext(x == 0)
4120         // (1 >> x) & 1 --> zext(x == 0)
4121         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4122           Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4123                                     Op0RHS, Constant::getNullValue(I.getType()));
4124           InsertNewInstBefore(NewICmp, I);
4125           return new ZExtInst(NewICmp, I.getType());
4126         }
4127         break;
4128       }
4129
4130       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4131         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4132           return Res;
4133     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4134       // If this is an integer truncation or change from signed-to-unsigned, and
4135       // if the source is an and/or with immediate, transform it.  This
4136       // frequently occurs for bitfield accesses.
4137       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4138         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4139             CastOp->getNumOperands() == 2)
4140           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4141             if (CastOp->getOpcode() == Instruction::And) {
4142               // Change: and (cast (and X, C1) to T), C2
4143               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4144               // This will fold the two constants together, which may allow 
4145               // other simplifications.
4146               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4147                 CastOp->getOperand(0), I.getType(), 
4148                 CastOp->getName()+".shrunk");
4149               NewCast = InsertNewInstBefore(NewCast, I);
4150               // trunc_or_bitcast(C1)&C2
4151               Constant *C3 =
4152                       ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4153               C3 = ConstantExpr::getAnd(C3, AndRHS);
4154               return BinaryOperator::CreateAnd(NewCast, C3);
4155             } else if (CastOp->getOpcode() == Instruction::Or) {
4156               // Change: and (cast (or X, C1) to T), C2
4157               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4158               Constant *C3 =
4159                       ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4160               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4161                 // trunc(C1)&C2
4162                 return ReplaceInstUsesWith(I, AndRHS);
4163             }
4164           }
4165       }
4166     }
4167
4168     // Try to fold constant and into select arguments.
4169     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4170       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4171         return R;
4172     if (isa<PHINode>(Op0))
4173       if (Instruction *NV = FoldOpIntoPhi(I))
4174         return NV;
4175   }
4176
4177   Value *Op0NotVal = dyn_castNotVal(Op0);
4178   Value *Op1NotVal = dyn_castNotVal(Op1);
4179
4180   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4181     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4182
4183   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4184   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4185     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4186                                                I.getName()+".demorgan");
4187     InsertNewInstBefore(Or, I);
4188     return BinaryOperator::CreateNot(Or);
4189   }
4190   
4191   {
4192     Value *A = 0, *B = 0, *C = 0, *D = 0;
4193     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4194       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4195         return ReplaceInstUsesWith(I, Op1);
4196     
4197       // (A|B) & ~(A&B) -> A^B
4198       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4199         if ((A == C && B == D) || (A == D && B == C))
4200           return BinaryOperator::CreateXor(A, B);
4201       }
4202     }
4203     
4204     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4205       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4206         return ReplaceInstUsesWith(I, Op0);
4207
4208       // ~(A&B) & (A|B) -> A^B
4209       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4210         if ((A == C && B == D) || (A == D && B == C))
4211           return BinaryOperator::CreateXor(A, B);
4212       }
4213     }
4214     
4215     if (Op0->hasOneUse() &&
4216         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4217       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4218         I.swapOperands();     // Simplify below
4219         std::swap(Op0, Op1);
4220       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4221         cast<BinaryOperator>(Op0)->swapOperands();
4222         I.swapOperands();     // Simplify below
4223         std::swap(Op0, Op1);
4224       }
4225     }
4226
4227     if (Op1->hasOneUse() &&
4228         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4229       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4230         cast<BinaryOperator>(Op1)->swapOperands();
4231         std::swap(A, B);
4232       }
4233       if (A == Op0) {                                // A&(A^B) -> A & ~B
4234         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4235         InsertNewInstBefore(NotB, I);
4236         return BinaryOperator::CreateAnd(A, NotB);
4237       }
4238     }
4239
4240     // (A&((~A)|B)) -> A&B
4241     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4242         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4243       return BinaryOperator::CreateAnd(A, Op1);
4244     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4245         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4246       return BinaryOperator::CreateAnd(A, Op0);
4247   }
4248   
4249   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4250     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4251     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4252       return R;
4253
4254     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4255       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4256         return Res;
4257   }
4258
4259   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4260   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4261     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4262       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4263         const Type *SrcTy = Op0C->getOperand(0)->getType();
4264         if (SrcTy == Op1C->getOperand(0)->getType() &&
4265             SrcTy->isIntOrIntVector() &&
4266             // Only do this if the casts both really cause code to be generated.
4267             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4268                               I.getType(), TD) &&
4269             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4270                               I.getType(), TD)) {
4271           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4272                                                          Op1C->getOperand(0),
4273                                                          I.getName());
4274           InsertNewInstBefore(NewOp, I);
4275           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4276         }
4277       }
4278     
4279   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4280   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4281     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4282       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4283           SI0->getOperand(1) == SI1->getOperand(1) &&
4284           (SI0->hasOneUse() || SI1->hasOneUse())) {
4285         Instruction *NewOp =
4286           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4287                                                         SI1->getOperand(0),
4288                                                         SI0->getName()), I);
4289         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4290                                       SI1->getOperand(1));
4291       }
4292   }
4293
4294   // If and'ing two fcmp, try combine them into one.
4295   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4296     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4297       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4298         return Res;
4299   }
4300
4301   return Changed ? &I : 0;
4302 }
4303
4304 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4305 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4306 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4307 /// the expression came from the corresponding "byte swapped" byte in some other
4308 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4309 /// we know that the expression deposits the low byte of %X into the high byte
4310 /// of the bswap result and that all other bytes are zero.  This expression is
4311 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4312 /// match.
4313 ///
4314 /// This function returns true if the match was unsuccessful and false if so.
4315 /// On entry to the function the "OverallLeftShift" is a signed integer value
4316 /// indicating the number of bytes that the subexpression is later shifted.  For
4317 /// example, if the expression is later right shifted by 16 bits, the
4318 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4319 /// byte of ByteValues is actually being set.
4320 ///
4321 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4322 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4323 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4324 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4325 /// always in the local (OverallLeftShift) coordinate space.
4326 ///
4327 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4328                               SmallVector<Value*, 8> &ByteValues) {
4329   if (Instruction *I = dyn_cast<Instruction>(V)) {
4330     // If this is an or instruction, it may be an inner node of the bswap.
4331     if (I->getOpcode() == Instruction::Or) {
4332       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4333                                ByteValues) ||
4334              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4335                                ByteValues);
4336     }
4337   
4338     // If this is a logical shift by a constant multiple of 8, recurse with
4339     // OverallLeftShift and ByteMask adjusted.
4340     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4341       unsigned ShAmt = 
4342         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4343       // Ensure the shift amount is defined and of a byte value.
4344       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4345         return true;
4346
4347       unsigned ByteShift = ShAmt >> 3;
4348       if (I->getOpcode() == Instruction::Shl) {
4349         // X << 2 -> collect(X, +2)
4350         OverallLeftShift += ByteShift;
4351         ByteMask >>= ByteShift;
4352       } else {
4353         // X >>u 2 -> collect(X, -2)
4354         OverallLeftShift -= ByteShift;
4355         ByteMask <<= ByteShift;
4356         ByteMask &= (~0U >> (32-ByteValues.size()));
4357       }
4358
4359       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4360       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4361
4362       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4363                                ByteValues);
4364     }
4365
4366     // If this is a logical 'and' with a mask that clears bytes, clear the
4367     // corresponding bytes in ByteMask.
4368     if (I->getOpcode() == Instruction::And &&
4369         isa<ConstantInt>(I->getOperand(1))) {
4370       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4371       unsigned NumBytes = ByteValues.size();
4372       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4373       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4374       
4375       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4376         // If this byte is masked out by a later operation, we don't care what
4377         // the and mask is.
4378         if ((ByteMask & (1 << i)) == 0)
4379           continue;
4380         
4381         // If the AndMask is all zeros for this byte, clear the bit.
4382         APInt MaskB = AndMask & Byte;
4383         if (MaskB == 0) {
4384           ByteMask &= ~(1U << i);
4385           continue;
4386         }
4387         
4388         // If the AndMask is not all ones for this byte, it's not a bytezap.
4389         if (MaskB != Byte)
4390           return true;
4391
4392         // Otherwise, this byte is kept.
4393       }
4394
4395       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4396                                ByteValues);
4397     }
4398   }
4399   
4400   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4401   // the input value to the bswap.  Some observations: 1) if more than one byte
4402   // is demanded from this input, then it could not be successfully assembled
4403   // into a byteswap.  At least one of the two bytes would not be aligned with
4404   // their ultimate destination.
4405   if (!isPowerOf2_32(ByteMask)) return true;
4406   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4407   
4408   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4409   // is demanded, it needs to go into byte 0 of the result.  This means that the
4410   // byte needs to be shifted until it lands in the right byte bucket.  The
4411   // shift amount depends on the position: if the byte is coming from the high
4412   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4413   // low part, it must be shifted left.
4414   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4415   if (InputByteNo < ByteValues.size()/2) {
4416     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4417       return true;
4418   } else {
4419     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4420       return true;
4421   }
4422   
4423   // If the destination byte value is already defined, the values are or'd
4424   // together, which isn't a bswap (unless it's an or of the same bits).
4425   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4426     return true;
4427   ByteValues[DestByteNo] = V;
4428   return false;
4429 }
4430
4431 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4432 /// If so, insert the new bswap intrinsic and return it.
4433 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4434   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4435   if (!ITy || ITy->getBitWidth() % 16 || 
4436       // ByteMask only allows up to 32-byte values.
4437       ITy->getBitWidth() > 32*8) 
4438     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4439   
4440   /// ByteValues - For each byte of the result, we keep track of which value
4441   /// defines each byte.
4442   SmallVector<Value*, 8> ByteValues;
4443   ByteValues.resize(ITy->getBitWidth()/8);
4444     
4445   // Try to find all the pieces corresponding to the bswap.
4446   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4447   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4448     return 0;
4449   
4450   // Check to see if all of the bytes come from the same value.
4451   Value *V = ByteValues[0];
4452   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4453   
4454   // Check to make sure that all of the bytes come from the same value.
4455   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4456     if (ByteValues[i] != V)
4457       return 0;
4458   const Type *Tys[] = { ITy };
4459   Module *M = I.getParent()->getParent()->getParent();
4460   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4461   return CallInst::Create(F, V);
4462 }
4463
4464 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4465 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4466 /// we can simplify this expression to "cond ? C : D or B".
4467 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4468                                          Value *C, Value *D,
4469                                          LLVMContext *Context) {
4470   // If A is not a select of -1/0, this cannot match.
4471   Value *Cond = 0;
4472   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4473     return 0;
4474
4475   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4476   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4477     return SelectInst::Create(Cond, C, B);
4478   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4479     return SelectInst::Create(Cond, C, B);
4480   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4481   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4482     return SelectInst::Create(Cond, C, D);
4483   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4484     return SelectInst::Create(Cond, C, D);
4485   return 0;
4486 }
4487
4488 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4489 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4490                                          ICmpInst *LHS, ICmpInst *RHS) {
4491   Value *Val, *Val2;
4492   ConstantInt *LHSCst, *RHSCst;
4493   ICmpInst::Predicate LHSCC, RHSCC;
4494   
4495   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4496   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4497              m_ConstantInt(LHSCst))) ||
4498       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4499              m_ConstantInt(RHSCst))))
4500     return 0;
4501   
4502   // From here on, we only handle:
4503   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4504   if (Val != Val2) return 0;
4505   
4506   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4507   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4508       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4509       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4510       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4511     return 0;
4512   
4513   // We can't fold (ugt x, C) | (sgt x, C2).
4514   if (!PredicatesFoldable(LHSCC, RHSCC))
4515     return 0;
4516   
4517   // Ensure that the larger constant is on the RHS.
4518   bool ShouldSwap;
4519   if (ICmpInst::isSignedPredicate(LHSCC) ||
4520       (ICmpInst::isEquality(LHSCC) && 
4521        ICmpInst::isSignedPredicate(RHSCC)))
4522     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4523   else
4524     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4525   
4526   if (ShouldSwap) {
4527     std::swap(LHS, RHS);
4528     std::swap(LHSCst, RHSCst);
4529     std::swap(LHSCC, RHSCC);
4530   }
4531   
4532   // At this point, we know we have have two icmp instructions
4533   // comparing a value against two constants and or'ing the result
4534   // together.  Because of the above check, we know that we only have
4535   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4536   // FoldICmpLogical check above), that the two constants are not
4537   // equal.
4538   assert(LHSCst != RHSCst && "Compares not folded above?");
4539
4540   switch (LHSCC) {
4541   default: llvm_unreachable("Unknown integer condition code!");
4542   case ICmpInst::ICMP_EQ:
4543     switch (RHSCC) {
4544     default: llvm_unreachable("Unknown integer condition code!");
4545     case ICmpInst::ICMP_EQ:
4546       if (LHSCst == SubOne(RHSCst)) {
4547         // (X == 13 | X == 14) -> X-13 <u 2
4548         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4549         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4550                                                      Val->getName()+".off");
4551         InsertNewInstBefore(Add, I);
4552         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4553         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
4554       }
4555       break;                         // (X == 13 | X == 15) -> no change
4556     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4557     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4558       break;
4559     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4560     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4561     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4562       return ReplaceInstUsesWith(I, RHS);
4563     }
4564     break;
4565   case ICmpInst::ICMP_NE:
4566     switch (RHSCC) {
4567     default: llvm_unreachable("Unknown integer condition code!");
4568     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4569     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4570     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4571       return ReplaceInstUsesWith(I, LHS);
4572     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4573     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4574     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4575       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4576     }
4577     break;
4578   case ICmpInst::ICMP_ULT:
4579     switch (RHSCC) {
4580     default: llvm_unreachable("Unknown integer condition code!");
4581     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4582       break;
4583     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4584       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4585       // this can cause overflow.
4586       if (RHSCst->isMaxValue(false))
4587         return ReplaceInstUsesWith(I, LHS);
4588       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4589                              false, false, I);
4590     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4591       break;
4592     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4593     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4594       return ReplaceInstUsesWith(I, RHS);
4595     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4596       break;
4597     }
4598     break;
4599   case ICmpInst::ICMP_SLT:
4600     switch (RHSCC) {
4601     default: llvm_unreachable("Unknown integer condition code!");
4602     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4603       break;
4604     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4605       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4606       // this can cause overflow.
4607       if (RHSCst->isMaxValue(true))
4608         return ReplaceInstUsesWith(I, LHS);
4609       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4610                              true, false, I);
4611     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4612       break;
4613     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4614     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4615       return ReplaceInstUsesWith(I, RHS);
4616     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4617       break;
4618     }
4619     break;
4620   case ICmpInst::ICMP_UGT:
4621     switch (RHSCC) {
4622     default: llvm_unreachable("Unknown integer condition code!");
4623     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4624     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4625       return ReplaceInstUsesWith(I, LHS);
4626     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4627       break;
4628     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4629     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4630       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4631     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4632       break;
4633     }
4634     break;
4635   case ICmpInst::ICMP_SGT:
4636     switch (RHSCC) {
4637     default: llvm_unreachable("Unknown integer condition code!");
4638     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4639     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4640       return ReplaceInstUsesWith(I, LHS);
4641     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4642       break;
4643     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4644     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4645       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4646     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4647       break;
4648     }
4649     break;
4650   }
4651   return 0;
4652 }
4653
4654 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4655                                          FCmpInst *RHS) {
4656   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4657       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4658       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4659     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4660       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4661         // If either of the constants are nans, then the whole thing returns
4662         // true.
4663         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4664           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4665         
4666         // Otherwise, no need to compare the two constants, compare the
4667         // rest.
4668         return new FCmpInst(*Context, FCmpInst::FCMP_UNO, 
4669                             LHS->getOperand(0), RHS->getOperand(0));
4670       }
4671     
4672     // Handle vector zeros.  This occurs because the canonical form of
4673     // "fcmp uno x,x" is "fcmp uno x, 0".
4674     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4675         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4676       return new FCmpInst(*Context, FCmpInst::FCMP_UNO, 
4677                           LHS->getOperand(0), RHS->getOperand(0));
4678     
4679     return 0;
4680   }
4681   
4682   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4683   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4684   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4685   
4686   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4687     // Swap RHS operands to match LHS.
4688     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4689     std::swap(Op1LHS, Op1RHS);
4690   }
4691   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4692     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4693     if (Op0CC == Op1CC)
4694       return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4695                           Op0LHS, Op0RHS);
4696     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4697       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4698     if (Op0CC == FCmpInst::FCMP_FALSE)
4699       return ReplaceInstUsesWith(I, RHS);
4700     if (Op1CC == FCmpInst::FCMP_FALSE)
4701       return ReplaceInstUsesWith(I, LHS);
4702     bool Op0Ordered;
4703     bool Op1Ordered;
4704     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4705     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4706     if (Op0Ordered == Op1Ordered) {
4707       // If both are ordered or unordered, return a new fcmp with
4708       // or'ed predicates.
4709       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4710                                Op0LHS, Op0RHS, Context);
4711       if (Instruction *I = dyn_cast<Instruction>(RV))
4712         return I;
4713       // Otherwise, it's a constant boolean value...
4714       return ReplaceInstUsesWith(I, RV);
4715     }
4716   }
4717   return 0;
4718 }
4719
4720 /// FoldOrWithConstants - This helper function folds:
4721 ///
4722 ///     ((A | B) & C1) | (B & C2)
4723 ///
4724 /// into:
4725 /// 
4726 ///     (A & C1) | B
4727 ///
4728 /// when the XOR of the two constants is "all ones" (-1).
4729 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4730                                                Value *A, Value *B, Value *C) {
4731   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4732   if (!CI1) return 0;
4733
4734   Value *V1 = 0;
4735   ConstantInt *CI2 = 0;
4736   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4737
4738   APInt Xor = CI1->getValue() ^ CI2->getValue();
4739   if (!Xor.isAllOnesValue()) return 0;
4740
4741   if (V1 == A || V1 == B) {
4742     Instruction *NewOp =
4743       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4744     return BinaryOperator::CreateOr(NewOp, V1);
4745   }
4746
4747   return 0;
4748 }
4749
4750 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4751   bool Changed = SimplifyCommutative(I);
4752   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4753
4754   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4755     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4756
4757   // or X, X = X
4758   if (Op0 == Op1)
4759     return ReplaceInstUsesWith(I, Op0);
4760
4761   // See if we can simplify any instructions used by the instruction whose sole 
4762   // purpose is to compute bits we don't care about.
4763   if (SimplifyDemandedInstructionBits(I))
4764     return &I;
4765   if (isa<VectorType>(I.getType())) {
4766     if (isa<ConstantAggregateZero>(Op1)) {
4767       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4768     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4769       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4770         return ReplaceInstUsesWith(I, I.getOperand(1));
4771     }
4772   }
4773
4774   // or X, -1 == -1
4775   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4776     ConstantInt *C1 = 0; Value *X = 0;
4777     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4778     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
4779         isOnlyUse(Op0)) {
4780       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4781       InsertNewInstBefore(Or, I);
4782       Or->takeName(Op0);
4783       return BinaryOperator::CreateAnd(Or, 
4784                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4785     }
4786
4787     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4788     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
4789         isOnlyUse(Op0)) {
4790       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4791       InsertNewInstBefore(Or, I);
4792       Or->takeName(Op0);
4793       return BinaryOperator::CreateXor(Or,
4794                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4795     }
4796
4797     // Try to fold constant and into select arguments.
4798     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4799       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4800         return R;
4801     if (isa<PHINode>(Op0))
4802       if (Instruction *NV = FoldOpIntoPhi(I))
4803         return NV;
4804   }
4805
4806   Value *A = 0, *B = 0;
4807   ConstantInt *C1 = 0, *C2 = 0;
4808
4809   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4810     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4811       return ReplaceInstUsesWith(I, Op1);
4812   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4813     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4814       return ReplaceInstUsesWith(I, Op0);
4815
4816   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4817   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4818   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4819       match(Op1, m_Or(m_Value(), m_Value())) ||
4820       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4821        match(Op1, m_Shift(m_Value(), m_Value())))) {
4822     if (Instruction *BSwap = MatchBSwap(I))
4823       return BSwap;
4824   }
4825   
4826   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4827   if (Op0->hasOneUse() &&
4828       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4829       MaskedValueIsZero(Op1, C1->getValue())) {
4830     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4831     InsertNewInstBefore(NOr, I);
4832     NOr->takeName(Op0);
4833     return BinaryOperator::CreateXor(NOr, C1);
4834   }
4835
4836   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4837   if (Op1->hasOneUse() &&
4838       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4839       MaskedValueIsZero(Op0, C1->getValue())) {
4840     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4841     InsertNewInstBefore(NOr, I);
4842     NOr->takeName(Op0);
4843     return BinaryOperator::CreateXor(NOr, C1);
4844   }
4845
4846   // (A & C)|(B & D)
4847   Value *C = 0, *D = 0;
4848   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4849       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4850     Value *V1 = 0, *V2 = 0, *V3 = 0;
4851     C1 = dyn_cast<ConstantInt>(C);
4852     C2 = dyn_cast<ConstantInt>(D);
4853     if (C1 && C2) {  // (A & C1)|(B & C2)
4854       // If we have: ((V + N) & C1) | (V & C2)
4855       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4856       // replace with V+N.
4857       if (C1->getValue() == ~C2->getValue()) {
4858         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4859             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4860           // Add commutes, try both ways.
4861           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4862             return ReplaceInstUsesWith(I, A);
4863           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4864             return ReplaceInstUsesWith(I, A);
4865         }
4866         // Or commutes, try both ways.
4867         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4868             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4869           // Add commutes, try both ways.
4870           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4871             return ReplaceInstUsesWith(I, B);
4872           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4873             return ReplaceInstUsesWith(I, B);
4874         }
4875       }
4876       V1 = 0; V2 = 0; V3 = 0;
4877     }
4878     
4879     // Check to see if we have any common things being and'ed.  If so, find the
4880     // terms for V1 & (V2|V3).
4881     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4882       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4883         V1 = A, V2 = C, V3 = D;
4884       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4885         V1 = A, V2 = B, V3 = C;
4886       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4887         V1 = C, V2 = A, V3 = D;
4888       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4889         V1 = C, V2 = A, V3 = B;
4890       
4891       if (V1) {
4892         Value *Or =
4893           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4894         return BinaryOperator::CreateAnd(V1, Or);
4895       }
4896     }
4897
4898     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4899     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4900       return Match;
4901     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4902       return Match;
4903     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4904       return Match;
4905     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4906       return Match;
4907
4908     // ((A&~B)|(~A&B)) -> A^B
4909     if ((match(C, m_Not(m_Specific(D))) &&
4910          match(B, m_Not(m_Specific(A)))))
4911       return BinaryOperator::CreateXor(A, D);
4912     // ((~B&A)|(~A&B)) -> A^B
4913     if ((match(A, m_Not(m_Specific(D))) &&
4914          match(B, m_Not(m_Specific(C)))))
4915       return BinaryOperator::CreateXor(C, D);
4916     // ((A&~B)|(B&~A)) -> A^B
4917     if ((match(C, m_Not(m_Specific(B))) &&
4918          match(D, m_Not(m_Specific(A)))))
4919       return BinaryOperator::CreateXor(A, B);
4920     // ((~B&A)|(B&~A)) -> A^B
4921     if ((match(A, m_Not(m_Specific(B))) &&
4922          match(D, m_Not(m_Specific(C)))))
4923       return BinaryOperator::CreateXor(C, B);
4924   }
4925   
4926   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4927   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4928     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4929       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4930           SI0->getOperand(1) == SI1->getOperand(1) &&
4931           (SI0->hasOneUse() || SI1->hasOneUse())) {
4932         Instruction *NewOp =
4933         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4934                                                      SI1->getOperand(0),
4935                                                      SI0->getName()), I);
4936         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4937                                       SI1->getOperand(1));
4938       }
4939   }
4940
4941   // ((A|B)&1)|(B&-2) -> (A&1) | B
4942   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4943       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4944     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4945     if (Ret) return Ret;
4946   }
4947   // (B&-2)|((A|B)&1) -> (A&1) | B
4948   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4949       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4950     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4951     if (Ret) return Ret;
4952   }
4953
4954   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4955     if (A == Op1)   // ~A | A == -1
4956       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4957   } else {
4958     A = 0;
4959   }
4960   // Note, A is still live here!
4961   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4962     if (Op0 == B)
4963       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4964
4965     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4966     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4967       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4968                                               I.getName()+".demorgan"), I);
4969       return BinaryOperator::CreateNot(And);
4970     }
4971   }
4972
4973   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4974   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4975     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4976       return R;
4977
4978     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4979       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4980         return Res;
4981   }
4982     
4983   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4984   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4985     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4986       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4987         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4988             !isa<ICmpInst>(Op1C->getOperand(0))) {
4989           const Type *SrcTy = Op0C->getOperand(0)->getType();
4990           if (SrcTy == Op1C->getOperand(0)->getType() &&
4991               SrcTy->isIntOrIntVector() &&
4992               // Only do this if the casts both really cause code to be
4993               // generated.
4994               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4995                                 I.getType(), TD) &&
4996               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4997                                 I.getType(), TD)) {
4998             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4999                                                           Op1C->getOperand(0),
5000                                                           I.getName());
5001             InsertNewInstBefore(NewOp, I);
5002             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5003           }
5004         }
5005       }
5006   }
5007   
5008     
5009   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
5010   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
5011     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5012       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5013         return Res;
5014   }
5015
5016   return Changed ? &I : 0;
5017 }
5018
5019 namespace {
5020
5021 // XorSelf - Implements: X ^ X --> 0
5022 struct XorSelf {
5023   Value *RHS;
5024   XorSelf(Value *rhs) : RHS(rhs) {}
5025   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5026   Instruction *apply(BinaryOperator &Xor) const {
5027     return &Xor;
5028   }
5029 };
5030
5031 }
5032
5033 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5034   bool Changed = SimplifyCommutative(I);
5035   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5036
5037   if (isa<UndefValue>(Op1)) {
5038     if (isa<UndefValue>(Op0))
5039       // Handle undef ^ undef -> 0 special case. This is a common
5040       // idiom (misuse).
5041       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5042     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5043   }
5044
5045   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5046   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5047     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5048     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5049   }
5050   
5051   // See if we can simplify any instructions used by the instruction whose sole 
5052   // purpose is to compute bits we don't care about.
5053   if (SimplifyDemandedInstructionBits(I))
5054     return &I;
5055   if (isa<VectorType>(I.getType()))
5056     if (isa<ConstantAggregateZero>(Op1))
5057       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5058
5059   // Is this a ~ operation?
5060   if (Value *NotOp = dyn_castNotVal(&I)) {
5061     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5062     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5063     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5064       if (Op0I->getOpcode() == Instruction::And || 
5065           Op0I->getOpcode() == Instruction::Or) {
5066         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5067         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5068           Instruction *NotY =
5069             BinaryOperator::CreateNot(Op0I->getOperand(1),
5070                                       Op0I->getOperand(1)->getName()+".not");
5071           InsertNewInstBefore(NotY, I);
5072           if (Op0I->getOpcode() == Instruction::And)
5073             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5074           else
5075             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5076         }
5077       }
5078     }
5079   }
5080   
5081   
5082   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5083     if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
5084       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5085       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5086         return new ICmpInst(*Context, ICI->getInversePredicate(),
5087                             ICI->getOperand(0), ICI->getOperand(1));
5088
5089       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5090         return new FCmpInst(*Context, FCI->getInversePredicate(),
5091                             FCI->getOperand(0), FCI->getOperand(1));
5092     }
5093
5094     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5095     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5096       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5097         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5098           Instruction::CastOps Opcode = Op0C->getOpcode();
5099           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5100             if (RHS == ConstantExpr::getCast(Opcode, 
5101                                              ConstantInt::getTrue(*Context),
5102                                              Op0C->getDestTy())) {
5103               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5104                                      *Context,
5105                                      CI->getOpcode(), CI->getInversePredicate(),
5106                                      CI->getOperand(0), CI->getOperand(1)), I);
5107               NewCI->takeName(CI);
5108               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5109             }
5110           }
5111         }
5112       }
5113     }
5114
5115     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5116       // ~(c-X) == X-c-1 == X+(-c-1)
5117       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5118         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5119           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5120           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5121                                       ConstantInt::get(I.getType(), 1));
5122           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5123         }
5124           
5125       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5126         if (Op0I->getOpcode() == Instruction::Add) {
5127           // ~(X-c) --> (-c-1)-X
5128           if (RHS->isAllOnesValue()) {
5129             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5130             return BinaryOperator::CreateSub(
5131                            ConstantExpr::getSub(NegOp0CI,
5132                                       ConstantInt::get(I.getType(), 1)),
5133                                       Op0I->getOperand(0));
5134           } else if (RHS->getValue().isSignBit()) {
5135             // (X + C) ^ signbit -> (X + C + signbit)
5136             Constant *C = ConstantInt::get(*Context,
5137                                            RHS->getValue() + Op0CI->getValue());
5138             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5139
5140           }
5141         } else if (Op0I->getOpcode() == Instruction::Or) {
5142           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5143           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5144             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5145             // Anything in both C1 and C2 is known to be zero, remove it from
5146             // NewRHS.
5147             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5148             NewRHS = ConstantExpr::getAnd(NewRHS, 
5149                                        ConstantExpr::getNot(CommonBits));
5150             AddToWorkList(Op0I);
5151             I.setOperand(0, Op0I->getOperand(0));
5152             I.setOperand(1, NewRHS);
5153             return &I;
5154           }
5155         }
5156       }
5157     }
5158
5159     // Try to fold constant and into select arguments.
5160     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5161       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5162         return R;
5163     if (isa<PHINode>(Op0))
5164       if (Instruction *NV = FoldOpIntoPhi(I))
5165         return NV;
5166   }
5167
5168   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5169     if (X == Op1)
5170       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5171
5172   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5173     if (X == Op0)
5174       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5175
5176   
5177   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5178   if (Op1I) {
5179     Value *A, *B;
5180     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5181       if (A == Op0) {              // B^(B|A) == (A|B)^B
5182         Op1I->swapOperands();
5183         I.swapOperands();
5184         std::swap(Op0, Op1);
5185       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5186         I.swapOperands();     // Simplified below.
5187         std::swap(Op0, Op1);
5188       }
5189     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5190       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5191     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5192       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5193     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
5194                Op1I->hasOneUse()){
5195       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5196         Op1I->swapOperands();
5197         std::swap(A, B);
5198       }
5199       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5200         I.swapOperands();     // Simplified below.
5201         std::swap(Op0, Op1);
5202       }
5203     }
5204   }
5205   
5206   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5207   if (Op0I) {
5208     Value *A, *B;
5209     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5210         Op0I->hasOneUse()) {
5211       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5212         std::swap(A, B);
5213       if (B == Op1) {                                // (A|B)^B == A & ~B
5214         Instruction *NotB =
5215           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5216         return BinaryOperator::CreateAnd(A, NotB);
5217       }
5218     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5219       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5220     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5221       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5222     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
5223                Op0I->hasOneUse()){
5224       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5225         std::swap(A, B);
5226       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5227           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5228         Instruction *N =
5229           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5230         return BinaryOperator::CreateAnd(N, Op1);
5231       }
5232     }
5233   }
5234   
5235   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5236   if (Op0I && Op1I && Op0I->isShift() && 
5237       Op0I->getOpcode() == Op1I->getOpcode() && 
5238       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5239       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5240     Instruction *NewOp =
5241       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5242                                                     Op1I->getOperand(0),
5243                                                     Op0I->getName()), I);
5244     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5245                                   Op1I->getOperand(1));
5246   }
5247     
5248   if (Op0I && Op1I) {
5249     Value *A, *B, *C, *D;
5250     // (A & B)^(A | B) -> A ^ B
5251     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5252         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5253       if ((A == C && B == D) || (A == D && B == C)) 
5254         return BinaryOperator::CreateXor(A, B);
5255     }
5256     // (A | B)^(A & B) -> A ^ B
5257     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5258         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5259       if ((A == C && B == D) || (A == D && B == C)) 
5260         return BinaryOperator::CreateXor(A, B);
5261     }
5262     
5263     // (A & B)^(C & D)
5264     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5265         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5266         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5267       // (X & Y)^(X & Y) -> (Y^Z) & X
5268       Value *X = 0, *Y = 0, *Z = 0;
5269       if (A == C)
5270         X = A, Y = B, Z = D;
5271       else if (A == D)
5272         X = A, Y = B, Z = C;
5273       else if (B == C)
5274         X = B, Y = A, Z = D;
5275       else if (B == D)
5276         X = B, Y = A, Z = C;
5277       
5278       if (X) {
5279         Instruction *NewOp =
5280         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5281         return BinaryOperator::CreateAnd(NewOp, X);
5282       }
5283     }
5284   }
5285     
5286   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5287   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5288     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5289       return R;
5290
5291   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5292   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5293     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5294       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5295         const Type *SrcTy = Op0C->getOperand(0)->getType();
5296         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5297             // Only do this if the casts both really cause code to be generated.
5298             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5299                               I.getType(), TD) &&
5300             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5301                               I.getType(), TD)) {
5302           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5303                                                          Op1C->getOperand(0),
5304                                                          I.getName());
5305           InsertNewInstBefore(NewOp, I);
5306           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5307         }
5308       }
5309   }
5310
5311   return Changed ? &I : 0;
5312 }
5313
5314 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5315                                    LLVMContext *Context) {
5316   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5317 }
5318
5319 static bool HasAddOverflow(ConstantInt *Result,
5320                            ConstantInt *In1, ConstantInt *In2,
5321                            bool IsSigned) {
5322   if (IsSigned)
5323     if (In2->getValue().isNegative())
5324       return Result->getValue().sgt(In1->getValue());
5325     else
5326       return Result->getValue().slt(In1->getValue());
5327   else
5328     return Result->getValue().ult(In1->getValue());
5329 }
5330
5331 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5332 /// overflowed for this type.
5333 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5334                             Constant *In2, LLVMContext *Context,
5335                             bool IsSigned = false) {
5336   Result = ConstantExpr::getAdd(In1, In2);
5337
5338   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5339     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5340       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5341       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5342                          ExtractElement(In1, Idx, Context),
5343                          ExtractElement(In2, Idx, Context),
5344                          IsSigned))
5345         return true;
5346     }
5347     return false;
5348   }
5349
5350   return HasAddOverflow(cast<ConstantInt>(Result),
5351                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5352                         IsSigned);
5353 }
5354
5355 static bool HasSubOverflow(ConstantInt *Result,
5356                            ConstantInt *In1, ConstantInt *In2,
5357                            bool IsSigned) {
5358   if (IsSigned)
5359     if (In2->getValue().isNegative())
5360       return Result->getValue().slt(In1->getValue());
5361     else
5362       return Result->getValue().sgt(In1->getValue());
5363   else
5364     return Result->getValue().ugt(In1->getValue());
5365 }
5366
5367 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5368 /// overflowed for this type.
5369 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5370                             Constant *In2, LLVMContext *Context,
5371                             bool IsSigned = false) {
5372   Result = ConstantExpr::getSub(In1, In2);
5373
5374   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5375     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5376       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5377       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5378                          ExtractElement(In1, Idx, Context),
5379                          ExtractElement(In2, Idx, Context),
5380                          IsSigned))
5381         return true;
5382     }
5383     return false;
5384   }
5385
5386   return HasSubOverflow(cast<ConstantInt>(Result),
5387                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5388                         IsSigned);
5389 }
5390
5391 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5392 /// code necessary to compute the offset from the base pointer (without adding
5393 /// in the base pointer).  Return the result as a signed integer of intptr size.
5394 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5395   TargetData &TD = *IC.getTargetData();
5396   gep_type_iterator GTI = gep_type_begin(GEP);
5397   const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
5398   LLVMContext *Context = IC.getContext();
5399   Value *Result = Constant::getNullValue(IntPtrTy);
5400
5401   // Build a mask for high order bits.
5402   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5403   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5404
5405   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5406        ++i, ++GTI) {
5407     Value *Op = *i;
5408     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5409     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5410       if (OpC->isZero()) continue;
5411       
5412       // Handle a struct index, which adds its field offset to the pointer.
5413       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5414         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5415         
5416         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5417           Result = 
5418              ConstantInt::get(*Context, 
5419                               RC->getValue() + APInt(IntPtrWidth, Size));
5420         else
5421           Result = IC.InsertNewInstBefore(
5422                    BinaryOperator::CreateAdd(Result,
5423                                         ConstantInt::get(IntPtrTy, Size),
5424                                              GEP->getName()+".offs"), I);
5425         continue;
5426       }
5427       
5428       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5429       Constant *OC =
5430               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5431       Scale = ConstantExpr::getMul(OC, Scale);
5432       if (Constant *RC = dyn_cast<Constant>(Result))
5433         Result = ConstantExpr::getAdd(RC, Scale);
5434       else {
5435         // Emit an add instruction.
5436         Result = IC.InsertNewInstBefore(
5437            BinaryOperator::CreateAdd(Result, Scale,
5438                                      GEP->getName()+".offs"), I);
5439       }
5440       continue;
5441     }
5442     // Convert to correct type.
5443     if (Op->getType() != IntPtrTy) {
5444       if (Constant *OpC = dyn_cast<Constant>(Op))
5445         Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
5446       else
5447         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5448                                                                 true,
5449                                                       Op->getName()+".c"), I);
5450     }
5451     if (Size != 1) {
5452       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5453       if (Constant *OpC = dyn_cast<Constant>(Op))
5454         Op = ConstantExpr::getMul(OpC, Scale);
5455       else    // We'll let instcombine(mul) convert this to a shl if possible.
5456         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5457                                                   GEP->getName()+".idx"), I);
5458     }
5459
5460     // Emit an add instruction.
5461     if (isa<Constant>(Op) && isa<Constant>(Result))
5462       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5463                                     cast<Constant>(Result));
5464     else
5465       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5466                                                   GEP->getName()+".offs"), I);
5467   }
5468   return Result;
5469 }
5470
5471
5472 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5473 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5474 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5475 /// be complex, and scales are involved.  The above expression would also be
5476 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5477 /// This later form is less amenable to optimization though, and we are allowed
5478 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5479 ///
5480 /// If we can't emit an optimized form for this expression, this returns null.
5481 /// 
5482 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5483                                           InstCombiner &IC) {
5484   TargetData &TD = *IC.getTargetData();
5485   gep_type_iterator GTI = gep_type_begin(GEP);
5486
5487   // Check to see if this gep only has a single variable index.  If so, and if
5488   // any constant indices are a multiple of its scale, then we can compute this
5489   // in terms of the scale of the variable index.  For example, if the GEP
5490   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5491   // because the expression will cross zero at the same point.
5492   unsigned i, e = GEP->getNumOperands();
5493   int64_t Offset = 0;
5494   for (i = 1; i != e; ++i, ++GTI) {
5495     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5496       // Compute the aggregate offset of constant indices.
5497       if (CI->isZero()) continue;
5498
5499       // Handle a struct index, which adds its field offset to the pointer.
5500       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5501         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5502       } else {
5503         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5504         Offset += Size*CI->getSExtValue();
5505       }
5506     } else {
5507       // Found our variable index.
5508       break;
5509     }
5510   }
5511   
5512   // If there are no variable indices, we must have a constant offset, just
5513   // evaluate it the general way.
5514   if (i == e) return 0;
5515   
5516   Value *VariableIdx = GEP->getOperand(i);
5517   // Determine the scale factor of the variable element.  For example, this is
5518   // 4 if the variable index is into an array of i32.
5519   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5520   
5521   // Verify that there are no other variable indices.  If so, emit the hard way.
5522   for (++i, ++GTI; i != e; ++i, ++GTI) {
5523     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5524     if (!CI) return 0;
5525    
5526     // Compute the aggregate offset of constant indices.
5527     if (CI->isZero()) continue;
5528     
5529     // Handle a struct index, which adds its field offset to the pointer.
5530     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5531       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5532     } else {
5533       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5534       Offset += Size*CI->getSExtValue();
5535     }
5536   }
5537   
5538   // Okay, we know we have a single variable index, which must be a
5539   // pointer/array/vector index.  If there is no offset, life is simple, return
5540   // the index.
5541   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5542   if (Offset == 0) {
5543     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5544     // we don't need to bother extending: the extension won't affect where the
5545     // computation crosses zero.
5546     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5547       VariableIdx = new TruncInst(VariableIdx, 
5548                                   TD.getIntPtrType(VariableIdx->getContext()),
5549                                   VariableIdx->getName(), &I);
5550     return VariableIdx;
5551   }
5552   
5553   // Otherwise, there is an index.  The computation we will do will be modulo
5554   // the pointer size, so get it.
5555   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5556   
5557   Offset &= PtrSizeMask;
5558   VariableScale &= PtrSizeMask;
5559
5560   // To do this transformation, any constant index must be a multiple of the
5561   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5562   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5563   // multiple of the variable scale.
5564   int64_t NewOffs = Offset / (int64_t)VariableScale;
5565   if (Offset != NewOffs*(int64_t)VariableScale)
5566     return 0;
5567
5568   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5569   const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
5570   if (VariableIdx->getType() != IntPtrTy)
5571     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5572                                               true /*SExt*/, 
5573                                               VariableIdx->getName(), &I);
5574   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5575   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5576 }
5577
5578
5579 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5580 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5581 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5582                                        ICmpInst::Predicate Cond,
5583                                        Instruction &I) {
5584   // Look through bitcasts.
5585   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5586     RHS = BCI->getOperand(0);
5587
5588   Value *PtrBase = GEPLHS->getOperand(0);
5589   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5590     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5591     // This transformation (ignoring the base and scales) is valid because we
5592     // know pointers can't overflow since the gep is inbounds.  See if we can
5593     // output an optimized form.
5594     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5595     
5596     // If not, synthesize the offset the hard way.
5597     if (Offset == 0)
5598       Offset = EmitGEPOffset(GEPLHS, I, *this);
5599     return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
5600                         Constant::getNullValue(Offset->getType()));
5601   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5602     // If the base pointers are different, but the indices are the same, just
5603     // compare the base pointer.
5604     if (PtrBase != GEPRHS->getOperand(0)) {
5605       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5606       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5607                         GEPRHS->getOperand(0)->getType();
5608       if (IndicesTheSame)
5609         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5610           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5611             IndicesTheSame = false;
5612             break;
5613           }
5614
5615       // If all indices are the same, just compare the base pointers.
5616       if (IndicesTheSame)
5617         return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), 
5618                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5619
5620       // Otherwise, the base pointers are different and the indices are
5621       // different, bail out.
5622       return 0;
5623     }
5624
5625     // If one of the GEPs has all zero indices, recurse.
5626     bool AllZeros = true;
5627     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5628       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5629           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5630         AllZeros = false;
5631         break;
5632       }
5633     if (AllZeros)
5634       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5635                           ICmpInst::getSwappedPredicate(Cond), I);
5636
5637     // If the other GEP has all zero indices, recurse.
5638     AllZeros = true;
5639     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5640       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5641           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5642         AllZeros = false;
5643         break;
5644       }
5645     if (AllZeros)
5646       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5647
5648     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5649       // If the GEPs only differ by one index, compare it.
5650       unsigned NumDifferences = 0;  // Keep track of # differences.
5651       unsigned DiffOperand = 0;     // The operand that differs.
5652       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5653         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5654           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5655                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5656             // Irreconcilable differences.
5657             NumDifferences = 2;
5658             break;
5659           } else {
5660             if (NumDifferences++) break;
5661             DiffOperand = i;
5662           }
5663         }
5664
5665       if (NumDifferences == 0)   // SAME GEP?
5666         return ReplaceInstUsesWith(I, // No comparison is needed here.
5667                                    ConstantInt::get(Type::getInt1Ty(*Context),
5668                                              ICmpInst::isTrueWhenEqual(Cond)));
5669
5670       else if (NumDifferences == 1) {
5671         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5672         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5673         // Make sure we do a signed comparison here.
5674         return new ICmpInst(*Context,
5675                             ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5676       }
5677     }
5678
5679     // Only lower this if the icmp is the only user of the GEP or if we expect
5680     // the result to fold to a constant!
5681     if (TD &&
5682         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5683         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5684       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5685       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5686       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5687       return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
5688     }
5689   }
5690   return 0;
5691 }
5692
5693 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5694 ///
5695 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5696                                                 Instruction *LHSI,
5697                                                 Constant *RHSC) {
5698   if (!isa<ConstantFP>(RHSC)) return 0;
5699   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5700   
5701   // Get the width of the mantissa.  We don't want to hack on conversions that
5702   // might lose information from the integer, e.g. "i64 -> float"
5703   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5704   if (MantissaWidth == -1) return 0;  // Unknown.
5705   
5706   // Check to see that the input is converted from an integer type that is small
5707   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5708   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5709   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5710   
5711   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5712   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5713   if (LHSUnsigned)
5714     ++InputSize;
5715   
5716   // If the conversion would lose info, don't hack on this.
5717   if ((int)InputSize > MantissaWidth)
5718     return 0;
5719   
5720   // Otherwise, we can potentially simplify the comparison.  We know that it
5721   // will always come through as an integer value and we know the constant is
5722   // not a NAN (it would have been previously simplified).
5723   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5724   
5725   ICmpInst::Predicate Pred;
5726   switch (I.getPredicate()) {
5727   default: llvm_unreachable("Unexpected predicate!");
5728   case FCmpInst::FCMP_UEQ:
5729   case FCmpInst::FCMP_OEQ:
5730     Pred = ICmpInst::ICMP_EQ;
5731     break;
5732   case FCmpInst::FCMP_UGT:
5733   case FCmpInst::FCMP_OGT:
5734     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5735     break;
5736   case FCmpInst::FCMP_UGE:
5737   case FCmpInst::FCMP_OGE:
5738     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5739     break;
5740   case FCmpInst::FCMP_ULT:
5741   case FCmpInst::FCMP_OLT:
5742     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5743     break;
5744   case FCmpInst::FCMP_ULE:
5745   case FCmpInst::FCMP_OLE:
5746     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5747     break;
5748   case FCmpInst::FCMP_UNE:
5749   case FCmpInst::FCMP_ONE:
5750     Pred = ICmpInst::ICMP_NE;
5751     break;
5752   case FCmpInst::FCMP_ORD:
5753     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5754   case FCmpInst::FCMP_UNO:
5755     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5756   }
5757   
5758   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5759   
5760   // Now we know that the APFloat is a normal number, zero or inf.
5761   
5762   // See if the FP constant is too large for the integer.  For example,
5763   // comparing an i8 to 300.0.
5764   unsigned IntWidth = IntTy->getScalarSizeInBits();
5765   
5766   if (!LHSUnsigned) {
5767     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5768     // and large values.
5769     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5770     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5771                           APFloat::rmNearestTiesToEven);
5772     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5773       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5774           Pred == ICmpInst::ICMP_SLE)
5775         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5776       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5777     }
5778   } else {
5779     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5780     // +INF and large values.
5781     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5782     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5783                           APFloat::rmNearestTiesToEven);
5784     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5785       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5786           Pred == ICmpInst::ICMP_ULE)
5787         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5788       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5789     }
5790   }
5791   
5792   if (!LHSUnsigned) {
5793     // See if the RHS value is < SignedMin.
5794     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5795     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5796                           APFloat::rmNearestTiesToEven);
5797     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5798       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5799           Pred == ICmpInst::ICMP_SGE)
5800         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5801       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5802     }
5803   }
5804
5805   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5806   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5807   // casting the FP value to the integer value and back, checking for equality.
5808   // Don't do this for zero, because -0.0 is not fractional.
5809   Constant *RHSInt = LHSUnsigned
5810     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5811     : ConstantExpr::getFPToSI(RHSC, IntTy);
5812   if (!RHS.isZero()) {
5813     bool Equal = LHSUnsigned
5814       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5815       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5816     if (!Equal) {
5817       // If we had a comparison against a fractional value, we have to adjust
5818       // the compare predicate and sometimes the value.  RHSC is rounded towards
5819       // zero at this point.
5820       switch (Pred) {
5821       default: llvm_unreachable("Unexpected integer comparison!");
5822       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5823         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5824       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5825         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5826       case ICmpInst::ICMP_ULE:
5827         // (float)int <= 4.4   --> int <= 4
5828         // (float)int <= -4.4  --> false
5829         if (RHS.isNegative())
5830           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5831         break;
5832       case ICmpInst::ICMP_SLE:
5833         // (float)int <= 4.4   --> int <= 4
5834         // (float)int <= -4.4  --> int < -4
5835         if (RHS.isNegative())
5836           Pred = ICmpInst::ICMP_SLT;
5837         break;
5838       case ICmpInst::ICMP_ULT:
5839         // (float)int < -4.4   --> false
5840         // (float)int < 4.4    --> int <= 4
5841         if (RHS.isNegative())
5842           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5843         Pred = ICmpInst::ICMP_ULE;
5844         break;
5845       case ICmpInst::ICMP_SLT:
5846         // (float)int < -4.4   --> int < -4
5847         // (float)int < 4.4    --> int <= 4
5848         if (!RHS.isNegative())
5849           Pred = ICmpInst::ICMP_SLE;
5850         break;
5851       case ICmpInst::ICMP_UGT:
5852         // (float)int > 4.4    --> int > 4
5853         // (float)int > -4.4   --> true
5854         if (RHS.isNegative())
5855           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5856         break;
5857       case ICmpInst::ICMP_SGT:
5858         // (float)int > 4.4    --> int > 4
5859         // (float)int > -4.4   --> int >= -4
5860         if (RHS.isNegative())
5861           Pred = ICmpInst::ICMP_SGE;
5862         break;
5863       case ICmpInst::ICMP_UGE:
5864         // (float)int >= -4.4   --> true
5865         // (float)int >= 4.4    --> int > 4
5866         if (!RHS.isNegative())
5867           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5868         Pred = ICmpInst::ICMP_UGT;
5869         break;
5870       case ICmpInst::ICMP_SGE:
5871         // (float)int >= -4.4   --> int >= -4
5872         // (float)int >= 4.4    --> int > 4
5873         if (!RHS.isNegative())
5874           Pred = ICmpInst::ICMP_SGT;
5875         break;
5876       }
5877     }
5878   }
5879
5880   // Lower this FP comparison into an appropriate integer version of the
5881   // comparison.
5882   return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
5883 }
5884
5885 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5886   bool Changed = SimplifyCompare(I);
5887   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5888
5889   // Fold trivial predicates.
5890   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5891     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5892   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5893     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5894   
5895   // Simplify 'fcmp pred X, X'
5896   if (Op0 == Op1) {
5897     switch (I.getPredicate()) {
5898     default: llvm_unreachable("Unknown predicate!");
5899     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5900     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5901     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5902       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5903     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5904     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5905     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5906       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5907       
5908     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5909     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5910     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5911     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5912       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5913       I.setPredicate(FCmpInst::FCMP_UNO);
5914       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5915       return &I;
5916       
5917     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5918     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5919     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5920     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5921       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5922       I.setPredicate(FCmpInst::FCMP_ORD);
5923       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5924       return &I;
5925     }
5926   }
5927     
5928   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5929     return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
5930
5931   // Handle fcmp with constant RHS
5932   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5933     // If the constant is a nan, see if we can fold the comparison based on it.
5934     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5935       if (CFP->getValueAPF().isNaN()) {
5936         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5937           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5938         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5939                "Comparison must be either ordered or unordered!");
5940         // True if unordered.
5941         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5942       }
5943     }
5944     
5945     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5946       switch (LHSI->getOpcode()) {
5947       case Instruction::PHI:
5948         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5949         // block.  If in the same block, we're encouraging jump threading.  If
5950         // not, we are just pessimizing the code by making an i1 phi.
5951         if (LHSI->getParent() == I.getParent())
5952           if (Instruction *NV = FoldOpIntoPhi(I))
5953             return NV;
5954         break;
5955       case Instruction::SIToFP:
5956       case Instruction::UIToFP:
5957         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5958           return NV;
5959         break;
5960       case Instruction::Select:
5961         // If either operand of the select is a constant, we can fold the
5962         // comparison into the select arms, which will cause one to be
5963         // constant folded and the select turned into a bitwise or.
5964         Value *Op1 = 0, *Op2 = 0;
5965         if (LHSI->hasOneUse()) {
5966           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5967             // Fold the known value into the constant operand.
5968             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5969             // Insert a new FCmp of the other select operand.
5970             Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5971                                                       LHSI->getOperand(2), RHSC,
5972                                                       I.getName()), I);
5973           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5974             // Fold the known value into the constant operand.
5975             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5976             // Insert a new FCmp of the other select operand.
5977             Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5978                                                       LHSI->getOperand(1), RHSC,
5979                                                       I.getName()), I);
5980           }
5981         }
5982
5983         if (Op1)
5984           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5985         break;
5986       }
5987   }
5988
5989   return Changed ? &I : 0;
5990 }
5991
5992 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5993   bool Changed = SimplifyCompare(I);
5994   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5995   const Type *Ty = Op0->getType();
5996
5997   // icmp X, X
5998   if (Op0 == Op1)
5999     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
6000                                                    I.isTrueWhenEqual()));
6001
6002   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
6003     return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
6004   
6005   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
6006   // addresses never equal each other!  We already know that Op0 != Op1.
6007   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
6008        isa<ConstantPointerNull>(Op0)) &&
6009       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
6010        isa<ConstantPointerNull>(Op1)))
6011     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
6012                                                    !I.isTrueWhenEqual()));
6013
6014   // icmp's with boolean values can always be turned into bitwise operations
6015   if (Ty == Type::getInt1Ty(*Context)) {
6016     switch (I.getPredicate()) {
6017     default: llvm_unreachable("Invalid icmp instruction!");
6018     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
6019       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
6020       InsertNewInstBefore(Xor, I);
6021       return BinaryOperator::CreateNot(Xor);
6022     }
6023     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6024       return BinaryOperator::CreateXor(Op0, Op1);
6025
6026     case ICmpInst::ICMP_UGT:
6027       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6028       // FALL THROUGH
6029     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6030       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
6031       InsertNewInstBefore(Not, I);
6032       return BinaryOperator::CreateAnd(Not, Op1);
6033     }
6034     case ICmpInst::ICMP_SGT:
6035       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6036       // FALL THROUGH
6037     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6038       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6039       InsertNewInstBefore(Not, I);
6040       return BinaryOperator::CreateAnd(Not, Op0);
6041     }
6042     case ICmpInst::ICMP_UGE:
6043       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6044       // FALL THROUGH
6045     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6046       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
6047       InsertNewInstBefore(Not, I);
6048       return BinaryOperator::CreateOr(Not, Op1);
6049     }
6050     case ICmpInst::ICMP_SGE:
6051       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6052       // FALL THROUGH
6053     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6054       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6055       InsertNewInstBefore(Not, I);
6056       return BinaryOperator::CreateOr(Not, Op0);
6057     }
6058     }
6059   }
6060
6061   unsigned BitWidth = 0;
6062   if (TD)
6063     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6064   else if (Ty->isIntOrIntVector())
6065     BitWidth = Ty->getScalarSizeInBits();
6066
6067   bool isSignBit = false;
6068
6069   // See if we are doing a comparison with a constant.
6070   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6071     Value *A = 0, *B = 0;
6072     
6073     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6074     if (I.isEquality() && CI->isNullValue() &&
6075         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6076       // (icmp cond A B) if cond is equality
6077       return new ICmpInst(*Context, I.getPredicate(), A, B);
6078     }
6079     
6080     // If we have an icmp le or icmp ge instruction, turn it into the
6081     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6082     // them being folded in the code below.
6083     switch (I.getPredicate()) {
6084     default: break;
6085     case ICmpInst::ICMP_ULE:
6086       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6087         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6088       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6089                           AddOne(CI));
6090     case ICmpInst::ICMP_SLE:
6091       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6092         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6093       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6094                           AddOne(CI));
6095     case ICmpInst::ICMP_UGE:
6096       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6097         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6098       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6099                           SubOne(CI));
6100     case ICmpInst::ICMP_SGE:
6101       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6102         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6103       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6104                           SubOne(CI));
6105     }
6106     
6107     // If this comparison is a normal comparison, it demands all
6108     // bits, if it is a sign bit comparison, it only demands the sign bit.
6109     bool UnusedBit;
6110     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6111   }
6112
6113   // See if we can fold the comparison based on range information we can get
6114   // by checking whether bits are known to be zero or one in the input.
6115   if (BitWidth != 0) {
6116     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6117     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6118
6119     if (SimplifyDemandedBits(I.getOperandUse(0),
6120                              isSignBit ? APInt::getSignBit(BitWidth)
6121                                        : APInt::getAllOnesValue(BitWidth),
6122                              Op0KnownZero, Op0KnownOne, 0))
6123       return &I;
6124     if (SimplifyDemandedBits(I.getOperandUse(1),
6125                              APInt::getAllOnesValue(BitWidth),
6126                              Op1KnownZero, Op1KnownOne, 0))
6127       return &I;
6128
6129     // Given the known and unknown bits, compute a range that the LHS could be
6130     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6131     // EQ and NE we use unsigned values.
6132     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6133     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6134     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6135       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6136                                              Op0Min, Op0Max);
6137       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6138                                              Op1Min, Op1Max);
6139     } else {
6140       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6141                                                Op0Min, Op0Max);
6142       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6143                                                Op1Min, Op1Max);
6144     }
6145
6146     // If Min and Max are known to be the same, then SimplifyDemandedBits
6147     // figured out that the LHS is a constant.  Just constant fold this now so
6148     // that code below can assume that Min != Max.
6149     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6150       return new ICmpInst(*Context, I.getPredicate(),
6151                           ConstantInt::get(*Context, Op0Min), Op1);
6152     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6153       return new ICmpInst(*Context, I.getPredicate(), Op0, 
6154                           ConstantInt::get(*Context, Op1Min));
6155
6156     // Based on the range information we know about the LHS, see if we can
6157     // simplify this comparison.  For example, (x&4) < 8  is always true.
6158     switch (I.getPredicate()) {
6159     default: llvm_unreachable("Unknown icmp opcode!");
6160     case ICmpInst::ICMP_EQ:
6161       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6162         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6163       break;
6164     case ICmpInst::ICMP_NE:
6165       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6166         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6167       break;
6168     case ICmpInst::ICMP_ULT:
6169       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6170         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6171       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6172         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6173       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6174         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6175       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6176         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6177           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6178                               SubOne(CI));
6179
6180         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6181         if (CI->isMinValue(true))
6182           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6183                            Constant::getAllOnesValue(Op0->getType()));
6184       }
6185       break;
6186     case ICmpInst::ICMP_UGT:
6187       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6188         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6189       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6190         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6191
6192       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6193         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6194       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6195         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6196           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6197                               AddOne(CI));
6198
6199         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6200         if (CI->isMaxValue(true))
6201           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6202                               Constant::getNullValue(Op0->getType()));
6203       }
6204       break;
6205     case ICmpInst::ICMP_SLT:
6206       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6207         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6208       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6209         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6210       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6211         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6212       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6213         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6214           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6215                               SubOne(CI));
6216       }
6217       break;
6218     case ICmpInst::ICMP_SGT:
6219       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6220         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6221       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6222         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6223
6224       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6225         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6226       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6227         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6228           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6229                               AddOne(CI));
6230       }
6231       break;
6232     case ICmpInst::ICMP_SGE:
6233       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6234       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6235         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6236       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6237         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6238       break;
6239     case ICmpInst::ICMP_SLE:
6240       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6241       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6242         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6243       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6244         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6245       break;
6246     case ICmpInst::ICMP_UGE:
6247       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6248       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6249         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6250       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6251         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6252       break;
6253     case ICmpInst::ICMP_ULE:
6254       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6255       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6256         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6257       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6258         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6259       break;
6260     }
6261
6262     // Turn a signed comparison into an unsigned one if both operands
6263     // are known to have the same sign.
6264     if (I.isSignedPredicate() &&
6265         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6266          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6267       return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
6268   }
6269
6270   // Test if the ICmpInst instruction is used exclusively by a select as
6271   // part of a minimum or maximum operation. If so, refrain from doing
6272   // any other folding. This helps out other analyses which understand
6273   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6274   // and CodeGen. And in this case, at least one of the comparison
6275   // operands has at least one user besides the compare (the select),
6276   // which would often largely negate the benefit of folding anyway.
6277   if (I.hasOneUse())
6278     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6279       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6280           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6281         return 0;
6282
6283   // See if we are doing a comparison between a constant and an instruction that
6284   // can be folded into the comparison.
6285   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6286     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6287     // instruction, see if that instruction also has constants so that the 
6288     // instruction can be folded into the icmp 
6289     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6290       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6291         return Res;
6292   }
6293
6294   // Handle icmp with constant (but not simple integer constant) RHS
6295   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6296     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6297       switch (LHSI->getOpcode()) {
6298       case Instruction::GetElementPtr:
6299         if (RHSC->isNullValue()) {
6300           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6301           bool isAllZeros = true;
6302           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6303             if (!isa<Constant>(LHSI->getOperand(i)) ||
6304                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6305               isAllZeros = false;
6306               break;
6307             }
6308           if (isAllZeros)
6309             return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
6310                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6311         }
6312         break;
6313
6314       case Instruction::PHI:
6315         // Only fold icmp into the PHI if the phi and fcmp are in the same
6316         // block.  If in the same block, we're encouraging jump threading.  If
6317         // not, we are just pessimizing the code by making an i1 phi.
6318         if (LHSI->getParent() == I.getParent())
6319           if (Instruction *NV = FoldOpIntoPhi(I))
6320             return NV;
6321         break;
6322       case Instruction::Select: {
6323         // If either operand of the select is a constant, we can fold the
6324         // comparison into the select arms, which will cause one to be
6325         // constant folded and the select turned into a bitwise or.
6326         Value *Op1 = 0, *Op2 = 0;
6327         if (LHSI->hasOneUse()) {
6328           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6329             // Fold the known value into the constant operand.
6330             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6331             // Insert a new ICmp of the other select operand.
6332             Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6333                                                    LHSI->getOperand(2), RHSC,
6334                                                    I.getName()), I);
6335           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6336             // Fold the known value into the constant operand.
6337             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6338             // Insert a new ICmp of the other select operand.
6339             Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6340                                                    LHSI->getOperand(1), RHSC,
6341                                                    I.getName()), I);
6342           }
6343         }
6344
6345         if (Op1)
6346           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6347         break;
6348       }
6349       case Instruction::Malloc:
6350         // If we have (malloc != null), and if the malloc has a single use, we
6351         // can assume it is successful and remove the malloc.
6352         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6353           AddToWorkList(LHSI);
6354           return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
6355                                                          !I.isTrueWhenEqual()));
6356         }
6357         break;
6358       }
6359   }
6360
6361   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6362   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6363     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6364       return NI;
6365   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6366     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6367                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6368       return NI;
6369
6370   // Test to see if the operands of the icmp are casted versions of other
6371   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6372   // now.
6373   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6374     if (isa<PointerType>(Op0->getType()) && 
6375         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6376       // We keep moving the cast from the left operand over to the right
6377       // operand, where it can often be eliminated completely.
6378       Op0 = CI->getOperand(0);
6379
6380       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6381       // so eliminate it as well.
6382       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6383         Op1 = CI2->getOperand(0);
6384
6385       // If Op1 is a constant, we can fold the cast into the constant.
6386       if (Op0->getType() != Op1->getType()) {
6387         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6388           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6389         } else {
6390           // Otherwise, cast the RHS right before the icmp
6391           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6392         }
6393       }
6394       return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
6395     }
6396   }
6397   
6398   if (isa<CastInst>(Op0)) {
6399     // Handle the special case of: icmp (cast bool to X), <cst>
6400     // This comes up when you have code like
6401     //   int X = A < B;
6402     //   if (X) ...
6403     // For generality, we handle any zero-extension of any operand comparison
6404     // with a constant or another cast from the same type.
6405     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6406       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6407         return R;
6408   }
6409   
6410   // See if it's the same type of instruction on the left and right.
6411   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6412     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6413       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6414           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6415         switch (Op0I->getOpcode()) {
6416         default: break;
6417         case Instruction::Add:
6418         case Instruction::Sub:
6419         case Instruction::Xor:
6420           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6421             return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
6422                                 Op1I->getOperand(0));
6423           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6424           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6425             if (CI->getValue().isSignBit()) {
6426               ICmpInst::Predicate Pred = I.isSignedPredicate()
6427                                              ? I.getUnsignedPredicate()
6428                                              : I.getSignedPredicate();
6429               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6430                                   Op1I->getOperand(0));
6431             }
6432             
6433             if (CI->getValue().isMaxSignedValue()) {
6434               ICmpInst::Predicate Pred = I.isSignedPredicate()
6435                                              ? I.getUnsignedPredicate()
6436                                              : I.getSignedPredicate();
6437               Pred = I.getSwappedPredicate(Pred);
6438               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6439                                   Op1I->getOperand(0));
6440             }
6441           }
6442           break;
6443         case Instruction::Mul:
6444           if (!I.isEquality())
6445             break;
6446
6447           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6448             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6449             // Mask = -1 >> count-trailing-zeros(Cst).
6450             if (!CI->isZero() && !CI->isOne()) {
6451               const APInt &AP = CI->getValue();
6452               ConstantInt *Mask = ConstantInt::get(*Context, 
6453                                       APInt::getLowBitsSet(AP.getBitWidth(),
6454                                                            AP.getBitWidth() -
6455                                                       AP.countTrailingZeros()));
6456               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6457                                                             Mask);
6458               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6459                                                             Mask);
6460               InsertNewInstBefore(And1, I);
6461               InsertNewInstBefore(And2, I);
6462               return new ICmpInst(*Context, I.getPredicate(), And1, And2);
6463             }
6464           }
6465           break;
6466         }
6467       }
6468     }
6469   }
6470   
6471   // ~x < ~y --> y < x
6472   { Value *A, *B;
6473     if (match(Op0, m_Not(m_Value(A))) &&
6474         match(Op1, m_Not(m_Value(B))))
6475       return new ICmpInst(*Context, I.getPredicate(), B, A);
6476   }
6477   
6478   if (I.isEquality()) {
6479     Value *A, *B, *C, *D;
6480     
6481     // -x == -y --> x == y
6482     if (match(Op0, m_Neg(m_Value(A))) &&
6483         match(Op1, m_Neg(m_Value(B))))
6484       return new ICmpInst(*Context, I.getPredicate(), A, B);
6485     
6486     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6487       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6488         Value *OtherVal = A == Op1 ? B : A;
6489         return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6490                             Constant::getNullValue(A->getType()));
6491       }
6492
6493       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6494         // A^c1 == C^c2 --> A == C^(c1^c2)
6495         ConstantInt *C1, *C2;
6496         if (match(B, m_ConstantInt(C1)) &&
6497             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6498           Constant *NC = 
6499                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6500           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6501           return new ICmpInst(*Context, I.getPredicate(), A,
6502                               InsertNewInstBefore(Xor, I));
6503         }
6504         
6505         // A^B == A^D -> B == D
6506         if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6507         if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6508         if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6509         if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
6510       }
6511     }
6512     
6513     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6514         (A == Op0 || B == Op0)) {
6515       // A == (A^B)  ->  B == 0
6516       Value *OtherVal = A == Op0 ? B : A;
6517       return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6518                           Constant::getNullValue(A->getType()));
6519     }
6520
6521     // (A-B) == A  ->  B == 0
6522     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6523       return new ICmpInst(*Context, I.getPredicate(), B, 
6524                           Constant::getNullValue(B->getType()));
6525
6526     // A == (A-B)  ->  B == 0
6527     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6528       return new ICmpInst(*Context, I.getPredicate(), B,
6529                           Constant::getNullValue(B->getType()));
6530     
6531     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6532     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6533         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6534         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6535       Value *X = 0, *Y = 0, *Z = 0;
6536       
6537       if (A == C) {
6538         X = B; Y = D; Z = A;
6539       } else if (A == D) {
6540         X = B; Y = C; Z = A;
6541       } else if (B == C) {
6542         X = A; Y = D; Z = B;
6543       } else if (B == D) {
6544         X = A; Y = C; Z = B;
6545       }
6546       
6547       if (X) {   // Build (X^Y) & Z
6548         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6549         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6550         I.setOperand(0, Op1);
6551         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6552         return &I;
6553       }
6554     }
6555   }
6556   return Changed ? &I : 0;
6557 }
6558
6559
6560 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6561 /// and CmpRHS are both known to be integer constants.
6562 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6563                                           ConstantInt *DivRHS) {
6564   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6565   const APInt &CmpRHSV = CmpRHS->getValue();
6566   
6567   // FIXME: If the operand types don't match the type of the divide 
6568   // then don't attempt this transform. The code below doesn't have the
6569   // logic to deal with a signed divide and an unsigned compare (and
6570   // vice versa). This is because (x /s C1) <s C2  produces different 
6571   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6572   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6573   // work. :(  The if statement below tests that condition and bails 
6574   // if it finds it. 
6575   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6576   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6577     return 0;
6578   if (DivRHS->isZero())
6579     return 0; // The ProdOV computation fails on divide by zero.
6580   if (DivIsSigned && DivRHS->isAllOnesValue())
6581     return 0; // The overflow computation also screws up here
6582   if (DivRHS->isOne())
6583     return 0; // Not worth bothering, and eliminates some funny cases
6584               // with INT_MIN.
6585
6586   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6587   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6588   // C2 (CI). By solving for X we can turn this into a range check 
6589   // instead of computing a divide. 
6590   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6591
6592   // Determine if the product overflows by seeing if the product is
6593   // not equal to the divide. Make sure we do the same kind of divide
6594   // as in the LHS instruction that we're folding. 
6595   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6596                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6597
6598   // Get the ICmp opcode
6599   ICmpInst::Predicate Pred = ICI.getPredicate();
6600
6601   // Figure out the interval that is being checked.  For example, a comparison
6602   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6603   // Compute this interval based on the constants involved and the signedness of
6604   // the compare/divide.  This computes a half-open interval, keeping track of
6605   // whether either value in the interval overflows.  After analysis each
6606   // overflow variable is set to 0 if it's corresponding bound variable is valid
6607   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6608   int LoOverflow = 0, HiOverflow = 0;
6609   Constant *LoBound = 0, *HiBound = 0;
6610   
6611   if (!DivIsSigned) {  // udiv
6612     // e.g. X/5 op 3  --> [15, 20)
6613     LoBound = Prod;
6614     HiOverflow = LoOverflow = ProdOV;
6615     if (!HiOverflow)
6616       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6617   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6618     if (CmpRHSV == 0) {       // (X / pos) op 0
6619       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6620       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6621       HiBound = DivRHS;
6622     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6623       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6624       HiOverflow = LoOverflow = ProdOV;
6625       if (!HiOverflow)
6626         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6627     } else {                       // (X / pos) op neg
6628       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6629       HiBound = AddOne(Prod);
6630       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6631       if (!LoOverflow) {
6632         ConstantInt* DivNeg =
6633                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6634         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6635                                      true) ? -1 : 0;
6636        }
6637     }
6638   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6639     if (CmpRHSV == 0) {       // (X / neg) op 0
6640       // e.g. X/-5 op 0  --> [-4, 5)
6641       LoBound = AddOne(DivRHS);
6642       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6643       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6644         HiOverflow = 1;            // [INTMIN+1, overflow)
6645         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6646       }
6647     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6648       // e.g. X/-5 op 3  --> [-19, -14)
6649       HiBound = AddOne(Prod);
6650       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6651       if (!LoOverflow)
6652         LoOverflow = AddWithOverflow(LoBound, HiBound,
6653                                      DivRHS, Context, true) ? -1 : 0;
6654     } else {                       // (X / neg) op neg
6655       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6656       LoOverflow = HiOverflow = ProdOV;
6657       if (!HiOverflow)
6658         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6659     }
6660     
6661     // Dividing by a negative swaps the condition.  LT <-> GT
6662     Pred = ICmpInst::getSwappedPredicate(Pred);
6663   }
6664
6665   Value *X = DivI->getOperand(0);
6666   switch (Pred) {
6667   default: llvm_unreachable("Unhandled icmp opcode!");
6668   case ICmpInst::ICMP_EQ:
6669     if (LoOverflow && HiOverflow)
6670       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6671     else if (HiOverflow)
6672       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6673                           ICmpInst::ICMP_UGE, X, LoBound);
6674     else if (LoOverflow)
6675       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6676                           ICmpInst::ICMP_ULT, X, HiBound);
6677     else
6678       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6679   case ICmpInst::ICMP_NE:
6680     if (LoOverflow && HiOverflow)
6681       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6682     else if (HiOverflow)
6683       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6684                           ICmpInst::ICMP_ULT, X, LoBound);
6685     else if (LoOverflow)
6686       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6687                           ICmpInst::ICMP_UGE, X, HiBound);
6688     else
6689       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6690   case ICmpInst::ICMP_ULT:
6691   case ICmpInst::ICMP_SLT:
6692     if (LoOverflow == +1)   // Low bound is greater than input range.
6693       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6694     if (LoOverflow == -1)   // Low bound is less than input range.
6695       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6696     return new ICmpInst(*Context, Pred, X, LoBound);
6697   case ICmpInst::ICMP_UGT:
6698   case ICmpInst::ICMP_SGT:
6699     if (HiOverflow == +1)       // High bound greater than input range.
6700       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6701     else if (HiOverflow == -1)  // High bound less than input range.
6702       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6703     if (Pred == ICmpInst::ICMP_UGT)
6704       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
6705     else
6706       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
6707   }
6708 }
6709
6710
6711 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6712 ///
6713 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6714                                                           Instruction *LHSI,
6715                                                           ConstantInt *RHS) {
6716   const APInt &RHSV = RHS->getValue();
6717   
6718   switch (LHSI->getOpcode()) {
6719   case Instruction::Trunc:
6720     if (ICI.isEquality() && LHSI->hasOneUse()) {
6721       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6722       // of the high bits truncated out of x are known.
6723       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6724              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6725       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6726       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6727       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6728       
6729       // If all the high bits are known, we can do this xform.
6730       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6731         // Pull in the high bits from known-ones set.
6732         APInt NewRHS(RHS->getValue());
6733         NewRHS.zext(SrcBits);
6734         NewRHS |= KnownOne;
6735         return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6736                             ConstantInt::get(*Context, NewRHS));
6737       }
6738     }
6739     break;
6740       
6741   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6742     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6743       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6744       // fold the xor.
6745       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6746           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6747         Value *CompareVal = LHSI->getOperand(0);
6748         
6749         // If the sign bit of the XorCST is not set, there is no change to
6750         // the operation, just stop using the Xor.
6751         if (!XorCST->getValue().isNegative()) {
6752           ICI.setOperand(0, CompareVal);
6753           AddToWorkList(LHSI);
6754           return &ICI;
6755         }
6756         
6757         // Was the old condition true if the operand is positive?
6758         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6759         
6760         // If so, the new one isn't.
6761         isTrueIfPositive ^= true;
6762         
6763         if (isTrueIfPositive)
6764           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
6765                               SubOne(RHS));
6766         else
6767           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
6768                               AddOne(RHS));
6769       }
6770
6771       if (LHSI->hasOneUse()) {
6772         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6773         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6774           const APInt &SignBit = XorCST->getValue();
6775           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6776                                          ? ICI.getUnsignedPredicate()
6777                                          : ICI.getSignedPredicate();
6778           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6779                               ConstantInt::get(*Context, RHSV ^ SignBit));
6780         }
6781
6782         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6783         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6784           const APInt &NotSignBit = XorCST->getValue();
6785           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6786                                          ? ICI.getUnsignedPredicate()
6787                                          : ICI.getSignedPredicate();
6788           Pred = ICI.getSwappedPredicate(Pred);
6789           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6790                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
6791         }
6792       }
6793     }
6794     break;
6795   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6796     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6797         LHSI->getOperand(0)->hasOneUse()) {
6798       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6799       
6800       // If the LHS is an AND of a truncating cast, we can widen the
6801       // and/compare to be the input width without changing the value
6802       // produced, eliminating a cast.
6803       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6804         // We can do this transformation if either the AND constant does not
6805         // have its sign bit set or if it is an equality comparison. 
6806         // Extending a relational comparison when we're checking the sign
6807         // bit would not work.
6808         if (Cast->hasOneUse() &&
6809             (ICI.isEquality() ||
6810              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6811           uint32_t BitWidth = 
6812             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6813           APInt NewCST = AndCST->getValue();
6814           NewCST.zext(BitWidth);
6815           APInt NewCI = RHSV;
6816           NewCI.zext(BitWidth);
6817           Instruction *NewAnd = 
6818             BinaryOperator::CreateAnd(Cast->getOperand(0),
6819                            ConstantInt::get(*Context, NewCST), LHSI->getName());
6820           InsertNewInstBefore(NewAnd, ICI);
6821           return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
6822                               ConstantInt::get(*Context, NewCI));
6823         }
6824       }
6825       
6826       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6827       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6828       // happens a LOT in code produced by the C front-end, for bitfield
6829       // access.
6830       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6831       if (Shift && !Shift->isShift())
6832         Shift = 0;
6833       
6834       ConstantInt *ShAmt;
6835       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6836       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6837       const Type *AndTy = AndCST->getType();          // Type of the and.
6838       
6839       // We can fold this as long as we can't shift unknown bits
6840       // into the mask.  This can only happen with signed shift
6841       // rights, as they sign-extend.
6842       if (ShAmt) {
6843         bool CanFold = Shift->isLogicalShift();
6844         if (!CanFold) {
6845           // To test for the bad case of the signed shr, see if any
6846           // of the bits shifted in could be tested after the mask.
6847           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6848           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6849           
6850           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6851           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6852                AndCST->getValue()) == 0)
6853             CanFold = true;
6854         }
6855         
6856         if (CanFold) {
6857           Constant *NewCst;
6858           if (Shift->getOpcode() == Instruction::Shl)
6859             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6860           else
6861             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6862           
6863           // Check to see if we are shifting out any of the bits being
6864           // compared.
6865           if (ConstantExpr::get(Shift->getOpcode(),
6866                                        NewCst, ShAmt) != RHS) {
6867             // If we shifted bits out, the fold is not going to work out.
6868             // As a special case, check to see if this means that the
6869             // result is always true or false now.
6870             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6871               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6872             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6873               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6874           } else {
6875             ICI.setOperand(1, NewCst);
6876             Constant *NewAndCST;
6877             if (Shift->getOpcode() == Instruction::Shl)
6878               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6879             else
6880               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6881             LHSI->setOperand(1, NewAndCST);
6882             LHSI->setOperand(0, Shift->getOperand(0));
6883             AddToWorkList(Shift); // Shift is dead.
6884             AddUsesToWorkList(ICI);
6885             return &ICI;
6886           }
6887         }
6888       }
6889       
6890       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6891       // preferable because it allows the C<<Y expression to be hoisted out
6892       // of a loop if Y is invariant and X is not.
6893       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6894           ICI.isEquality() && !Shift->isArithmeticShift() &&
6895           !isa<Constant>(Shift->getOperand(0))) {
6896         // Compute C << Y.
6897         Value *NS;
6898         if (Shift->getOpcode() == Instruction::LShr) {
6899           NS = BinaryOperator::CreateShl(AndCST, 
6900                                          Shift->getOperand(1), "tmp");
6901         } else {
6902           // Insert a logical shift.
6903           NS = BinaryOperator::CreateLShr(AndCST,
6904                                           Shift->getOperand(1), "tmp");
6905         }
6906         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6907         
6908         // Compute X & (C << Y).
6909         Instruction *NewAnd = 
6910           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6911         InsertNewInstBefore(NewAnd, ICI);
6912         
6913         ICI.setOperand(0, NewAnd);
6914         return &ICI;
6915       }
6916     }
6917     break;
6918     
6919   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6920     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6921     if (!ShAmt) break;
6922     
6923     uint32_t TypeBits = RHSV.getBitWidth();
6924     
6925     // Check that the shift amount is in range.  If not, don't perform
6926     // undefined shifts.  When the shift is visited it will be
6927     // simplified.
6928     if (ShAmt->uge(TypeBits))
6929       break;
6930     
6931     if (ICI.isEquality()) {
6932       // If we are comparing against bits always shifted out, the
6933       // comparison cannot succeed.
6934       Constant *Comp =
6935         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6936                                                                  ShAmt);
6937       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6938         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6939         Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6940         return ReplaceInstUsesWith(ICI, Cst);
6941       }
6942       
6943       if (LHSI->hasOneUse()) {
6944         // Otherwise strength reduce the shift into an and.
6945         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6946         Constant *Mask =
6947           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
6948                                                        TypeBits-ShAmtVal));
6949         
6950         Instruction *AndI =
6951           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6952                                     Mask, LHSI->getName()+".mask");
6953         Value *And = InsertNewInstBefore(AndI, ICI);
6954         return new ICmpInst(*Context, ICI.getPredicate(), And,
6955                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6956       }
6957     }
6958     
6959     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6960     bool TrueIfSigned = false;
6961     if (LHSI->hasOneUse() &&
6962         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6963       // (X << 31) <s 0  --> (X&1) != 0
6964       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6965                                            (TypeBits-ShAmt->getZExtValue()-1));
6966       Instruction *AndI =
6967         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6968                                   Mask, LHSI->getName()+".mask");
6969       Value *And = InsertNewInstBefore(AndI, ICI);
6970       
6971       return new ICmpInst(*Context,
6972                           TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6973                           And, Constant::getNullValue(And->getType()));
6974     }
6975     break;
6976   }
6977     
6978   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6979   case Instruction::AShr: {
6980     // Only handle equality comparisons of shift-by-constant.
6981     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6982     if (!ShAmt || !ICI.isEquality()) break;
6983
6984     // Check that the shift amount is in range.  If not, don't perform
6985     // undefined shifts.  When the shift is visited it will be
6986     // simplified.
6987     uint32_t TypeBits = RHSV.getBitWidth();
6988     if (ShAmt->uge(TypeBits))
6989       break;
6990     
6991     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6992       
6993     // If we are comparing against bits always shifted out, the
6994     // comparison cannot succeed.
6995     APInt Comp = RHSV << ShAmtVal;
6996     if (LHSI->getOpcode() == Instruction::LShr)
6997       Comp = Comp.lshr(ShAmtVal);
6998     else
6999       Comp = Comp.ashr(ShAmtVal);
7000     
7001     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7002       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7003       Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
7004       return ReplaceInstUsesWith(ICI, Cst);
7005     }
7006     
7007     // Otherwise, check to see if the bits shifted out are known to be zero.
7008     // If so, we can compare against the unshifted value:
7009     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
7010     if (LHSI->hasOneUse() &&
7011         MaskedValueIsZero(LHSI->getOperand(0), 
7012                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7013       return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
7014                           ConstantExpr::getShl(RHS, ShAmt));
7015     }
7016       
7017     if (LHSI->hasOneUse()) {
7018       // Otherwise strength reduce the shift into an and.
7019       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7020       Constant *Mask = ConstantInt::get(*Context, Val);
7021       
7022       Instruction *AndI =
7023         BinaryOperator::CreateAnd(LHSI->getOperand(0),
7024                                   Mask, LHSI->getName()+".mask");
7025       Value *And = InsertNewInstBefore(AndI, ICI);
7026       return new ICmpInst(*Context, ICI.getPredicate(), And,
7027                           ConstantExpr::getShl(RHS, ShAmt));
7028     }
7029     break;
7030   }
7031     
7032   case Instruction::SDiv:
7033   case Instruction::UDiv:
7034     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7035     // Fold this div into the comparison, producing a range check. 
7036     // Determine, based on the divide type, what the range is being 
7037     // checked.  If there is an overflow on the low or high side, remember 
7038     // it, otherwise compute the range [low, hi) bounding the new value.
7039     // See: InsertRangeTest above for the kinds of replacements possible.
7040     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7041       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7042                                           DivRHS))
7043         return R;
7044     break;
7045
7046   case Instruction::Add:
7047     // Fold: icmp pred (add, X, C1), C2
7048
7049     if (!ICI.isEquality()) {
7050       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7051       if (!LHSC) break;
7052       const APInt &LHSV = LHSC->getValue();
7053
7054       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7055                             .subtract(LHSV);
7056
7057       if (ICI.isSignedPredicate()) {
7058         if (CR.getLower().isSignBit()) {
7059           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7060                               ConstantInt::get(*Context, CR.getUpper()));
7061         } else if (CR.getUpper().isSignBit()) {
7062           return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7063                               ConstantInt::get(*Context, CR.getLower()));
7064         }
7065       } else {
7066         if (CR.getLower().isMinValue()) {
7067           return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7068                               ConstantInt::get(*Context, CR.getUpper()));
7069         } else if (CR.getUpper().isMinValue()) {
7070           return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7071                               ConstantInt::get(*Context, CR.getLower()));
7072         }
7073       }
7074     }
7075     break;
7076   }
7077   
7078   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7079   if (ICI.isEquality()) {
7080     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7081     
7082     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7083     // the second operand is a constant, simplify a bit.
7084     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7085       switch (BO->getOpcode()) {
7086       case Instruction::SRem:
7087         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7088         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7089           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7090           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7091             Instruction *NewRem =
7092               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7093                                          BO->getName());
7094             InsertNewInstBefore(NewRem, ICI);
7095             return new ICmpInst(*Context, ICI.getPredicate(), NewRem, 
7096                                 Constant::getNullValue(BO->getType()));
7097           }
7098         }
7099         break;
7100       case Instruction::Add:
7101         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7102         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7103           if (BO->hasOneUse())
7104             return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7105                                 ConstantExpr::getSub(RHS, BOp1C));
7106         } else if (RHSV == 0) {
7107           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7108           // efficiently invertible, or if the add has just this one use.
7109           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7110           
7111           if (Value *NegVal = dyn_castNegVal(BOp1))
7112             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
7113           else if (Value *NegVal = dyn_castNegVal(BOp0))
7114             return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
7115           else if (BO->hasOneUse()) {
7116             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
7117             InsertNewInstBefore(Neg, ICI);
7118             Neg->takeName(BO);
7119             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
7120           }
7121         }
7122         break;
7123       case Instruction::Xor:
7124         // For the xor case, we can xor two constants together, eliminating
7125         // the explicit xor.
7126         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7127           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0), 
7128                               ConstantExpr::getXor(RHS, BOC));
7129         
7130         // FALLTHROUGH
7131       case Instruction::Sub:
7132         // Replace (([sub|xor] A, B) != 0) with (A != B)
7133         if (RHSV == 0)
7134           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7135                               BO->getOperand(1));
7136         break;
7137         
7138       case Instruction::Or:
7139         // If bits are being or'd in that are not present in the constant we
7140         // are comparing against, then the comparison could never succeed!
7141         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7142           Constant *NotCI = ConstantExpr::getNot(RHS);
7143           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7144             return ReplaceInstUsesWith(ICI,
7145                                        ConstantInt::get(Type::getInt1Ty(*Context), 
7146                                        isICMP_NE));
7147         }
7148         break;
7149         
7150       case Instruction::And:
7151         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7152           // If bits are being compared against that are and'd out, then the
7153           // comparison can never succeed!
7154           if ((RHSV & ~BOC->getValue()) != 0)
7155             return ReplaceInstUsesWith(ICI,
7156                                        ConstantInt::get(Type::getInt1Ty(*Context),
7157                                        isICMP_NE));
7158           
7159           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7160           if (RHS == BOC && RHSV.isPowerOf2())
7161             return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
7162                                 ICmpInst::ICMP_NE, LHSI,
7163                                 Constant::getNullValue(RHS->getType()));
7164           
7165           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7166           if (BOC->getValue().isSignBit()) {
7167             Value *X = BO->getOperand(0);
7168             Constant *Zero = Constant::getNullValue(X->getType());
7169             ICmpInst::Predicate pred = isICMP_NE ? 
7170               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7171             return new ICmpInst(*Context, pred, X, Zero);
7172           }
7173           
7174           // ((X & ~7) == 0) --> X < 8
7175           if (RHSV == 0 && isHighOnes(BOC)) {
7176             Value *X = BO->getOperand(0);
7177             Constant *NegX = ConstantExpr::getNeg(BOC);
7178             ICmpInst::Predicate pred = isICMP_NE ? 
7179               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7180             return new ICmpInst(*Context, pred, X, NegX);
7181           }
7182         }
7183       default: break;
7184       }
7185     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7186       // Handle icmp {eq|ne} <intrinsic>, intcst.
7187       if (II->getIntrinsicID() == Intrinsic::bswap) {
7188         AddToWorkList(II);
7189         ICI.setOperand(0, II->getOperand(1));
7190         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7191         return &ICI;
7192       }
7193     }
7194   }
7195   return 0;
7196 }
7197
7198 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7199 /// We only handle extending casts so far.
7200 ///
7201 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7202   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7203   Value *LHSCIOp        = LHSCI->getOperand(0);
7204   const Type *SrcTy     = LHSCIOp->getType();
7205   const Type *DestTy    = LHSCI->getType();
7206   Value *RHSCIOp;
7207
7208   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7209   // integer type is the same size as the pointer type.
7210   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7211       TD->getPointerSizeInBits() ==
7212          cast<IntegerType>(DestTy)->getBitWidth()) {
7213     Value *RHSOp = 0;
7214     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7215       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7216     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7217       RHSOp = RHSC->getOperand(0);
7218       // If the pointer types don't match, insert a bitcast.
7219       if (LHSCIOp->getType() != RHSOp->getType())
7220         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7221     }
7222
7223     if (RHSOp)
7224       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
7225   }
7226   
7227   // The code below only handles extension cast instructions, so far.
7228   // Enforce this.
7229   if (LHSCI->getOpcode() != Instruction::ZExt &&
7230       LHSCI->getOpcode() != Instruction::SExt)
7231     return 0;
7232
7233   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7234   bool isSignedCmp = ICI.isSignedPredicate();
7235
7236   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7237     // Not an extension from the same type?
7238     RHSCIOp = CI->getOperand(0);
7239     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7240       return 0;
7241     
7242     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7243     // and the other is a zext), then we can't handle this.
7244     if (CI->getOpcode() != LHSCI->getOpcode())
7245       return 0;
7246
7247     // Deal with equality cases early.
7248     if (ICI.isEquality())
7249       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7250
7251     // A signed comparison of sign extended values simplifies into a
7252     // signed comparison.
7253     if (isSignedCmp && isSignedExt)
7254       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7255
7256     // The other three cases all fold into an unsigned comparison.
7257     return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7258   }
7259
7260   // If we aren't dealing with a constant on the RHS, exit early
7261   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7262   if (!CI)
7263     return 0;
7264
7265   // Compute the constant that would happen if we truncated to SrcTy then
7266   // reextended to DestTy.
7267   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7268   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7269                                                 Res1, DestTy);
7270
7271   // If the re-extended constant didn't change...
7272   if (Res2 == CI) {
7273     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7274     // For example, we might have:
7275     //    %A = sext i16 %X to i32
7276     //    %B = icmp ugt i32 %A, 1330
7277     // It is incorrect to transform this into 
7278     //    %B = icmp ugt i16 %X, 1330
7279     // because %A may have negative value. 
7280     //
7281     // However, we allow this when the compare is EQ/NE, because they are
7282     // signless.
7283     if (isSignedExt == isSignedCmp || ICI.isEquality())
7284       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
7285     return 0;
7286   }
7287
7288   // The re-extended constant changed so the constant cannot be represented 
7289   // in the shorter type. Consequently, we cannot emit a simple comparison.
7290
7291   // First, handle some easy cases. We know the result cannot be equal at this
7292   // point so handle the ICI.isEquality() cases
7293   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7294     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7295   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7296     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7297
7298   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7299   // should have been folded away previously and not enter in here.
7300   Value *Result;
7301   if (isSignedCmp) {
7302     // We're performing a signed comparison.
7303     if (cast<ConstantInt>(CI)->getValue().isNegative())
7304       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7305     else
7306       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7307   } else {
7308     // We're performing an unsigned comparison.
7309     if (isSignedExt) {
7310       // We're performing an unsigned comp with a sign extended value.
7311       // This is true if the input is >= 0. [aka >s -1]
7312       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7313       Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT, 
7314                                    LHSCIOp, NegOne, ICI.getName()), ICI);
7315     } else {
7316       // Unsigned extend & unsigned compare -> always true.
7317       Result = ConstantInt::getTrue(*Context);
7318     }
7319   }
7320
7321   // Finally, return the value computed.
7322   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7323       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7324     return ReplaceInstUsesWith(ICI, Result);
7325
7326   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7327           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7328          "ICmp should be folded!");
7329   if (Constant *CI = dyn_cast<Constant>(Result))
7330     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7331   return BinaryOperator::CreateNot(Result);
7332 }
7333
7334 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7335   return commonShiftTransforms(I);
7336 }
7337
7338 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7339   return commonShiftTransforms(I);
7340 }
7341
7342 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7343   if (Instruction *R = commonShiftTransforms(I))
7344     return R;
7345   
7346   Value *Op0 = I.getOperand(0);
7347   
7348   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7349   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7350     if (CSI->isAllOnesValue())
7351       return ReplaceInstUsesWith(I, CSI);
7352
7353   // See if we can turn a signed shr into an unsigned shr.
7354   if (MaskedValueIsZero(Op0,
7355                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7356     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7357
7358   // Arithmetic shifting an all-sign-bit value is a no-op.
7359   unsigned NumSignBits = ComputeNumSignBits(Op0);
7360   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7361     return ReplaceInstUsesWith(I, Op0);
7362
7363   return 0;
7364 }
7365
7366 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7367   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7368   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7369
7370   // shl X, 0 == X and shr X, 0 == X
7371   // shl 0, X == 0 and shr 0, X == 0
7372   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7373       Op0 == Constant::getNullValue(Op0->getType()))
7374     return ReplaceInstUsesWith(I, Op0);
7375   
7376   if (isa<UndefValue>(Op0)) {            
7377     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7378       return ReplaceInstUsesWith(I, Op0);
7379     else                                    // undef << X -> 0, undef >>u X -> 0
7380       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7381   }
7382   if (isa<UndefValue>(Op1)) {
7383     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7384       return ReplaceInstUsesWith(I, Op0);          
7385     else                                     // X << undef, X >>u undef -> 0
7386       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7387   }
7388
7389   // See if we can fold away this shift.
7390   if (SimplifyDemandedInstructionBits(I))
7391     return &I;
7392
7393   // Try to fold constant and into select arguments.
7394   if (isa<Constant>(Op0))
7395     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7396       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7397         return R;
7398
7399   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7400     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7401       return Res;
7402   return 0;
7403 }
7404
7405 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7406                                                BinaryOperator &I) {
7407   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7408
7409   // See if we can simplify any instructions used by the instruction whose sole 
7410   // purpose is to compute bits we don't care about.
7411   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7412   
7413   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7414   // a signed shift.
7415   //
7416   if (Op1->uge(TypeBits)) {
7417     if (I.getOpcode() != Instruction::AShr)
7418       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7419     else {
7420       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7421       return &I;
7422     }
7423   }
7424   
7425   // ((X*C1) << C2) == (X * (C1 << C2))
7426   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7427     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7428       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7429         return BinaryOperator::CreateMul(BO->getOperand(0),
7430                                         ConstantExpr::getShl(BOOp, Op1));
7431   
7432   // Try to fold constant and into select arguments.
7433   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7434     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7435       return R;
7436   if (isa<PHINode>(Op0))
7437     if (Instruction *NV = FoldOpIntoPhi(I))
7438       return NV;
7439   
7440   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7441   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7442     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7443     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7444     // place.  Don't try to do this transformation in this case.  Also, we
7445     // require that the input operand is a shift-by-constant so that we have
7446     // confidence that the shifts will get folded together.  We could do this
7447     // xform in more cases, but it is unlikely to be profitable.
7448     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7449         isa<ConstantInt>(TrOp->getOperand(1))) {
7450       // Okay, we'll do this xform.  Make the shift of shift.
7451       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7452       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7453                                                 I.getName());
7454       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7455
7456       // For logical shifts, the truncation has the effect of making the high
7457       // part of the register be zeros.  Emulate this by inserting an AND to
7458       // clear the top bits as needed.  This 'and' will usually be zapped by
7459       // other xforms later if dead.
7460       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7461       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7462       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7463       
7464       // The mask we constructed says what the trunc would do if occurring
7465       // between the shifts.  We want to know the effect *after* the second
7466       // shift.  We know that it is a logical shift by a constant, so adjust the
7467       // mask as appropriate.
7468       if (I.getOpcode() == Instruction::Shl)
7469         MaskV <<= Op1->getZExtValue();
7470       else {
7471         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7472         MaskV = MaskV.lshr(Op1->getZExtValue());
7473       }
7474
7475       Instruction *And =
7476         BinaryOperator::CreateAnd(NSh, ConstantInt::get(*Context, MaskV), 
7477                                   TI->getName());
7478       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7479
7480       // Return the value truncated to the interesting size.
7481       return new TruncInst(And, I.getType());
7482     }
7483   }
7484   
7485   if (Op0->hasOneUse()) {
7486     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7487       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7488       Value *V1, *V2;
7489       ConstantInt *CC;
7490       switch (Op0BO->getOpcode()) {
7491         default: break;
7492         case Instruction::Add:
7493         case Instruction::And:
7494         case Instruction::Or:
7495         case Instruction::Xor: {
7496           // These operators commute.
7497           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7498           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7499               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7500                     m_Specific(Op1)))){
7501             Instruction *YS = BinaryOperator::CreateShl(
7502                                             Op0BO->getOperand(0), Op1,
7503                                             Op0BO->getName());
7504             InsertNewInstBefore(YS, I); // (Y << C)
7505             Instruction *X = 
7506               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7507                                      Op0BO->getOperand(1)->getName());
7508             InsertNewInstBefore(X, I);  // (X + (Y << C))
7509             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7510             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7511                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7512           }
7513           
7514           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7515           Value *Op0BOOp1 = Op0BO->getOperand(1);
7516           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7517               match(Op0BOOp1, 
7518                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7519                           m_ConstantInt(CC))) &&
7520               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7521             Instruction *YS = BinaryOperator::CreateShl(
7522                                                      Op0BO->getOperand(0), Op1,
7523                                                      Op0BO->getName());
7524             InsertNewInstBefore(YS, I); // (Y << C)
7525             Instruction *XM =
7526               BinaryOperator::CreateAnd(V1,
7527                                         ConstantExpr::getShl(CC, Op1),
7528                                         V1->getName()+".mask");
7529             InsertNewInstBefore(XM, I); // X & (CC << C)
7530             
7531             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7532           }
7533         }
7534           
7535         // FALL THROUGH.
7536         case Instruction::Sub: {
7537           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7538           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7539               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7540                     m_Specific(Op1)))) {
7541             Instruction *YS = BinaryOperator::CreateShl(
7542                                                      Op0BO->getOperand(1), Op1,
7543                                                      Op0BO->getName());
7544             InsertNewInstBefore(YS, I); // (Y << C)
7545             Instruction *X =
7546               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7547                                      Op0BO->getOperand(0)->getName());
7548             InsertNewInstBefore(X, I);  // (X + (Y << C))
7549             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7550             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7551                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7552           }
7553           
7554           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7555           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7556               match(Op0BO->getOperand(0),
7557                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7558                           m_ConstantInt(CC))) && V2 == Op1 &&
7559               cast<BinaryOperator>(Op0BO->getOperand(0))
7560                   ->getOperand(0)->hasOneUse()) {
7561             Instruction *YS = BinaryOperator::CreateShl(
7562                                                      Op0BO->getOperand(1), Op1,
7563                                                      Op0BO->getName());
7564             InsertNewInstBefore(YS, I); // (Y << C)
7565             Instruction *XM =
7566               BinaryOperator::CreateAnd(V1, 
7567                                         ConstantExpr::getShl(CC, Op1),
7568                                         V1->getName()+".mask");
7569             InsertNewInstBefore(XM, I); // X & (CC << C)
7570             
7571             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7572           }
7573           
7574           break;
7575         }
7576       }
7577       
7578       
7579       // If the operand is an bitwise operator with a constant RHS, and the
7580       // shift is the only use, we can pull it out of the shift.
7581       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7582         bool isValid = true;     // Valid only for And, Or, Xor
7583         bool highBitSet = false; // Transform if high bit of constant set?
7584         
7585         switch (Op0BO->getOpcode()) {
7586           default: isValid = false; break;   // Do not perform transform!
7587           case Instruction::Add:
7588             isValid = isLeftShift;
7589             break;
7590           case Instruction::Or:
7591           case Instruction::Xor:
7592             highBitSet = false;
7593             break;
7594           case Instruction::And:
7595             highBitSet = true;
7596             break;
7597         }
7598         
7599         // If this is a signed shift right, and the high bit is modified
7600         // by the logical operation, do not perform the transformation.
7601         // The highBitSet boolean indicates the value of the high bit of
7602         // the constant which would cause it to be modified for this
7603         // operation.
7604         //
7605         if (isValid && I.getOpcode() == Instruction::AShr)
7606           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7607         
7608         if (isValid) {
7609           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7610           
7611           Instruction *NewShift =
7612             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7613           InsertNewInstBefore(NewShift, I);
7614           NewShift->takeName(Op0BO);
7615           
7616           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7617                                         NewRHS);
7618         }
7619       }
7620     }
7621   }
7622   
7623   // Find out if this is a shift of a shift by a constant.
7624   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7625   if (ShiftOp && !ShiftOp->isShift())
7626     ShiftOp = 0;
7627   
7628   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7629     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7630     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7631     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7632     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7633     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7634     Value *X = ShiftOp->getOperand(0);
7635     
7636     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7637     
7638     const IntegerType *Ty = cast<IntegerType>(I.getType());
7639     
7640     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7641     if (I.getOpcode() == ShiftOp->getOpcode()) {
7642       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7643       // saturates.
7644       if (AmtSum >= TypeBits) {
7645         if (I.getOpcode() != Instruction::AShr)
7646           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7647         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7648       }
7649       
7650       return BinaryOperator::Create(I.getOpcode(), X,
7651                                     ConstantInt::get(Ty, AmtSum));
7652     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7653                I.getOpcode() == Instruction::AShr) {
7654       if (AmtSum >= TypeBits)
7655         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7656       
7657       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7658       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7659     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7660                I.getOpcode() == Instruction::LShr) {
7661       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7662       if (AmtSum >= TypeBits)
7663         AmtSum = TypeBits-1;
7664       
7665       Instruction *Shift =
7666         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7667       InsertNewInstBefore(Shift, I);
7668
7669       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7670       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7671     }
7672     
7673     // Okay, if we get here, one shift must be left, and the other shift must be
7674     // right.  See if the amounts are equal.
7675     if (ShiftAmt1 == ShiftAmt2) {
7676       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7677       if (I.getOpcode() == Instruction::Shl) {
7678         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7679         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7680       }
7681       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7682       if (I.getOpcode() == Instruction::LShr) {
7683         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7684         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7685       }
7686       // We can simplify ((X << C) >>s C) into a trunc + sext.
7687       // NOTE: we could do this for any C, but that would make 'unusual' integer
7688       // types.  For now, just stick to ones well-supported by the code
7689       // generators.
7690       const Type *SExtType = 0;
7691       switch (Ty->getBitWidth() - ShiftAmt1) {
7692       case 1  :
7693       case 8  :
7694       case 16 :
7695       case 32 :
7696       case 64 :
7697       case 128:
7698         SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7699         break;
7700       default: break;
7701       }
7702       if (SExtType) {
7703         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7704         InsertNewInstBefore(NewTrunc, I);
7705         return new SExtInst(NewTrunc, Ty);
7706       }
7707       // Otherwise, we can't handle it yet.
7708     } else if (ShiftAmt1 < ShiftAmt2) {
7709       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7710       
7711       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7712       if (I.getOpcode() == Instruction::Shl) {
7713         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7714                ShiftOp->getOpcode() == Instruction::AShr);
7715         Instruction *Shift =
7716           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7717         InsertNewInstBefore(Shift, I);
7718         
7719         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7720         return BinaryOperator::CreateAnd(Shift,
7721                                          ConstantInt::get(*Context, Mask));
7722       }
7723       
7724       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7725       if (I.getOpcode() == Instruction::LShr) {
7726         assert(ShiftOp->getOpcode() == Instruction::Shl);
7727         Instruction *Shift =
7728           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7729         InsertNewInstBefore(Shift, I);
7730         
7731         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7732         return BinaryOperator::CreateAnd(Shift,
7733                                          ConstantInt::get(*Context, Mask));
7734       }
7735       
7736       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7737     } else {
7738       assert(ShiftAmt2 < ShiftAmt1);
7739       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7740
7741       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7742       if (I.getOpcode() == Instruction::Shl) {
7743         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7744                ShiftOp->getOpcode() == Instruction::AShr);
7745         Instruction *Shift =
7746           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7747                                  ConstantInt::get(Ty, ShiftDiff));
7748         InsertNewInstBefore(Shift, I);
7749         
7750         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7751         return BinaryOperator::CreateAnd(Shift,
7752                                          ConstantInt::get(*Context, Mask));
7753       }
7754       
7755       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7756       if (I.getOpcode() == Instruction::LShr) {
7757         assert(ShiftOp->getOpcode() == Instruction::Shl);
7758         Instruction *Shift =
7759           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7760         InsertNewInstBefore(Shift, I);
7761         
7762         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7763         return BinaryOperator::CreateAnd(Shift,
7764                                          ConstantInt::get(*Context, Mask));
7765       }
7766       
7767       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7768     }
7769   }
7770   return 0;
7771 }
7772
7773
7774 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7775 /// expression.  If so, decompose it, returning some value X, such that Val is
7776 /// X*Scale+Offset.
7777 ///
7778 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7779                                         int &Offset, LLVMContext *Context) {
7780   assert(Val->getType() == Type::getInt32Ty(*Context) && "Unexpected allocation size type!");
7781   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7782     Offset = CI->getZExtValue();
7783     Scale  = 0;
7784     return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7785   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7786     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7787       if (I->getOpcode() == Instruction::Shl) {
7788         // This is a value scaled by '1 << the shift amt'.
7789         Scale = 1U << RHS->getZExtValue();
7790         Offset = 0;
7791         return I->getOperand(0);
7792       } else if (I->getOpcode() == Instruction::Mul) {
7793         // This value is scaled by 'RHS'.
7794         Scale = RHS->getZExtValue();
7795         Offset = 0;
7796         return I->getOperand(0);
7797       } else if (I->getOpcode() == Instruction::Add) {
7798         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7799         // where C1 is divisible by C2.
7800         unsigned SubScale;
7801         Value *SubVal = 
7802           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7803                                     Offset, Context);
7804         Offset += RHS->getZExtValue();
7805         Scale = SubScale;
7806         return SubVal;
7807       }
7808     }
7809   }
7810
7811   // Otherwise, we can't look past this.
7812   Scale = 1;
7813   Offset = 0;
7814   return Val;
7815 }
7816
7817
7818 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7819 /// try to eliminate the cast by moving the type information into the alloc.
7820 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7821                                                    AllocationInst &AI) {
7822   const PointerType *PTy = cast<PointerType>(CI.getType());
7823   
7824   // Remove any uses of AI that are dead.
7825   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7826   
7827   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7828     Instruction *User = cast<Instruction>(*UI++);
7829     if (isInstructionTriviallyDead(User)) {
7830       while (UI != E && *UI == User)
7831         ++UI; // If this instruction uses AI more than once, don't break UI.
7832       
7833       ++NumDeadInst;
7834       DOUT << "IC: DCE: " << *User << '\n';
7835       EraseInstFromFunction(*User);
7836     }
7837   }
7838
7839   // This requires TargetData to get the alloca alignment and size information.
7840   if (!TD) return 0;
7841
7842   // Get the type really allocated and the type casted to.
7843   const Type *AllocElTy = AI.getAllocatedType();
7844   const Type *CastElTy = PTy->getElementType();
7845   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7846
7847   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7848   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7849   if (CastElTyAlign < AllocElTyAlign) return 0;
7850
7851   // If the allocation has multiple uses, only promote it if we are strictly
7852   // increasing the alignment of the resultant allocation.  If we keep it the
7853   // same, we open the door to infinite loops of various kinds.  (A reference
7854   // from a dbg.declare doesn't count as a use for this purpose.)
7855   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7856       CastElTyAlign == AllocElTyAlign) return 0;
7857
7858   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7859   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7860   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7861
7862   // See if we can satisfy the modulus by pulling a scale out of the array
7863   // size argument.
7864   unsigned ArraySizeScale;
7865   int ArrayOffset;
7866   Value *NumElements = // See if the array size is a decomposable linear expr.
7867     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7868                               ArrayOffset, Context);
7869  
7870   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7871   // do the xform.
7872   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7873       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7874
7875   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7876   Value *Amt = 0;
7877   if (Scale == 1) {
7878     Amt = NumElements;
7879   } else {
7880     // If the allocation size is constant, form a constant mul expression
7881     Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7882     if (isa<ConstantInt>(NumElements))
7883       Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
7884                                  cast<ConstantInt>(Amt));
7885     // otherwise multiply the amount and the number of elements
7886     else {
7887       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7888       Amt = InsertNewInstBefore(Tmp, AI);
7889     }
7890   }
7891   
7892   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7893     Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7894     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7895     Amt = InsertNewInstBefore(Tmp, AI);
7896   }
7897   
7898   AllocationInst *New;
7899   if (isa<MallocInst>(AI))
7900     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7901   else
7902     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7903   InsertNewInstBefore(New, AI);
7904   New->takeName(&AI);
7905   
7906   // If the allocation has one real use plus a dbg.declare, just remove the
7907   // declare.
7908   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7909     EraseInstFromFunction(*DI);
7910   }
7911   // If the allocation has multiple real uses, insert a cast and change all
7912   // things that used it to use the new cast.  This will also hack on CI, but it
7913   // will die soon.
7914   else if (!AI.hasOneUse()) {
7915     AddUsesToWorkList(AI);
7916     // New is the allocation instruction, pointer typed. AI is the original
7917     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7918     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7919     InsertNewInstBefore(NewCast, AI);
7920     AI.replaceAllUsesWith(NewCast);
7921   }
7922   return ReplaceInstUsesWith(CI, New);
7923 }
7924
7925 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7926 /// and return it as type Ty without inserting any new casts and without
7927 /// changing the computed value.  This is used by code that tries to decide
7928 /// whether promoting or shrinking integer operations to wider or smaller types
7929 /// will allow us to eliminate a truncate or extend.
7930 ///
7931 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7932 /// extension operation if Ty is larger.
7933 ///
7934 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7935 /// should return true if trunc(V) can be computed by computing V in the smaller
7936 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7937 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7938 /// efficiently truncated.
7939 ///
7940 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7941 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7942 /// the final result.
7943 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7944                                               unsigned CastOpc,
7945                                               int &NumCastsRemoved){
7946   // We can always evaluate constants in another type.
7947   if (isa<Constant>(V))
7948     return true;
7949   
7950   Instruction *I = dyn_cast<Instruction>(V);
7951   if (!I) return false;
7952   
7953   const Type *OrigTy = V->getType();
7954   
7955   // If this is an extension or truncate, we can often eliminate it.
7956   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7957     // If this is a cast from the destination type, we can trivially eliminate
7958     // it, and this will remove a cast overall.
7959     if (I->getOperand(0)->getType() == Ty) {
7960       // If the first operand is itself a cast, and is eliminable, do not count
7961       // this as an eliminable cast.  We would prefer to eliminate those two
7962       // casts first.
7963       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7964         ++NumCastsRemoved;
7965       return true;
7966     }
7967   }
7968
7969   // We can't extend or shrink something that has multiple uses: doing so would
7970   // require duplicating the instruction in general, which isn't profitable.
7971   if (!I->hasOneUse()) return false;
7972
7973   unsigned Opc = I->getOpcode();
7974   switch (Opc) {
7975   case Instruction::Add:
7976   case Instruction::Sub:
7977   case Instruction::Mul:
7978   case Instruction::And:
7979   case Instruction::Or:
7980   case Instruction::Xor:
7981     // These operators can all arbitrarily be extended or truncated.
7982     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7983                                       NumCastsRemoved) &&
7984            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7985                                       NumCastsRemoved);
7986
7987   case Instruction::UDiv:
7988   case Instruction::URem: {
7989     // UDiv and URem can be truncated if all the truncated bits are zero.
7990     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7991     uint32_t BitWidth = Ty->getScalarSizeInBits();
7992     if (BitWidth < OrigBitWidth) {
7993       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7994       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7995           MaskedValueIsZero(I->getOperand(1), Mask)) {
7996         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7997                                           NumCastsRemoved) &&
7998                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7999                                           NumCastsRemoved);
8000       }
8001     }
8002     break;
8003   }
8004   case Instruction::Shl:
8005     // If we are truncating the result of this SHL, and if it's a shift of a
8006     // constant amount, we can always perform a SHL in a smaller type.
8007     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8008       uint32_t BitWidth = Ty->getScalarSizeInBits();
8009       if (BitWidth < OrigTy->getScalarSizeInBits() &&
8010           CI->getLimitedValue(BitWidth) < BitWidth)
8011         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8012                                           NumCastsRemoved);
8013     }
8014     break;
8015   case Instruction::LShr:
8016     // If this is a truncate of a logical shr, we can truncate it to a smaller
8017     // lshr iff we know that the bits we would otherwise be shifting in are
8018     // already zeros.
8019     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8020       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8021       uint32_t BitWidth = Ty->getScalarSizeInBits();
8022       if (BitWidth < OrigBitWidth &&
8023           MaskedValueIsZero(I->getOperand(0),
8024             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8025           CI->getLimitedValue(BitWidth) < BitWidth) {
8026         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8027                                           NumCastsRemoved);
8028       }
8029     }
8030     break;
8031   case Instruction::ZExt:
8032   case Instruction::SExt:
8033   case Instruction::Trunc:
8034     // If this is the same kind of case as our original (e.g. zext+zext), we
8035     // can safely replace it.  Note that replacing it does not reduce the number
8036     // of casts in the input.
8037     if (Opc == CastOpc)
8038       return true;
8039
8040     // sext (zext ty1), ty2 -> zext ty2
8041     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8042       return true;
8043     break;
8044   case Instruction::Select: {
8045     SelectInst *SI = cast<SelectInst>(I);
8046     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8047                                       NumCastsRemoved) &&
8048            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8049                                       NumCastsRemoved);
8050   }
8051   case Instruction::PHI: {
8052     // We can change a phi if we can change all operands.
8053     PHINode *PN = cast<PHINode>(I);
8054     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8055       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8056                                       NumCastsRemoved))
8057         return false;
8058     return true;
8059   }
8060   default:
8061     // TODO: Can handle more cases here.
8062     break;
8063   }
8064   
8065   return false;
8066 }
8067
8068 /// EvaluateInDifferentType - Given an expression that 
8069 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8070 /// evaluate the expression.
8071 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8072                                              bool isSigned) {
8073   if (Constant *C = dyn_cast<Constant>(V))
8074     return ConstantExpr::getIntegerCast(C, Ty,
8075                                                isSigned /*Sext or ZExt*/);
8076
8077   // Otherwise, it must be an instruction.
8078   Instruction *I = cast<Instruction>(V);
8079   Instruction *Res = 0;
8080   unsigned Opc = I->getOpcode();
8081   switch (Opc) {
8082   case Instruction::Add:
8083   case Instruction::Sub:
8084   case Instruction::Mul:
8085   case Instruction::And:
8086   case Instruction::Or:
8087   case Instruction::Xor:
8088   case Instruction::AShr:
8089   case Instruction::LShr:
8090   case Instruction::Shl:
8091   case Instruction::UDiv:
8092   case Instruction::URem: {
8093     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8094     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8095     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8096     break;
8097   }    
8098   case Instruction::Trunc:
8099   case Instruction::ZExt:
8100   case Instruction::SExt:
8101     // If the source type of the cast is the type we're trying for then we can
8102     // just return the source.  There's no need to insert it because it is not
8103     // new.
8104     if (I->getOperand(0)->getType() == Ty)
8105       return I->getOperand(0);
8106     
8107     // Otherwise, must be the same type of cast, so just reinsert a new one.
8108     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8109                            Ty);
8110     break;
8111   case Instruction::Select: {
8112     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8113     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8114     Res = SelectInst::Create(I->getOperand(0), True, False);
8115     break;
8116   }
8117   case Instruction::PHI: {
8118     PHINode *OPN = cast<PHINode>(I);
8119     PHINode *NPN = PHINode::Create(Ty);
8120     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8121       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8122       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8123     }
8124     Res = NPN;
8125     break;
8126   }
8127   default: 
8128     // TODO: Can handle more cases here.
8129     llvm_unreachable("Unreachable!");
8130     break;
8131   }
8132   
8133   Res->takeName(I);
8134   return InsertNewInstBefore(Res, *I);
8135 }
8136
8137 /// @brief Implement the transforms common to all CastInst visitors.
8138 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8139   Value *Src = CI.getOperand(0);
8140
8141   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8142   // eliminate it now.
8143   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8144     if (Instruction::CastOps opc = 
8145         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8146       // The first cast (CSrc) is eliminable so we need to fix up or replace
8147       // the second cast (CI). CSrc will then have a good chance of being dead.
8148       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8149     }
8150   }
8151
8152   // If we are casting a select then fold the cast into the select
8153   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8154     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8155       return NV;
8156
8157   // If we are casting a PHI then fold the cast into the PHI
8158   if (isa<PHINode>(Src))
8159     if (Instruction *NV = FoldOpIntoPhi(CI))
8160       return NV;
8161   
8162   return 0;
8163 }
8164
8165 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8166 /// or not there is a sequence of GEP indices into the type that will land us at
8167 /// the specified offset.  If so, fill them into NewIndices and return the
8168 /// resultant element type, otherwise return null.
8169 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8170                                        SmallVectorImpl<Value*> &NewIndices,
8171                                        const TargetData *TD,
8172                                        LLVMContext *Context) {
8173   if (!TD) return 0;
8174   if (!Ty->isSized()) return 0;
8175   
8176   // Start with the index over the outer type.  Note that the type size
8177   // might be zero (even if the offset isn't zero) if the indexed type
8178   // is something like [0 x {int, int}]
8179   const Type *IntPtrTy = TD->getIntPtrType(*Context);
8180   int64_t FirstIdx = 0;
8181   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8182     FirstIdx = Offset/TySize;
8183     Offset -= FirstIdx*TySize;
8184     
8185     // Handle hosts where % returns negative instead of values [0..TySize).
8186     if (Offset < 0) {
8187       --FirstIdx;
8188       Offset += TySize;
8189       assert(Offset >= 0);
8190     }
8191     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8192   }
8193   
8194   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8195     
8196   // Index into the types.  If we fail, set OrigBase to null.
8197   while (Offset) {
8198     // Indexing into tail padding between struct/array elements.
8199     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8200       return 0;
8201     
8202     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8203       const StructLayout *SL = TD->getStructLayout(STy);
8204       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8205              "Offset must stay within the indexed type");
8206       
8207       unsigned Elt = SL->getElementContainingOffset(Offset);
8208       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8209       
8210       Offset -= SL->getElementOffset(Elt);
8211       Ty = STy->getElementType(Elt);
8212     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8213       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8214       assert(EltSize && "Cannot index into a zero-sized array");
8215       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8216       Offset %= EltSize;
8217       Ty = AT->getElementType();
8218     } else {
8219       // Otherwise, we can't index into the middle of this atomic type, bail.
8220       return 0;
8221     }
8222   }
8223   
8224   return Ty;
8225 }
8226
8227 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8228 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8229   Value *Src = CI.getOperand(0);
8230   
8231   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8232     // If casting the result of a getelementptr instruction with no offset, turn
8233     // this into a cast of the original pointer!
8234     if (GEP->hasAllZeroIndices()) {
8235       // Changing the cast operand is usually not a good idea but it is safe
8236       // here because the pointer operand is being replaced with another 
8237       // pointer operand so the opcode doesn't need to change.
8238       AddToWorkList(GEP);
8239       CI.setOperand(0, GEP->getOperand(0));
8240       return &CI;
8241     }
8242     
8243     // If the GEP has a single use, and the base pointer is a bitcast, and the
8244     // GEP computes a constant offset, see if we can convert these three
8245     // instructions into fewer.  This typically happens with unions and other
8246     // non-type-safe code.
8247     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8248       if (GEP->hasAllConstantIndices()) {
8249         // We are guaranteed to get a constant from EmitGEPOffset.
8250         ConstantInt *OffsetV =
8251                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8252         int64_t Offset = OffsetV->getSExtValue();
8253         
8254         // Get the base pointer input of the bitcast, and the type it points to.
8255         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8256         const Type *GEPIdxTy =
8257           cast<PointerType>(OrigBase->getType())->getElementType();
8258         SmallVector<Value*, 8> NewIndices;
8259         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8260           // If we were able to index down into an element, create the GEP
8261           // and bitcast the result.  This eliminates one bitcast, potentially
8262           // two.
8263           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8264                                                         NewIndices.begin(),
8265                                                         NewIndices.end(), "");
8266           InsertNewInstBefore(NGEP, CI);
8267           NGEP->takeName(GEP);
8268           if (cast<GEPOperator>(GEP)->isInBounds())
8269             cast<GEPOperator>(NGEP)->setIsInBounds(true);
8270           
8271           if (isa<BitCastInst>(CI))
8272             return new BitCastInst(NGEP, CI.getType());
8273           assert(isa<PtrToIntInst>(CI));
8274           return new PtrToIntInst(NGEP, CI.getType());
8275         }
8276       }      
8277     }
8278   }
8279     
8280   return commonCastTransforms(CI);
8281 }
8282
8283 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8284 /// type like i42.  We don't want to introduce operations on random non-legal
8285 /// integer types where they don't already exist in the code.  In the future,
8286 /// we should consider making this based off target-data, so that 32-bit targets
8287 /// won't get i64 operations etc.
8288 static bool isSafeIntegerType(const Type *Ty) {
8289   switch (Ty->getPrimitiveSizeInBits()) {
8290   case 8:
8291   case 16:
8292   case 32:
8293   case 64:
8294     return true;
8295   default: 
8296     return false;
8297   }
8298 }
8299
8300 /// commonIntCastTransforms - This function implements the common transforms
8301 /// for trunc, zext, and sext.
8302 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8303   if (Instruction *Result = commonCastTransforms(CI))
8304     return Result;
8305
8306   Value *Src = CI.getOperand(0);
8307   const Type *SrcTy = Src->getType();
8308   const Type *DestTy = CI.getType();
8309   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8310   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8311
8312   // See if we can simplify any instructions used by the LHS whose sole 
8313   // purpose is to compute bits we don't care about.
8314   if (SimplifyDemandedInstructionBits(CI))
8315     return &CI;
8316
8317   // If the source isn't an instruction or has more than one use then we
8318   // can't do anything more. 
8319   Instruction *SrcI = dyn_cast<Instruction>(Src);
8320   if (!SrcI || !Src->hasOneUse())
8321     return 0;
8322
8323   // Attempt to propagate the cast into the instruction for int->int casts.
8324   int NumCastsRemoved = 0;
8325   // Only do this if the dest type is a simple type, don't convert the
8326   // expression tree to something weird like i93 unless the source is also
8327   // strange.
8328   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8329        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8330       CanEvaluateInDifferentType(SrcI, DestTy,
8331                                  CI.getOpcode(), NumCastsRemoved)) {
8332     // If this cast is a truncate, evaluting in a different type always
8333     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8334     // we need to do an AND to maintain the clear top-part of the computation,
8335     // so we require that the input have eliminated at least one cast.  If this
8336     // is a sign extension, we insert two new casts (to do the extension) so we
8337     // require that two casts have been eliminated.
8338     bool DoXForm = false;
8339     bool JustReplace = false;
8340     switch (CI.getOpcode()) {
8341     default:
8342       // All the others use floating point so we shouldn't actually 
8343       // get here because of the check above.
8344       llvm_unreachable("Unknown cast type");
8345     case Instruction::Trunc:
8346       DoXForm = true;
8347       break;
8348     case Instruction::ZExt: {
8349       DoXForm = NumCastsRemoved >= 1;
8350       if (!DoXForm && 0) {
8351         // If it's unnecessary to issue an AND to clear the high bits, it's
8352         // always profitable to do this xform.
8353         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8354         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8355         if (MaskedValueIsZero(TryRes, Mask))
8356           return ReplaceInstUsesWith(CI, TryRes);
8357         
8358         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8359           if (TryI->use_empty())
8360             EraseInstFromFunction(*TryI);
8361       }
8362       break;
8363     }
8364     case Instruction::SExt: {
8365       DoXForm = NumCastsRemoved >= 2;
8366       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8367         // If we do not have to emit the truncate + sext pair, then it's always
8368         // profitable to do this xform.
8369         //
8370         // It's not safe to eliminate the trunc + sext pair if one of the
8371         // eliminated cast is a truncate. e.g.
8372         // t2 = trunc i32 t1 to i16
8373         // t3 = sext i16 t2 to i32
8374         // !=
8375         // i32 t1
8376         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8377         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8378         if (NumSignBits > (DestBitSize - SrcBitSize))
8379           return ReplaceInstUsesWith(CI, TryRes);
8380         
8381         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8382           if (TryI->use_empty())
8383             EraseInstFromFunction(*TryI);
8384       }
8385       break;
8386     }
8387     }
8388     
8389     if (DoXForm) {
8390       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8391            << " cast: " << CI;
8392       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8393                                            CI.getOpcode() == Instruction::SExt);
8394       if (JustReplace)
8395         // Just replace this cast with the result.
8396         return ReplaceInstUsesWith(CI, Res);
8397
8398       assert(Res->getType() == DestTy);
8399       switch (CI.getOpcode()) {
8400       default: llvm_unreachable("Unknown cast type!");
8401       case Instruction::Trunc:
8402         // Just replace this cast with the result.
8403         return ReplaceInstUsesWith(CI, Res);
8404       case Instruction::ZExt: {
8405         assert(SrcBitSize < DestBitSize && "Not a zext?");
8406
8407         // If the high bits are already zero, just replace this cast with the
8408         // result.
8409         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8410         if (MaskedValueIsZero(Res, Mask))
8411           return ReplaceInstUsesWith(CI, Res);
8412
8413         // We need to emit an AND to clear the high bits.
8414         Constant *C = ConstantInt::get(*Context, 
8415                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8416         return BinaryOperator::CreateAnd(Res, C);
8417       }
8418       case Instruction::SExt: {
8419         // If the high bits are already filled with sign bit, just replace this
8420         // cast with the result.
8421         unsigned NumSignBits = ComputeNumSignBits(Res);
8422         if (NumSignBits > (DestBitSize - SrcBitSize))
8423           return ReplaceInstUsesWith(CI, Res);
8424
8425         // We need to emit a cast to truncate, then a cast to sext.
8426         return CastInst::Create(Instruction::SExt,
8427             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8428                              CI), DestTy);
8429       }
8430       }
8431     }
8432   }
8433   
8434   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8435   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8436
8437   switch (SrcI->getOpcode()) {
8438   case Instruction::Add:
8439   case Instruction::Mul:
8440   case Instruction::And:
8441   case Instruction::Or:
8442   case Instruction::Xor:
8443     // If we are discarding information, rewrite.
8444     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8445       // Don't insert two casts unless at least one can be eliminated.
8446       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8447           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8448         Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8449         Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8450         return BinaryOperator::Create(
8451             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8452       }
8453     }
8454
8455     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8456     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8457         SrcI->getOpcode() == Instruction::Xor &&
8458         Op1 == ConstantInt::getTrue(*Context) &&
8459         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8460       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8461       return BinaryOperator::CreateXor(New,
8462                                       ConstantInt::get(CI.getType(), 1));
8463     }
8464     break;
8465
8466   case Instruction::Shl: {
8467     // Canonicalize trunc inside shl, if we can.
8468     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8469     if (CI && DestBitSize < SrcBitSize &&
8470         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8471       Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8472       Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8473       return BinaryOperator::CreateShl(Op0c, Op1c);
8474     }
8475     break;
8476   }
8477   }
8478   return 0;
8479 }
8480
8481 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8482   if (Instruction *Result = commonIntCastTransforms(CI))
8483     return Result;
8484   
8485   Value *Src = CI.getOperand(0);
8486   const Type *Ty = CI.getType();
8487   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8488   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8489
8490   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8491   if (DestBitWidth == 1) {
8492     Constant *One = ConstantInt::get(Src->getType(), 1);
8493     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8494     Value *Zero = Constant::getNullValue(Src->getType());
8495     return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
8496   }
8497
8498   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8499   ConstantInt *ShAmtV = 0;
8500   Value *ShiftOp = 0;
8501   if (Src->hasOneUse() &&
8502       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8503     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8504     
8505     // Get a mask for the bits shifting in.
8506     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8507     if (MaskedValueIsZero(ShiftOp, Mask)) {
8508       if (ShAmt >= DestBitWidth)        // All zeros.
8509         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8510       
8511       // Okay, we can shrink this.  Truncate the input, then return a new
8512       // shift.
8513       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8514       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8515       return BinaryOperator::CreateLShr(V1, V2);
8516     }
8517   }
8518   
8519   return 0;
8520 }
8521
8522 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8523 /// in order to eliminate the icmp.
8524 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8525                                              bool DoXform) {
8526   // If we are just checking for a icmp eq of a single bit and zext'ing it
8527   // to an integer, then shift the bit to the appropriate place and then
8528   // cast to integer to avoid the comparison.
8529   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8530     const APInt &Op1CV = Op1C->getValue();
8531       
8532     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8533     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8534     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8535         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8536       if (!DoXform) return ICI;
8537
8538       Value *In = ICI->getOperand(0);
8539       Value *Sh = ConstantInt::get(In->getType(),
8540                                    In->getType()->getScalarSizeInBits()-1);
8541       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8542                                                         In->getName()+".lobit"),
8543                                CI);
8544       if (In->getType() != CI.getType())
8545         In = CastInst::CreateIntegerCast(In, CI.getType(),
8546                                          false/*ZExt*/, "tmp", &CI);
8547
8548       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8549         Constant *One = ConstantInt::get(In->getType(), 1);
8550         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8551                                                          In->getName()+".not"),
8552                                  CI);
8553       }
8554
8555       return ReplaceInstUsesWith(CI, In);
8556     }
8557       
8558       
8559       
8560     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8561     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8562     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8563     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8564     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8565     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8566     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8567     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8568     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8569         // This only works for EQ and NE
8570         ICI->isEquality()) {
8571       // If Op1C some other power of two, convert:
8572       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8573       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8574       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8575       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8576         
8577       APInt KnownZeroMask(~KnownZero);
8578       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8579         if (!DoXform) return ICI;
8580
8581         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8582         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8583           // (X&4) == 2 --> false
8584           // (X&4) != 2 --> true
8585           Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8586           Res = ConstantExpr::getZExt(Res, CI.getType());
8587           return ReplaceInstUsesWith(CI, Res);
8588         }
8589           
8590         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8591         Value *In = ICI->getOperand(0);
8592         if (ShiftAmt) {
8593           // Perform a logical shr by shiftamt.
8594           // Insert the shift to put the result in the low bit.
8595           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8596                               ConstantInt::get(In->getType(), ShiftAmt),
8597                                                    In->getName()+".lobit"), CI);
8598         }
8599           
8600         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8601           Constant *One = ConstantInt::get(In->getType(), 1);
8602           In = BinaryOperator::CreateXor(In, One, "tmp");
8603           InsertNewInstBefore(cast<Instruction>(In), CI);
8604         }
8605           
8606         if (CI.getType() == In->getType())
8607           return ReplaceInstUsesWith(CI, In);
8608         else
8609           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8610       }
8611     }
8612   }
8613
8614   return 0;
8615 }
8616
8617 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8618   // If one of the common conversion will work ..
8619   if (Instruction *Result = commonIntCastTransforms(CI))
8620     return Result;
8621
8622   Value *Src = CI.getOperand(0);
8623
8624   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8625   // types and if the sizes are just right we can convert this into a logical
8626   // 'and' which will be much cheaper than the pair of casts.
8627   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8628     // Get the sizes of the types involved.  We know that the intermediate type
8629     // will be smaller than A or C, but don't know the relation between A and C.
8630     Value *A = CSrc->getOperand(0);
8631     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8632     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8633     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8634     // If we're actually extending zero bits, then if
8635     // SrcSize <  DstSize: zext(a & mask)
8636     // SrcSize == DstSize: a & mask
8637     // SrcSize  > DstSize: trunc(a) & mask
8638     if (SrcSize < DstSize) {
8639       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8640       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8641       Instruction *And =
8642         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8643       InsertNewInstBefore(And, CI);
8644       return new ZExtInst(And, CI.getType());
8645     } else if (SrcSize == DstSize) {
8646       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8647       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8648                                                            AndValue));
8649     } else if (SrcSize > DstSize) {
8650       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8651       InsertNewInstBefore(Trunc, CI);
8652       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8653       return BinaryOperator::CreateAnd(Trunc, 
8654                                        ConstantInt::get(Trunc->getType(),
8655                                                                AndValue));
8656     }
8657   }
8658
8659   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8660     return transformZExtICmp(ICI, CI);
8661
8662   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8663   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8664     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8665     // of the (zext icmp) will be transformed.
8666     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8667     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8668     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8669         (transformZExtICmp(LHS, CI, false) ||
8670          transformZExtICmp(RHS, CI, false))) {
8671       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8672       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8673       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8674     }
8675   }
8676
8677   // zext(trunc(t) & C) -> (t & zext(C)).
8678   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8679     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8680       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8681         Value *TI0 = TI->getOperand(0);
8682         if (TI0->getType() == CI.getType())
8683           return
8684             BinaryOperator::CreateAnd(TI0,
8685                                 ConstantExpr::getZExt(C, CI.getType()));
8686       }
8687
8688   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8689   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8690     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8691       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8692         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8693             And->getOperand(1) == C)
8694           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8695             Value *TI0 = TI->getOperand(0);
8696             if (TI0->getType() == CI.getType()) {
8697               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8698               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8699               InsertNewInstBefore(NewAnd, *And);
8700               return BinaryOperator::CreateXor(NewAnd, ZC);
8701             }
8702           }
8703
8704   return 0;
8705 }
8706
8707 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8708   if (Instruction *I = commonIntCastTransforms(CI))
8709     return I;
8710   
8711   Value *Src = CI.getOperand(0);
8712   
8713   // Canonicalize sign-extend from i1 to a select.
8714   if (Src->getType() == Type::getInt1Ty(*Context))
8715     return SelectInst::Create(Src,
8716                               Constant::getAllOnesValue(CI.getType()),
8717                               Constant::getNullValue(CI.getType()));
8718
8719   // See if the value being truncated is already sign extended.  If so, just
8720   // eliminate the trunc/sext pair.
8721   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8722     Value *Op = cast<User>(Src)->getOperand(0);
8723     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8724     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8725     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8726     unsigned NumSignBits = ComputeNumSignBits(Op);
8727
8728     if (OpBits == DestBits) {
8729       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8730       // bits, it is already ready.
8731       if (NumSignBits > DestBits-MidBits)
8732         return ReplaceInstUsesWith(CI, Op);
8733     } else if (OpBits < DestBits) {
8734       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8735       // bits, just sext from i32.
8736       if (NumSignBits > OpBits-MidBits)
8737         return new SExtInst(Op, CI.getType(), "tmp");
8738     } else {
8739       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8740       // bits, just truncate to i32.
8741       if (NumSignBits > OpBits-MidBits)
8742         return new TruncInst(Op, CI.getType(), "tmp");
8743     }
8744   }
8745
8746   // If the input is a shl/ashr pair of a same constant, then this is a sign
8747   // extension from a smaller value.  If we could trust arbitrary bitwidth
8748   // integers, we could turn this into a truncate to the smaller bit and then
8749   // use a sext for the whole extension.  Since we don't, look deeper and check
8750   // for a truncate.  If the source and dest are the same type, eliminate the
8751   // trunc and extend and just do shifts.  For example, turn:
8752   //   %a = trunc i32 %i to i8
8753   //   %b = shl i8 %a, 6
8754   //   %c = ashr i8 %b, 6
8755   //   %d = sext i8 %c to i32
8756   // into:
8757   //   %a = shl i32 %i, 30
8758   //   %d = ashr i32 %a, 30
8759   Value *A = 0;
8760   ConstantInt *BA = 0, *CA = 0;
8761   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8762                         m_ConstantInt(CA))) &&
8763       BA == CA && isa<TruncInst>(A)) {
8764     Value *I = cast<TruncInst>(A)->getOperand(0);
8765     if (I->getType() == CI.getType()) {
8766       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8767       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8768       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8769       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8770       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8771                                                         CI.getName()), CI);
8772       return BinaryOperator::CreateAShr(I, ShAmtV);
8773     }
8774   }
8775   
8776   return 0;
8777 }
8778
8779 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8780 /// in the specified FP type without changing its value.
8781 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8782                               LLVMContext *Context) {
8783   bool losesInfo;
8784   APFloat F = CFP->getValueAPF();
8785   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8786   if (!losesInfo)
8787     return ConstantFP::get(*Context, F);
8788   return 0;
8789 }
8790
8791 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8792 /// through it until we get the source value.
8793 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8794   if (Instruction *I = dyn_cast<Instruction>(V))
8795     if (I->getOpcode() == Instruction::FPExt)
8796       return LookThroughFPExtensions(I->getOperand(0), Context);
8797   
8798   // If this value is a constant, return the constant in the smallest FP type
8799   // that can accurately represent it.  This allows us to turn
8800   // (float)((double)X+2.0) into x+2.0f.
8801   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8802     if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8803       return V;  // No constant folding of this.
8804     // See if the value can be truncated to float and then reextended.
8805     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8806       return V;
8807     if (CFP->getType() == Type::getDoubleTy(*Context))
8808       return V;  // Won't shrink.
8809     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8810       return V;
8811     // Don't try to shrink to various long double types.
8812   }
8813   
8814   return V;
8815 }
8816
8817 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8818   if (Instruction *I = commonCastTransforms(CI))
8819     return I;
8820   
8821   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8822   // smaller than the destination type, we can eliminate the truncate by doing
8823   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8824   // many builtins (sqrt, etc).
8825   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8826   if (OpI && OpI->hasOneUse()) {
8827     switch (OpI->getOpcode()) {
8828     default: break;
8829     case Instruction::FAdd:
8830     case Instruction::FSub:
8831     case Instruction::FMul:
8832     case Instruction::FDiv:
8833     case Instruction::FRem:
8834       const Type *SrcTy = OpI->getType();
8835       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8836       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8837       if (LHSTrunc->getType() != SrcTy && 
8838           RHSTrunc->getType() != SrcTy) {
8839         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8840         // If the source types were both smaller than the destination type of
8841         // the cast, do this xform.
8842         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8843             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8844           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8845                                       CI.getType(), CI);
8846           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8847                                       CI.getType(), CI);
8848           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8849         }
8850       }
8851       break;  
8852     }
8853   }
8854   return 0;
8855 }
8856
8857 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8858   return commonCastTransforms(CI);
8859 }
8860
8861 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8862   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8863   if (OpI == 0)
8864     return commonCastTransforms(FI);
8865
8866   // fptoui(uitofp(X)) --> X
8867   // fptoui(sitofp(X)) --> X
8868   // This is safe if the intermediate type has enough bits in its mantissa to
8869   // accurately represent all values of X.  For example, do not do this with
8870   // i64->float->i64.  This is also safe for sitofp case, because any negative
8871   // 'X' value would cause an undefined result for the fptoui. 
8872   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8873       OpI->getOperand(0)->getType() == FI.getType() &&
8874       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8875                     OpI->getType()->getFPMantissaWidth())
8876     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8877
8878   return commonCastTransforms(FI);
8879 }
8880
8881 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8882   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8883   if (OpI == 0)
8884     return commonCastTransforms(FI);
8885   
8886   // fptosi(sitofp(X)) --> X
8887   // fptosi(uitofp(X)) --> X
8888   // This is safe if the intermediate type has enough bits in its mantissa to
8889   // accurately represent all values of X.  For example, do not do this with
8890   // i64->float->i64.  This is also safe for sitofp case, because any negative
8891   // 'X' value would cause an undefined result for the fptoui. 
8892   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8893       OpI->getOperand(0)->getType() == FI.getType() &&
8894       (int)FI.getType()->getScalarSizeInBits() <=
8895                     OpI->getType()->getFPMantissaWidth())
8896     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8897   
8898   return commonCastTransforms(FI);
8899 }
8900
8901 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8902   return commonCastTransforms(CI);
8903 }
8904
8905 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8906   return commonCastTransforms(CI);
8907 }
8908
8909 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8910   // If the destination integer type is smaller than the intptr_t type for
8911   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8912   // trunc to be exposed to other transforms.  Don't do this for extending
8913   // ptrtoint's, because we don't know if the target sign or zero extends its
8914   // pointers.
8915   if (TD &&
8916       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8917     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8918                                              TD->getIntPtrType(CI.getContext()),
8919                                                     "tmp"), CI);
8920     return new TruncInst(P, CI.getType());
8921   }
8922   
8923   return commonPointerCastTransforms(CI);
8924 }
8925
8926 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8927   // If the source integer type is larger than the intptr_t type for
8928   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8929   // allows the trunc to be exposed to other transforms.  Don't do this for
8930   // extending inttoptr's, because we don't know if the target sign or zero
8931   // extends to pointers.
8932   if (TD &&
8933       CI.getOperand(0)->getType()->getScalarSizeInBits() >
8934       TD->getPointerSizeInBits()) {
8935     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8936                                              TD->getIntPtrType(CI.getContext()),
8937                                                  "tmp"), CI);
8938     return new IntToPtrInst(P, CI.getType());
8939   }
8940   
8941   if (Instruction *I = commonCastTransforms(CI))
8942     return I;
8943
8944   return 0;
8945 }
8946
8947 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8948   // If the operands are integer typed then apply the integer transforms,
8949   // otherwise just apply the common ones.
8950   Value *Src = CI.getOperand(0);
8951   const Type *SrcTy = Src->getType();
8952   const Type *DestTy = CI.getType();
8953
8954   if (isa<PointerType>(SrcTy)) {
8955     if (Instruction *I = commonPointerCastTransforms(CI))
8956       return I;
8957   } else {
8958     if (Instruction *Result = commonCastTransforms(CI))
8959       return Result;
8960   }
8961
8962
8963   // Get rid of casts from one type to the same type. These are useless and can
8964   // be replaced by the operand.
8965   if (DestTy == Src->getType())
8966     return ReplaceInstUsesWith(CI, Src);
8967
8968   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8969     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8970     const Type *DstElTy = DstPTy->getElementType();
8971     const Type *SrcElTy = SrcPTy->getElementType();
8972     
8973     // If the address spaces don't match, don't eliminate the bitcast, which is
8974     // required for changing types.
8975     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8976       return 0;
8977     
8978     // If we are casting a malloc or alloca to a pointer to a type of the same
8979     // size, rewrite the allocation instruction to allocate the "right" type.
8980     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8981       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8982         return V;
8983     
8984     // If the source and destination are pointers, and this cast is equivalent
8985     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8986     // This can enhance SROA and other transforms that want type-safe pointers.
8987     Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8988     unsigned NumZeros = 0;
8989     while (SrcElTy != DstElTy && 
8990            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8991            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8992       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8993       ++NumZeros;
8994     }
8995
8996     // If we found a path from the src to dest, create the getelementptr now.
8997     if (SrcElTy == DstElTy) {
8998       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8999       Instruction *GEP = GetElementPtrInst::Create(Src,
9000                                                    Idxs.begin(), Idxs.end(), "",
9001                                                    ((Instruction*) NULL));
9002       cast<GEPOperator>(GEP)->setIsInBounds(true);
9003       return GEP;
9004     }
9005   }
9006
9007   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9008     if (DestVTy->getNumElements() == 1) {
9009       if (!isa<VectorType>(SrcTy)) {
9010         Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
9011                                        DestVTy->getElementType(), CI);
9012         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
9013                                          Constant::getNullValue(Type::getInt32Ty(*Context)));
9014       }
9015       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9016     }
9017   }
9018
9019   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9020     if (SrcVTy->getNumElements() == 1) {
9021       if (!isa<VectorType>(DestTy)) {
9022         Instruction *Elem =
9023           ExtractElementInst::Create(Src, Constant::getNullValue(Type::getInt32Ty(*Context)));
9024         InsertNewInstBefore(Elem, CI);
9025         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9026       }
9027     }
9028   }
9029
9030   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9031     if (SVI->hasOneUse()) {
9032       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9033       // a bitconvert to a vector with the same # elts.
9034       if (isa<VectorType>(DestTy) && 
9035           cast<VectorType>(DestTy)->getNumElements() ==
9036                 SVI->getType()->getNumElements() &&
9037           SVI->getType()->getNumElements() ==
9038             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9039         CastInst *Tmp;
9040         // If either of the operands is a cast from CI.getType(), then
9041         // evaluating the shuffle in the casted destination's type will allow
9042         // us to eliminate at least one cast.
9043         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9044              Tmp->getOperand(0)->getType() == DestTy) ||
9045             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9046              Tmp->getOperand(0)->getType() == DestTy)) {
9047           Value *LHS = InsertCastBefore(Instruction::BitCast,
9048                                         SVI->getOperand(0), DestTy, CI);
9049           Value *RHS = InsertCastBefore(Instruction::BitCast,
9050                                         SVI->getOperand(1), DestTy, CI);
9051           // Return a new shuffle vector.  Use the same element ID's, as we
9052           // know the vector types match #elts.
9053           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9054         }
9055       }
9056     }
9057   }
9058   return 0;
9059 }
9060
9061 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9062 ///   %C = or %A, %B
9063 ///   %D = select %cond, %C, %A
9064 /// into:
9065 ///   %C = select %cond, %B, 0
9066 ///   %D = or %A, %C
9067 ///
9068 /// Assuming that the specified instruction is an operand to the select, return
9069 /// a bitmask indicating which operands of this instruction are foldable if they
9070 /// equal the other incoming value of the select.
9071 ///
9072 static unsigned GetSelectFoldableOperands(Instruction *I) {
9073   switch (I->getOpcode()) {
9074   case Instruction::Add:
9075   case Instruction::Mul:
9076   case Instruction::And:
9077   case Instruction::Or:
9078   case Instruction::Xor:
9079     return 3;              // Can fold through either operand.
9080   case Instruction::Sub:   // Can only fold on the amount subtracted.
9081   case Instruction::Shl:   // Can only fold on the shift amount.
9082   case Instruction::LShr:
9083   case Instruction::AShr:
9084     return 1;
9085   default:
9086     return 0;              // Cannot fold
9087   }
9088 }
9089
9090 /// GetSelectFoldableConstant - For the same transformation as the previous
9091 /// function, return the identity constant that goes into the select.
9092 static Constant *GetSelectFoldableConstant(Instruction *I,
9093                                            LLVMContext *Context) {
9094   switch (I->getOpcode()) {
9095   default: llvm_unreachable("This cannot happen!");
9096   case Instruction::Add:
9097   case Instruction::Sub:
9098   case Instruction::Or:
9099   case Instruction::Xor:
9100   case Instruction::Shl:
9101   case Instruction::LShr:
9102   case Instruction::AShr:
9103     return Constant::getNullValue(I->getType());
9104   case Instruction::And:
9105     return Constant::getAllOnesValue(I->getType());
9106   case Instruction::Mul:
9107     return ConstantInt::get(I->getType(), 1);
9108   }
9109 }
9110
9111 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9112 /// have the same opcode and only one use each.  Try to simplify this.
9113 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9114                                           Instruction *FI) {
9115   if (TI->getNumOperands() == 1) {
9116     // If this is a non-volatile load or a cast from the same type,
9117     // merge.
9118     if (TI->isCast()) {
9119       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9120         return 0;
9121     } else {
9122       return 0;  // unknown unary op.
9123     }
9124
9125     // Fold this by inserting a select from the input values.
9126     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9127                                           FI->getOperand(0), SI.getName()+".v");
9128     InsertNewInstBefore(NewSI, SI);
9129     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9130                             TI->getType());
9131   }
9132
9133   // Only handle binary operators here.
9134   if (!isa<BinaryOperator>(TI))
9135     return 0;
9136
9137   // Figure out if the operations have any operands in common.
9138   Value *MatchOp, *OtherOpT, *OtherOpF;
9139   bool MatchIsOpZero;
9140   if (TI->getOperand(0) == FI->getOperand(0)) {
9141     MatchOp  = TI->getOperand(0);
9142     OtherOpT = TI->getOperand(1);
9143     OtherOpF = FI->getOperand(1);
9144     MatchIsOpZero = true;
9145   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9146     MatchOp  = TI->getOperand(1);
9147     OtherOpT = TI->getOperand(0);
9148     OtherOpF = FI->getOperand(0);
9149     MatchIsOpZero = false;
9150   } else if (!TI->isCommutative()) {
9151     return 0;
9152   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9153     MatchOp  = TI->getOperand(0);
9154     OtherOpT = TI->getOperand(1);
9155     OtherOpF = FI->getOperand(0);
9156     MatchIsOpZero = true;
9157   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9158     MatchOp  = TI->getOperand(1);
9159     OtherOpT = TI->getOperand(0);
9160     OtherOpF = FI->getOperand(1);
9161     MatchIsOpZero = true;
9162   } else {
9163     return 0;
9164   }
9165
9166   // If we reach here, they do have operations in common.
9167   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9168                                          OtherOpF, SI.getName()+".v");
9169   InsertNewInstBefore(NewSI, SI);
9170
9171   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9172     if (MatchIsOpZero)
9173       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9174     else
9175       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9176   }
9177   llvm_unreachable("Shouldn't get here");
9178   return 0;
9179 }
9180
9181 static bool isSelect01(Constant *C1, Constant *C2) {
9182   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9183   if (!C1I)
9184     return false;
9185   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9186   if (!C2I)
9187     return false;
9188   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9189 }
9190
9191 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9192 /// facilitate further optimization.
9193 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9194                                             Value *FalseVal) {
9195   // See the comment above GetSelectFoldableOperands for a description of the
9196   // transformation we are doing here.
9197   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9198     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9199         !isa<Constant>(FalseVal)) {
9200       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9201         unsigned OpToFold = 0;
9202         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9203           OpToFold = 1;
9204         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9205           OpToFold = 2;
9206         }
9207
9208         if (OpToFold) {
9209           Constant *C = GetSelectFoldableConstant(TVI, Context);
9210           Value *OOp = TVI->getOperand(2-OpToFold);
9211           // Avoid creating select between 2 constants unless it's selecting
9212           // between 0 and 1.
9213           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9214             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9215             InsertNewInstBefore(NewSel, SI);
9216             NewSel->takeName(TVI);
9217             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9218               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9219             llvm_unreachable("Unknown instruction!!");
9220           }
9221         }
9222       }
9223     }
9224   }
9225
9226   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9227     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9228         !isa<Constant>(TrueVal)) {
9229       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9230         unsigned OpToFold = 0;
9231         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9232           OpToFold = 1;
9233         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9234           OpToFold = 2;
9235         }
9236
9237         if (OpToFold) {
9238           Constant *C = GetSelectFoldableConstant(FVI, Context);
9239           Value *OOp = FVI->getOperand(2-OpToFold);
9240           // Avoid creating select between 2 constants unless it's selecting
9241           // between 0 and 1.
9242           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9243             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9244             InsertNewInstBefore(NewSel, SI);
9245             NewSel->takeName(FVI);
9246             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9247               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9248             llvm_unreachable("Unknown instruction!!");
9249           }
9250         }
9251       }
9252     }
9253   }
9254
9255   return 0;
9256 }
9257
9258 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9259 /// ICmpInst as its first operand.
9260 ///
9261 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9262                                                    ICmpInst *ICI) {
9263   bool Changed = false;
9264   ICmpInst::Predicate Pred = ICI->getPredicate();
9265   Value *CmpLHS = ICI->getOperand(0);
9266   Value *CmpRHS = ICI->getOperand(1);
9267   Value *TrueVal = SI.getTrueValue();
9268   Value *FalseVal = SI.getFalseValue();
9269
9270   // Check cases where the comparison is with a constant that
9271   // can be adjusted to fit the min/max idiom. We may edit ICI in
9272   // place here, so make sure the select is the only user.
9273   if (ICI->hasOneUse())
9274     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9275       switch (Pred) {
9276       default: break;
9277       case ICmpInst::ICMP_ULT:
9278       case ICmpInst::ICMP_SLT: {
9279         // X < MIN ? T : F  -->  F
9280         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9281           return ReplaceInstUsesWith(SI, FalseVal);
9282         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9283         Constant *AdjustedRHS = SubOne(CI);
9284         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9285             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9286           Pred = ICmpInst::getSwappedPredicate(Pred);
9287           CmpRHS = AdjustedRHS;
9288           std::swap(FalseVal, TrueVal);
9289           ICI->setPredicate(Pred);
9290           ICI->setOperand(1, CmpRHS);
9291           SI.setOperand(1, TrueVal);
9292           SI.setOperand(2, FalseVal);
9293           Changed = true;
9294         }
9295         break;
9296       }
9297       case ICmpInst::ICMP_UGT:
9298       case ICmpInst::ICMP_SGT: {
9299         // X > MAX ? T : F  -->  F
9300         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9301           return ReplaceInstUsesWith(SI, FalseVal);
9302         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9303         Constant *AdjustedRHS = AddOne(CI);
9304         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9305             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9306           Pred = ICmpInst::getSwappedPredicate(Pred);
9307           CmpRHS = AdjustedRHS;
9308           std::swap(FalseVal, TrueVal);
9309           ICI->setPredicate(Pred);
9310           ICI->setOperand(1, CmpRHS);
9311           SI.setOperand(1, TrueVal);
9312           SI.setOperand(2, FalseVal);
9313           Changed = true;
9314         }
9315         break;
9316       }
9317       }
9318
9319       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9320       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9321       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9322       if (match(TrueVal, m_ConstantInt<-1>()) &&
9323           match(FalseVal, m_ConstantInt<0>()))
9324         Pred = ICI->getPredicate();
9325       else if (match(TrueVal, m_ConstantInt<0>()) &&
9326                match(FalseVal, m_ConstantInt<-1>()))
9327         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9328       
9329       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9330         // If we are just checking for a icmp eq of a single bit and zext'ing it
9331         // to an integer, then shift the bit to the appropriate place and then
9332         // cast to integer to avoid the comparison.
9333         const APInt &Op1CV = CI->getValue();
9334     
9335         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9336         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9337         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9338             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9339           Value *In = ICI->getOperand(0);
9340           Value *Sh = ConstantInt::get(In->getType(),
9341                                        In->getType()->getScalarSizeInBits()-1);
9342           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9343                                                         In->getName()+".lobit"),
9344                                    *ICI);
9345           if (In->getType() != SI.getType())
9346             In = CastInst::CreateIntegerCast(In, SI.getType(),
9347                                              true/*SExt*/, "tmp", ICI);
9348     
9349           if (Pred == ICmpInst::ICMP_SGT)
9350             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9351                                        In->getName()+".not"), *ICI);
9352     
9353           return ReplaceInstUsesWith(SI, In);
9354         }
9355       }
9356     }
9357
9358   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9359     // Transform (X == Y) ? X : Y  -> Y
9360     if (Pred == ICmpInst::ICMP_EQ)
9361       return ReplaceInstUsesWith(SI, FalseVal);
9362     // Transform (X != Y) ? X : Y  -> X
9363     if (Pred == ICmpInst::ICMP_NE)
9364       return ReplaceInstUsesWith(SI, TrueVal);
9365     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9366
9367   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9368     // Transform (X == Y) ? Y : X  -> X
9369     if (Pred == ICmpInst::ICMP_EQ)
9370       return ReplaceInstUsesWith(SI, FalseVal);
9371     // Transform (X != Y) ? Y : X  -> Y
9372     if (Pred == ICmpInst::ICMP_NE)
9373       return ReplaceInstUsesWith(SI, TrueVal);
9374     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9375   }
9376
9377   /// NOTE: if we wanted to, this is where to detect integer ABS
9378
9379   return Changed ? &SI : 0;
9380 }
9381
9382 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9383   Value *CondVal = SI.getCondition();
9384   Value *TrueVal = SI.getTrueValue();
9385   Value *FalseVal = SI.getFalseValue();
9386
9387   // select true, X, Y  -> X
9388   // select false, X, Y -> Y
9389   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9390     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9391
9392   // select C, X, X -> X
9393   if (TrueVal == FalseVal)
9394     return ReplaceInstUsesWith(SI, TrueVal);
9395
9396   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9397     return ReplaceInstUsesWith(SI, FalseVal);
9398   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9399     return ReplaceInstUsesWith(SI, TrueVal);
9400   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9401     if (isa<Constant>(TrueVal))
9402       return ReplaceInstUsesWith(SI, TrueVal);
9403     else
9404       return ReplaceInstUsesWith(SI, FalseVal);
9405   }
9406
9407   if (SI.getType() == Type::getInt1Ty(*Context)) {
9408     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9409       if (C->getZExtValue()) {
9410         // Change: A = select B, true, C --> A = or B, C
9411         return BinaryOperator::CreateOr(CondVal, FalseVal);
9412       } else {
9413         // Change: A = select B, false, C --> A = and !B, C
9414         Value *NotCond =
9415           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9416                                              "not."+CondVal->getName()), SI);
9417         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9418       }
9419     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9420       if (C->getZExtValue() == false) {
9421         // Change: A = select B, C, false --> A = and B, C
9422         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9423       } else {
9424         // Change: A = select B, C, true --> A = or !B, C
9425         Value *NotCond =
9426           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9427                                              "not."+CondVal->getName()), SI);
9428         return BinaryOperator::CreateOr(NotCond, TrueVal);
9429       }
9430     }
9431     
9432     // select a, b, a  -> a&b
9433     // select a, a, b  -> a|b
9434     if (CondVal == TrueVal)
9435       return BinaryOperator::CreateOr(CondVal, FalseVal);
9436     else if (CondVal == FalseVal)
9437       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9438   }
9439
9440   // Selecting between two integer constants?
9441   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9442     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9443       // select C, 1, 0 -> zext C to int
9444       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9445         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9446       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9447         // select C, 0, 1 -> zext !C to int
9448         Value *NotCond =
9449           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9450                                                "not."+CondVal->getName()), SI);
9451         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9452       }
9453
9454       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9455         // If one of the constants is zero (we know they can't both be) and we
9456         // have an icmp instruction with zero, and we have an 'and' with the
9457         // non-constant value, eliminate this whole mess.  This corresponds to
9458         // cases like this: ((X & 27) ? 27 : 0)
9459         if (TrueValC->isZero() || FalseValC->isZero())
9460           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9461               cast<Constant>(IC->getOperand(1))->isNullValue())
9462             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9463               if (ICA->getOpcode() == Instruction::And &&
9464                   isa<ConstantInt>(ICA->getOperand(1)) &&
9465                   (ICA->getOperand(1) == TrueValC ||
9466                    ICA->getOperand(1) == FalseValC) &&
9467                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9468                 // Okay, now we know that everything is set up, we just don't
9469                 // know whether we have a icmp_ne or icmp_eq and whether the 
9470                 // true or false val is the zero.
9471                 bool ShouldNotVal = !TrueValC->isZero();
9472                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9473                 Value *V = ICA;
9474                 if (ShouldNotVal)
9475                   V = InsertNewInstBefore(BinaryOperator::Create(
9476                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9477                 return ReplaceInstUsesWith(SI, V);
9478               }
9479       }
9480     }
9481
9482   // See if we are selecting two values based on a comparison of the two values.
9483   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9484     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9485       // Transform (X == Y) ? X : Y  -> Y
9486       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9487         // This is not safe in general for floating point:  
9488         // consider X== -0, Y== +0.
9489         // It becomes safe if either operand is a nonzero constant.
9490         ConstantFP *CFPt, *CFPf;
9491         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9492               !CFPt->getValueAPF().isZero()) ||
9493             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9494              !CFPf->getValueAPF().isZero()))
9495         return ReplaceInstUsesWith(SI, FalseVal);
9496       }
9497       // Transform (X != Y) ? X : Y  -> X
9498       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9499         return ReplaceInstUsesWith(SI, TrueVal);
9500       // NOTE: if we wanted to, this is where to detect MIN/MAX
9501
9502     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9503       // Transform (X == Y) ? Y : X  -> X
9504       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9505         // This is not safe in general for floating point:  
9506         // consider X== -0, Y== +0.
9507         // It becomes safe if either operand is a nonzero constant.
9508         ConstantFP *CFPt, *CFPf;
9509         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9510               !CFPt->getValueAPF().isZero()) ||
9511             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9512              !CFPf->getValueAPF().isZero()))
9513           return ReplaceInstUsesWith(SI, FalseVal);
9514       }
9515       // Transform (X != Y) ? Y : X  -> Y
9516       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9517         return ReplaceInstUsesWith(SI, TrueVal);
9518       // NOTE: if we wanted to, this is where to detect MIN/MAX
9519     }
9520     // NOTE: if we wanted to, this is where to detect ABS
9521   }
9522
9523   // See if we are selecting two values based on a comparison of the two values.
9524   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9525     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9526       return Result;
9527
9528   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9529     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9530       if (TI->hasOneUse() && FI->hasOneUse()) {
9531         Instruction *AddOp = 0, *SubOp = 0;
9532
9533         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9534         if (TI->getOpcode() == FI->getOpcode())
9535           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9536             return IV;
9537
9538         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9539         // even legal for FP.
9540         if ((TI->getOpcode() == Instruction::Sub &&
9541              FI->getOpcode() == Instruction::Add) ||
9542             (TI->getOpcode() == Instruction::FSub &&
9543              FI->getOpcode() == Instruction::FAdd)) {
9544           AddOp = FI; SubOp = TI;
9545         } else if ((FI->getOpcode() == Instruction::Sub &&
9546                     TI->getOpcode() == Instruction::Add) ||
9547                    (FI->getOpcode() == Instruction::FSub &&
9548                     TI->getOpcode() == Instruction::FAdd)) {
9549           AddOp = TI; SubOp = FI;
9550         }
9551
9552         if (AddOp) {
9553           Value *OtherAddOp = 0;
9554           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9555             OtherAddOp = AddOp->getOperand(1);
9556           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9557             OtherAddOp = AddOp->getOperand(0);
9558           }
9559
9560           if (OtherAddOp) {
9561             // So at this point we know we have (Y -> OtherAddOp):
9562             //        select C, (add X, Y), (sub X, Z)
9563             Value *NegVal;  // Compute -Z
9564             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9565               NegVal = ConstantExpr::getNeg(C);
9566             } else {
9567               NegVal = InsertNewInstBefore(
9568                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
9569                                               "tmp"), SI);
9570             }
9571
9572             Value *NewTrueOp = OtherAddOp;
9573             Value *NewFalseOp = NegVal;
9574             if (AddOp != TI)
9575               std::swap(NewTrueOp, NewFalseOp);
9576             Instruction *NewSel =
9577               SelectInst::Create(CondVal, NewTrueOp,
9578                                  NewFalseOp, SI.getName() + ".p");
9579
9580             NewSel = InsertNewInstBefore(NewSel, SI);
9581             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9582           }
9583         }
9584       }
9585
9586   // See if we can fold the select into one of our operands.
9587   if (SI.getType()->isInteger()) {
9588     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9589     if (FoldI)
9590       return FoldI;
9591   }
9592
9593   if (BinaryOperator::isNot(CondVal)) {
9594     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9595     SI.setOperand(1, FalseVal);
9596     SI.setOperand(2, TrueVal);
9597     return &SI;
9598   }
9599
9600   return 0;
9601 }
9602
9603 /// EnforceKnownAlignment - If the specified pointer points to an object that
9604 /// we control, modify the object's alignment to PrefAlign. This isn't
9605 /// often possible though. If alignment is important, a more reliable approach
9606 /// is to simply align all global variables and allocation instructions to
9607 /// their preferred alignment from the beginning.
9608 ///
9609 static unsigned EnforceKnownAlignment(Value *V,
9610                                       unsigned Align, unsigned PrefAlign) {
9611
9612   User *U = dyn_cast<User>(V);
9613   if (!U) return Align;
9614
9615   switch (Operator::getOpcode(U)) {
9616   default: break;
9617   case Instruction::BitCast:
9618     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9619   case Instruction::GetElementPtr: {
9620     // If all indexes are zero, it is just the alignment of the base pointer.
9621     bool AllZeroOperands = true;
9622     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9623       if (!isa<Constant>(*i) ||
9624           !cast<Constant>(*i)->isNullValue()) {
9625         AllZeroOperands = false;
9626         break;
9627       }
9628
9629     if (AllZeroOperands) {
9630       // Treat this like a bitcast.
9631       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9632     }
9633     break;
9634   }
9635   }
9636
9637   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9638     // If there is a large requested alignment and we can, bump up the alignment
9639     // of the global.
9640     if (!GV->isDeclaration()) {
9641       if (GV->getAlignment() >= PrefAlign)
9642         Align = GV->getAlignment();
9643       else {
9644         GV->setAlignment(PrefAlign);
9645         Align = PrefAlign;
9646       }
9647     }
9648   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9649     // If there is a requested alignment and if this is an alloca, round up.  We
9650     // don't do this for malloc, because some systems can't respect the request.
9651     if (isa<AllocaInst>(AI)) {
9652       if (AI->getAlignment() >= PrefAlign)
9653         Align = AI->getAlignment();
9654       else {
9655         AI->setAlignment(PrefAlign);
9656         Align = PrefAlign;
9657       }
9658     }
9659   }
9660
9661   return Align;
9662 }
9663
9664 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9665 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9666 /// and it is more than the alignment of the ultimate object, see if we can
9667 /// increase the alignment of the ultimate object, making this check succeed.
9668 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9669                                                   unsigned PrefAlign) {
9670   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9671                       sizeof(PrefAlign) * CHAR_BIT;
9672   APInt Mask = APInt::getAllOnesValue(BitWidth);
9673   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9674   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9675   unsigned TrailZ = KnownZero.countTrailingOnes();
9676   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9677
9678   if (PrefAlign > Align)
9679     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9680   
9681     // We don't need to make any adjustment.
9682   return Align;
9683 }
9684
9685 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9686   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9687   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9688   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9689   unsigned CopyAlign = MI->getAlignment();
9690
9691   if (CopyAlign < MinAlign) {
9692     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9693                                              MinAlign, false));
9694     return MI;
9695   }
9696   
9697   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9698   // load/store.
9699   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9700   if (MemOpLength == 0) return 0;
9701   
9702   // Source and destination pointer types are always "i8*" for intrinsic.  See
9703   // if the size is something we can handle with a single primitive load/store.
9704   // A single load+store correctly handles overlapping memory in the memmove
9705   // case.
9706   unsigned Size = MemOpLength->getZExtValue();
9707   if (Size == 0) return MI;  // Delete this mem transfer.
9708   
9709   if (Size > 8 || (Size&(Size-1)))
9710     return 0;  // If not 1/2/4/8 bytes, exit.
9711   
9712   // Use an integer load+store unless we can find something better.
9713   Type *NewPtrTy =
9714                 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9715   
9716   // Memcpy forces the use of i8* for the source and destination.  That means
9717   // that if you're using memcpy to move one double around, you'll get a cast
9718   // from double* to i8*.  We'd much rather use a double load+store rather than
9719   // an i64 load+store, here because this improves the odds that the source or
9720   // dest address will be promotable.  See if we can find a better type than the
9721   // integer datatype.
9722   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9723     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9724     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9725       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9726       // down through these levels if so.
9727       while (!SrcETy->isSingleValueType()) {
9728         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9729           if (STy->getNumElements() == 1)
9730             SrcETy = STy->getElementType(0);
9731           else
9732             break;
9733         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9734           if (ATy->getNumElements() == 1)
9735             SrcETy = ATy->getElementType();
9736           else
9737             break;
9738         } else
9739           break;
9740       }
9741       
9742       if (SrcETy->isSingleValueType())
9743         NewPtrTy = PointerType::getUnqual(SrcETy);
9744     }
9745   }
9746   
9747   
9748   // If the memcpy/memmove provides better alignment info than we can
9749   // infer, use it.
9750   SrcAlign = std::max(SrcAlign, CopyAlign);
9751   DstAlign = std::max(DstAlign, CopyAlign);
9752   
9753   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9754   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9755   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9756   InsertNewInstBefore(L, *MI);
9757   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9758
9759   // Set the size of the copy to 0, it will be deleted on the next iteration.
9760   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9761   return MI;
9762 }
9763
9764 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9765   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9766   if (MI->getAlignment() < Alignment) {
9767     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9768                                              Alignment, false));
9769     return MI;
9770   }
9771   
9772   // Extract the length and alignment and fill if they are constant.
9773   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9774   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9775   if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9776     return 0;
9777   uint64_t Len = LenC->getZExtValue();
9778   Alignment = MI->getAlignment();
9779   
9780   // If the length is zero, this is a no-op
9781   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9782   
9783   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9784   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9785     const Type *ITy = IntegerType::get(*Context, Len*8);  // n=1 -> i8.
9786     
9787     Value *Dest = MI->getDest();
9788     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9789
9790     // Alignment 0 is identity for alignment 1 for memset, but not store.
9791     if (Alignment == 0) Alignment = 1;
9792     
9793     // Extract the fill value and store.
9794     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9795     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9796                                       Dest, false, Alignment), *MI);
9797     
9798     // Set the size of the copy to 0, it will be deleted on the next iteration.
9799     MI->setLength(Constant::getNullValue(LenC->getType()));
9800     return MI;
9801   }
9802
9803   return 0;
9804 }
9805
9806
9807 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9808 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9809 /// the heavy lifting.
9810 ///
9811 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9812   // If the caller function is nounwind, mark the call as nounwind, even if the
9813   // callee isn't.
9814   if (CI.getParent()->getParent()->doesNotThrow() &&
9815       !CI.doesNotThrow()) {
9816     CI.setDoesNotThrow();
9817     return &CI;
9818   }
9819   
9820   
9821   
9822   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9823   if (!II) return visitCallSite(&CI);
9824   
9825   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9826   // visitCallSite.
9827   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9828     bool Changed = false;
9829
9830     // memmove/cpy/set of zero bytes is a noop.
9831     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9832       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9833
9834       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9835         if (CI->getZExtValue() == 1) {
9836           // Replace the instruction with just byte operations.  We would
9837           // transform other cases to loads/stores, but we don't know if
9838           // alignment is sufficient.
9839         }
9840     }
9841
9842     // If we have a memmove and the source operation is a constant global,
9843     // then the source and dest pointers can't alias, so we can change this
9844     // into a call to memcpy.
9845     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9846       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9847         if (GVSrc->isConstant()) {
9848           Module *M = CI.getParent()->getParent()->getParent();
9849           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9850           const Type *Tys[1];
9851           Tys[0] = CI.getOperand(3)->getType();
9852           CI.setOperand(0, 
9853                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9854           Changed = true;
9855         }
9856
9857       // memmove(x,x,size) -> noop.
9858       if (MMI->getSource() == MMI->getDest())
9859         return EraseInstFromFunction(CI);
9860     }
9861
9862     // If we can determine a pointer alignment that is bigger than currently
9863     // set, update the alignment.
9864     if (isa<MemTransferInst>(MI)) {
9865       if (Instruction *I = SimplifyMemTransfer(MI))
9866         return I;
9867     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9868       if (Instruction *I = SimplifyMemSet(MSI))
9869         return I;
9870     }
9871           
9872     if (Changed) return II;
9873   }
9874   
9875   switch (II->getIntrinsicID()) {
9876   default: break;
9877   case Intrinsic::bswap:
9878     // bswap(bswap(x)) -> x
9879     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9880       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9881         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9882     break;
9883   case Intrinsic::ppc_altivec_lvx:
9884   case Intrinsic::ppc_altivec_lvxl:
9885   case Intrinsic::x86_sse_loadu_ps:
9886   case Intrinsic::x86_sse2_loadu_pd:
9887   case Intrinsic::x86_sse2_loadu_dq:
9888     // Turn PPC lvx     -> load if the pointer is known aligned.
9889     // Turn X86 loadups -> load if the pointer is known aligned.
9890     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9891       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9892                                    PointerType::getUnqual(II->getType()),
9893                                        CI);
9894       return new LoadInst(Ptr);
9895     }
9896     break;
9897   case Intrinsic::ppc_altivec_stvx:
9898   case Intrinsic::ppc_altivec_stvxl:
9899     // Turn stvx -> store if the pointer is known aligned.
9900     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9901       const Type *OpPtrTy = 
9902         PointerType::getUnqual(II->getOperand(1)->getType());
9903       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9904       return new StoreInst(II->getOperand(1), Ptr);
9905     }
9906     break;
9907   case Intrinsic::x86_sse_storeu_ps:
9908   case Intrinsic::x86_sse2_storeu_pd:
9909   case Intrinsic::x86_sse2_storeu_dq:
9910     // Turn X86 storeu -> store if the pointer is known aligned.
9911     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9912       const Type *OpPtrTy = 
9913         PointerType::getUnqual(II->getOperand(2)->getType());
9914       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9915       return new StoreInst(II->getOperand(2), Ptr);
9916     }
9917     break;
9918     
9919   case Intrinsic::x86_sse_cvttss2si: {
9920     // These intrinsics only demands the 0th element of its input vector.  If
9921     // we can simplify the input based on that, do so now.
9922     unsigned VWidth =
9923       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9924     APInt DemandedElts(VWidth, 1);
9925     APInt UndefElts(VWidth, 0);
9926     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9927                                               UndefElts)) {
9928       II->setOperand(1, V);
9929       return II;
9930     }
9931     break;
9932   }
9933     
9934   case Intrinsic::ppc_altivec_vperm:
9935     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9936     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9937       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9938       
9939       // Check that all of the elements are integer constants or undefs.
9940       bool AllEltsOk = true;
9941       for (unsigned i = 0; i != 16; ++i) {
9942         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9943             !isa<UndefValue>(Mask->getOperand(i))) {
9944           AllEltsOk = false;
9945           break;
9946         }
9947       }
9948       
9949       if (AllEltsOk) {
9950         // Cast the input vectors to byte vectors.
9951         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9952         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9953         Value *Result = UndefValue::get(Op0->getType());
9954         
9955         // Only extract each element once.
9956         Value *ExtractedElts[32];
9957         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9958         
9959         for (unsigned i = 0; i != 16; ++i) {
9960           if (isa<UndefValue>(Mask->getOperand(i)))
9961             continue;
9962           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9963           Idx &= 31;  // Match the hardware behavior.
9964           
9965           if (ExtractedElts[Idx] == 0) {
9966             Instruction *Elt = 
9967               ExtractElementInst::Create(Idx < 16 ? Op0 : Op1, 
9968                   ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false), "tmp");
9969             InsertNewInstBefore(Elt, CI);
9970             ExtractedElts[Idx] = Elt;
9971           }
9972         
9973           // Insert this value into the result vector.
9974           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9975                                ConstantInt::get(Type::getInt32Ty(*Context), i, false), 
9976                                "tmp");
9977           InsertNewInstBefore(cast<Instruction>(Result), CI);
9978         }
9979         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9980       }
9981     }
9982     break;
9983
9984   case Intrinsic::stackrestore: {
9985     // If the save is right next to the restore, remove the restore.  This can
9986     // happen when variable allocas are DCE'd.
9987     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9988       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9989         BasicBlock::iterator BI = SS;
9990         if (&*++BI == II)
9991           return EraseInstFromFunction(CI);
9992       }
9993     }
9994     
9995     // Scan down this block to see if there is another stack restore in the
9996     // same block without an intervening call/alloca.
9997     BasicBlock::iterator BI = II;
9998     TerminatorInst *TI = II->getParent()->getTerminator();
9999     bool CannotRemove = false;
10000     for (++BI; &*BI != TI; ++BI) {
10001       if (isa<AllocaInst>(BI)) {
10002         CannotRemove = true;
10003         break;
10004       }
10005       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10006         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10007           // If there is a stackrestore below this one, remove this one.
10008           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10009             return EraseInstFromFunction(CI);
10010           // Otherwise, ignore the intrinsic.
10011         } else {
10012           // If we found a non-intrinsic call, we can't remove the stack
10013           // restore.
10014           CannotRemove = true;
10015           break;
10016         }
10017       }
10018     }
10019     
10020     // If the stack restore is in a return/unwind block and if there are no
10021     // allocas or calls between the restore and the return, nuke the restore.
10022     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10023       return EraseInstFromFunction(CI);
10024     break;
10025   }
10026   }
10027
10028   return visitCallSite(II);
10029 }
10030
10031 // InvokeInst simplification
10032 //
10033 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10034   return visitCallSite(&II);
10035 }
10036
10037 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10038 /// passed through the varargs area, we can eliminate the use of the cast.
10039 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10040                                          const CastInst * const CI,
10041                                          const TargetData * const TD,
10042                                          const int ix) {
10043   if (!CI->isLosslessCast())
10044     return false;
10045
10046   // The size of ByVal arguments is derived from the type, so we
10047   // can't change to a type with a different size.  If the size were
10048   // passed explicitly we could avoid this check.
10049   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10050     return true;
10051
10052   const Type* SrcTy = 
10053             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10054   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10055   if (!SrcTy->isSized() || !DstTy->isSized())
10056     return false;
10057   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10058     return false;
10059   return true;
10060 }
10061
10062 // visitCallSite - Improvements for call and invoke instructions.
10063 //
10064 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10065   bool Changed = false;
10066
10067   // If the callee is a constexpr cast of a function, attempt to move the cast
10068   // to the arguments of the call/invoke.
10069   if (transformConstExprCastCall(CS)) return 0;
10070
10071   Value *Callee = CS.getCalledValue();
10072
10073   if (Function *CalleeF = dyn_cast<Function>(Callee))
10074     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10075       Instruction *OldCall = CS.getInstruction();
10076       // If the call and callee calling conventions don't match, this call must
10077       // be unreachable, as the call is undefined.
10078       new StoreInst(ConstantInt::getTrue(*Context),
10079                 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), 
10080                                   OldCall);
10081       if (!OldCall->use_empty())
10082         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10083       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10084         return EraseInstFromFunction(*OldCall);
10085       return 0;
10086     }
10087
10088   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10089     // This instruction is not reachable, just remove it.  We insert a store to
10090     // undef so that we know that this code is not reachable, despite the fact
10091     // that we can't modify the CFG here.
10092     new StoreInst(ConstantInt::getTrue(*Context),
10093                UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
10094                   CS.getInstruction());
10095
10096     if (!CS.getInstruction()->use_empty())
10097       CS.getInstruction()->
10098         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10099
10100     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10101       // Don't break the CFG, insert a dummy cond branch.
10102       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10103                          ConstantInt::getTrue(*Context), II);
10104     }
10105     return EraseInstFromFunction(*CS.getInstruction());
10106   }
10107
10108   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10109     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10110       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10111         return transformCallThroughTrampoline(CS);
10112
10113   const PointerType *PTy = cast<PointerType>(Callee->getType());
10114   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10115   if (FTy->isVarArg()) {
10116     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10117     // See if we can optimize any arguments passed through the varargs area of
10118     // the call.
10119     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10120            E = CS.arg_end(); I != E; ++I, ++ix) {
10121       CastInst *CI = dyn_cast<CastInst>(*I);
10122       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10123         *I = CI->getOperand(0);
10124         Changed = true;
10125       }
10126     }
10127   }
10128
10129   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10130     // Inline asm calls cannot throw - mark them 'nounwind'.
10131     CS.setDoesNotThrow();
10132     Changed = true;
10133   }
10134
10135   return Changed ? CS.getInstruction() : 0;
10136 }
10137
10138 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10139 // attempt to move the cast to the arguments of the call/invoke.
10140 //
10141 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10142   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10143   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10144   if (CE->getOpcode() != Instruction::BitCast || 
10145       !isa<Function>(CE->getOperand(0)))
10146     return false;
10147   Function *Callee = cast<Function>(CE->getOperand(0));
10148   Instruction *Caller = CS.getInstruction();
10149   const AttrListPtr &CallerPAL = CS.getAttributes();
10150
10151   // Okay, this is a cast from a function to a different type.  Unless doing so
10152   // would cause a type conversion of one of our arguments, change this call to
10153   // be a direct call with arguments casted to the appropriate types.
10154   //
10155   const FunctionType *FT = Callee->getFunctionType();
10156   const Type *OldRetTy = Caller->getType();
10157   const Type *NewRetTy = FT->getReturnType();
10158
10159   if (isa<StructType>(NewRetTy))
10160     return false; // TODO: Handle multiple return values.
10161
10162   // Check to see if we are changing the return type...
10163   if (OldRetTy != NewRetTy) {
10164     if (Callee->isDeclaration() &&
10165         // Conversion is ok if changing from one pointer type to another or from
10166         // a pointer to an integer of the same size.
10167         !((isa<PointerType>(OldRetTy) || !TD ||
10168            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10169           (isa<PointerType>(NewRetTy) || !TD ||
10170            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10171       return false;   // Cannot transform this return value.
10172
10173     if (!Caller->use_empty() &&
10174         // void -> non-void is handled specially
10175         NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
10176       return false;   // Cannot transform this return value.
10177
10178     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10179       Attributes RAttrs = CallerPAL.getRetAttributes();
10180       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10181         return false;   // Attribute not compatible with transformed value.
10182     }
10183
10184     // If the callsite is an invoke instruction, and the return value is used by
10185     // a PHI node in a successor, we cannot change the return type of the call
10186     // because there is no place to put the cast instruction (without breaking
10187     // the critical edge).  Bail out in this case.
10188     if (!Caller->use_empty())
10189       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10190         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10191              UI != E; ++UI)
10192           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10193             if (PN->getParent() == II->getNormalDest() ||
10194                 PN->getParent() == II->getUnwindDest())
10195               return false;
10196   }
10197
10198   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10199   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10200
10201   CallSite::arg_iterator AI = CS.arg_begin();
10202   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10203     const Type *ParamTy = FT->getParamType(i);
10204     const Type *ActTy = (*AI)->getType();
10205
10206     if (!CastInst::isCastable(ActTy, ParamTy))
10207       return false;   // Cannot transform this parameter value.
10208
10209     if (CallerPAL.getParamAttributes(i + 1) 
10210         & Attribute::typeIncompatible(ParamTy))
10211       return false;   // Attribute not compatible with transformed value.
10212
10213     // Converting from one pointer type to another or between a pointer and an
10214     // integer of the same size is safe even if we do not have a body.
10215     bool isConvertible = ActTy == ParamTy ||
10216       (TD && ((isa<PointerType>(ParamTy) ||
10217       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10218               (isa<PointerType>(ActTy) ||
10219               ActTy == TD->getIntPtrType(Caller->getContext()))));
10220     if (Callee->isDeclaration() && !isConvertible) return false;
10221   }
10222
10223   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10224       Callee->isDeclaration())
10225     return false;   // Do not delete arguments unless we have a function body.
10226
10227   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10228       !CallerPAL.isEmpty())
10229     // In this case we have more arguments than the new function type, but we
10230     // won't be dropping them.  Check that these extra arguments have attributes
10231     // that are compatible with being a vararg call argument.
10232     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10233       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10234         break;
10235       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10236       if (PAttrs & Attribute::VarArgsIncompatible)
10237         return false;
10238     }
10239
10240   // Okay, we decided that this is a safe thing to do: go ahead and start
10241   // inserting cast instructions as necessary...
10242   std::vector<Value*> Args;
10243   Args.reserve(NumActualArgs);
10244   SmallVector<AttributeWithIndex, 8> attrVec;
10245   attrVec.reserve(NumCommonArgs);
10246
10247   // Get any return attributes.
10248   Attributes RAttrs = CallerPAL.getRetAttributes();
10249
10250   // If the return value is not being used, the type may not be compatible
10251   // with the existing attributes.  Wipe out any problematic attributes.
10252   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10253
10254   // Add the new return attributes.
10255   if (RAttrs)
10256     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10257
10258   AI = CS.arg_begin();
10259   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10260     const Type *ParamTy = FT->getParamType(i);
10261     if ((*AI)->getType() == ParamTy) {
10262       Args.push_back(*AI);
10263     } else {
10264       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10265           false, ParamTy, false);
10266       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10267       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10268     }
10269
10270     // Add any parameter attributes.
10271     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10272       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10273   }
10274
10275   // If the function takes more arguments than the call was taking, add them
10276   // now...
10277   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10278     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10279
10280   // If we are removing arguments to the function, emit an obnoxious warning...
10281   if (FT->getNumParams() < NumActualArgs) {
10282     if (!FT->isVarArg()) {
10283       errs() << "WARNING: While resolving call to function '"
10284              << Callee->getName() << "' arguments were dropped!\n";
10285     } else {
10286       // Add all of the arguments in their promoted form to the arg list...
10287       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10288         const Type *PTy = getPromotedType((*AI)->getType());
10289         if (PTy != (*AI)->getType()) {
10290           // Must promote to pass through va_arg area!
10291           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10292                                                                 PTy, false);
10293           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10294           InsertNewInstBefore(Cast, *Caller);
10295           Args.push_back(Cast);
10296         } else {
10297           Args.push_back(*AI);
10298         }
10299
10300         // Add any parameter attributes.
10301         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10302           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10303       }
10304     }
10305   }
10306
10307   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10308     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10309
10310   if (NewRetTy == Type::getVoidTy(*Context))
10311     Caller->setName("");   // Void type should not have a name.
10312
10313   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10314                                                      attrVec.end());
10315
10316   Instruction *NC;
10317   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10318     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10319                             Args.begin(), Args.end(),
10320                             Caller->getName(), Caller);
10321     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10322     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10323   } else {
10324     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10325                           Caller->getName(), Caller);
10326     CallInst *CI = cast<CallInst>(Caller);
10327     if (CI->isTailCall())
10328       cast<CallInst>(NC)->setTailCall();
10329     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10330     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10331   }
10332
10333   // Insert a cast of the return type as necessary.
10334   Value *NV = NC;
10335   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10336     if (NV->getType() != Type::getVoidTy(*Context)) {
10337       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10338                                                             OldRetTy, false);
10339       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10340
10341       // If this is an invoke instruction, we should insert it after the first
10342       // non-phi, instruction in the normal successor block.
10343       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10344         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10345         InsertNewInstBefore(NC, *I);
10346       } else {
10347         // Otherwise, it's a call, just insert cast right after the call instr
10348         InsertNewInstBefore(NC, *Caller);
10349       }
10350       AddUsersToWorkList(*Caller);
10351     } else {
10352       NV = UndefValue::get(Caller->getType());
10353     }
10354   }
10355
10356   if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10357     Caller->replaceAllUsesWith(NV);
10358   Caller->eraseFromParent();
10359   RemoveFromWorkList(Caller);
10360   return true;
10361 }
10362
10363 // transformCallThroughTrampoline - Turn a call to a function created by the
10364 // init_trampoline intrinsic into a direct call to the underlying function.
10365 //
10366 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10367   Value *Callee = CS.getCalledValue();
10368   const PointerType *PTy = cast<PointerType>(Callee->getType());
10369   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10370   const AttrListPtr &Attrs = CS.getAttributes();
10371
10372   // If the call already has the 'nest' attribute somewhere then give up -
10373   // otherwise 'nest' would occur twice after splicing in the chain.
10374   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10375     return 0;
10376
10377   IntrinsicInst *Tramp =
10378     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10379
10380   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10381   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10382   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10383
10384   const AttrListPtr &NestAttrs = NestF->getAttributes();
10385   if (!NestAttrs.isEmpty()) {
10386     unsigned NestIdx = 1;
10387     const Type *NestTy = 0;
10388     Attributes NestAttr = Attribute::None;
10389
10390     // Look for a parameter marked with the 'nest' attribute.
10391     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10392          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10393       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10394         // Record the parameter type and any other attributes.
10395         NestTy = *I;
10396         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10397         break;
10398       }
10399
10400     if (NestTy) {
10401       Instruction *Caller = CS.getInstruction();
10402       std::vector<Value*> NewArgs;
10403       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10404
10405       SmallVector<AttributeWithIndex, 8> NewAttrs;
10406       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10407
10408       // Insert the nest argument into the call argument list, which may
10409       // mean appending it.  Likewise for attributes.
10410
10411       // Add any result attributes.
10412       if (Attributes Attr = Attrs.getRetAttributes())
10413         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10414
10415       {
10416         unsigned Idx = 1;
10417         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10418         do {
10419           if (Idx == NestIdx) {
10420             // Add the chain argument and attributes.
10421             Value *NestVal = Tramp->getOperand(3);
10422             if (NestVal->getType() != NestTy)
10423               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10424             NewArgs.push_back(NestVal);
10425             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10426           }
10427
10428           if (I == E)
10429             break;
10430
10431           // Add the original argument and attributes.
10432           NewArgs.push_back(*I);
10433           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10434             NewAttrs.push_back
10435               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10436
10437           ++Idx, ++I;
10438         } while (1);
10439       }
10440
10441       // Add any function attributes.
10442       if (Attributes Attr = Attrs.getFnAttributes())
10443         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10444
10445       // The trampoline may have been bitcast to a bogus type (FTy).
10446       // Handle this by synthesizing a new function type, equal to FTy
10447       // with the chain parameter inserted.
10448
10449       std::vector<const Type*> NewTypes;
10450       NewTypes.reserve(FTy->getNumParams()+1);
10451
10452       // Insert the chain's type into the list of parameter types, which may
10453       // mean appending it.
10454       {
10455         unsigned Idx = 1;
10456         FunctionType::param_iterator I = FTy->param_begin(),
10457           E = FTy->param_end();
10458
10459         do {
10460           if (Idx == NestIdx)
10461             // Add the chain's type.
10462             NewTypes.push_back(NestTy);
10463
10464           if (I == E)
10465             break;
10466
10467           // Add the original type.
10468           NewTypes.push_back(*I);
10469
10470           ++Idx, ++I;
10471         } while (1);
10472       }
10473
10474       // Replace the trampoline call with a direct call.  Let the generic
10475       // code sort out any function type mismatches.
10476       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10477                                                 FTy->isVarArg());
10478       Constant *NewCallee =
10479         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10480         NestF : ConstantExpr::getBitCast(NestF, 
10481                                          PointerType::getUnqual(NewFTy));
10482       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10483                                                    NewAttrs.end());
10484
10485       Instruction *NewCaller;
10486       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10487         NewCaller = InvokeInst::Create(NewCallee,
10488                                        II->getNormalDest(), II->getUnwindDest(),
10489                                        NewArgs.begin(), NewArgs.end(),
10490                                        Caller->getName(), Caller);
10491         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10492         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10493       } else {
10494         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10495                                      Caller->getName(), Caller);
10496         if (cast<CallInst>(Caller)->isTailCall())
10497           cast<CallInst>(NewCaller)->setTailCall();
10498         cast<CallInst>(NewCaller)->
10499           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10500         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10501       }
10502       if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10503         Caller->replaceAllUsesWith(NewCaller);
10504       Caller->eraseFromParent();
10505       RemoveFromWorkList(Caller);
10506       return 0;
10507     }
10508   }
10509
10510   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10511   // parameter, there is no need to adjust the argument list.  Let the generic
10512   // code sort out any function type mismatches.
10513   Constant *NewCallee =
10514     NestF->getType() == PTy ? NestF : 
10515                               ConstantExpr::getBitCast(NestF, PTy);
10516   CS.setCalledFunction(NewCallee);
10517   return CS.getInstruction();
10518 }
10519
10520 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10521 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10522 /// and a single binop.
10523 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10524   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10525   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10526   unsigned Opc = FirstInst->getOpcode();
10527   Value *LHSVal = FirstInst->getOperand(0);
10528   Value *RHSVal = FirstInst->getOperand(1);
10529     
10530   const Type *LHSType = LHSVal->getType();
10531   const Type *RHSType = RHSVal->getType();
10532   
10533   // Scan to see if all operands are the same opcode, all have one use, and all
10534   // kill their operands (i.e. the operands have one use).
10535   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10536     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10537     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10538         // Verify type of the LHS matches so we don't fold cmp's of different
10539         // types or GEP's with different index types.
10540         I->getOperand(0)->getType() != LHSType ||
10541         I->getOperand(1)->getType() != RHSType)
10542       return 0;
10543
10544     // If they are CmpInst instructions, check their predicates
10545     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10546       if (cast<CmpInst>(I)->getPredicate() !=
10547           cast<CmpInst>(FirstInst)->getPredicate())
10548         return 0;
10549     
10550     // Keep track of which operand needs a phi node.
10551     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10552     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10553   }
10554   
10555   // Otherwise, this is safe to transform!
10556   
10557   Value *InLHS = FirstInst->getOperand(0);
10558   Value *InRHS = FirstInst->getOperand(1);
10559   PHINode *NewLHS = 0, *NewRHS = 0;
10560   if (LHSVal == 0) {
10561     NewLHS = PHINode::Create(LHSType,
10562                              FirstInst->getOperand(0)->getName() + ".pn");
10563     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10564     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10565     InsertNewInstBefore(NewLHS, PN);
10566     LHSVal = NewLHS;
10567   }
10568   
10569   if (RHSVal == 0) {
10570     NewRHS = PHINode::Create(RHSType,
10571                              FirstInst->getOperand(1)->getName() + ".pn");
10572     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10573     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10574     InsertNewInstBefore(NewRHS, PN);
10575     RHSVal = NewRHS;
10576   }
10577   
10578   // Add all operands to the new PHIs.
10579   if (NewLHS || NewRHS) {
10580     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10581       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10582       if (NewLHS) {
10583         Value *NewInLHS = InInst->getOperand(0);
10584         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10585       }
10586       if (NewRHS) {
10587         Value *NewInRHS = InInst->getOperand(1);
10588         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10589       }
10590     }
10591   }
10592     
10593   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10594     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10595   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10596   return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10597                          LHSVal, RHSVal);
10598 }
10599
10600 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10601   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10602   
10603   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10604                                         FirstInst->op_end());
10605   // This is true if all GEP bases are allocas and if all indices into them are
10606   // constants.
10607   bool AllBasePointersAreAllocas = true;
10608   
10609   // Scan to see if all operands are the same opcode, all have one use, and all
10610   // kill their operands (i.e. the operands have one use).
10611   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10612     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10613     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10614       GEP->getNumOperands() != FirstInst->getNumOperands())
10615       return 0;
10616
10617     // Keep track of whether or not all GEPs are of alloca pointers.
10618     if (AllBasePointersAreAllocas &&
10619         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10620          !GEP->hasAllConstantIndices()))
10621       AllBasePointersAreAllocas = false;
10622     
10623     // Compare the operand lists.
10624     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10625       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10626         continue;
10627       
10628       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10629       // if one of the PHIs has a constant for the index.  The index may be
10630       // substantially cheaper to compute for the constants, so making it a
10631       // variable index could pessimize the path.  This also handles the case
10632       // for struct indices, which must always be constant.
10633       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10634           isa<ConstantInt>(GEP->getOperand(op)))
10635         return 0;
10636       
10637       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10638         return 0;
10639       FixedOperands[op] = 0;  // Needs a PHI.
10640     }
10641   }
10642   
10643   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10644   // bother doing this transformation.  At best, this will just save a bit of
10645   // offset calculation, but all the predecessors will have to materialize the
10646   // stack address into a register anyway.  We'd actually rather *clone* the
10647   // load up into the predecessors so that we have a load of a gep of an alloca,
10648   // which can usually all be folded into the load.
10649   if (AllBasePointersAreAllocas)
10650     return 0;
10651   
10652   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10653   // that is variable.
10654   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10655   
10656   bool HasAnyPHIs = false;
10657   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10658     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10659     Value *FirstOp = FirstInst->getOperand(i);
10660     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10661                                      FirstOp->getName()+".pn");
10662     InsertNewInstBefore(NewPN, PN);
10663     
10664     NewPN->reserveOperandSpace(e);
10665     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10666     OperandPhis[i] = NewPN;
10667     FixedOperands[i] = NewPN;
10668     HasAnyPHIs = true;
10669   }
10670
10671   
10672   // Add all operands to the new PHIs.
10673   if (HasAnyPHIs) {
10674     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10675       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10676       BasicBlock *InBB = PN.getIncomingBlock(i);
10677       
10678       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10679         if (PHINode *OpPhi = OperandPhis[op])
10680           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10681     }
10682   }
10683   
10684   Value *Base = FixedOperands[0];
10685   GetElementPtrInst *GEP =
10686     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10687                               FixedOperands.end());
10688   if (cast<GEPOperator>(FirstInst)->isInBounds())
10689     cast<GEPOperator>(GEP)->setIsInBounds(true);
10690   return GEP;
10691 }
10692
10693
10694 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10695 /// sink the load out of the block that defines it.  This means that it must be
10696 /// obvious the value of the load is not changed from the point of the load to
10697 /// the end of the block it is in.
10698 ///
10699 /// Finally, it is safe, but not profitable, to sink a load targetting a
10700 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10701 /// to a register.
10702 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10703   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10704   
10705   for (++BBI; BBI != E; ++BBI)
10706     if (BBI->mayWriteToMemory())
10707       return false;
10708   
10709   // Check for non-address taken alloca.  If not address-taken already, it isn't
10710   // profitable to do this xform.
10711   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10712     bool isAddressTaken = false;
10713     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10714          UI != E; ++UI) {
10715       if (isa<LoadInst>(UI)) continue;
10716       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10717         // If storing TO the alloca, then the address isn't taken.
10718         if (SI->getOperand(1) == AI) continue;
10719       }
10720       isAddressTaken = true;
10721       break;
10722     }
10723     
10724     if (!isAddressTaken && AI->isStaticAlloca())
10725       return false;
10726   }
10727   
10728   // If this load is a load from a GEP with a constant offset from an alloca,
10729   // then we don't want to sink it.  In its present form, it will be
10730   // load [constant stack offset].  Sinking it will cause us to have to
10731   // materialize the stack addresses in each predecessor in a register only to
10732   // do a shared load from register in the successor.
10733   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10734     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10735       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10736         return false;
10737   
10738   return true;
10739 }
10740
10741
10742 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10743 // operator and they all are only used by the PHI, PHI together their
10744 // inputs, and do the operation once, to the result of the PHI.
10745 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10746   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10747
10748   // Scan the instruction, looking for input operations that can be folded away.
10749   // If all input operands to the phi are the same instruction (e.g. a cast from
10750   // the same type or "+42") we can pull the operation through the PHI, reducing
10751   // code size and simplifying code.
10752   Constant *ConstantOp = 0;
10753   const Type *CastSrcTy = 0;
10754   bool isVolatile = false;
10755   if (isa<CastInst>(FirstInst)) {
10756     CastSrcTy = FirstInst->getOperand(0)->getType();
10757   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10758     // Can fold binop, compare or shift here if the RHS is a constant, 
10759     // otherwise call FoldPHIArgBinOpIntoPHI.
10760     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10761     if (ConstantOp == 0)
10762       return FoldPHIArgBinOpIntoPHI(PN);
10763   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10764     isVolatile = LI->isVolatile();
10765     // We can't sink the load if the loaded value could be modified between the
10766     // load and the PHI.
10767     if (LI->getParent() != PN.getIncomingBlock(0) ||
10768         !isSafeAndProfitableToSinkLoad(LI))
10769       return 0;
10770     
10771     // If the PHI is of volatile loads and the load block has multiple
10772     // successors, sinking it would remove a load of the volatile value from
10773     // the path through the other successor.
10774     if (isVolatile &&
10775         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10776       return 0;
10777     
10778   } else if (isa<GetElementPtrInst>(FirstInst)) {
10779     return FoldPHIArgGEPIntoPHI(PN);
10780   } else {
10781     return 0;  // Cannot fold this operation.
10782   }
10783
10784   // Check to see if all arguments are the same operation.
10785   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10786     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10787     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10788     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10789       return 0;
10790     if (CastSrcTy) {
10791       if (I->getOperand(0)->getType() != CastSrcTy)
10792         return 0;  // Cast operation must match.
10793     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10794       // We can't sink the load if the loaded value could be modified between 
10795       // the load and the PHI.
10796       if (LI->isVolatile() != isVolatile ||
10797           LI->getParent() != PN.getIncomingBlock(i) ||
10798           !isSafeAndProfitableToSinkLoad(LI))
10799         return 0;
10800       
10801       // If the PHI is of volatile loads and the load block has multiple
10802       // successors, sinking it would remove a load of the volatile value from
10803       // the path through the other successor.
10804       if (isVolatile &&
10805           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10806         return 0;
10807       
10808     } else if (I->getOperand(1) != ConstantOp) {
10809       return 0;
10810     }
10811   }
10812
10813   // Okay, they are all the same operation.  Create a new PHI node of the
10814   // correct type, and PHI together all of the LHS's of the instructions.
10815   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10816                                    PN.getName()+".in");
10817   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10818
10819   Value *InVal = FirstInst->getOperand(0);
10820   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10821
10822   // Add all operands to the new PHI.
10823   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10824     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10825     if (NewInVal != InVal)
10826       InVal = 0;
10827     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10828   }
10829
10830   Value *PhiVal;
10831   if (InVal) {
10832     // The new PHI unions all of the same values together.  This is really
10833     // common, so we handle it intelligently here for compile-time speed.
10834     PhiVal = InVal;
10835     delete NewPN;
10836   } else {
10837     InsertNewInstBefore(NewPN, PN);
10838     PhiVal = NewPN;
10839   }
10840
10841   // Insert and return the new operation.
10842   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10843     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10844   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10845     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10846   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10847     return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10848                            PhiVal, ConstantOp);
10849   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10850   
10851   // If this was a volatile load that we are merging, make sure to loop through
10852   // and mark all the input loads as non-volatile.  If we don't do this, we will
10853   // insert a new volatile load and the old ones will not be deletable.
10854   if (isVolatile)
10855     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10856       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10857   
10858   return new LoadInst(PhiVal, "", isVolatile);
10859 }
10860
10861 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10862 /// that is dead.
10863 static bool DeadPHICycle(PHINode *PN,
10864                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10865   if (PN->use_empty()) return true;
10866   if (!PN->hasOneUse()) return false;
10867
10868   // Remember this node, and if we find the cycle, return.
10869   if (!PotentiallyDeadPHIs.insert(PN))
10870     return true;
10871   
10872   // Don't scan crazily complex things.
10873   if (PotentiallyDeadPHIs.size() == 16)
10874     return false;
10875
10876   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10877     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10878
10879   return false;
10880 }
10881
10882 /// PHIsEqualValue - Return true if this phi node is always equal to
10883 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10884 ///   z = some value; x = phi (y, z); y = phi (x, z)
10885 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10886                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10887   // See if we already saw this PHI node.
10888   if (!ValueEqualPHIs.insert(PN))
10889     return true;
10890   
10891   // Don't scan crazily complex things.
10892   if (ValueEqualPHIs.size() == 16)
10893     return false;
10894  
10895   // Scan the operands to see if they are either phi nodes or are equal to
10896   // the value.
10897   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10898     Value *Op = PN->getIncomingValue(i);
10899     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10900       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10901         return false;
10902     } else if (Op != NonPhiInVal)
10903       return false;
10904   }
10905   
10906   return true;
10907 }
10908
10909
10910 // PHINode simplification
10911 //
10912 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10913   // If LCSSA is around, don't mess with Phi nodes
10914   if (MustPreserveLCSSA) return 0;
10915   
10916   if (Value *V = PN.hasConstantValue())
10917     return ReplaceInstUsesWith(PN, V);
10918
10919   // If all PHI operands are the same operation, pull them through the PHI,
10920   // reducing code size.
10921   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10922       isa<Instruction>(PN.getIncomingValue(1)) &&
10923       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10924       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10925       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10926       // than themselves more than once.
10927       PN.getIncomingValue(0)->hasOneUse())
10928     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10929       return Result;
10930
10931   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10932   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10933   // PHI)... break the cycle.
10934   if (PN.hasOneUse()) {
10935     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10936     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10937       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10938       PotentiallyDeadPHIs.insert(&PN);
10939       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10940         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10941     }
10942    
10943     // If this phi has a single use, and if that use just computes a value for
10944     // the next iteration of a loop, delete the phi.  This occurs with unused
10945     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10946     // common case here is good because the only other things that catch this
10947     // are induction variable analysis (sometimes) and ADCE, which is only run
10948     // late.
10949     if (PHIUser->hasOneUse() &&
10950         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10951         PHIUser->use_back() == &PN) {
10952       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10953     }
10954   }
10955
10956   // We sometimes end up with phi cycles that non-obviously end up being the
10957   // same value, for example:
10958   //   z = some value; x = phi (y, z); y = phi (x, z)
10959   // where the phi nodes don't necessarily need to be in the same block.  Do a
10960   // quick check to see if the PHI node only contains a single non-phi value, if
10961   // so, scan to see if the phi cycle is actually equal to that value.
10962   {
10963     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10964     // Scan for the first non-phi operand.
10965     while (InValNo != NumOperandVals && 
10966            isa<PHINode>(PN.getIncomingValue(InValNo)))
10967       ++InValNo;
10968
10969     if (InValNo != NumOperandVals) {
10970       Value *NonPhiInVal = PN.getOperand(InValNo);
10971       
10972       // Scan the rest of the operands to see if there are any conflicts, if so
10973       // there is no need to recursively scan other phis.
10974       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10975         Value *OpVal = PN.getIncomingValue(InValNo);
10976         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10977           break;
10978       }
10979       
10980       // If we scanned over all operands, then we have one unique value plus
10981       // phi values.  Scan PHI nodes to see if they all merge in each other or
10982       // the value.
10983       if (InValNo == NumOperandVals) {
10984         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10985         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10986           return ReplaceInstUsesWith(PN, NonPhiInVal);
10987       }
10988     }
10989   }
10990   return 0;
10991 }
10992
10993 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10994                                    Instruction *InsertPoint,
10995                                    InstCombiner *IC) {
10996   unsigned PtrSize = DTy->getScalarSizeInBits();
10997   unsigned VTySize = V->getType()->getScalarSizeInBits();
10998   // We must cast correctly to the pointer type. Ensure that we
10999   // sign extend the integer value if it is smaller as this is
11000   // used for address computation.
11001   Instruction::CastOps opcode = 
11002      (VTySize < PtrSize ? Instruction::SExt :
11003       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
11004   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
11005 }
11006
11007
11008 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11009   Value *PtrOp = GEP.getOperand(0);
11010   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
11011   // If so, eliminate the noop.
11012   if (GEP.getNumOperands() == 1)
11013     return ReplaceInstUsesWith(GEP, PtrOp);
11014
11015   if (isa<UndefValue>(GEP.getOperand(0)))
11016     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
11017
11018   bool HasZeroPointerIndex = false;
11019   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11020     HasZeroPointerIndex = C->isNullValue();
11021
11022   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11023     return ReplaceInstUsesWith(GEP, PtrOp);
11024
11025   // Eliminate unneeded casts for indices.
11026   bool MadeChange = false;
11027   
11028   gep_type_iterator GTI = gep_type_begin(GEP);
11029   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11030        i != e; ++i, ++GTI) {
11031     if (TD && isa<SequentialType>(*GTI)) {
11032       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
11033         if (CI->getOpcode() == Instruction::ZExt ||
11034             CI->getOpcode() == Instruction::SExt) {
11035           const Type *SrcTy = CI->getOperand(0)->getType();
11036           // We can eliminate a cast from i32 to i64 iff the target 
11037           // is a 32-bit pointer target.
11038           if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
11039             MadeChange = true;
11040             *i = CI->getOperand(0);
11041           }
11042         }
11043       }
11044       // If we are using a wider index than needed for this platform, shrink it
11045       // to what we need.  If narrower, sign-extend it to what we need.
11046       // If the incoming value needs a cast instruction,
11047       // insert it.  This explicit cast can make subsequent optimizations more
11048       // obvious.
11049       Value *Op = *i;
11050       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
11051         if (Constant *C = dyn_cast<Constant>(Op)) {
11052           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType(GEP.getContext()));
11053           MadeChange = true;
11054         } else {
11055           Op = InsertCastBefore(Instruction::Trunc, Op, 
11056                                 TD->getIntPtrType(GEP.getContext()),
11057                                 GEP);
11058           *i = Op;
11059           MadeChange = true;
11060         }
11061       } else if (TD->getTypeSizeInBits(Op->getType()) 
11062                   < TD->getPointerSizeInBits()) {
11063         if (Constant *C = dyn_cast<Constant>(Op)) {
11064           *i = ConstantExpr::getSExt(C, TD->getIntPtrType(GEP.getContext()));
11065           MadeChange = true;
11066         } else {
11067           Op = InsertCastBefore(Instruction::SExt, Op, 
11068                                 TD->getIntPtrType(GEP.getContext()), GEP);
11069           *i = Op;
11070           MadeChange = true;
11071         }
11072       }
11073     }
11074   }
11075   if (MadeChange) return &GEP;
11076
11077   // Combine Indices - If the source pointer to this getelementptr instruction
11078   // is a getelementptr instruction, combine the indices of the two
11079   // getelementptr instructions into a single instruction.
11080   //
11081   SmallVector<Value*, 8> SrcGEPOperands;
11082   bool BothInBounds = cast<GEPOperator>(&GEP)->isInBounds();
11083   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
11084     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11085     if (!Src->isInBounds())
11086       BothInBounds = false;
11087   }
11088
11089   if (!SrcGEPOperands.empty()) {
11090     // Note that if our source is a gep chain itself that we wait for that
11091     // chain to be resolved before we perform this transformation.  This
11092     // avoids us creating a TON of code in some cases.
11093     //
11094     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11095         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11096       return 0;   // Wait until our source is folded to completion.
11097
11098     SmallVector<Value*, 8> Indices;
11099
11100     // Find out whether the last index in the source GEP is a sequential idx.
11101     bool EndsWithSequential = false;
11102     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11103            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11104       EndsWithSequential = !isa<StructType>(*I);
11105
11106     // Can we combine the two pointer arithmetics offsets?
11107     if (EndsWithSequential) {
11108       // Replace: gep (gep %P, long B), long A, ...
11109       // With:    T = long A+B; gep %P, T, ...
11110       //
11111       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11112       if (SO1 == Constant::getNullValue(SO1->getType())) {
11113         Sum = GO1;
11114       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11115         Sum = SO1;
11116       } else {
11117         // If they aren't the same type, convert both to an integer of the
11118         // target's pointer size.
11119         if (SO1->getType() != GO1->getType()) {
11120           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11121             SO1 =
11122                 ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
11123           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11124             GO1 =
11125                 ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
11126           } else if (TD) {
11127             unsigned PS = TD->getPointerSizeInBits();
11128             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11129               // Convert GO1 to SO1's type.
11130               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11131
11132             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11133               // Convert SO1 to GO1's type.
11134               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11135             } else {
11136               const Type *PT = TD->getIntPtrType(GEP.getContext());
11137               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11138               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11139             }
11140           }
11141         }
11142         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11143           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), 
11144                                             cast<Constant>(GO1));
11145         else {
11146           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11147           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11148         }
11149       }
11150
11151       // Recycle the GEP we already have if possible.
11152       if (SrcGEPOperands.size() == 2) {
11153         GEP.setOperand(0, SrcGEPOperands[0]);
11154         GEP.setOperand(1, Sum);
11155         return &GEP;
11156       } else {
11157         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11158                        SrcGEPOperands.end()-1);
11159         Indices.push_back(Sum);
11160         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11161       }
11162     } else if (isa<Constant>(*GEP.idx_begin()) &&
11163                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11164                SrcGEPOperands.size() != 1) {
11165       // Otherwise we can do the fold if the first index of the GEP is a zero
11166       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11167                      SrcGEPOperands.end());
11168       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11169     }
11170
11171     if (!Indices.empty()) {
11172       GetElementPtrInst *NewGEP = GetElementPtrInst::Create(SrcGEPOperands[0],
11173                                                             Indices.begin(),
11174                                                             Indices.end(),
11175                                                             GEP.getName());
11176       if (BothInBounds)
11177         cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11178       return NewGEP;
11179     }
11180
11181   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11182     // GEP of global variable.  If all of the indices for this GEP are
11183     // constants, we can promote this to a constexpr instead of an instruction.
11184
11185     // Scan for nonconstants...
11186     SmallVector<Constant*, 8> Indices;
11187     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11188     for (; I != E && isa<Constant>(*I); ++I)
11189       Indices.push_back(cast<Constant>(*I));
11190
11191     if (I == E) {  // If they are all constants...
11192       Constant *CE = ConstantExpr::getGetElementPtr(GV,
11193                                                     &Indices[0],Indices.size());
11194
11195       // Replace all uses of the GEP with the new constexpr...
11196       return ReplaceInstUsesWith(GEP, CE);
11197     }
11198   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11199     if (!isa<PointerType>(X->getType())) {
11200       // Not interesting.  Source pointer must be a cast from pointer.
11201     } else if (HasZeroPointerIndex) {
11202       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11203       // into     : GEP [10 x i8]* X, i32 0, ...
11204       //
11205       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11206       //           into     : GEP i8* X, ...
11207       // 
11208       // This occurs when the program declares an array extern like "int X[];"
11209       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11210       const PointerType *XTy = cast<PointerType>(X->getType());
11211       if (const ArrayType *CATy =
11212           dyn_cast<ArrayType>(CPTy->getElementType())) {
11213         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11214         if (CATy->getElementType() == XTy->getElementType()) {
11215           // -> GEP i8* X, ...
11216           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11217           GetElementPtrInst *NewGEP =
11218             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11219                                       GEP.getName());
11220           if (cast<GEPOperator>(&GEP)->isInBounds())
11221             cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11222           return NewGEP;
11223         } else if (const ArrayType *XATy =
11224                  dyn_cast<ArrayType>(XTy->getElementType())) {
11225           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11226           if (CATy->getElementType() == XATy->getElementType()) {
11227             // -> GEP [10 x i8]* X, i32 0, ...
11228             // At this point, we know that the cast source type is a pointer
11229             // to an array of the same type as the destination pointer
11230             // array.  Because the array type is never stepped over (there
11231             // is a leading zero) we can fold the cast into this GEP.
11232             GEP.setOperand(0, X);
11233             return &GEP;
11234           }
11235         }
11236       }
11237     } else if (GEP.getNumOperands() == 2) {
11238       // Transform things like:
11239       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11240       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11241       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11242       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11243       if (TD && isa<ArrayType>(SrcElTy) &&
11244           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11245           TD->getTypeAllocSize(ResElTy)) {
11246         Value *Idx[2];
11247         Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11248         Idx[1] = GEP.getOperand(1);
11249         GetElementPtrInst *NewGEP =
11250           GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11251         if (cast<GEPOperator>(&GEP)->isInBounds())
11252           cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11253         Value *V = InsertNewInstBefore(NewGEP, GEP);
11254         // V and GEP are both pointer types --> BitCast
11255         return new BitCastInst(V, GEP.getType());
11256       }
11257       
11258       // Transform things like:
11259       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11260       //   (where tmp = 8*tmp2) into:
11261       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11262       
11263       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
11264         uint64_t ArrayEltSize =
11265             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11266         
11267         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11268         // allow either a mul, shift, or constant here.
11269         Value *NewIdx = 0;
11270         ConstantInt *Scale = 0;
11271         if (ArrayEltSize == 1) {
11272           NewIdx = GEP.getOperand(1);
11273           Scale = 
11274                ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11275         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11276           NewIdx = ConstantInt::get(CI->getType(), 1);
11277           Scale = CI;
11278         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11279           if (Inst->getOpcode() == Instruction::Shl &&
11280               isa<ConstantInt>(Inst->getOperand(1))) {
11281             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11282             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11283             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11284                                      1ULL << ShAmtVal);
11285             NewIdx = Inst->getOperand(0);
11286           } else if (Inst->getOpcode() == Instruction::Mul &&
11287                      isa<ConstantInt>(Inst->getOperand(1))) {
11288             Scale = cast<ConstantInt>(Inst->getOperand(1));
11289             NewIdx = Inst->getOperand(0);
11290           }
11291         }
11292         
11293         // If the index will be to exactly the right offset with the scale taken
11294         // out, perform the transformation. Note, we don't know whether Scale is
11295         // signed or not. We'll use unsigned version of division/modulo
11296         // operation after making sure Scale doesn't have the sign bit set.
11297         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11298             Scale->getZExtValue() % ArrayEltSize == 0) {
11299           Scale = ConstantInt::get(Scale->getType(),
11300                                    Scale->getZExtValue() / ArrayEltSize);
11301           if (Scale->getZExtValue() != 1) {
11302             Constant *C =
11303                    ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11304                                                        false /*ZExt*/);
11305             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11306             NewIdx = InsertNewInstBefore(Sc, GEP);
11307           }
11308
11309           // Insert the new GEP instruction.
11310           Value *Idx[2];
11311           Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11312           Idx[1] = NewIdx;
11313           Instruction *NewGEP =
11314             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11315           if (cast<GEPOperator>(&GEP)->isInBounds())
11316             cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11317           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11318           // The NewGEP must be pointer typed, so must the old one -> BitCast
11319           return new BitCastInst(NewGEP, GEP.getType());
11320         }
11321       }
11322     }
11323   }
11324   
11325   /// See if we can simplify:
11326   ///   X = bitcast A to B*
11327   ///   Y = gep X, <...constant indices...>
11328   /// into a gep of the original struct.  This is important for SROA and alias
11329   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11330   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11331     if (TD &&
11332         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11333       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11334       // a constant back from EmitGEPOffset.
11335       ConstantInt *OffsetV =
11336                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11337       int64_t Offset = OffsetV->getSExtValue();
11338       
11339       // If this GEP instruction doesn't move the pointer, just replace the GEP
11340       // with a bitcast of the real input to the dest type.
11341       if (Offset == 0) {
11342         // If the bitcast is of an allocation, and the allocation will be
11343         // converted to match the type of the cast, don't touch this.
11344         if (isa<AllocationInst>(BCI->getOperand(0))) {
11345           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11346           if (Instruction *I = visitBitCast(*BCI)) {
11347             if (I != BCI) {
11348               I->takeName(BCI);
11349               BCI->getParent()->getInstList().insert(BCI, I);
11350               ReplaceInstUsesWith(*BCI, I);
11351             }
11352             return &GEP;
11353           }
11354         }
11355         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11356       }
11357       
11358       // Otherwise, if the offset is non-zero, we need to find out if there is a
11359       // field at Offset in 'A's type.  If so, we can pull the cast through the
11360       // GEP.
11361       SmallVector<Value*, 8> NewIndices;
11362       const Type *InTy =
11363         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11364       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11365         Instruction *NGEP =
11366            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11367                                      NewIndices.end());
11368         if (NGEP->getType() == GEP.getType()) return NGEP;
11369         if (cast<GEPOperator>(&GEP)->isInBounds())
11370           cast<GEPOperator>(NGEP)->setIsInBounds(true);
11371         InsertNewInstBefore(NGEP, GEP);
11372         NGEP->takeName(&GEP);
11373         return new BitCastInst(NGEP, GEP.getType());
11374       }
11375     }
11376   }    
11377     
11378   return 0;
11379 }
11380
11381 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11382   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11383   if (AI.isArrayAllocation()) {  // Check C != 1
11384     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11385       const Type *NewTy = 
11386         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11387       AllocationInst *New = 0;
11388
11389       // Create and insert the replacement instruction...
11390       if (isa<MallocInst>(AI))
11391         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11392       else {
11393         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11394         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11395       }
11396
11397       InsertNewInstBefore(New, AI);
11398
11399       // Scan to the end of the allocation instructions, to skip over a block of
11400       // allocas if possible...also skip interleaved debug info
11401       //
11402       BasicBlock::iterator It = New;
11403       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11404
11405       // Now that I is pointing to the first non-allocation-inst in the block,
11406       // insert our getelementptr instruction...
11407       //
11408       Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11409       Value *Idx[2];
11410       Idx[0] = NullIdx;
11411       Idx[1] = NullIdx;
11412       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11413                                            New->getName()+".sub", It);
11414       cast<GEPOperator>(V)->setIsInBounds(true);
11415
11416       // Now make everything use the getelementptr instead of the original
11417       // allocation.
11418       return ReplaceInstUsesWith(AI, V);
11419     } else if (isa<UndefValue>(AI.getArraySize())) {
11420       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11421     }
11422   }
11423
11424   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11425     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11426     // Note that we only do this for alloca's, because malloc should allocate
11427     // and return a unique pointer, even for a zero byte allocation.
11428     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11429       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11430
11431     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11432     if (AI.getAlignment() == 0)
11433       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11434   }
11435
11436   return 0;
11437 }
11438
11439 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11440   Value *Op = FI.getOperand(0);
11441
11442   // free undef -> unreachable.
11443   if (isa<UndefValue>(Op)) {
11444     // Insert a new store to null because we cannot modify the CFG here.
11445     new StoreInst(ConstantInt::getTrue(*Context),
11446            UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
11447     return EraseInstFromFunction(FI);
11448   }
11449   
11450   // If we have 'free null' delete the instruction.  This can happen in stl code
11451   // when lots of inlining happens.
11452   if (isa<ConstantPointerNull>(Op))
11453     return EraseInstFromFunction(FI);
11454   
11455   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11456   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11457     FI.setOperand(0, CI->getOperand(0));
11458     return &FI;
11459   }
11460   
11461   // Change free (gep X, 0,0,0,0) into free(X)
11462   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11463     if (GEPI->hasAllZeroIndices()) {
11464       AddToWorkList(GEPI);
11465       FI.setOperand(0, GEPI->getOperand(0));
11466       return &FI;
11467     }
11468   }
11469   
11470   // Change free(malloc) into nothing, if the malloc has a single use.
11471   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11472     if (MI->hasOneUse()) {
11473       EraseInstFromFunction(FI);
11474       return EraseInstFromFunction(*MI);
11475     }
11476
11477   return 0;
11478 }
11479
11480
11481 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11482 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11483                                         const TargetData *TD) {
11484   User *CI = cast<User>(LI.getOperand(0));
11485   Value *CastOp = CI->getOperand(0);
11486   LLVMContext *Context = IC.getContext();
11487
11488   if (TD) {
11489     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11490       // Instead of loading constant c string, use corresponding integer value
11491       // directly if string length is small enough.
11492       std::string Str;
11493       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11494         unsigned len = Str.length();
11495         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11496         unsigned numBits = Ty->getPrimitiveSizeInBits();
11497         // Replace LI with immediate integer store.
11498         if ((numBits >> 3) == len + 1) {
11499           APInt StrVal(numBits, 0);
11500           APInt SingleChar(numBits, 0);
11501           if (TD->isLittleEndian()) {
11502             for (signed i = len-1; i >= 0; i--) {
11503               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11504               StrVal = (StrVal << 8) | SingleChar;
11505             }
11506           } else {
11507             for (unsigned i = 0; i < len; i++) {
11508               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11509               StrVal = (StrVal << 8) | SingleChar;
11510             }
11511             // Append NULL at the end.
11512             SingleChar = 0;
11513             StrVal = (StrVal << 8) | SingleChar;
11514           }
11515           Value *NL = ConstantInt::get(*Context, StrVal);
11516           return IC.ReplaceInstUsesWith(LI, NL);
11517         }
11518       }
11519     }
11520   }
11521
11522   const PointerType *DestTy = cast<PointerType>(CI->getType());
11523   const Type *DestPTy = DestTy->getElementType();
11524   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11525
11526     // If the address spaces don't match, don't eliminate the cast.
11527     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11528       return 0;
11529
11530     const Type *SrcPTy = SrcTy->getElementType();
11531
11532     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11533          isa<VectorType>(DestPTy)) {
11534       // If the source is an array, the code below will not succeed.  Check to
11535       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11536       // constants.
11537       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11538         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11539           if (ASrcTy->getNumElements() != 0) {
11540             Value *Idxs[2];
11541             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
11542             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11543             SrcTy = cast<PointerType>(CastOp->getType());
11544             SrcPTy = SrcTy->getElementType();
11545           }
11546
11547       if (IC.getTargetData() &&
11548           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11549             isa<VectorType>(SrcPTy)) &&
11550           // Do not allow turning this into a load of an integer, which is then
11551           // casted to a pointer, this pessimizes pointer analysis a lot.
11552           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11553           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11554                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11555
11556         // Okay, we are casting from one integer or pointer type to another of
11557         // the same size.  Instead of casting the pointer before the load, cast
11558         // the result of the loaded value.
11559         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11560                                                              CI->getName(),
11561                                                          LI.isVolatile()),LI);
11562         // Now cast the result of the load.
11563         return new BitCastInst(NewLoad, LI.getType());
11564       }
11565     }
11566   }
11567   return 0;
11568 }
11569
11570 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11571   Value *Op = LI.getOperand(0);
11572
11573   // Attempt to improve the alignment.
11574   if (TD) {
11575     unsigned KnownAlign =
11576       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11577     if (KnownAlign >
11578         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11579                                   LI.getAlignment()))
11580       LI.setAlignment(KnownAlign);
11581   }
11582
11583   // load (cast X) --> cast (load X) iff safe
11584   if (isa<CastInst>(Op))
11585     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11586       return Res;
11587
11588   // None of the following transforms are legal for volatile loads.
11589   if (LI.isVolatile()) return 0;
11590   
11591   // Do really simple store-to-load forwarding and load CSE, to catch cases
11592   // where there are several consequtive memory accesses to the same location,
11593   // separated by a few arithmetic operations.
11594   BasicBlock::iterator BBI = &LI;
11595   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11596     return ReplaceInstUsesWith(LI, AvailableVal);
11597
11598   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11599     const Value *GEPI0 = GEPI->getOperand(0);
11600     // TODO: Consider a target hook for valid address spaces for this xform.
11601     if (isa<ConstantPointerNull>(GEPI0) &&
11602         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11603       // Insert a new store to null instruction before the load to indicate
11604       // that this code is not reachable.  We do this instead of inserting
11605       // an unreachable instruction directly because we cannot modify the
11606       // CFG.
11607       new StoreInst(UndefValue::get(LI.getType()),
11608                     Constant::getNullValue(Op->getType()), &LI);
11609       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11610     }
11611   } 
11612
11613   if (Constant *C = dyn_cast<Constant>(Op)) {
11614     // load null/undef -> undef
11615     // TODO: Consider a target hook for valid address spaces for this xform.
11616     if (isa<UndefValue>(C) || (C->isNullValue() && 
11617         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11618       // Insert a new store to null instruction before the load to indicate that
11619       // this code is not reachable.  We do this instead of inserting an
11620       // unreachable instruction directly because we cannot modify the CFG.
11621       new StoreInst(UndefValue::get(LI.getType()),
11622                     Constant::getNullValue(Op->getType()), &LI);
11623       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11624     }
11625
11626     // Instcombine load (constant global) into the value loaded.
11627     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11628       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11629         return ReplaceInstUsesWith(LI, GV->getInitializer());
11630
11631     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11632     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11633       if (CE->getOpcode() == Instruction::GetElementPtr) {
11634         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11635           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11636             if (Constant *V = 
11637                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11638                                                       *Context))
11639               return ReplaceInstUsesWith(LI, V);
11640         if (CE->getOperand(0)->isNullValue()) {
11641           // Insert a new store to null instruction before the load to indicate
11642           // that this code is not reachable.  We do this instead of inserting
11643           // an unreachable instruction directly because we cannot modify the
11644           // CFG.
11645           new StoreInst(UndefValue::get(LI.getType()),
11646                         Constant::getNullValue(Op->getType()), &LI);
11647           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11648         }
11649
11650       } else if (CE->isCast()) {
11651         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11652           return Res;
11653       }
11654     }
11655   }
11656     
11657   // If this load comes from anywhere in a constant global, and if the global
11658   // is all undef or zero, we know what it loads.
11659   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11660     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11661       if (GV->getInitializer()->isNullValue())
11662         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11663       else if (isa<UndefValue>(GV->getInitializer()))
11664         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11665     }
11666   }
11667
11668   if (Op->hasOneUse()) {
11669     // Change select and PHI nodes to select values instead of addresses: this
11670     // helps alias analysis out a lot, allows many others simplifications, and
11671     // exposes redundancy in the code.
11672     //
11673     // Note that we cannot do the transformation unless we know that the
11674     // introduced loads cannot trap!  Something like this is valid as long as
11675     // the condition is always false: load (select bool %C, int* null, int* %G),
11676     // but it would not be valid if we transformed it to load from null
11677     // unconditionally.
11678     //
11679     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11680       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11681       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11682           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11683         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11684                                      SI->getOperand(1)->getName()+".val"), LI);
11685         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11686                                      SI->getOperand(2)->getName()+".val"), LI);
11687         return SelectInst::Create(SI->getCondition(), V1, V2);
11688       }
11689
11690       // load (select (cond, null, P)) -> load P
11691       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11692         if (C->isNullValue()) {
11693           LI.setOperand(0, SI->getOperand(2));
11694           return &LI;
11695         }
11696
11697       // load (select (cond, P, null)) -> load P
11698       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11699         if (C->isNullValue()) {
11700           LI.setOperand(0, SI->getOperand(1));
11701           return &LI;
11702         }
11703     }
11704   }
11705   return 0;
11706 }
11707
11708 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11709 /// when possible.  This makes it generally easy to do alias analysis and/or
11710 /// SROA/mem2reg of the memory object.
11711 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11712   User *CI = cast<User>(SI.getOperand(1));
11713   Value *CastOp = CI->getOperand(0);
11714
11715   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11716   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11717   if (SrcTy == 0) return 0;
11718   
11719   const Type *SrcPTy = SrcTy->getElementType();
11720
11721   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11722     return 0;
11723   
11724   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11725   /// to its first element.  This allows us to handle things like:
11726   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11727   /// on 32-bit hosts.
11728   SmallVector<Value*, 4> NewGEPIndices;
11729   
11730   // If the source is an array, the code below will not succeed.  Check to
11731   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11732   // constants.
11733   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11734     // Index through pointer.
11735     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11736     NewGEPIndices.push_back(Zero);
11737     
11738     while (1) {
11739       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11740         if (!STy->getNumElements()) /* Struct can be empty {} */
11741           break;
11742         NewGEPIndices.push_back(Zero);
11743         SrcPTy = STy->getElementType(0);
11744       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11745         NewGEPIndices.push_back(Zero);
11746         SrcPTy = ATy->getElementType();
11747       } else {
11748         break;
11749       }
11750     }
11751     
11752     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11753   }
11754
11755   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11756     return 0;
11757   
11758   // If the pointers point into different address spaces or if they point to
11759   // values with different sizes, we can't do the transformation.
11760   if (!IC.getTargetData() ||
11761       SrcTy->getAddressSpace() != 
11762         cast<PointerType>(CI->getType())->getAddressSpace() ||
11763       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11764       IC.getTargetData()->getTypeSizeInBits(DestPTy))
11765     return 0;
11766
11767   // Okay, we are casting from one integer or pointer type to another of
11768   // the same size.  Instead of casting the pointer before 
11769   // the store, cast the value to be stored.
11770   Value *NewCast;
11771   Value *SIOp0 = SI.getOperand(0);
11772   Instruction::CastOps opcode = Instruction::BitCast;
11773   const Type* CastSrcTy = SIOp0->getType();
11774   const Type* CastDstTy = SrcPTy;
11775   if (isa<PointerType>(CastDstTy)) {
11776     if (CastSrcTy->isInteger())
11777       opcode = Instruction::IntToPtr;
11778   } else if (isa<IntegerType>(CastDstTy)) {
11779     if (isa<PointerType>(SIOp0->getType()))
11780       opcode = Instruction::PtrToInt;
11781   }
11782   
11783   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11784   // emit a GEP to index into its first field.
11785   if (!NewGEPIndices.empty()) {
11786     if (Constant *C = dyn_cast<Constant>(CastOp))
11787       CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0], 
11788                                               NewGEPIndices.size());
11789     else
11790       CastOp = IC.InsertNewInstBefore(
11791               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11792                                         NewGEPIndices.end()), SI);
11793     cast<GEPOperator>(CastOp)->setIsInBounds(true);
11794   }
11795   
11796   if (Constant *C = dyn_cast<Constant>(SIOp0))
11797     NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11798   else
11799     NewCast = IC.InsertNewInstBefore(
11800       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11801       SI);
11802   return new StoreInst(NewCast, CastOp);
11803 }
11804
11805 /// equivalentAddressValues - Test if A and B will obviously have the same
11806 /// value. This includes recognizing that %t0 and %t1 will have the same
11807 /// value in code like this:
11808 ///   %t0 = getelementptr \@a, 0, 3
11809 ///   store i32 0, i32* %t0
11810 ///   %t1 = getelementptr \@a, 0, 3
11811 ///   %t2 = load i32* %t1
11812 ///
11813 static bool equivalentAddressValues(Value *A, Value *B) {
11814   // Test if the values are trivially equivalent.
11815   if (A == B) return true;
11816   
11817   // Test if the values come form identical arithmetic instructions.
11818   if (isa<BinaryOperator>(A) ||
11819       isa<CastInst>(A) ||
11820       isa<PHINode>(A) ||
11821       isa<GetElementPtrInst>(A))
11822     if (Instruction *BI = dyn_cast<Instruction>(B))
11823       if (cast<Instruction>(A)->isIdenticalTo(BI))
11824         return true;
11825   
11826   // Otherwise they may not be equivalent.
11827   return false;
11828 }
11829
11830 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11831 // return the llvm.dbg.declare.
11832 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11833   if (!V->hasNUses(2))
11834     return 0;
11835   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11836        UI != E; ++UI) {
11837     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11838       return DI;
11839     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11840       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11841         return DI;
11842       }
11843   }
11844   return 0;
11845 }
11846
11847 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11848   Value *Val = SI.getOperand(0);
11849   Value *Ptr = SI.getOperand(1);
11850
11851   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11852     EraseInstFromFunction(SI);
11853     ++NumCombined;
11854     return 0;
11855   }
11856   
11857   // If the RHS is an alloca with a single use, zapify the store, making the
11858   // alloca dead.
11859   // If the RHS is an alloca with a two uses, the other one being a 
11860   // llvm.dbg.declare, zapify the store and the declare, making the
11861   // alloca dead.  We must do this to prevent declare's from affecting
11862   // codegen.
11863   if (!SI.isVolatile()) {
11864     if (Ptr->hasOneUse()) {
11865       if (isa<AllocaInst>(Ptr)) {
11866         EraseInstFromFunction(SI);
11867         ++NumCombined;
11868         return 0;
11869       }
11870       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11871         if (isa<AllocaInst>(GEP->getOperand(0))) {
11872           if (GEP->getOperand(0)->hasOneUse()) {
11873             EraseInstFromFunction(SI);
11874             ++NumCombined;
11875             return 0;
11876           }
11877           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11878             EraseInstFromFunction(*DI);
11879             EraseInstFromFunction(SI);
11880             ++NumCombined;
11881             return 0;
11882           }
11883         }
11884       }
11885     }
11886     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11887       EraseInstFromFunction(*DI);
11888       EraseInstFromFunction(SI);
11889       ++NumCombined;
11890       return 0;
11891     }
11892   }
11893
11894   // Attempt to improve the alignment.
11895   if (TD) {
11896     unsigned KnownAlign =
11897       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11898     if (KnownAlign >
11899         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11900                                   SI.getAlignment()))
11901       SI.setAlignment(KnownAlign);
11902   }
11903
11904   // Do really simple DSE, to catch cases where there are several consecutive
11905   // stores to the same location, separated by a few arithmetic operations. This
11906   // situation often occurs with bitfield accesses.
11907   BasicBlock::iterator BBI = &SI;
11908   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11909        --ScanInsts) {
11910     --BBI;
11911     // Don't count debug info directives, lest they affect codegen,
11912     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11913     // It is necessary for correctness to skip those that feed into a
11914     // llvm.dbg.declare, as these are not present when debugging is off.
11915     if (isa<DbgInfoIntrinsic>(BBI) ||
11916         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11917       ScanInsts++;
11918       continue;
11919     }    
11920     
11921     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11922       // Prev store isn't volatile, and stores to the same location?
11923       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11924                                                           SI.getOperand(1))) {
11925         ++NumDeadStore;
11926         ++BBI;
11927         EraseInstFromFunction(*PrevSI);
11928         continue;
11929       }
11930       break;
11931     }
11932     
11933     // If this is a load, we have to stop.  However, if the loaded value is from
11934     // the pointer we're loading and is producing the pointer we're storing,
11935     // then *this* store is dead (X = load P; store X -> P).
11936     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11937       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11938           !SI.isVolatile()) {
11939         EraseInstFromFunction(SI);
11940         ++NumCombined;
11941         return 0;
11942       }
11943       // Otherwise, this is a load from some other location.  Stores before it
11944       // may not be dead.
11945       break;
11946     }
11947     
11948     // Don't skip over loads or things that can modify memory.
11949     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11950       break;
11951   }
11952   
11953   
11954   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11955
11956   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11957   if (isa<ConstantPointerNull>(Ptr) &&
11958       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11959     if (!isa<UndefValue>(Val)) {
11960       SI.setOperand(0, UndefValue::get(Val->getType()));
11961       if (Instruction *U = dyn_cast<Instruction>(Val))
11962         AddToWorkList(U);  // Dropped a use.
11963       ++NumCombined;
11964     }
11965     return 0;  // Do not modify these!
11966   }
11967
11968   // store undef, Ptr -> noop
11969   if (isa<UndefValue>(Val)) {
11970     EraseInstFromFunction(SI);
11971     ++NumCombined;
11972     return 0;
11973   }
11974
11975   // If the pointer destination is a cast, see if we can fold the cast into the
11976   // source instead.
11977   if (isa<CastInst>(Ptr))
11978     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11979       return Res;
11980   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11981     if (CE->isCast())
11982       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11983         return Res;
11984
11985   
11986   // If this store is the last instruction in the basic block (possibly
11987   // excepting debug info instructions and the pointer bitcasts that feed
11988   // into them), and if the block ends with an unconditional branch, try
11989   // to move it to the successor block.
11990   BBI = &SI; 
11991   do {
11992     ++BBI;
11993   } while (isa<DbgInfoIntrinsic>(BBI) ||
11994            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11995   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11996     if (BI->isUnconditional())
11997       if (SimplifyStoreAtEndOfBlock(SI))
11998         return 0;  // xform done!
11999   
12000   return 0;
12001 }
12002
12003 /// SimplifyStoreAtEndOfBlock - Turn things like:
12004 ///   if () { *P = v1; } else { *P = v2 }
12005 /// into a phi node with a store in the successor.
12006 ///
12007 /// Simplify things like:
12008 ///   *P = v1; if () { *P = v2; }
12009 /// into a phi node with a store in the successor.
12010 ///
12011 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12012   BasicBlock *StoreBB = SI.getParent();
12013   
12014   // Check to see if the successor block has exactly two incoming edges.  If
12015   // so, see if the other predecessor contains a store to the same location.
12016   // if so, insert a PHI node (if needed) and move the stores down.
12017   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
12018   
12019   // Determine whether Dest has exactly two predecessors and, if so, compute
12020   // the other predecessor.
12021   pred_iterator PI = pred_begin(DestBB);
12022   BasicBlock *OtherBB = 0;
12023   if (*PI != StoreBB)
12024     OtherBB = *PI;
12025   ++PI;
12026   if (PI == pred_end(DestBB))
12027     return false;
12028   
12029   if (*PI != StoreBB) {
12030     if (OtherBB)
12031       return false;
12032     OtherBB = *PI;
12033   }
12034   if (++PI != pred_end(DestBB))
12035     return false;
12036
12037   // Bail out if all the relevant blocks aren't distinct (this can happen,
12038   // for example, if SI is in an infinite loop)
12039   if (StoreBB == DestBB || OtherBB == DestBB)
12040     return false;
12041
12042   // Verify that the other block ends in a branch and is not otherwise empty.
12043   BasicBlock::iterator BBI = OtherBB->getTerminator();
12044   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12045   if (!OtherBr || BBI == OtherBB->begin())
12046     return false;
12047   
12048   // If the other block ends in an unconditional branch, check for the 'if then
12049   // else' case.  there is an instruction before the branch.
12050   StoreInst *OtherStore = 0;
12051   if (OtherBr->isUnconditional()) {
12052     --BBI;
12053     // Skip over debugging info.
12054     while (isa<DbgInfoIntrinsic>(BBI) ||
12055            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12056       if (BBI==OtherBB->begin())
12057         return false;
12058       --BBI;
12059     }
12060     // If this isn't a store, or isn't a store to the same location, bail out.
12061     OtherStore = dyn_cast<StoreInst>(BBI);
12062     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12063       return false;
12064   } else {
12065     // Otherwise, the other block ended with a conditional branch. If one of the
12066     // destinations is StoreBB, then we have the if/then case.
12067     if (OtherBr->getSuccessor(0) != StoreBB && 
12068         OtherBr->getSuccessor(1) != StoreBB)
12069       return false;
12070     
12071     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12072     // if/then triangle.  See if there is a store to the same ptr as SI that
12073     // lives in OtherBB.
12074     for (;; --BBI) {
12075       // Check to see if we find the matching store.
12076       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12077         if (OtherStore->getOperand(1) != SI.getOperand(1))
12078           return false;
12079         break;
12080       }
12081       // If we find something that may be using or overwriting the stored
12082       // value, or if we run out of instructions, we can't do the xform.
12083       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12084           BBI == OtherBB->begin())
12085         return false;
12086     }
12087     
12088     // In order to eliminate the store in OtherBr, we have to
12089     // make sure nothing reads or overwrites the stored value in
12090     // StoreBB.
12091     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12092       // FIXME: This should really be AA driven.
12093       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12094         return false;
12095     }
12096   }
12097   
12098   // Insert a PHI node now if we need it.
12099   Value *MergedVal = OtherStore->getOperand(0);
12100   if (MergedVal != SI.getOperand(0)) {
12101     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12102     PN->reserveOperandSpace(2);
12103     PN->addIncoming(SI.getOperand(0), SI.getParent());
12104     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12105     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12106   }
12107   
12108   // Advance to a place where it is safe to insert the new store and
12109   // insert it.
12110   BBI = DestBB->getFirstNonPHI();
12111   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12112                                     OtherStore->isVolatile()), *BBI);
12113   
12114   // Nuke the old stores.
12115   EraseInstFromFunction(SI);
12116   EraseInstFromFunction(*OtherStore);
12117   ++NumCombined;
12118   return true;
12119 }
12120
12121
12122 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12123   // Change br (not X), label True, label False to: br X, label False, True
12124   Value *X = 0;
12125   BasicBlock *TrueDest;
12126   BasicBlock *FalseDest;
12127   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
12128       !isa<Constant>(X)) {
12129     // Swap Destinations and condition...
12130     BI.setCondition(X);
12131     BI.setSuccessor(0, FalseDest);
12132     BI.setSuccessor(1, TrueDest);
12133     return &BI;
12134   }
12135
12136   // Cannonicalize fcmp_one -> fcmp_oeq
12137   FCmpInst::Predicate FPred; Value *Y;
12138   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12139                              TrueDest, FalseDest)))
12140     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12141          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12142       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12143       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12144       Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12145       NewSCC->takeName(I);
12146       // Swap Destinations and condition...
12147       BI.setCondition(NewSCC);
12148       BI.setSuccessor(0, FalseDest);
12149       BI.setSuccessor(1, TrueDest);
12150       RemoveFromWorkList(I);
12151       I->eraseFromParent();
12152       AddToWorkList(NewSCC);
12153       return &BI;
12154     }
12155
12156   // Cannonicalize icmp_ne -> icmp_eq
12157   ICmpInst::Predicate IPred;
12158   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12159                       TrueDest, FalseDest)))
12160     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12161          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12162          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12163       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12164       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12165       Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12166       NewSCC->takeName(I);
12167       // Swap Destinations and condition...
12168       BI.setCondition(NewSCC);
12169       BI.setSuccessor(0, FalseDest);
12170       BI.setSuccessor(1, TrueDest);
12171       RemoveFromWorkList(I);
12172       I->eraseFromParent();;
12173       AddToWorkList(NewSCC);
12174       return &BI;
12175     }
12176
12177   return 0;
12178 }
12179
12180 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12181   Value *Cond = SI.getCondition();
12182   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12183     if (I->getOpcode() == Instruction::Add)
12184       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12185         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12186         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12187           SI.setOperand(i,
12188                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12189                                                 AddRHS));
12190         SI.setOperand(0, I->getOperand(0));
12191         AddToWorkList(I);
12192         return &SI;
12193       }
12194   }
12195   return 0;
12196 }
12197
12198 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12199   Value *Agg = EV.getAggregateOperand();
12200
12201   if (!EV.hasIndices())
12202     return ReplaceInstUsesWith(EV, Agg);
12203
12204   if (Constant *C = dyn_cast<Constant>(Agg)) {
12205     if (isa<UndefValue>(C))
12206       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12207       
12208     if (isa<ConstantAggregateZero>(C))
12209       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12210
12211     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12212       // Extract the element indexed by the first index out of the constant
12213       Value *V = C->getOperand(*EV.idx_begin());
12214       if (EV.getNumIndices() > 1)
12215         // Extract the remaining indices out of the constant indexed by the
12216         // first index
12217         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12218       else
12219         return ReplaceInstUsesWith(EV, V);
12220     }
12221     return 0; // Can't handle other constants
12222   } 
12223   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12224     // We're extracting from an insertvalue instruction, compare the indices
12225     const unsigned *exti, *exte, *insi, *inse;
12226     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12227          exte = EV.idx_end(), inse = IV->idx_end();
12228          exti != exte && insi != inse;
12229          ++exti, ++insi) {
12230       if (*insi != *exti)
12231         // The insert and extract both reference distinctly different elements.
12232         // This means the extract is not influenced by the insert, and we can
12233         // replace the aggregate operand of the extract with the aggregate
12234         // operand of the insert. i.e., replace
12235         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12236         // %E = extractvalue { i32, { i32 } } %I, 0
12237         // with
12238         // %E = extractvalue { i32, { i32 } } %A, 0
12239         return ExtractValueInst::Create(IV->getAggregateOperand(),
12240                                         EV.idx_begin(), EV.idx_end());
12241     }
12242     if (exti == exte && insi == inse)
12243       // Both iterators are at the end: Index lists are identical. Replace
12244       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12245       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12246       // with "i32 42"
12247       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12248     if (exti == exte) {
12249       // The extract list is a prefix of the insert list. i.e. replace
12250       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12251       // %E = extractvalue { i32, { i32 } } %I, 1
12252       // with
12253       // %X = extractvalue { i32, { i32 } } %A, 1
12254       // %E = insertvalue { i32 } %X, i32 42, 0
12255       // by switching the order of the insert and extract (though the
12256       // insertvalue should be left in, since it may have other uses).
12257       Value *NewEV = InsertNewInstBefore(
12258         ExtractValueInst::Create(IV->getAggregateOperand(),
12259                                  EV.idx_begin(), EV.idx_end()),
12260         EV);
12261       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12262                                      insi, inse);
12263     }
12264     if (insi == inse)
12265       // The insert list is a prefix of the extract list
12266       // We can simply remove the common indices from the extract and make it
12267       // operate on the inserted value instead of the insertvalue result.
12268       // i.e., replace
12269       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12270       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12271       // with
12272       // %E extractvalue { i32 } { i32 42 }, 0
12273       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12274                                       exti, exte);
12275   }
12276   // Can't simplify extracts from other values. Note that nested extracts are
12277   // already simplified implicitely by the above (extract ( extract (insert) )
12278   // will be translated into extract ( insert ( extract ) ) first and then just
12279   // the value inserted, if appropriate).
12280   return 0;
12281 }
12282
12283 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12284 /// is to leave as a vector operation.
12285 static bool CheapToScalarize(Value *V, bool isConstant) {
12286   if (isa<ConstantAggregateZero>(V)) 
12287     return true;
12288   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12289     if (isConstant) return true;
12290     // If all elts are the same, we can extract.
12291     Constant *Op0 = C->getOperand(0);
12292     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12293       if (C->getOperand(i) != Op0)
12294         return false;
12295     return true;
12296   }
12297   Instruction *I = dyn_cast<Instruction>(V);
12298   if (!I) return false;
12299   
12300   // Insert element gets simplified to the inserted element or is deleted if
12301   // this is constant idx extract element and its a constant idx insertelt.
12302   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12303       isa<ConstantInt>(I->getOperand(2)))
12304     return true;
12305   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12306     return true;
12307   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12308     if (BO->hasOneUse() &&
12309         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12310          CheapToScalarize(BO->getOperand(1), isConstant)))
12311       return true;
12312   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12313     if (CI->hasOneUse() &&
12314         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12315          CheapToScalarize(CI->getOperand(1), isConstant)))
12316       return true;
12317   
12318   return false;
12319 }
12320
12321 /// Read and decode a shufflevector mask.
12322 ///
12323 /// It turns undef elements into values that are larger than the number of
12324 /// elements in the input.
12325 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12326   unsigned NElts = SVI->getType()->getNumElements();
12327   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12328     return std::vector<unsigned>(NElts, 0);
12329   if (isa<UndefValue>(SVI->getOperand(2)))
12330     return std::vector<unsigned>(NElts, 2*NElts);
12331
12332   std::vector<unsigned> Result;
12333   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12334   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12335     if (isa<UndefValue>(*i))
12336       Result.push_back(NElts*2);  // undef -> 8
12337     else
12338       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12339   return Result;
12340 }
12341
12342 /// FindScalarElement - Given a vector and an element number, see if the scalar
12343 /// value is already around as a register, for example if it were inserted then
12344 /// extracted from the vector.
12345 static Value *FindScalarElement(Value *V, unsigned EltNo,
12346                                 LLVMContext *Context) {
12347   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12348   const VectorType *PTy = cast<VectorType>(V->getType());
12349   unsigned Width = PTy->getNumElements();
12350   if (EltNo >= Width)  // Out of range access.
12351     return UndefValue::get(PTy->getElementType());
12352   
12353   if (isa<UndefValue>(V))
12354     return UndefValue::get(PTy->getElementType());
12355   else if (isa<ConstantAggregateZero>(V))
12356     return Constant::getNullValue(PTy->getElementType());
12357   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12358     return CP->getOperand(EltNo);
12359   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12360     // If this is an insert to a variable element, we don't know what it is.
12361     if (!isa<ConstantInt>(III->getOperand(2))) 
12362       return 0;
12363     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12364     
12365     // If this is an insert to the element we are looking for, return the
12366     // inserted value.
12367     if (EltNo == IIElt) 
12368       return III->getOperand(1);
12369     
12370     // Otherwise, the insertelement doesn't modify the value, recurse on its
12371     // vector input.
12372     return FindScalarElement(III->getOperand(0), EltNo, Context);
12373   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12374     unsigned LHSWidth =
12375       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12376     unsigned InEl = getShuffleMask(SVI)[EltNo];
12377     if (InEl < LHSWidth)
12378       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12379     else if (InEl < LHSWidth*2)
12380       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12381     else
12382       return UndefValue::get(PTy->getElementType());
12383   }
12384   
12385   // Otherwise, we don't know.
12386   return 0;
12387 }
12388
12389 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12390   // If vector val is undef, replace extract with scalar undef.
12391   if (isa<UndefValue>(EI.getOperand(0)))
12392     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12393
12394   // If vector val is constant 0, replace extract with scalar 0.
12395   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12396     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12397   
12398   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12399     // If vector val is constant with all elements the same, replace EI with
12400     // that element. When the elements are not identical, we cannot replace yet
12401     // (we do that below, but only when the index is constant).
12402     Constant *op0 = C->getOperand(0);
12403     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12404       if (C->getOperand(i) != op0) {
12405         op0 = 0; 
12406         break;
12407       }
12408     if (op0)
12409       return ReplaceInstUsesWith(EI, op0);
12410   }
12411   
12412   // If extracting a specified index from the vector, see if we can recursively
12413   // find a previously computed scalar that was inserted into the vector.
12414   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12415     unsigned IndexVal = IdxC->getZExtValue();
12416     unsigned VectorWidth = 
12417       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12418       
12419     // If this is extracting an invalid index, turn this into undef, to avoid
12420     // crashing the code below.
12421     if (IndexVal >= VectorWidth)
12422       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12423     
12424     // This instruction only demands the single element from the input vector.
12425     // If the input vector has a single use, simplify it based on this use
12426     // property.
12427     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12428       APInt UndefElts(VectorWidth, 0);
12429       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12430       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12431                                                 DemandedMask, UndefElts)) {
12432         EI.setOperand(0, V);
12433         return &EI;
12434       }
12435     }
12436     
12437     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12438       return ReplaceInstUsesWith(EI, Elt);
12439     
12440     // If the this extractelement is directly using a bitcast from a vector of
12441     // the same number of elements, see if we can find the source element from
12442     // it.  In this case, we will end up needing to bitcast the scalars.
12443     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12444       if (const VectorType *VT = 
12445               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12446         if (VT->getNumElements() == VectorWidth)
12447           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12448                                              IndexVal, Context))
12449             return new BitCastInst(Elt, EI.getType());
12450     }
12451   }
12452   
12453   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12454     if (I->hasOneUse()) {
12455       // Push extractelement into predecessor operation if legal and
12456       // profitable to do so
12457       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12458         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12459         if (CheapToScalarize(BO, isConstantElt)) {
12460           ExtractElementInst *newEI0 = 
12461             ExtractElementInst::Create(BO->getOperand(0), EI.getOperand(1),
12462                                    EI.getName()+".lhs");
12463           ExtractElementInst *newEI1 =
12464             ExtractElementInst::Create(BO->getOperand(1), EI.getOperand(1),
12465                                    EI.getName()+".rhs");
12466           InsertNewInstBefore(newEI0, EI);
12467           InsertNewInstBefore(newEI1, EI);
12468           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12469         }
12470       } else if (isa<LoadInst>(I)) {
12471         unsigned AS = 
12472           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12473         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12474                                   PointerType::get(EI.getType(), AS),*I);
12475         GetElementPtrInst *GEP =
12476           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12477         cast<GEPOperator>(GEP)->setIsInBounds(true);
12478         InsertNewInstBefore(GEP, *I);
12479         LoadInst* Load = new LoadInst(GEP, "tmp");
12480         InsertNewInstBefore(Load, *I);
12481         return ReplaceInstUsesWith(EI, Load);
12482       }
12483     }
12484     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12485       // Extracting the inserted element?
12486       if (IE->getOperand(2) == EI.getOperand(1))
12487         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12488       // If the inserted and extracted elements are constants, they must not
12489       // be the same value, extract from the pre-inserted value instead.
12490       if (isa<Constant>(IE->getOperand(2)) &&
12491           isa<Constant>(EI.getOperand(1))) {
12492         AddUsesToWorkList(EI);
12493         EI.setOperand(0, IE->getOperand(0));
12494         return &EI;
12495       }
12496     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12497       // If this is extracting an element from a shufflevector, figure out where
12498       // it came from and extract from the appropriate input element instead.
12499       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12500         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12501         Value *Src;
12502         unsigned LHSWidth =
12503           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12504
12505         if (SrcIdx < LHSWidth)
12506           Src = SVI->getOperand(0);
12507         else if (SrcIdx < LHSWidth*2) {
12508           SrcIdx -= LHSWidth;
12509           Src = SVI->getOperand(1);
12510         } else {
12511           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12512         }
12513         return ExtractElementInst::Create(Src,
12514                          ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx, false));
12515       }
12516     }
12517     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12518   }
12519   return 0;
12520 }
12521
12522 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12523 /// elements from either LHS or RHS, return the shuffle mask and true. 
12524 /// Otherwise, return false.
12525 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12526                                          std::vector<Constant*> &Mask,
12527                                          LLVMContext *Context) {
12528   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12529          "Invalid CollectSingleShuffleElements");
12530   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12531
12532   if (isa<UndefValue>(V)) {
12533     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12534     return true;
12535   } else if (V == LHS) {
12536     for (unsigned i = 0; i != NumElts; ++i)
12537       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12538     return true;
12539   } else if (V == RHS) {
12540     for (unsigned i = 0; i != NumElts; ++i)
12541       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12542     return true;
12543   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12544     // If this is an insert of an extract from some other vector, include it.
12545     Value *VecOp    = IEI->getOperand(0);
12546     Value *ScalarOp = IEI->getOperand(1);
12547     Value *IdxOp    = IEI->getOperand(2);
12548     
12549     if (!isa<ConstantInt>(IdxOp))
12550       return false;
12551     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12552     
12553     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12554       // Okay, we can handle this if the vector we are insertinting into is
12555       // transitively ok.
12556       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12557         // If so, update the mask to reflect the inserted undef.
12558         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12559         return true;
12560       }      
12561     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12562       if (isa<ConstantInt>(EI->getOperand(1)) &&
12563           EI->getOperand(0)->getType() == V->getType()) {
12564         unsigned ExtractedIdx =
12565           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12566         
12567         // This must be extracting from either LHS or RHS.
12568         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12569           // Okay, we can handle this if the vector we are insertinting into is
12570           // transitively ok.
12571           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12572             // If so, update the mask to reflect the inserted value.
12573             if (EI->getOperand(0) == LHS) {
12574               Mask[InsertedIdx % NumElts] = 
12575                  ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12576             } else {
12577               assert(EI->getOperand(0) == RHS);
12578               Mask[InsertedIdx % NumElts] = 
12579                 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12580               
12581             }
12582             return true;
12583           }
12584         }
12585       }
12586     }
12587   }
12588   // TODO: Handle shufflevector here!
12589   
12590   return false;
12591 }
12592
12593 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12594 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12595 /// that computes V and the LHS value of the shuffle.
12596 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12597                                      Value *&RHS, LLVMContext *Context) {
12598   assert(isa<VectorType>(V->getType()) && 
12599          (RHS == 0 || V->getType() == RHS->getType()) &&
12600          "Invalid shuffle!");
12601   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12602
12603   if (isa<UndefValue>(V)) {
12604     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12605     return V;
12606   } else if (isa<ConstantAggregateZero>(V)) {
12607     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12608     return V;
12609   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12610     // If this is an insert of an extract from some other vector, include it.
12611     Value *VecOp    = IEI->getOperand(0);
12612     Value *ScalarOp = IEI->getOperand(1);
12613     Value *IdxOp    = IEI->getOperand(2);
12614     
12615     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12616       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12617           EI->getOperand(0)->getType() == V->getType()) {
12618         unsigned ExtractedIdx =
12619           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12620         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12621         
12622         // Either the extracted from or inserted into vector must be RHSVec,
12623         // otherwise we'd end up with a shuffle of three inputs.
12624         if (EI->getOperand(0) == RHS || RHS == 0) {
12625           RHS = EI->getOperand(0);
12626           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12627           Mask[InsertedIdx % NumElts] = 
12628             ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12629           return V;
12630         }
12631         
12632         if (VecOp == RHS) {
12633           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12634                                             RHS, Context);
12635           // Everything but the extracted element is replaced with the RHS.
12636           for (unsigned i = 0; i != NumElts; ++i) {
12637             if (i != InsertedIdx)
12638               Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12639           }
12640           return V;
12641         }
12642         
12643         // If this insertelement is a chain that comes from exactly these two
12644         // vectors, return the vector and the effective shuffle.
12645         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12646                                          Context))
12647           return EI->getOperand(0);
12648         
12649       }
12650     }
12651   }
12652   // TODO: Handle shufflevector here!
12653   
12654   // Otherwise, can't do anything fancy.  Return an identity vector.
12655   for (unsigned i = 0; i != NumElts; ++i)
12656     Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12657   return V;
12658 }
12659
12660 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12661   Value *VecOp    = IE.getOperand(0);
12662   Value *ScalarOp = IE.getOperand(1);
12663   Value *IdxOp    = IE.getOperand(2);
12664   
12665   // Inserting an undef or into an undefined place, remove this.
12666   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12667     ReplaceInstUsesWith(IE, VecOp);
12668   
12669   // If the inserted element was extracted from some other vector, and if the 
12670   // indexes are constant, try to turn this into a shufflevector operation.
12671   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12672     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12673         EI->getOperand(0)->getType() == IE.getType()) {
12674       unsigned NumVectorElts = IE.getType()->getNumElements();
12675       unsigned ExtractedIdx =
12676         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12677       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12678       
12679       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12680         return ReplaceInstUsesWith(IE, VecOp);
12681       
12682       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12683         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12684       
12685       // If we are extracting a value from a vector, then inserting it right
12686       // back into the same place, just use the input vector.
12687       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12688         return ReplaceInstUsesWith(IE, VecOp);      
12689       
12690       // We could theoretically do this for ANY input.  However, doing so could
12691       // turn chains of insertelement instructions into a chain of shufflevector
12692       // instructions, and right now we do not merge shufflevectors.  As such,
12693       // only do this in a situation where it is clear that there is benefit.
12694       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12695         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12696         // the values of VecOp, except then one read from EIOp0.
12697         // Build a new shuffle mask.
12698         std::vector<Constant*> Mask;
12699         if (isa<UndefValue>(VecOp))
12700           Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
12701         else {
12702           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12703           Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
12704                                                        NumVectorElts));
12705         } 
12706         Mask[InsertedIdx] = 
12707                            ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12708         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12709                                      ConstantVector::get(Mask));
12710       }
12711       
12712       // If this insertelement isn't used by some other insertelement, turn it
12713       // (and any insertelements it points to), into one big shuffle.
12714       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12715         std::vector<Constant*> Mask;
12716         Value *RHS = 0;
12717         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12718         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12719         // We now have a shuffle of LHS, RHS, Mask.
12720         return new ShuffleVectorInst(LHS, RHS,
12721                                      ConstantVector::get(Mask));
12722       }
12723     }
12724   }
12725
12726   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12727   APInt UndefElts(VWidth, 0);
12728   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12729   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12730     return &IE;
12731
12732   return 0;
12733 }
12734
12735
12736 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12737   Value *LHS = SVI.getOperand(0);
12738   Value *RHS = SVI.getOperand(1);
12739   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12740
12741   bool MadeChange = false;
12742
12743   // Undefined shuffle mask -> undefined value.
12744   if (isa<UndefValue>(SVI.getOperand(2)))
12745     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12746
12747   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12748
12749   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12750     return 0;
12751
12752   APInt UndefElts(VWidth, 0);
12753   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12754   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12755     LHS = SVI.getOperand(0);
12756     RHS = SVI.getOperand(1);
12757     MadeChange = true;
12758   }
12759   
12760   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12761   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12762   if (LHS == RHS || isa<UndefValue>(LHS)) {
12763     if (isa<UndefValue>(LHS) && LHS == RHS) {
12764       // shuffle(undef,undef,mask) -> undef.
12765       return ReplaceInstUsesWith(SVI, LHS);
12766     }
12767     
12768     // Remap any references to RHS to use LHS.
12769     std::vector<Constant*> Elts;
12770     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12771       if (Mask[i] >= 2*e)
12772         Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12773       else {
12774         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12775             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12776           Mask[i] = 2*e;     // Turn into undef.
12777           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12778         } else {
12779           Mask[i] = Mask[i] % e;  // Force to LHS.
12780           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12781         }
12782       }
12783     }
12784     SVI.setOperand(0, SVI.getOperand(1));
12785     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12786     SVI.setOperand(2, ConstantVector::get(Elts));
12787     LHS = SVI.getOperand(0);
12788     RHS = SVI.getOperand(1);
12789     MadeChange = true;
12790   }
12791   
12792   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12793   bool isLHSID = true, isRHSID = true;
12794     
12795   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12796     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12797     // Is this an identity shuffle of the LHS value?
12798     isLHSID &= (Mask[i] == i);
12799       
12800     // Is this an identity shuffle of the RHS value?
12801     isRHSID &= (Mask[i]-e == i);
12802   }
12803
12804   // Eliminate identity shuffles.
12805   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12806   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12807   
12808   // If the LHS is a shufflevector itself, see if we can combine it with this
12809   // one without producing an unusual shuffle.  Here we are really conservative:
12810   // we are absolutely afraid of producing a shuffle mask not in the input
12811   // program, because the code gen may not be smart enough to turn a merged
12812   // shuffle into two specific shuffles: it may produce worse code.  As such,
12813   // we only merge two shuffles if the result is one of the two input shuffle
12814   // masks.  In this case, merging the shuffles just removes one instruction,
12815   // which we know is safe.  This is good for things like turning:
12816   // (splat(splat)) -> splat.
12817   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12818     if (isa<UndefValue>(RHS)) {
12819       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12820
12821       std::vector<unsigned> NewMask;
12822       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12823         if (Mask[i] >= 2*e)
12824           NewMask.push_back(2*e);
12825         else
12826           NewMask.push_back(LHSMask[Mask[i]]);
12827       
12828       // If the result mask is equal to the src shuffle or this shuffle mask, do
12829       // the replacement.
12830       if (NewMask == LHSMask || NewMask == Mask) {
12831         unsigned LHSInNElts =
12832           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12833         std::vector<Constant*> Elts;
12834         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12835           if (NewMask[i] >= LHSInNElts*2) {
12836             Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12837           } else {
12838             Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12839           }
12840         }
12841         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12842                                      LHSSVI->getOperand(1),
12843                                      ConstantVector::get(Elts));
12844       }
12845     }
12846   }
12847
12848   return MadeChange ? &SVI : 0;
12849 }
12850
12851
12852
12853
12854 /// TryToSinkInstruction - Try to move the specified instruction from its
12855 /// current block into the beginning of DestBlock, which can only happen if it's
12856 /// safe to move the instruction past all of the instructions between it and the
12857 /// end of its block.
12858 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12859   assert(I->hasOneUse() && "Invariants didn't hold!");
12860
12861   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12862   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12863     return false;
12864
12865   // Do not sink alloca instructions out of the entry block.
12866   if (isa<AllocaInst>(I) && I->getParent() ==
12867         &DestBlock->getParent()->getEntryBlock())
12868     return false;
12869
12870   // We can only sink load instructions if there is nothing between the load and
12871   // the end of block that could change the value.
12872   if (I->mayReadFromMemory()) {
12873     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12874          Scan != E; ++Scan)
12875       if (Scan->mayWriteToMemory())
12876         return false;
12877   }
12878
12879   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12880
12881   CopyPrecedingStopPoint(I, InsertPos);
12882   I->moveBefore(InsertPos);
12883   ++NumSunkInst;
12884   return true;
12885 }
12886
12887
12888 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12889 /// all reachable code to the worklist.
12890 ///
12891 /// This has a couple of tricks to make the code faster and more powerful.  In
12892 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12893 /// them to the worklist (this significantly speeds up instcombine on code where
12894 /// many instructions are dead or constant).  Additionally, if we find a branch
12895 /// whose condition is a known constant, we only visit the reachable successors.
12896 ///
12897 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12898                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12899                                        InstCombiner &IC,
12900                                        const TargetData *TD) {
12901   SmallVector<BasicBlock*, 256> Worklist;
12902   Worklist.push_back(BB);
12903
12904   while (!Worklist.empty()) {
12905     BB = Worklist.back();
12906     Worklist.pop_back();
12907     
12908     // We have now visited this block!  If we've already been here, ignore it.
12909     if (!Visited.insert(BB)) continue;
12910
12911     DbgInfoIntrinsic *DBI_Prev = NULL;
12912     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12913       Instruction *Inst = BBI++;
12914       
12915       // DCE instruction if trivially dead.
12916       if (isInstructionTriviallyDead(Inst)) {
12917         ++NumDeadInst;
12918         DOUT << "IC: DCE: " << *Inst << '\n';
12919         Inst->eraseFromParent();
12920         continue;
12921       }
12922       
12923       // ConstantProp instruction if trivially constant.
12924       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12925         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst << '\n';
12926         Inst->replaceAllUsesWith(C);
12927         ++NumConstProp;
12928         Inst->eraseFromParent();
12929         continue;
12930       }
12931      
12932       // If there are two consecutive llvm.dbg.stoppoint calls then
12933       // it is likely that the optimizer deleted code in between these
12934       // two intrinsics. 
12935       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12936       if (DBI_Next) {
12937         if (DBI_Prev
12938             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12939             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12940           IC.RemoveFromWorkList(DBI_Prev);
12941           DBI_Prev->eraseFromParent();
12942         }
12943         DBI_Prev = DBI_Next;
12944       } else {
12945         DBI_Prev = 0;
12946       }
12947
12948       IC.AddToWorkList(Inst);
12949     }
12950
12951     // Recursively visit successors.  If this is a branch or switch on a
12952     // constant, only visit the reachable successor.
12953     TerminatorInst *TI = BB->getTerminator();
12954     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12955       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12956         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12957         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12958         Worklist.push_back(ReachableBB);
12959         continue;
12960       }
12961     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12962       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12963         // See if this is an explicit destination.
12964         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12965           if (SI->getCaseValue(i) == Cond) {
12966             BasicBlock *ReachableBB = SI->getSuccessor(i);
12967             Worklist.push_back(ReachableBB);
12968             continue;
12969           }
12970         
12971         // Otherwise it is the default destination.
12972         Worklist.push_back(SI->getSuccessor(0));
12973         continue;
12974       }
12975     }
12976     
12977     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12978       Worklist.push_back(TI->getSuccessor(i));
12979   }
12980 }
12981
12982 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12983   bool Changed = false;
12984   TD = getAnalysisIfAvailable<TargetData>();
12985   
12986   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12987         << F.getNameStr() << "\n");
12988
12989   {
12990     // Do a depth-first traversal of the function, populate the worklist with
12991     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12992     // track of which blocks we visit.
12993     SmallPtrSet<BasicBlock*, 64> Visited;
12994     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12995
12996     // Do a quick scan over the function.  If we find any blocks that are
12997     // unreachable, remove any instructions inside of them.  This prevents
12998     // the instcombine code from having to deal with some bad special cases.
12999     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13000       if (!Visited.count(BB)) {
13001         Instruction *Term = BB->getTerminator();
13002         while (Term != BB->begin()) {   // Remove instrs bottom-up
13003           BasicBlock::iterator I = Term; --I;
13004
13005           DOUT << "IC: DCE: " << *I << '\n';
13006           // A debug intrinsic shouldn't force another iteration if we weren't
13007           // going to do one without it.
13008           if (!isa<DbgInfoIntrinsic>(I)) {
13009             ++NumDeadInst;
13010             Changed = true;
13011           }
13012           if (!I->use_empty())
13013             I->replaceAllUsesWith(UndefValue::get(I->getType()));
13014           I->eraseFromParent();
13015         }
13016       }
13017   }
13018
13019   while (!Worklist.empty()) {
13020     Instruction *I = RemoveOneFromWorkList();
13021     if (I == 0) continue;  // skip null values.
13022
13023     // Check to see if we can DCE the instruction.
13024     if (isInstructionTriviallyDead(I)) {
13025       // Add operands to the worklist.
13026       if (I->getNumOperands() < 4)
13027         AddUsesToWorkList(*I);
13028       ++NumDeadInst;
13029
13030       DOUT << "IC: DCE: " << *I << '\n';
13031
13032       I->eraseFromParent();
13033       RemoveFromWorkList(I);
13034       Changed = true;
13035       continue;
13036     }
13037
13038     // Instruction isn't dead, see if we can constant propagate it.
13039     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
13040       DOUT << "IC: ConstFold to: " << *C << " from: " << *I << '\n';
13041
13042       // Add operands to the worklist.
13043       AddUsesToWorkList(*I);
13044       ReplaceInstUsesWith(*I, C);
13045
13046       ++NumConstProp;
13047       I->eraseFromParent();
13048       RemoveFromWorkList(I);
13049       Changed = true;
13050       continue;
13051     }
13052
13053     if (TD) {
13054       // See if we can constant fold its operands.
13055       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13056         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
13057           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
13058                                   F.getContext(), TD))
13059             if (NewC != CE) {
13060               i->set(NewC);
13061               Changed = true;
13062             }
13063     }
13064
13065     // See if we can trivially sink this instruction to a successor basic block.
13066     if (I->hasOneUse()) {
13067       BasicBlock *BB = I->getParent();
13068       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13069       if (UserParent != BB) {
13070         bool UserIsSuccessor = false;
13071         // See if the user is one of our successors.
13072         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13073           if (*SI == UserParent) {
13074             UserIsSuccessor = true;
13075             break;
13076           }
13077
13078         // If the user is one of our immediate successors, and if that successor
13079         // only has us as a predecessors (we'd have to split the critical edge
13080         // otherwise), we can keep going.
13081         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13082             next(pred_begin(UserParent)) == pred_end(UserParent))
13083           // Okay, the CFG is simple enough, try to sink this instruction.
13084           Changed |= TryToSinkInstruction(I, UserParent);
13085       }
13086     }
13087
13088     // Now that we have an instruction, try combining it to simplify it...
13089 #ifndef NDEBUG
13090     std::string OrigI;
13091 #endif
13092     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13093     if (Instruction *Result = visit(*I)) {
13094       ++NumCombined;
13095       // Should we replace the old instruction with a new one?
13096       if (Result != I) {
13097         DOUT << "IC: Old = " << *I << '\n'
13098              << "    New = " << *Result << '\n';
13099
13100         // Everything uses the new instruction now.
13101         I->replaceAllUsesWith(Result);
13102
13103         // Push the new instruction and any users onto the worklist.
13104         AddToWorkList(Result);
13105         AddUsersToWorkList(*Result);
13106
13107         // Move the name to the new instruction first.
13108         Result->takeName(I);
13109
13110         // Insert the new instruction into the basic block...
13111         BasicBlock *InstParent = I->getParent();
13112         BasicBlock::iterator InsertPos = I;
13113
13114         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13115           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13116             ++InsertPos;
13117
13118         InstParent->getInstList().insert(InsertPos, Result);
13119
13120         // Make sure that we reprocess all operands now that we reduced their
13121         // use counts.
13122         AddUsesToWorkList(*I);
13123
13124         // Instructions can end up on the worklist more than once.  Make sure
13125         // we do not process an instruction that has been deleted.
13126         RemoveFromWorkList(I);
13127
13128         // Erase the old instruction.
13129         InstParent->getInstList().erase(I);
13130       } else {
13131 #ifndef NDEBUG
13132         DOUT << "IC: Mod = " << OrigI << '\n'
13133              << "    New = " << *I << '\n';
13134 #endif
13135
13136         // If the instruction was modified, it's possible that it is now dead.
13137         // if so, remove it.
13138         if (isInstructionTriviallyDead(I)) {
13139           // Make sure we process all operands now that we are reducing their
13140           // use counts.
13141           AddUsesToWorkList(*I);
13142
13143           // Instructions may end up in the worklist more than once.  Erase all
13144           // occurrences of this instruction.
13145           RemoveFromWorkList(I);
13146           I->eraseFromParent();
13147         } else {
13148           AddToWorkList(I);
13149           AddUsersToWorkList(*I);
13150         }
13151       }
13152       Changed = true;
13153     }
13154   }
13155
13156   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13157     
13158   // Do an explicit clear, this shrinks the map if needed.
13159   WorklistMap.clear();
13160   return Changed;
13161 }
13162
13163
13164 bool InstCombiner::runOnFunction(Function &F) {
13165   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13166   Context = &F.getContext();
13167   
13168   bool EverMadeChange = false;
13169
13170   // Iterate while there is work to do.
13171   unsigned Iteration = 0;
13172   while (DoOneIteration(F, Iteration++))
13173     EverMadeChange = true;
13174   return EverMadeChange;
13175 }
13176
13177 FunctionPass *llvm::createInstructionCombiningPass() {
13178   return new InstCombiner();
13179 }