68a21ea03917596b5879feaa50bfd275f3f099ec
[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(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(I.getOperand(0)) < getComplexity(I.getOperand(1)))
516     Changed = !I.swapOperands();
517
518   if (!I.isAssociative()) return Changed;
519   Instruction::BinaryOps Opcode = I.getOpcode();
520   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
521     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
522       if (isa<Constant>(I.getOperand(1))) {
523         Constant *Folded = ConstantExpr::get(I.getOpcode(),
524                                              cast<Constant>(I.getOperand(1)),
525                                              cast<Constant>(Op->getOperand(1)));
526         I.setOperand(0, Op->getOperand(0));
527         I.setOperand(1, Folded);
528         return true;
529       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
530         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
531             isOnlyUse(Op) && isOnlyUse(Op1)) {
532           Constant *C1 = cast<Constant>(Op->getOperand(1));
533           Constant *C2 = cast<Constant>(Op1->getOperand(1));
534
535           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
536           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
537           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
538                                                     Op1->getOperand(0),
539                                                     Op1->getName(), &I);
540           AddToWorkList(New);
541           I.setOperand(0, New);
542           I.setOperand(1, Folded);
543           return true;
544         }
545     }
546   return Changed;
547 }
548
549 /// SimplifyCompare - For a CmpInst this function just orders the operands
550 /// so that theyare listed from right (least complex) to left (most complex).
551 /// This puts constants before unary operators before binary operators.
552 bool InstCombiner::SimplifyCompare(CmpInst &I) {
553   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
554     return false;
555   I.swapOperands();
556   // Compare instructions are not associative so there's nothing else we can do.
557   return true;
558 }
559
560 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
561 // if the LHS is a constant zero (which is the 'negate' form).
562 //
563 static inline Value *dyn_castNegVal(Value *V) {
564   if (BinaryOperator::isNeg(V))
565     return BinaryOperator::getNegArgument(V);
566
567   // Constants can be considered to be negated values if they can be folded.
568   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
569     return ConstantExpr::getNeg(C);
570
571   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
572     if (C->getType()->getElementType()->isInteger())
573       return ConstantExpr::getNeg(C);
574
575   return 0;
576 }
577
578 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
579 // instruction if the LHS is a constant negative zero (which is the 'negate'
580 // form).
581 //
582 static inline Value *dyn_castFNegVal(Value *V) {
583   if (BinaryOperator::isFNeg(V))
584     return BinaryOperator::getFNegArgument(V);
585
586   // Constants can be considered to be negated values if they can be folded.
587   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
588     return ConstantExpr::getFNeg(C);
589
590   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
591     if (C->getType()->getElementType()->isFloatingPoint())
592       return ConstantExpr::getFNeg(C);
593
594   return 0;
595 }
596
597 static inline Value *dyn_castNotVal(Value *V) {
598   if (BinaryOperator::isNot(V))
599     return BinaryOperator::getNotArgument(V);
600
601   // Constants can be considered to be not'ed values...
602   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
603     return ConstantInt::get(C->getType(), ~C->getValue());
604   return 0;
605 }
606
607 // dyn_castFoldableMul - If this value is a multiply that can be folded into
608 // other computations (because it has a constant operand), return the
609 // non-constant operand of the multiply, and set CST to point to the multiplier.
610 // Otherwise, return null.
611 //
612 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
613   if (V->hasOneUse() && V->getType()->isInteger())
614     if (Instruction *I = dyn_cast<Instruction>(V)) {
615       if (I->getOpcode() == Instruction::Mul)
616         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
617           return I->getOperand(0);
618       if (I->getOpcode() == Instruction::Shl)
619         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
620           // The multiplier is really 1 << CST.
621           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
622           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
623           CST = ConstantInt::get(V->getType()->getContext(),
624                                  APInt(BitWidth, 1).shl(CSTVal));
625           return I->getOperand(0);
626         }
627     }
628   return 0;
629 }
630
631 /// AddOne - Add one to a ConstantInt
632 static Constant *AddOne(Constant *C) {
633   return ConstantExpr::getAdd(C, 
634     ConstantInt::get(C->getType(), 1));
635 }
636 /// SubOne - Subtract one from a ConstantInt
637 static Constant *SubOne(ConstantInt *C) {
638   return ConstantExpr::getSub(C, 
639     ConstantInt::get(C->getType(), 1));
640 }
641 /// MultiplyOverflows - True if the multiply can not be expressed in an int
642 /// this size.
643 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
644   uint32_t W = C1->getBitWidth();
645   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
646   if (sign) {
647     LHSExt.sext(W * 2);
648     RHSExt.sext(W * 2);
649   } else {
650     LHSExt.zext(W * 2);
651     RHSExt.zext(W * 2);
652   }
653
654   APInt MulExt = LHSExt * RHSExt;
655
656   if (sign) {
657     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
658     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
659     return MulExt.slt(Min) || MulExt.sgt(Max);
660   } else 
661     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
662 }
663
664
665 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
666 /// specified instruction is a constant integer.  If so, check to see if there
667 /// are any bits set in the constant that are not demanded.  If so, shrink the
668 /// constant and return true.
669 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
670                                    APInt Demanded) {
671   assert(I && "No instruction?");
672   assert(OpNo < I->getNumOperands() && "Operand index too large");
673
674   // If the operand is not a constant integer, nothing to do.
675   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
676   if (!OpC) return false;
677
678   // If there are no bits set that aren't demanded, nothing to do.
679   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
680   if ((~Demanded & OpC->getValue()) == 0)
681     return false;
682
683   // This instruction is producing bits that are not demanded. Shrink the RHS.
684   Demanded &= OpC->getValue();
685   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
686   return true;
687 }
688
689 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
690 // set of known zero and one bits, compute the maximum and minimum values that
691 // could have the specified known zero and known one bits, returning them in
692 // min/max.
693 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
694                                                    const APInt& KnownOne,
695                                                    APInt& Min, APInt& Max) {
696   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
697          KnownZero.getBitWidth() == Min.getBitWidth() &&
698          KnownZero.getBitWidth() == Max.getBitWidth() &&
699          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
700   APInt UnknownBits = ~(KnownZero|KnownOne);
701
702   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
703   // bit if it is unknown.
704   Min = KnownOne;
705   Max = KnownOne|UnknownBits;
706   
707   if (UnknownBits.isNegative()) { // Sign bit is unknown
708     Min.set(Min.getBitWidth()-1);
709     Max.clear(Max.getBitWidth()-1);
710   }
711 }
712
713 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
714 // a set of known zero and one bits, compute the maximum and minimum values that
715 // could have the specified known zero and known one bits, returning them in
716 // min/max.
717 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
718                                                      const APInt &KnownOne,
719                                                      APInt &Min, APInt &Max) {
720   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
721          KnownZero.getBitWidth() == Min.getBitWidth() &&
722          KnownZero.getBitWidth() == Max.getBitWidth() &&
723          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
724   APInt UnknownBits = ~(KnownZero|KnownOne);
725   
726   // The minimum value is when the unknown bits are all zeros.
727   Min = KnownOne;
728   // The maximum value is when the unknown bits are all ones.
729   Max = KnownOne|UnknownBits;
730 }
731
732 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
733 /// SimplifyDemandedBits knows about.  See if the instruction has any
734 /// properties that allow us to simplify its operands.
735 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
736   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
737   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
738   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
739   
740   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
741                                      KnownZero, KnownOne, 0);
742   if (V == 0) return false;
743   if (V == &Inst) return true;
744   ReplaceInstUsesWith(Inst, V);
745   return true;
746 }
747
748 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
749 /// specified instruction operand if possible, updating it in place.  It returns
750 /// true if it made any change and false otherwise.
751 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
752                                         APInt &KnownZero, APInt &KnownOne,
753                                         unsigned Depth) {
754   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
755                                           KnownZero, KnownOne, Depth);
756   if (NewVal == 0) return false;
757   U.set(NewVal);
758   return true;
759 }
760
761
762 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
763 /// value based on the demanded bits.  When this function is called, it is known
764 /// that only the bits set in DemandedMask of the result of V are ever used
765 /// downstream. Consequently, depending on the mask and V, it may be possible
766 /// to replace V with a constant or one of its operands. In such cases, this
767 /// function does the replacement and returns true. In all other cases, it
768 /// returns false after analyzing the expression and setting KnownOne and known
769 /// to be one in the expression.  KnownZero contains all the bits that are known
770 /// to be zero in the expression. These are provided to potentially allow the
771 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
772 /// the expression. KnownOne and KnownZero always follow the invariant that 
773 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
774 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
775 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
776 /// and KnownOne must all be the same.
777 ///
778 /// This returns null if it did not change anything and it permits no
779 /// simplification.  This returns V itself if it did some simplification of V's
780 /// operands based on the information about what bits are demanded. This returns
781 /// some other non-null value if it found out that V is equal to another value
782 /// in the context where the specified bits are demanded, but not for all users.
783 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
784                                              APInt &KnownZero, APInt &KnownOne,
785                                              unsigned Depth) {
786   assert(V != 0 && "Null pointer of Value???");
787   assert(Depth <= 6 && "Limit Search Depth");
788   uint32_t BitWidth = DemandedMask.getBitWidth();
789   const Type *VTy = V->getType();
790   assert((TD || !isa<PointerType>(VTy)) &&
791          "SimplifyDemandedBits needs to know bit widths!");
792   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
793          (!VTy->isIntOrIntVector() ||
794           VTy->getScalarSizeInBits() == BitWidth) &&
795          KnownZero.getBitWidth() == BitWidth &&
796          KnownOne.getBitWidth() == BitWidth &&
797          "Value *V, DemandedMask, KnownZero and KnownOne "
798          "must have same BitWidth");
799   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
800     // We know all of the bits for a constant!
801     KnownOne = CI->getValue() & DemandedMask;
802     KnownZero = ~KnownOne & DemandedMask;
803     return 0;
804   }
805   if (isa<ConstantPointerNull>(V)) {
806     // We know all of the bits for a constant!
807     KnownOne.clear();
808     KnownZero = DemandedMask;
809     return 0;
810   }
811
812   KnownZero.clear();
813   KnownOne.clear();
814   if (DemandedMask == 0) {   // Not demanding any bits from V.
815     if (isa<UndefValue>(V))
816       return 0;
817     return UndefValue::get(VTy);
818   }
819   
820   if (Depth == 6)        // Limit search depth.
821     return 0;
822   
823   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
824   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
825
826   Instruction *I = dyn_cast<Instruction>(V);
827   if (!I) {
828     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
829     return 0;        // Only analyze instructions.
830   }
831
832   // If there are multiple uses of this value and we aren't at the root, then
833   // we can't do any simplifications of the operands, because DemandedMask
834   // only reflects the bits demanded by *one* of the users.
835   if (Depth != 0 && !I->hasOneUse()) {
836     // Despite the fact that we can't simplify this instruction in all User's
837     // context, we can at least compute the knownzero/knownone bits, and we can
838     // do simplifications that apply to *just* the one user if we know that
839     // this instruction has a simpler value in that context.
840     if (I->getOpcode() == Instruction::And) {
841       // If either the LHS or the RHS are Zero, the result is zero.
842       ComputeMaskedBits(I->getOperand(1), DemandedMask,
843                         RHSKnownZero, RHSKnownOne, Depth+1);
844       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
845                         LHSKnownZero, LHSKnownOne, Depth+1);
846       
847       // If all of the demanded bits are known 1 on one side, return the other.
848       // These bits cannot contribute to the result of the 'and' in this
849       // context.
850       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
851           (DemandedMask & ~LHSKnownZero))
852         return I->getOperand(0);
853       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
854           (DemandedMask & ~RHSKnownZero))
855         return I->getOperand(1);
856       
857       // If all of the demanded bits in the inputs are known zeros, return zero.
858       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
859         return Constant::getNullValue(VTy);
860       
861     } else if (I->getOpcode() == Instruction::Or) {
862       // We can simplify (X|Y) -> X or Y in the user's context if we know that
863       // only bits from X or Y are demanded.
864       
865       // If either the LHS or the RHS are One, the result is One.
866       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
867                         RHSKnownZero, RHSKnownOne, Depth+1);
868       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
869                         LHSKnownZero, LHSKnownOne, Depth+1);
870       
871       // If all of the demanded bits are known zero on one side, return the
872       // other.  These bits cannot contribute to the result of the 'or' in this
873       // context.
874       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
875           (DemandedMask & ~LHSKnownOne))
876         return I->getOperand(0);
877       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
878           (DemandedMask & ~RHSKnownOne))
879         return I->getOperand(1);
880       
881       // If all of the potentially set bits on one side are known to be set on
882       // the other side, just use the 'other' side.
883       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
884           (DemandedMask & (~RHSKnownZero)))
885         return I->getOperand(0);
886       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
887           (DemandedMask & (~LHSKnownZero)))
888         return I->getOperand(1);
889     }
890     
891     // Compute the KnownZero/KnownOne bits to simplify things downstream.
892     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
893     return 0;
894   }
895   
896   // If this is the root being simplified, allow it to have multiple uses,
897   // just set the DemandedMask to all bits so that we can try to simplify the
898   // operands.  This allows visitTruncInst (for example) to simplify the
899   // operand of a trunc without duplicating all the logic below.
900   if (Depth == 0 && !V->hasOneUse())
901     DemandedMask = APInt::getAllOnesValue(BitWidth);
902   
903   switch (I->getOpcode()) {
904   default:
905     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
906     break;
907   case Instruction::And:
908     // If either the LHS or the RHS are Zero, the result is zero.
909     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
910                              RHSKnownZero, RHSKnownOne, Depth+1) ||
911         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
912                              LHSKnownZero, LHSKnownOne, Depth+1))
913       return I;
914     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
915     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
916
917     // If all of the demanded bits are known 1 on one side, return the other.
918     // These bits cannot contribute to the result of the 'and'.
919     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
920         (DemandedMask & ~LHSKnownZero))
921       return I->getOperand(0);
922     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
923         (DemandedMask & ~RHSKnownZero))
924       return I->getOperand(1);
925     
926     // If all of the demanded bits in the inputs are known zeros, return zero.
927     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
928       return Constant::getNullValue(VTy);
929       
930     // If the RHS is a constant, see if we can simplify it.
931     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
932       return I;
933       
934     // Output known-1 bits are only known if set in both the LHS & RHS.
935     RHSKnownOne &= LHSKnownOne;
936     // Output known-0 are known to be clear if zero in either the LHS | RHS.
937     RHSKnownZero |= LHSKnownZero;
938     break;
939   case Instruction::Or:
940     // If either the LHS or the RHS are One, the result is One.
941     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
942                              RHSKnownZero, RHSKnownOne, Depth+1) ||
943         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
944                              LHSKnownZero, LHSKnownOne, Depth+1))
945       return I;
946     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
947     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
948     
949     // If all of the demanded bits are known zero on one side, return the other.
950     // These bits cannot contribute to the result of the 'or'.
951     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
952         (DemandedMask & ~LHSKnownOne))
953       return I->getOperand(0);
954     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
955         (DemandedMask & ~RHSKnownOne))
956       return I->getOperand(1);
957
958     // If all of the potentially set bits on one side are known to be set on
959     // the other side, just use the 'other' side.
960     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
961         (DemandedMask & (~RHSKnownZero)))
962       return I->getOperand(0);
963     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
964         (DemandedMask & (~LHSKnownZero)))
965       return I->getOperand(1);
966         
967     // If the RHS is a constant, see if we can simplify it.
968     if (ShrinkDemandedConstant(I, 1, DemandedMask))
969       return I;
970           
971     // Output known-0 bits are only known if clear in both the LHS & RHS.
972     RHSKnownZero &= LHSKnownZero;
973     // Output known-1 are known to be set if set in either the LHS | RHS.
974     RHSKnownOne |= LHSKnownOne;
975     break;
976   case Instruction::Xor: {
977     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
978                              RHSKnownZero, RHSKnownOne, Depth+1) ||
979         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
980                              LHSKnownZero, LHSKnownOne, Depth+1))
981       return I;
982     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
983     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
984     
985     // If all of the demanded bits are known zero on one side, return the other.
986     // These bits cannot contribute to the result of the 'xor'.
987     if ((DemandedMask & RHSKnownZero) == DemandedMask)
988       return I->getOperand(0);
989     if ((DemandedMask & LHSKnownZero) == DemandedMask)
990       return I->getOperand(1);
991     
992     // Output known-0 bits are known if clear or set in both the LHS & RHS.
993     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
994                          (RHSKnownOne & LHSKnownOne);
995     // Output known-1 are known to be set if set in only one of the LHS, RHS.
996     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
997                         (RHSKnownOne & LHSKnownZero);
998     
999     // If all of the demanded bits are known to be zero on one side or the
1000     // other, turn this into an *inclusive* or.
1001     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1002     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1003       Instruction *Or =
1004         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1005                                  I->getName());
1006       return InsertNewInstBefore(Or, *I);
1007     }
1008     
1009     // If all of the demanded bits on one side are known, and all of the set
1010     // bits on that side are also known to be set on the other side, turn this
1011     // into an AND, as we know the bits will be cleared.
1012     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1013     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1014       // all known
1015       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1016         Constant *AndC = Constant::getIntegerValue(VTy,
1017                                                    ~RHSKnownOne & DemandedMask);
1018         Instruction *And = 
1019           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1020         return InsertNewInstBefore(And, *I);
1021       }
1022     }
1023     
1024     // If the RHS is a constant, see if we can simplify it.
1025     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1026     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1027       return I;
1028     
1029     RHSKnownZero = KnownZeroOut;
1030     RHSKnownOne  = KnownOneOut;
1031     break;
1032   }
1033   case Instruction::Select:
1034     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1035                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1036         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1037                              LHSKnownZero, LHSKnownOne, Depth+1))
1038       return I;
1039     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1040     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1041     
1042     // If the operands are constants, see if we can simplify them.
1043     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1044         ShrinkDemandedConstant(I, 2, DemandedMask))
1045       return I;
1046     
1047     // Only known if known in both the LHS and RHS.
1048     RHSKnownOne &= LHSKnownOne;
1049     RHSKnownZero &= LHSKnownZero;
1050     break;
1051   case Instruction::Trunc: {
1052     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1053     DemandedMask.zext(truncBf);
1054     RHSKnownZero.zext(truncBf);
1055     RHSKnownOne.zext(truncBf);
1056     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1057                              RHSKnownZero, RHSKnownOne, Depth+1))
1058       return I;
1059     DemandedMask.trunc(BitWidth);
1060     RHSKnownZero.trunc(BitWidth);
1061     RHSKnownOne.trunc(BitWidth);
1062     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1063     break;
1064   }
1065   case Instruction::BitCast:
1066     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1067       return false;  // vector->int or fp->int?
1068
1069     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1070       if (const VectorType *SrcVTy =
1071             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1072         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1073           // Don't touch a bitcast between vectors of different element counts.
1074           return false;
1075       } else
1076         // Don't touch a scalar-to-vector bitcast.
1077         return false;
1078     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1079       // Don't touch a vector-to-scalar bitcast.
1080       return false;
1081
1082     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1083                              RHSKnownZero, RHSKnownOne, Depth+1))
1084       return I;
1085     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1086     break;
1087   case Instruction::ZExt: {
1088     // Compute the bits in the result that are not present in the input.
1089     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1090     
1091     DemandedMask.trunc(SrcBitWidth);
1092     RHSKnownZero.trunc(SrcBitWidth);
1093     RHSKnownOne.trunc(SrcBitWidth);
1094     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1095                              RHSKnownZero, RHSKnownOne, Depth+1))
1096       return I;
1097     DemandedMask.zext(BitWidth);
1098     RHSKnownZero.zext(BitWidth);
1099     RHSKnownOne.zext(BitWidth);
1100     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1101     // The top bits are known to be zero.
1102     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1103     break;
1104   }
1105   case Instruction::SExt: {
1106     // Compute the bits in the result that are not present in the input.
1107     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1108     
1109     APInt InputDemandedBits = DemandedMask & 
1110                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1111
1112     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1113     // If any of the sign extended bits are demanded, we know that the sign
1114     // bit is demanded.
1115     if ((NewBits & DemandedMask) != 0)
1116       InputDemandedBits.set(SrcBitWidth-1);
1117       
1118     InputDemandedBits.trunc(SrcBitWidth);
1119     RHSKnownZero.trunc(SrcBitWidth);
1120     RHSKnownOne.trunc(SrcBitWidth);
1121     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1122                              RHSKnownZero, RHSKnownOne, Depth+1))
1123       return I;
1124     InputDemandedBits.zext(BitWidth);
1125     RHSKnownZero.zext(BitWidth);
1126     RHSKnownOne.zext(BitWidth);
1127     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1128       
1129     // If the sign bit of the input is known set or clear, then we know the
1130     // top bits of the result.
1131
1132     // If the input sign bit is known zero, or if the NewBits are not demanded
1133     // convert this into a zero extension.
1134     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1135       // Convert to ZExt cast
1136       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1137       return InsertNewInstBefore(NewCast, *I);
1138     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1139       RHSKnownOne |= NewBits;
1140     }
1141     break;
1142   }
1143   case Instruction::Add: {
1144     // Figure out what the input bits are.  If the top bits of the and result
1145     // are not demanded, then the add doesn't demand them from its input
1146     // either.
1147     unsigned NLZ = DemandedMask.countLeadingZeros();
1148       
1149     // If there is a constant on the RHS, there are a variety of xformations
1150     // we can do.
1151     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1152       // If null, this should be simplified elsewhere.  Some of the xforms here
1153       // won't work if the RHS is zero.
1154       if (RHS->isZero())
1155         break;
1156       
1157       // If the top bit of the output is demanded, demand everything from the
1158       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1159       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1160
1161       // Find information about known zero/one bits in the input.
1162       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1163                                LHSKnownZero, LHSKnownOne, Depth+1))
1164         return I;
1165
1166       // If the RHS of the add has bits set that can't affect the input, reduce
1167       // the constant.
1168       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1169         return I;
1170       
1171       // Avoid excess work.
1172       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1173         break;
1174       
1175       // Turn it into OR if input bits are zero.
1176       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1177         Instruction *Or =
1178           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1179                                    I->getName());
1180         return InsertNewInstBefore(Or, *I);
1181       }
1182       
1183       // We can say something about the output known-zero and known-one bits,
1184       // depending on potential carries from the input constant and the
1185       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1186       // bits set and the RHS constant is 0x01001, then we know we have a known
1187       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1188       
1189       // To compute this, we first compute the potential carry bits.  These are
1190       // the bits which may be modified.  I'm not aware of a better way to do
1191       // this scan.
1192       const APInt &RHSVal = RHS->getValue();
1193       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1194       
1195       // Now that we know which bits have carries, compute the known-1/0 sets.
1196       
1197       // Bits are known one if they are known zero in one operand and one in the
1198       // other, and there is no input carry.
1199       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1200                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1201       
1202       // Bits are known zero if they are known zero in both operands and there
1203       // is no input carry.
1204       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1205     } else {
1206       // If the high-bits of this ADD are not demanded, then it does not demand
1207       // the high bits of its LHS or RHS.
1208       if (DemandedMask[BitWidth-1] == 0) {
1209         // Right fill the mask of bits for this ADD to demand the most
1210         // significant bit and all those below it.
1211         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1212         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1213                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1214             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1215                                  LHSKnownZero, LHSKnownOne, Depth+1))
1216           return I;
1217       }
1218     }
1219     break;
1220   }
1221   case Instruction::Sub:
1222     // If the high-bits of this SUB are not demanded, then it does not demand
1223     // the high bits of its LHS or RHS.
1224     if (DemandedMask[BitWidth-1] == 0) {
1225       // Right fill the mask of bits for this SUB to demand the most
1226       // significant bit and all those below it.
1227       uint32_t NLZ = DemandedMask.countLeadingZeros();
1228       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1229       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1230                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1231           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1232                                LHSKnownZero, LHSKnownOne, Depth+1))
1233         return I;
1234     }
1235     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1236     // the known zeros and ones.
1237     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1238     break;
1239   case Instruction::Shl:
1240     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1241       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1242       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1243       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1244                                RHSKnownZero, RHSKnownOne, Depth+1))
1245         return I;
1246       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1247       RHSKnownZero <<= ShiftAmt;
1248       RHSKnownOne  <<= ShiftAmt;
1249       // low bits known zero.
1250       if (ShiftAmt)
1251         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1252     }
1253     break;
1254   case Instruction::LShr:
1255     // For a logical shift right
1256     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1257       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1258       
1259       // Unsigned shift right.
1260       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1261       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1262                                RHSKnownZero, RHSKnownOne, Depth+1))
1263         return I;
1264       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1265       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1266       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1267       if (ShiftAmt) {
1268         // Compute the new bits that are at the top now.
1269         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1270         RHSKnownZero |= HighBits;  // high bits known zero.
1271       }
1272     }
1273     break;
1274   case Instruction::AShr:
1275     // If this is an arithmetic shift right and only the low-bit is set, we can
1276     // always convert this into a logical shr, even if the shift amount is
1277     // variable.  The low bit of the shift cannot be an input sign bit unless
1278     // the shift amount is >= the size of the datatype, which is undefined.
1279     if (DemandedMask == 1) {
1280       // Perform the logical shift right.
1281       Instruction *NewVal = BinaryOperator::CreateLShr(
1282                         I->getOperand(0), I->getOperand(1), I->getName());
1283       return InsertNewInstBefore(NewVal, *I);
1284     }    
1285
1286     // If the sign bit is the only bit demanded by this ashr, then there is no
1287     // need to do it, the shift doesn't change the high bit.
1288     if (DemandedMask.isSignBit())
1289       return I->getOperand(0);
1290     
1291     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1292       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1293       
1294       // Signed shift right.
1295       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1296       // If any of the "high bits" are demanded, we should set the sign bit as
1297       // demanded.
1298       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1299         DemandedMaskIn.set(BitWidth-1);
1300       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1301                                RHSKnownZero, RHSKnownOne, Depth+1))
1302         return I;
1303       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1304       // Compute the new bits that are at the top now.
1305       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1306       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1307       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1308         
1309       // Handle the sign bits.
1310       APInt SignBit(APInt::getSignBit(BitWidth));
1311       // Adjust to where it is now in the mask.
1312       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1313         
1314       // If the input sign bit is known to be zero, or if none of the top bits
1315       // are demanded, turn this into an unsigned shift right.
1316       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1317           (HighBits & ~DemandedMask) == HighBits) {
1318         // Perform the logical shift right.
1319         Instruction *NewVal = BinaryOperator::CreateLShr(
1320                           I->getOperand(0), SA, I->getName());
1321         return InsertNewInstBefore(NewVal, *I);
1322       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1323         RHSKnownOne |= HighBits;
1324       }
1325     }
1326     break;
1327   case Instruction::SRem:
1328     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1329       APInt RA = Rem->getValue().abs();
1330       if (RA.isPowerOf2()) {
1331         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1332           return I->getOperand(0);
1333
1334         APInt LowBits = RA - 1;
1335         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1336         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1337                                  LHSKnownZero, LHSKnownOne, Depth+1))
1338           return I;
1339
1340         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1341           LHSKnownZero |= ~LowBits;
1342
1343         KnownZero |= LHSKnownZero & DemandedMask;
1344
1345         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1346       }
1347     }
1348     break;
1349   case Instruction::URem: {
1350     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1351     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1352     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1353                              KnownZero2, KnownOne2, Depth+1) ||
1354         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1355                              KnownZero2, KnownOne2, Depth+1))
1356       return I;
1357
1358     unsigned Leaders = KnownZero2.countLeadingOnes();
1359     Leaders = std::max(Leaders,
1360                        KnownZero2.countLeadingOnes());
1361     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1362     break;
1363   }
1364   case Instruction::Call:
1365     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1366       switch (II->getIntrinsicID()) {
1367       default: break;
1368       case Intrinsic::bswap: {
1369         // If the only bits demanded come from one byte of the bswap result,
1370         // just shift the input byte into position to eliminate the bswap.
1371         unsigned NLZ = DemandedMask.countLeadingZeros();
1372         unsigned NTZ = DemandedMask.countTrailingZeros();
1373           
1374         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1375         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1376         // have 14 leading zeros, round to 8.
1377         NLZ &= ~7;
1378         NTZ &= ~7;
1379         // If we need exactly one byte, we can do this transformation.
1380         if (BitWidth-NLZ-NTZ == 8) {
1381           unsigned ResultBit = NTZ;
1382           unsigned InputBit = BitWidth-NTZ-8;
1383           
1384           // Replace this with either a left or right shift to get the byte into
1385           // the right place.
1386           Instruction *NewVal;
1387           if (InputBit > ResultBit)
1388             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1389                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1390           else
1391             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1392                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1393           NewVal->takeName(I);
1394           return InsertNewInstBefore(NewVal, *I);
1395         }
1396           
1397         // TODO: Could compute known zero/one bits based on the input.
1398         break;
1399       }
1400       }
1401     }
1402     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1403     break;
1404   }
1405   
1406   // If the client is only demanding bits that we know, return the known
1407   // constant.
1408   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1409     return Constant::getIntegerValue(VTy, RHSKnownOne);
1410   return false;
1411 }
1412
1413
1414 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1415 /// any number of elements. DemandedElts contains the set of elements that are
1416 /// actually used by the caller.  This method analyzes which elements of the
1417 /// operand are undef and returns that information in UndefElts.
1418 ///
1419 /// If the information about demanded elements can be used to simplify the
1420 /// operation, the operation is simplified, then the resultant value is
1421 /// returned.  This returns null if no change was made.
1422 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1423                                                 APInt& UndefElts,
1424                                                 unsigned Depth) {
1425   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1426   APInt EltMask(APInt::getAllOnesValue(VWidth));
1427   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1428
1429   if (isa<UndefValue>(V)) {
1430     // If the entire vector is undefined, just return this info.
1431     UndefElts = EltMask;
1432     return 0;
1433   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1434     UndefElts = EltMask;
1435     return UndefValue::get(V->getType());
1436   }
1437
1438   UndefElts = 0;
1439   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1440     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1441     Constant *Undef = UndefValue::get(EltTy);
1442
1443     std::vector<Constant*> Elts;
1444     for (unsigned i = 0; i != VWidth; ++i)
1445       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1446         Elts.push_back(Undef);
1447         UndefElts.set(i);
1448       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1449         Elts.push_back(Undef);
1450         UndefElts.set(i);
1451       } else {                               // Otherwise, defined.
1452         Elts.push_back(CP->getOperand(i));
1453       }
1454
1455     // If we changed the constant, return it.
1456     Constant *NewCP = ConstantVector::get(Elts);
1457     return NewCP != CP ? NewCP : 0;
1458   } else if (isa<ConstantAggregateZero>(V)) {
1459     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1460     // set to undef.
1461     
1462     // Check if this is identity. If so, return 0 since we are not simplifying
1463     // anything.
1464     if (DemandedElts == ((1ULL << VWidth) -1))
1465       return 0;
1466     
1467     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1468     Constant *Zero = Constant::getNullValue(EltTy);
1469     Constant *Undef = UndefValue::get(EltTy);
1470     std::vector<Constant*> Elts;
1471     for (unsigned i = 0; i != VWidth; ++i) {
1472       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1473       Elts.push_back(Elt);
1474     }
1475     UndefElts = DemandedElts ^ EltMask;
1476     return ConstantVector::get(Elts);
1477   }
1478   
1479   // Limit search depth.
1480   if (Depth == 10)
1481     return 0;
1482
1483   // If multiple users are using the root value, procede with
1484   // simplification conservatively assuming that all elements
1485   // are needed.
1486   if (!V->hasOneUse()) {
1487     // Quit if we find multiple users of a non-root value though.
1488     // They'll be handled when it's their turn to be visited by
1489     // the main instcombine process.
1490     if (Depth != 0)
1491       // TODO: Just compute the UndefElts information recursively.
1492       return 0;
1493
1494     // Conservatively assume that all elements are needed.
1495     DemandedElts = EltMask;
1496   }
1497   
1498   Instruction *I = dyn_cast<Instruction>(V);
1499   if (!I) return 0;        // Only analyze instructions.
1500   
1501   bool MadeChange = false;
1502   APInt UndefElts2(VWidth, 0);
1503   Value *TmpV;
1504   switch (I->getOpcode()) {
1505   default: break;
1506     
1507   case Instruction::InsertElement: {
1508     // If this is a variable index, we don't know which element it overwrites.
1509     // demand exactly the same input as we produce.
1510     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1511     if (Idx == 0) {
1512       // Note that we can't propagate undef elt info, because we don't know
1513       // which elt is getting updated.
1514       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1515                                         UndefElts2, Depth+1);
1516       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1517       break;
1518     }
1519     
1520     // If this is inserting an element that isn't demanded, remove this
1521     // insertelement.
1522     unsigned IdxNo = Idx->getZExtValue();
1523     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1524       return AddSoonDeadInstToWorklist(*I, 0);
1525     
1526     // Otherwise, the element inserted overwrites whatever was there, so the
1527     // input demanded set is simpler than the output set.
1528     APInt DemandedElts2 = DemandedElts;
1529     DemandedElts2.clear(IdxNo);
1530     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1531                                       UndefElts, Depth+1);
1532     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1533
1534     // The inserted element is defined.
1535     UndefElts.clear(IdxNo);
1536     break;
1537   }
1538   case Instruction::ShuffleVector: {
1539     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1540     uint64_t LHSVWidth =
1541       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1542     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1543     for (unsigned i = 0; i < VWidth; i++) {
1544       if (DemandedElts[i]) {
1545         unsigned MaskVal = Shuffle->getMaskValue(i);
1546         if (MaskVal != -1u) {
1547           assert(MaskVal < LHSVWidth * 2 &&
1548                  "shufflevector mask index out of range!");
1549           if (MaskVal < LHSVWidth)
1550             LeftDemanded.set(MaskVal);
1551           else
1552             RightDemanded.set(MaskVal - LHSVWidth);
1553         }
1554       }
1555     }
1556
1557     APInt UndefElts4(LHSVWidth, 0);
1558     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1559                                       UndefElts4, Depth+1);
1560     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1561
1562     APInt UndefElts3(LHSVWidth, 0);
1563     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1564                                       UndefElts3, Depth+1);
1565     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1566
1567     bool NewUndefElts = false;
1568     for (unsigned i = 0; i < VWidth; i++) {
1569       unsigned MaskVal = Shuffle->getMaskValue(i);
1570       if (MaskVal == -1u) {
1571         UndefElts.set(i);
1572       } else if (MaskVal < LHSVWidth) {
1573         if (UndefElts4[MaskVal]) {
1574           NewUndefElts = true;
1575           UndefElts.set(i);
1576         }
1577       } else {
1578         if (UndefElts3[MaskVal - LHSVWidth]) {
1579           NewUndefElts = true;
1580           UndefElts.set(i);
1581         }
1582       }
1583     }
1584
1585     if (NewUndefElts) {
1586       // Add additional discovered undefs.
1587       std::vector<Constant*> Elts;
1588       for (unsigned i = 0; i < VWidth; ++i) {
1589         if (UndefElts[i])
1590           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1591         else
1592           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1593                                           Shuffle->getMaskValue(i)));
1594       }
1595       I->setOperand(2, ConstantVector::get(Elts));
1596       MadeChange = true;
1597     }
1598     break;
1599   }
1600   case Instruction::BitCast: {
1601     // Vector->vector casts only.
1602     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1603     if (!VTy) break;
1604     unsigned InVWidth = VTy->getNumElements();
1605     APInt InputDemandedElts(InVWidth, 0);
1606     unsigned Ratio;
1607
1608     if (VWidth == InVWidth) {
1609       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1610       // elements as are demanded of us.
1611       Ratio = 1;
1612       InputDemandedElts = DemandedElts;
1613     } else if (VWidth > InVWidth) {
1614       // Untested so far.
1615       break;
1616       
1617       // If there are more elements in the result than there are in the source,
1618       // then an input element is live if any of the corresponding output
1619       // elements are live.
1620       Ratio = VWidth/InVWidth;
1621       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1622         if (DemandedElts[OutIdx])
1623           InputDemandedElts.set(OutIdx/Ratio);
1624       }
1625     } else {
1626       // Untested so far.
1627       break;
1628       
1629       // If there are more elements in the source than there are in the result,
1630       // then an input element is live if the corresponding output element is
1631       // live.
1632       Ratio = InVWidth/VWidth;
1633       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1634         if (DemandedElts[InIdx/Ratio])
1635           InputDemandedElts.set(InIdx);
1636     }
1637     
1638     // div/rem demand all inputs, because they don't want divide by zero.
1639     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1640                                       UndefElts2, Depth+1);
1641     if (TmpV) {
1642       I->setOperand(0, TmpV);
1643       MadeChange = true;
1644     }
1645     
1646     UndefElts = UndefElts2;
1647     if (VWidth > InVWidth) {
1648       llvm_unreachable("Unimp");
1649       // If there are more elements in the result than there are in the source,
1650       // then an output element is undef if the corresponding input element is
1651       // undef.
1652       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1653         if (UndefElts2[OutIdx/Ratio])
1654           UndefElts.set(OutIdx);
1655     } else if (VWidth < InVWidth) {
1656       llvm_unreachable("Unimp");
1657       // If there are more elements in the source than there are in the result,
1658       // then a result element is undef if all of the corresponding input
1659       // elements are undef.
1660       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1661       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1662         if (!UndefElts2[InIdx])            // Not undef?
1663           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1664     }
1665     break;
1666   }
1667   case Instruction::And:
1668   case Instruction::Or:
1669   case Instruction::Xor:
1670   case Instruction::Add:
1671   case Instruction::Sub:
1672   case Instruction::Mul:
1673     // div/rem demand all inputs, because they don't want divide by zero.
1674     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1675                                       UndefElts, Depth+1);
1676     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1677     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1678                                       UndefElts2, Depth+1);
1679     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1680       
1681     // Output elements are undefined if both are undefined.  Consider things
1682     // like undef&0.  The result is known zero, not undef.
1683     UndefElts &= UndefElts2;
1684     break;
1685     
1686   case Instruction::Call: {
1687     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1688     if (!II) break;
1689     switch (II->getIntrinsicID()) {
1690     default: break;
1691       
1692     // Binary vector operations that work column-wise.  A dest element is a
1693     // function of the corresponding input elements from the two inputs.
1694     case Intrinsic::x86_sse_sub_ss:
1695     case Intrinsic::x86_sse_mul_ss:
1696     case Intrinsic::x86_sse_min_ss:
1697     case Intrinsic::x86_sse_max_ss:
1698     case Intrinsic::x86_sse2_sub_sd:
1699     case Intrinsic::x86_sse2_mul_sd:
1700     case Intrinsic::x86_sse2_min_sd:
1701     case Intrinsic::x86_sse2_max_sd:
1702       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1703                                         UndefElts, Depth+1);
1704       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1705       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1706                                         UndefElts2, Depth+1);
1707       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1708
1709       // If only the low elt is demanded and this is a scalarizable intrinsic,
1710       // scalarize it now.
1711       if (DemandedElts == 1) {
1712         switch (II->getIntrinsicID()) {
1713         default: break;
1714         case Intrinsic::x86_sse_sub_ss:
1715         case Intrinsic::x86_sse_mul_ss:
1716         case Intrinsic::x86_sse2_sub_sd:
1717         case Intrinsic::x86_sse2_mul_sd:
1718           // TODO: Lower MIN/MAX/ABS/etc
1719           Value *LHS = II->getOperand(1);
1720           Value *RHS = II->getOperand(2);
1721           // Extract the element as scalars.
1722           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1723             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1724           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1725             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1726           
1727           switch (II->getIntrinsicID()) {
1728           default: llvm_unreachable("Case stmts out of sync!");
1729           case Intrinsic::x86_sse_sub_ss:
1730           case Intrinsic::x86_sse2_sub_sd:
1731             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1732                                                         II->getName()), *II);
1733             break;
1734           case Intrinsic::x86_sse_mul_ss:
1735           case Intrinsic::x86_sse2_mul_sd:
1736             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1737                                                          II->getName()), *II);
1738             break;
1739           }
1740           
1741           Instruction *New =
1742             InsertElementInst::Create(
1743               UndefValue::get(II->getType()), TmpV,
1744               ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1745           InsertNewInstBefore(New, *II);
1746           AddSoonDeadInstToWorklist(*II, 0);
1747           return New;
1748         }            
1749       }
1750         
1751       // Output elements are undefined if both are undefined.  Consider things
1752       // like undef&0.  The result is known zero, not undef.
1753       UndefElts &= UndefElts2;
1754       break;
1755     }
1756     break;
1757   }
1758   }
1759   return MadeChange ? I : 0;
1760 }
1761
1762
1763 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1764 /// function is designed to check a chain of associative operators for a
1765 /// potential to apply a certain optimization.  Since the optimization may be
1766 /// applicable if the expression was reassociated, this checks the chain, then
1767 /// reassociates the expression as necessary to expose the optimization
1768 /// opportunity.  This makes use of a special Functor, which must define
1769 /// 'shouldApply' and 'apply' methods.
1770 ///
1771 template<typename Functor>
1772 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1773   unsigned Opcode = Root.getOpcode();
1774   Value *LHS = Root.getOperand(0);
1775
1776   // Quick check, see if the immediate LHS matches...
1777   if (F.shouldApply(LHS))
1778     return F.apply(Root);
1779
1780   // Otherwise, if the LHS is not of the same opcode as the root, return.
1781   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1782   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1783     // Should we apply this transform to the RHS?
1784     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1785
1786     // If not to the RHS, check to see if we should apply to the LHS...
1787     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1788       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1789       ShouldApply = true;
1790     }
1791
1792     // If the functor wants to apply the optimization to the RHS of LHSI,
1793     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1794     if (ShouldApply) {
1795       // Now all of the instructions are in the current basic block, go ahead
1796       // and perform the reassociation.
1797       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1798
1799       // First move the selected RHS to the LHS of the root...
1800       Root.setOperand(0, LHSI->getOperand(1));
1801
1802       // Make what used to be the LHS of the root be the user of the root...
1803       Value *ExtraOperand = TmpLHSI->getOperand(1);
1804       if (&Root == TmpLHSI) {
1805         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1806         return 0;
1807       }
1808       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1809       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1810       BasicBlock::iterator ARI = &Root; ++ARI;
1811       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1812       ARI = Root;
1813
1814       // Now propagate the ExtraOperand down the chain of instructions until we
1815       // get to LHSI.
1816       while (TmpLHSI != LHSI) {
1817         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1818         // Move the instruction to immediately before the chain we are
1819         // constructing to avoid breaking dominance properties.
1820         NextLHSI->moveBefore(ARI);
1821         ARI = NextLHSI;
1822
1823         Value *NextOp = NextLHSI->getOperand(1);
1824         NextLHSI->setOperand(1, ExtraOperand);
1825         TmpLHSI = NextLHSI;
1826         ExtraOperand = NextOp;
1827       }
1828
1829       // Now that the instructions are reassociated, have the functor perform
1830       // the transformation...
1831       return F.apply(Root);
1832     }
1833
1834     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1835   }
1836   return 0;
1837 }
1838
1839 namespace {
1840
1841 // AddRHS - Implements: X + X --> X << 1
1842 struct AddRHS {
1843   Value *RHS;
1844   explicit AddRHS(Value *rhs) : RHS(rhs) {}
1845   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1846   Instruction *apply(BinaryOperator &Add) const {
1847     return BinaryOperator::CreateShl(Add.getOperand(0),
1848                                      ConstantInt::get(Add.getType(), 1));
1849   }
1850 };
1851
1852 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1853 //                 iff C1&C2 == 0
1854 struct AddMaskingAnd {
1855   Constant *C2;
1856   explicit AddMaskingAnd(Constant *c) : C2(c) {}
1857   bool shouldApply(Value *LHS) const {
1858     ConstantInt *C1;
1859     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1860            ConstantExpr::getAnd(C1, C2)->isNullValue();
1861   }
1862   Instruction *apply(BinaryOperator &Add) const {
1863     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1864   }
1865 };
1866
1867 }
1868
1869 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1870                                              InstCombiner *IC) {
1871   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1872     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1873   }
1874
1875   // Figure out if the constant is the left or the right argument.
1876   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1877   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1878
1879   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1880     if (ConstIsRHS)
1881       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1882     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1883   }
1884
1885   Value *Op0 = SO, *Op1 = ConstOperand;
1886   if (!ConstIsRHS)
1887     std::swap(Op0, Op1);
1888   Instruction *New;
1889   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1890     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1891   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1892     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1893                           Op0, Op1, SO->getName()+".cmp");
1894   else {
1895     llvm_unreachable("Unknown binary instruction type!");
1896   }
1897   return IC->InsertNewInstBefore(New, I);
1898 }
1899
1900 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1901 // constant as the other operand, try to fold the binary operator into the
1902 // select arguments.  This also works for Cast instructions, which obviously do
1903 // not have a second operand.
1904 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1905                                      InstCombiner *IC) {
1906   // Don't modify shared select instructions
1907   if (!SI->hasOneUse()) return 0;
1908   Value *TV = SI->getOperand(1);
1909   Value *FV = SI->getOperand(2);
1910
1911   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1912     // Bool selects with constant operands can be folded to logical ops.
1913     if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
1914
1915     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1916     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1917
1918     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1919                               SelectFalseVal);
1920   }
1921   return 0;
1922 }
1923
1924
1925 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1926 /// node as operand #0, see if we can fold the instruction into the PHI (which
1927 /// is only possible if all operands to the PHI are constants).
1928 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1929   PHINode *PN = cast<PHINode>(I.getOperand(0));
1930   unsigned NumPHIValues = PN->getNumIncomingValues();
1931   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1932
1933   // Check to see if all of the operands of the PHI are constants.  If there is
1934   // one non-constant value, remember the BB it is.  If there is more than one
1935   // or if *it* is a PHI, bail out.
1936   BasicBlock *NonConstBB = 0;
1937   for (unsigned i = 0; i != NumPHIValues; ++i)
1938     if (!isa<Constant>(PN->getIncomingValue(i))) {
1939       if (NonConstBB) return 0;  // More than one non-const value.
1940       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1941       NonConstBB = PN->getIncomingBlock(i);
1942       
1943       // If the incoming non-constant value is in I's block, we have an infinite
1944       // loop.
1945       if (NonConstBB == I.getParent())
1946         return 0;
1947     }
1948   
1949   // If there is exactly one non-constant value, we can insert a copy of the
1950   // operation in that block.  However, if this is a critical edge, we would be
1951   // inserting the computation one some other paths (e.g. inside a loop).  Only
1952   // do this if the pred block is unconditionally branching into the phi block.
1953   if (NonConstBB) {
1954     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1955     if (!BI || !BI->isUnconditional()) return 0;
1956   }
1957
1958   // Okay, we can do the transformation: create the new PHI node.
1959   PHINode *NewPN = PHINode::Create(I.getType(), "");
1960   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1961   InsertNewInstBefore(NewPN, *PN);
1962   NewPN->takeName(PN);
1963
1964   // Next, add all of the operands to the PHI.
1965   if (I.getNumOperands() == 2) {
1966     Constant *C = cast<Constant>(I.getOperand(1));
1967     for (unsigned i = 0; i != NumPHIValues; ++i) {
1968       Value *InV = 0;
1969       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1970         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1971           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1972         else
1973           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1974       } else {
1975         assert(PN->getIncomingBlock(i) == NonConstBB);
1976         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1977           InV = BinaryOperator::Create(BO->getOpcode(),
1978                                        PN->getIncomingValue(i), C, "phitmp",
1979                                        NonConstBB->getTerminator());
1980         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1981           InV = CmpInst::Create(CI->getOpcode(),
1982                                 CI->getPredicate(),
1983                                 PN->getIncomingValue(i), C, "phitmp",
1984                                 NonConstBB->getTerminator());
1985         else
1986           llvm_unreachable("Unknown binop!");
1987         
1988         AddToWorkList(cast<Instruction>(InV));
1989       }
1990       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1991     }
1992   } else { 
1993     CastInst *CI = cast<CastInst>(&I);
1994     const Type *RetTy = CI->getType();
1995     for (unsigned i = 0; i != NumPHIValues; ++i) {
1996       Value *InV;
1997       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1998         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1999       } else {
2000         assert(PN->getIncomingBlock(i) == NonConstBB);
2001         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2002                                I.getType(), "phitmp", 
2003                                NonConstBB->getTerminator());
2004         AddToWorkList(cast<Instruction>(InV));
2005       }
2006       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2007     }
2008   }
2009   return ReplaceInstUsesWith(I, NewPN);
2010 }
2011
2012
2013 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2014 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2015 /// This basically requires proving that the add in the original type would not
2016 /// overflow to change the sign bit or have a carry out.
2017 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2018   // There are different heuristics we can use for this.  Here are some simple
2019   // ones.
2020   
2021   // Add has the property that adding any two 2's complement numbers can only 
2022   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2023   // have at least two sign bits, we know that the addition of the two values will
2024   // sign extend fine.
2025   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2026     return true;
2027   
2028   
2029   // If one of the operands only has one non-zero bit, and if the other operand
2030   // has a known-zero bit in a more significant place than it (not including the
2031   // sign bit) the ripple may go up to and fill the zero, but won't change the
2032   // sign.  For example, (X & ~4) + 1.
2033   
2034   // TODO: Implement.
2035   
2036   return false;
2037 }
2038
2039
2040 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2041   bool Changed = SimplifyCommutative(I);
2042   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2043
2044   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2045     // X + undef -> undef
2046     if (isa<UndefValue>(RHS))
2047       return ReplaceInstUsesWith(I, RHS);
2048
2049     // X + 0 --> X
2050     if (RHSC->isNullValue())
2051       return ReplaceInstUsesWith(I, LHS);
2052
2053     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2054       // X + (signbit) --> X ^ signbit
2055       const APInt& Val = CI->getValue();
2056       uint32_t BitWidth = Val.getBitWidth();
2057       if (Val == APInt::getSignBit(BitWidth))
2058         return BinaryOperator::CreateXor(LHS, RHS);
2059       
2060       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2061       // (X & 254)+1 -> (X&254)|1
2062       if (SimplifyDemandedInstructionBits(I))
2063         return &I;
2064
2065       // zext(bool) + C -> bool ? C + 1 : C
2066       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2067         if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2068           return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2069     }
2070
2071     if (isa<PHINode>(LHS))
2072       if (Instruction *NV = FoldOpIntoPhi(I))
2073         return NV;
2074     
2075     ConstantInt *XorRHS = 0;
2076     Value *XorLHS = 0;
2077     if (isa<ConstantInt>(RHSC) &&
2078         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2079       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2080       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2081       
2082       uint32_t Size = TySizeBits / 2;
2083       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2084       APInt CFF80Val(-C0080Val);
2085       do {
2086         if (TySizeBits > Size) {
2087           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2088           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2089           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2090               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2091             // This is a sign extend if the top bits are known zero.
2092             if (!MaskedValueIsZero(XorLHS, 
2093                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2094               Size = 0;  // Not a sign ext, but can't be any others either.
2095             break;
2096           }
2097         }
2098         Size >>= 1;
2099         C0080Val = APIntOps::lshr(C0080Val, Size);
2100         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2101       } while (Size >= 1);
2102       
2103       // FIXME: This shouldn't be necessary. When the backends can handle types
2104       // with funny bit widths then this switch statement should be removed. It
2105       // is just here to get the size of the "middle" type back up to something
2106       // that the back ends can handle.
2107       const Type *MiddleType = 0;
2108       switch (Size) {
2109         default: break;
2110         case 32: MiddleType = Type::getInt32Ty(*Context); break;
2111         case 16: MiddleType = Type::getInt16Ty(*Context); break;
2112         case  8: MiddleType = Type::getInt8Ty(*Context); break;
2113       }
2114       if (MiddleType) {
2115         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2116         InsertNewInstBefore(NewTrunc, I);
2117         return new SExtInst(NewTrunc, I.getType(), I.getName());
2118       }
2119     }
2120   }
2121
2122   if (I.getType() == Type::getInt1Ty(*Context))
2123     return BinaryOperator::CreateXor(LHS, RHS);
2124
2125   // X + X --> X << 1
2126   if (I.getType()->isInteger()) {
2127     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2128       return Result;
2129
2130     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2131       if (RHSI->getOpcode() == Instruction::Sub)
2132         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2133           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2134     }
2135     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2136       if (LHSI->getOpcode() == Instruction::Sub)
2137         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2138           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2139     }
2140   }
2141
2142   // -A + B  -->  B - A
2143   // -A + -B  -->  -(A + B)
2144   if (Value *LHSV = dyn_castNegVal(LHS)) {
2145     if (LHS->getType()->isIntOrIntVector()) {
2146       if (Value *RHSV = dyn_castNegVal(RHS)) {
2147         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2148         InsertNewInstBefore(NewAdd, I);
2149         return BinaryOperator::CreateNeg(NewAdd);
2150       }
2151     }
2152     
2153     return BinaryOperator::CreateSub(RHS, LHSV);
2154   }
2155
2156   // A + -B  -->  A - B
2157   if (!isa<Constant>(RHS))
2158     if (Value *V = dyn_castNegVal(RHS))
2159       return BinaryOperator::CreateSub(LHS, V);
2160
2161
2162   ConstantInt *C2;
2163   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2164     if (X == RHS)   // X*C + X --> X * (C+1)
2165       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2166
2167     // X*C1 + X*C2 --> X * (C1+C2)
2168     ConstantInt *C1;
2169     if (X == dyn_castFoldableMul(RHS, C1))
2170       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2171   }
2172
2173   // X + X*C --> X * (C+1)
2174   if (dyn_castFoldableMul(RHS, C2) == LHS)
2175     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2176
2177   // X + ~X --> -1   since   ~X = -X-1
2178   if (dyn_castNotVal(LHS) == RHS ||
2179       dyn_castNotVal(RHS) == LHS)
2180     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2181   
2182
2183   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2184   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2185     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2186       return R;
2187   
2188   // A+B --> A|B iff A and B have no bits set in common.
2189   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2190     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2191     APInt LHSKnownOne(IT->getBitWidth(), 0);
2192     APInt LHSKnownZero(IT->getBitWidth(), 0);
2193     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2194     if (LHSKnownZero != 0) {
2195       APInt RHSKnownOne(IT->getBitWidth(), 0);
2196       APInt RHSKnownZero(IT->getBitWidth(), 0);
2197       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2198       
2199       // No bits in common -> bitwise or.
2200       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2201         return BinaryOperator::CreateOr(LHS, RHS);
2202     }
2203   }
2204
2205   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2206   if (I.getType()->isIntOrIntVector()) {
2207     Value *W, *X, *Y, *Z;
2208     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2209         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2210       if (W != Y) {
2211         if (W == Z) {
2212           std::swap(Y, Z);
2213         } else if (Y == X) {
2214           std::swap(W, X);
2215         } else if (X == Z) {
2216           std::swap(Y, Z);
2217           std::swap(W, X);
2218         }
2219       }
2220
2221       if (W == Y) {
2222         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2223                                                             LHS->getName()), I);
2224         return BinaryOperator::CreateMul(W, NewAdd);
2225       }
2226     }
2227   }
2228
2229   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2230     Value *X = 0;
2231     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2232       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2233
2234     // (X & FF00) + xx00  -> (X+xx00) & FF00
2235     if (LHS->hasOneUse() &&
2236         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2237       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2238       if (Anded == CRHS) {
2239         // See if all bits from the first bit set in the Add RHS up are included
2240         // in the mask.  First, get the rightmost bit.
2241         const APInt& AddRHSV = CRHS->getValue();
2242
2243         // Form a mask of all bits from the lowest bit added through the top.
2244         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2245
2246         // See if the and mask includes all of these bits.
2247         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2248
2249         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2250           // Okay, the xform is safe.  Insert the new add pronto.
2251           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2252                                                             LHS->getName()), I);
2253           return BinaryOperator::CreateAnd(NewAdd, C2);
2254         }
2255       }
2256     }
2257
2258     // Try to fold constant add into select arguments.
2259     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2260       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2261         return R;
2262   }
2263
2264   // add (select X 0 (sub n A)) A  -->  select X A n
2265   {
2266     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2267     Value *A = RHS;
2268     if (!SI) {
2269       SI = dyn_cast<SelectInst>(RHS);
2270       A = LHS;
2271     }
2272     if (SI && SI->hasOneUse()) {
2273       Value *TV = SI->getTrueValue();
2274       Value *FV = SI->getFalseValue();
2275       Value *N;
2276
2277       // Can we fold the add into the argument of the select?
2278       // We check both true and false select arguments for a matching subtract.
2279       if (match(FV, m_Zero()) &&
2280           match(TV, m_Sub(m_Value(N), m_Specific(A))))
2281         // Fold the add into the true select value.
2282         return SelectInst::Create(SI->getCondition(), N, A);
2283       if (match(TV, m_Zero()) &&
2284           match(FV, m_Sub(m_Value(N), m_Specific(A))))
2285         // Fold the add into the false select value.
2286         return SelectInst::Create(SI->getCondition(), A, N);
2287     }
2288   }
2289
2290   // Check for (add (sext x), y), see if we can merge this into an
2291   // integer add followed by a sext.
2292   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2293     // (add (sext x), cst) --> (sext (add x, cst'))
2294     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2295       Constant *CI = 
2296         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2297       if (LHSConv->hasOneUse() &&
2298           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2299           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2300         // Insert the new, smaller add.
2301         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2302                                                         CI, "addconv");
2303         InsertNewInstBefore(NewAdd, I);
2304         return new SExtInst(NewAdd, I.getType());
2305       }
2306     }
2307     
2308     // (add (sext x), (sext y)) --> (sext (add int x, y))
2309     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2310       // Only do this if x/y have the same type, if at last one of them has a
2311       // single use (so we don't increase the number of sexts), and if the
2312       // integer add will not overflow.
2313       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2314           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2315           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2316                                    RHSConv->getOperand(0))) {
2317         // Insert the new integer add.
2318         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2319                                                         RHSConv->getOperand(0),
2320                                                         "addconv");
2321         InsertNewInstBefore(NewAdd, I);
2322         return new SExtInst(NewAdd, I.getType());
2323       }
2324     }
2325   }
2326
2327   return Changed ? &I : 0;
2328 }
2329
2330 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2331   bool Changed = SimplifyCommutative(I);
2332   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2333
2334   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2335     // X + 0 --> X
2336     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2337       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2338                               (I.getType())->getValueAPF()))
2339         return ReplaceInstUsesWith(I, LHS);
2340     }
2341
2342     if (isa<PHINode>(LHS))
2343       if (Instruction *NV = FoldOpIntoPhi(I))
2344         return NV;
2345   }
2346
2347   // -A + B  -->  B - A
2348   // -A + -B  -->  -(A + B)
2349   if (Value *LHSV = dyn_castFNegVal(LHS))
2350     return BinaryOperator::CreateFSub(RHS, LHSV);
2351
2352   // A + -B  -->  A - B
2353   if (!isa<Constant>(RHS))
2354     if (Value *V = dyn_castFNegVal(RHS))
2355       return BinaryOperator::CreateFSub(LHS, V);
2356
2357   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2358   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2359     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2360       return ReplaceInstUsesWith(I, LHS);
2361
2362   // Check for (add double (sitofp x), y), see if we can merge this into an
2363   // integer add followed by a promotion.
2364   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2365     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2366     // ... if the constant fits in the integer value.  This is useful for things
2367     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2368     // requires a constant pool load, and generally allows the add to be better
2369     // instcombined.
2370     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2371       Constant *CI = 
2372       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2373       if (LHSConv->hasOneUse() &&
2374           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2375           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2376         // Insert the new integer add.
2377         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2378                                                         CI, "addconv");
2379         InsertNewInstBefore(NewAdd, I);
2380         return new SIToFPInst(NewAdd, I.getType());
2381       }
2382     }
2383     
2384     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2385     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2386       // Only do this if x/y have the same type, if at last one of them has a
2387       // single use (so we don't increase the number of int->fp conversions),
2388       // and if the integer add will not overflow.
2389       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2390           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2391           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2392                                    RHSConv->getOperand(0))) {
2393         // Insert the new integer add.
2394         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2395                                                         RHSConv->getOperand(0),
2396                                                         "addconv");
2397         InsertNewInstBefore(NewAdd, I);
2398         return new SIToFPInst(NewAdd, I.getType());
2399       }
2400     }
2401   }
2402   
2403   return Changed ? &I : 0;
2404 }
2405
2406 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2407   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2408
2409   if (Op0 == Op1)                        // sub X, X  -> 0
2410     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2411
2412   // If this is a 'B = x-(-A)', change to B = x+A...
2413   if (Value *V = dyn_castNegVal(Op1))
2414     return BinaryOperator::CreateAdd(Op0, V);
2415
2416   if (isa<UndefValue>(Op0))
2417     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2418   if (isa<UndefValue>(Op1))
2419     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2420
2421   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2422     // Replace (-1 - A) with (~A)...
2423     if (C->isAllOnesValue())
2424       return BinaryOperator::CreateNot(Op1);
2425
2426     // C - ~X == X + (1+C)
2427     Value *X = 0;
2428     if (match(Op1, m_Not(m_Value(X))))
2429       return BinaryOperator::CreateAdd(X, AddOne(C));
2430
2431     // -(X >>u 31) -> (X >>s 31)
2432     // -(X >>s 31) -> (X >>u 31)
2433     if (C->isZero()) {
2434       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2435         if (SI->getOpcode() == Instruction::LShr) {
2436           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2437             // Check to see if we are shifting out everything but the sign bit.
2438             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2439                 SI->getType()->getPrimitiveSizeInBits()-1) {
2440               // Ok, the transformation is safe.  Insert AShr.
2441               return BinaryOperator::Create(Instruction::AShr, 
2442                                           SI->getOperand(0), CU, SI->getName());
2443             }
2444           }
2445         }
2446         else if (SI->getOpcode() == Instruction::AShr) {
2447           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2448             // Check to see if we are shifting out everything but the sign bit.
2449             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2450                 SI->getType()->getPrimitiveSizeInBits()-1) {
2451               // Ok, the transformation is safe.  Insert LShr. 
2452               return BinaryOperator::CreateLShr(
2453                                           SI->getOperand(0), CU, SI->getName());
2454             }
2455           }
2456         }
2457       }
2458     }
2459
2460     // Try to fold constant sub into select arguments.
2461     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2462       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2463         return R;
2464
2465     // C - zext(bool) -> bool ? C - 1 : C
2466     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2467       if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2468         return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2469   }
2470
2471   if (I.getType() == Type::getInt1Ty(*Context))
2472     return BinaryOperator::CreateXor(Op0, Op1);
2473
2474   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2475     if (Op1I->getOpcode() == Instruction::Add) {
2476       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2477         return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2478                                          I.getName());
2479       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2480         return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2481                                          I.getName());
2482       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2483         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2484           // C1-(X+C2) --> (C1-C2)-X
2485           return BinaryOperator::CreateSub(
2486             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2487       }
2488     }
2489
2490     if (Op1I->hasOneUse()) {
2491       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2492       // is not used by anyone else...
2493       //
2494       if (Op1I->getOpcode() == Instruction::Sub) {
2495         // Swap the two operands of the subexpr...
2496         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2497         Op1I->setOperand(0, IIOp1);
2498         Op1I->setOperand(1, IIOp0);
2499
2500         // Create the new top level add instruction...
2501         return BinaryOperator::CreateAdd(Op0, Op1);
2502       }
2503
2504       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2505       //
2506       if (Op1I->getOpcode() == Instruction::And &&
2507           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2508         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2509
2510         Value *NewNot =
2511           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2512         return BinaryOperator::CreateAnd(Op0, NewNot);
2513       }
2514
2515       // 0 - (X sdiv C)  -> (X sdiv -C)
2516       if (Op1I->getOpcode() == Instruction::SDiv)
2517         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2518           if (CSI->isZero())
2519             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2520               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2521                                           ConstantExpr::getNeg(DivRHS));
2522
2523       // X - X*C --> X * (1-C)
2524       ConstantInt *C2 = 0;
2525       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2526         Constant *CP1 = 
2527           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2528                                              C2);
2529         return BinaryOperator::CreateMul(Op0, CP1);
2530       }
2531     }
2532   }
2533
2534   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2535     if (Op0I->getOpcode() == Instruction::Add) {
2536       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2537         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2538       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2539         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2540     } else if (Op0I->getOpcode() == Instruction::Sub) {
2541       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2542         return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2543                                          I.getName());
2544     }
2545   }
2546
2547   ConstantInt *C1;
2548   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2549     if (X == Op1)  // X*C - X --> X * (C-1)
2550       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2551
2552     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2553     if (X == dyn_castFoldableMul(Op1, C2))
2554       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2555   }
2556   return 0;
2557 }
2558
2559 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2560   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2561
2562   // If this is a 'B = x-(-A)', change to B = x+A...
2563   if (Value *V = dyn_castFNegVal(Op1))
2564     return BinaryOperator::CreateFAdd(Op0, V);
2565
2566   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2567     if (Op1I->getOpcode() == Instruction::FAdd) {
2568       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2569         return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2570                                           I.getName());
2571       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2572         return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2573                                           I.getName());
2574     }
2575   }
2576
2577   return 0;
2578 }
2579
2580 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2581 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2582 /// TrueIfSigned if the result of the comparison is true when the input value is
2583 /// signed.
2584 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2585                            bool &TrueIfSigned) {
2586   switch (pred) {
2587   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2588     TrueIfSigned = true;
2589     return RHS->isZero();
2590   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2591     TrueIfSigned = true;
2592     return RHS->isAllOnesValue();
2593   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2594     TrueIfSigned = false;
2595     return RHS->isAllOnesValue();
2596   case ICmpInst::ICMP_UGT:
2597     // True if LHS u> RHS and RHS == high-bit-mask - 1
2598     TrueIfSigned = true;
2599     return RHS->getValue() ==
2600       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2601   case ICmpInst::ICMP_UGE: 
2602     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2603     TrueIfSigned = true;
2604     return RHS->getValue().isSignBit();
2605   default:
2606     return false;
2607   }
2608 }
2609
2610 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2611   bool Changed = SimplifyCommutative(I);
2612   Value *Op0 = I.getOperand(0);
2613
2614   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2615     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2616
2617   // Simplify mul instructions with a constant RHS...
2618   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2619     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2620
2621       // ((X << C1)*C2) == (X * (C2 << C1))
2622       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2623         if (SI->getOpcode() == Instruction::Shl)
2624           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2625             return BinaryOperator::CreateMul(SI->getOperand(0),
2626                                         ConstantExpr::getShl(CI, ShOp));
2627
2628       if (CI->isZero())
2629         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2630       if (CI->equalsInt(1))                  // X * 1  == X
2631         return ReplaceInstUsesWith(I, Op0);
2632       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2633         return BinaryOperator::CreateNeg(Op0, I.getName());
2634
2635       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2636       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2637         return BinaryOperator::CreateShl(Op0,
2638                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2639       }
2640     } else if (isa<VectorType>(Op1->getType())) {
2641       if (Op1->isNullValue())
2642         return ReplaceInstUsesWith(I, Op1);
2643
2644       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2645         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2646           return BinaryOperator::CreateNeg(Op0, I.getName());
2647
2648         // As above, vector X*splat(1.0) -> X in all defined cases.
2649         if (Constant *Splat = Op1V->getSplatValue()) {
2650           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2651             if (CI->equalsInt(1))
2652               return ReplaceInstUsesWith(I, Op0);
2653         }
2654       }
2655     }
2656     
2657     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2658       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2659           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2660         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2661         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2662                                                      Op1, "tmp");
2663         InsertNewInstBefore(Add, I);
2664         Value *C1C2 = ConstantExpr::getMul(Op1, 
2665                                            cast<Constant>(Op0I->getOperand(1)));
2666         return BinaryOperator::CreateAdd(Add, C1C2);
2667         
2668       }
2669
2670     // Try to fold constant mul into select arguments.
2671     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2672       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2673         return R;
2674
2675     if (isa<PHINode>(Op0))
2676       if (Instruction *NV = FoldOpIntoPhi(I))
2677         return NV;
2678   }
2679
2680   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2681     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2682       return BinaryOperator::CreateMul(Op0v, Op1v);
2683
2684   // (X / Y) *  Y = X - (X % Y)
2685   // (X / Y) * -Y = (X % Y) - X
2686   {
2687     Value *Op1 = I.getOperand(1);
2688     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2689     if (!BO ||
2690         (BO->getOpcode() != Instruction::UDiv && 
2691          BO->getOpcode() != Instruction::SDiv)) {
2692       Op1 = Op0;
2693       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2694     }
2695     Value *Neg = dyn_castNegVal(Op1);
2696     if (BO && BO->hasOneUse() &&
2697         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2698         (BO->getOpcode() == Instruction::UDiv ||
2699          BO->getOpcode() == Instruction::SDiv)) {
2700       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2701
2702       // If the division is exact, X % Y is zero.
2703       if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2704         if (SDiv->isExact()) {
2705           if (Op1BO == Op1)
2706             return ReplaceInstUsesWith(I, Op0BO);
2707           else
2708             return BinaryOperator::CreateNeg(Op0BO);
2709         }
2710
2711       Instruction *Rem;
2712       if (BO->getOpcode() == Instruction::UDiv)
2713         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2714       else
2715         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2716
2717       InsertNewInstBefore(Rem, I);
2718       Rem->takeName(BO);
2719
2720       if (Op1BO == Op1)
2721         return BinaryOperator::CreateSub(Op0BO, Rem);
2722       else
2723         return BinaryOperator::CreateSub(Rem, Op0BO);
2724     }
2725   }
2726
2727   if (I.getType() == Type::getInt1Ty(*Context))
2728     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2729
2730   // If one of the operands of the multiply is a cast from a boolean value, then
2731   // we know the bool is either zero or one, so this is a 'masking' multiply.
2732   // See if we can simplify things based on how the boolean was originally
2733   // formed.
2734   CastInst *BoolCast = 0;
2735   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2736     if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2737       BoolCast = CI;
2738   if (!BoolCast)
2739     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2740       if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2741         BoolCast = CI;
2742   if (BoolCast) {
2743     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2744       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2745       const Type *SCOpTy = SCIOp0->getType();
2746       bool TIS = false;
2747       
2748       // If the icmp is true iff the sign bit of X is set, then convert this
2749       // multiply into a shift/and combination.
2750       if (isa<ConstantInt>(SCIOp1) &&
2751           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2752           TIS) {
2753         // Shift the X value right to turn it into "all signbits".
2754         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2755                                           SCOpTy->getPrimitiveSizeInBits()-1);
2756         Value *V =
2757           InsertNewInstBefore(
2758             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2759                                             BoolCast->getOperand(0)->getName()+
2760                                             ".mask"), I);
2761
2762         // If the multiply type is not the same as the source type, sign extend
2763         // or truncate to the multiply type.
2764         if (I.getType() != V->getType()) {
2765           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2766           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2767           Instruction::CastOps opcode = 
2768             (SrcBits == DstBits ? Instruction::BitCast : 
2769              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2770           V = InsertCastBefore(opcode, V, I.getType(), I);
2771         }
2772
2773         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2774         return BinaryOperator::CreateAnd(V, OtherOp);
2775       }
2776     }
2777   }
2778
2779   return Changed ? &I : 0;
2780 }
2781
2782 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2783   bool Changed = SimplifyCommutative(I);
2784   Value *Op0 = I.getOperand(0);
2785
2786   // Simplify mul instructions with a constant RHS...
2787   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2788     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2789       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2790       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2791       if (Op1F->isExactlyValue(1.0))
2792         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2793     } else if (isa<VectorType>(Op1->getType())) {
2794       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2795         // As above, vector X*splat(1.0) -> X in all defined cases.
2796         if (Constant *Splat = Op1V->getSplatValue()) {
2797           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2798             if (F->isExactlyValue(1.0))
2799               return ReplaceInstUsesWith(I, Op0);
2800         }
2801       }
2802     }
2803
2804     // Try to fold constant mul into select arguments.
2805     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2806       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2807         return R;
2808
2809     if (isa<PHINode>(Op0))
2810       if (Instruction *NV = FoldOpIntoPhi(I))
2811         return NV;
2812   }
2813
2814   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
2815     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2816       return BinaryOperator::CreateFMul(Op0v, Op1v);
2817
2818   return Changed ? &I : 0;
2819 }
2820
2821 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2822 /// instruction.
2823 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2824   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2825   
2826   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2827   int NonNullOperand = -1;
2828   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2829     if (ST->isNullValue())
2830       NonNullOperand = 2;
2831   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2832   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2833     if (ST->isNullValue())
2834       NonNullOperand = 1;
2835   
2836   if (NonNullOperand == -1)
2837     return false;
2838   
2839   Value *SelectCond = SI->getOperand(0);
2840   
2841   // Change the div/rem to use 'Y' instead of the select.
2842   I.setOperand(1, SI->getOperand(NonNullOperand));
2843   
2844   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2845   // problem.  However, the select, or the condition of the select may have
2846   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2847   // propagate the known value for the select into other uses of it, and
2848   // propagate a known value of the condition into its other users.
2849   
2850   // If the select and condition only have a single use, don't bother with this,
2851   // early exit.
2852   if (SI->use_empty() && SelectCond->hasOneUse())
2853     return true;
2854   
2855   // Scan the current block backward, looking for other uses of SI.
2856   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2857   
2858   while (BBI != BBFront) {
2859     --BBI;
2860     // If we found a call to a function, we can't assume it will return, so
2861     // information from below it cannot be propagated above it.
2862     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2863       break;
2864     
2865     // Replace uses of the select or its condition with the known values.
2866     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2867          I != E; ++I) {
2868       if (*I == SI) {
2869         *I = SI->getOperand(NonNullOperand);
2870         AddToWorkList(BBI);
2871       } else if (*I == SelectCond) {
2872         *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2873                                    ConstantInt::getFalse(*Context);
2874         AddToWorkList(BBI);
2875       }
2876     }
2877     
2878     // If we past the instruction, quit looking for it.
2879     if (&*BBI == SI)
2880       SI = 0;
2881     if (&*BBI == SelectCond)
2882       SelectCond = 0;
2883     
2884     // If we ran out of things to eliminate, break out of the loop.
2885     if (SelectCond == 0 && SI == 0)
2886       break;
2887     
2888   }
2889   return true;
2890 }
2891
2892
2893 /// This function implements the transforms on div instructions that work
2894 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2895 /// used by the visitors to those instructions.
2896 /// @brief Transforms common to all three div instructions
2897 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2898   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2899
2900   // undef / X -> 0        for integer.
2901   // undef / X -> undef    for FP (the undef could be a snan).
2902   if (isa<UndefValue>(Op0)) {
2903     if (Op0->getType()->isFPOrFPVector())
2904       return ReplaceInstUsesWith(I, Op0);
2905     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2906   }
2907
2908   // X / undef -> undef
2909   if (isa<UndefValue>(Op1))
2910     return ReplaceInstUsesWith(I, Op1);
2911
2912   return 0;
2913 }
2914
2915 /// This function implements the transforms common to both integer division
2916 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2917 /// division instructions.
2918 /// @brief Common integer divide transforms
2919 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2920   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2921
2922   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2923   if (Op0 == Op1) {
2924     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2925       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2926       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2927       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2928     }
2929
2930     Constant *CI = ConstantInt::get(I.getType(), 1);
2931     return ReplaceInstUsesWith(I, CI);
2932   }
2933   
2934   if (Instruction *Common = commonDivTransforms(I))
2935     return Common;
2936   
2937   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2938   // This does not apply for fdiv.
2939   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2940     return &I;
2941
2942   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2943     // div X, 1 == X
2944     if (RHS->equalsInt(1))
2945       return ReplaceInstUsesWith(I, Op0);
2946
2947     // (X / C1) / C2  -> X / (C1*C2)
2948     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2949       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2950         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2951           if (MultiplyOverflows(RHS, LHSRHS,
2952                                 I.getOpcode()==Instruction::SDiv))
2953             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2954           else 
2955             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2956                                       ConstantExpr::getMul(RHS, LHSRHS));
2957         }
2958
2959     if (!RHS->isZero()) { // avoid X udiv 0
2960       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2961         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2962           return R;
2963       if (isa<PHINode>(Op0))
2964         if (Instruction *NV = FoldOpIntoPhi(I))
2965           return NV;
2966     }
2967   }
2968
2969   // 0 / X == 0, we don't need to preserve faults!
2970   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2971     if (LHS->equalsInt(0))
2972       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2973
2974   // It can't be division by zero, hence it must be division by one.
2975   if (I.getType() == Type::getInt1Ty(*Context))
2976     return ReplaceInstUsesWith(I, Op0);
2977
2978   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2979     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2980       // div X, 1 == X
2981       if (X->isOne())
2982         return ReplaceInstUsesWith(I, Op0);
2983   }
2984
2985   return 0;
2986 }
2987
2988 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2989   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2990
2991   // Handle the integer div common cases
2992   if (Instruction *Common = commonIDivTransforms(I))
2993     return Common;
2994
2995   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2996     // X udiv C^2 -> X >> C
2997     // Check to see if this is an unsigned division with an exact power of 2,
2998     // if so, convert to a right shift.
2999     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3000       return BinaryOperator::CreateLShr(Op0, 
3001             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3002
3003     // X udiv C, where C >= signbit
3004     if (C->getValue().isNegative()) {
3005       Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
3006                                       I);
3007       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3008                                 ConstantInt::get(I.getType(), 1));
3009     }
3010   }
3011
3012   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3013   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3014     if (RHSI->getOpcode() == Instruction::Shl &&
3015         isa<ConstantInt>(RHSI->getOperand(0))) {
3016       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3017       if (C1.isPowerOf2()) {
3018         Value *N = RHSI->getOperand(1);
3019         const Type *NTy = N->getType();
3020         if (uint32_t C2 = C1.logBase2()) {
3021           Constant *C2V = ConstantInt::get(NTy, C2);
3022           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3023         }
3024         return BinaryOperator::CreateLShr(Op0, N);
3025       }
3026     }
3027   }
3028   
3029   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3030   // where C1&C2 are powers of two.
3031   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3032     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3033       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3034         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3035         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3036           // Compute the shift amounts
3037           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3038           // Construct the "on true" case of the select
3039           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3040           Instruction *TSI = BinaryOperator::CreateLShr(
3041                                                  Op0, TC, SI->getName()+".t");
3042           TSI = InsertNewInstBefore(TSI, I);
3043   
3044           // Construct the "on false" case of the select
3045           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3046           Instruction *FSI = BinaryOperator::CreateLShr(
3047                                                  Op0, FC, SI->getName()+".f");
3048           FSI = InsertNewInstBefore(FSI, I);
3049
3050           // construct the select instruction and return it.
3051           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3052         }
3053       }
3054   return 0;
3055 }
3056
3057 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3058   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3059
3060   // Handle the integer div common cases
3061   if (Instruction *Common = commonIDivTransforms(I))
3062     return Common;
3063
3064   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3065     // sdiv X, -1 == -X
3066     if (RHS->isAllOnesValue())
3067       return BinaryOperator::CreateNeg(Op0);
3068
3069     // sdiv X, C  -->  ashr X, log2(C)
3070     if (cast<SDivOperator>(&I)->isExact() &&
3071         RHS->getValue().isNonNegative() &&
3072         RHS->getValue().isPowerOf2()) {
3073       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3074                                             RHS->getValue().exactLogBase2());
3075       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3076     }
3077
3078     // -X/C  -->  X/-C  provided the negation doesn't overflow.
3079     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3080       if (isa<Constant>(Sub->getOperand(0)) &&
3081           cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3082           Sub->hasNoSignedWrap())
3083         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3084                                           ConstantExpr::getNeg(RHS));
3085   }
3086
3087   // If the sign bits of both operands are zero (i.e. we can prove they are
3088   // unsigned inputs), turn this into a udiv.
3089   if (I.getType()->isInteger()) {
3090     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3091     if (MaskedValueIsZero(Op0, Mask)) {
3092       if (MaskedValueIsZero(Op1, Mask)) {
3093         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3094         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3095       }
3096       ConstantInt *ShiftedInt;
3097       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3098           ShiftedInt->getValue().isPowerOf2()) {
3099         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3100         // Safe because the only negative value (1 << Y) can take on is
3101         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3102         // the sign bit set.
3103         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3104       }
3105     }
3106   }
3107   
3108   return 0;
3109 }
3110
3111 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3112   return commonDivTransforms(I);
3113 }
3114
3115 /// This function implements the transforms on rem instructions that work
3116 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3117 /// is used by the visitors to those instructions.
3118 /// @brief Transforms common to all three rem instructions
3119 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3120   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3121
3122   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3123     if (I.getType()->isFPOrFPVector())
3124       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3125     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3126   }
3127   if (isa<UndefValue>(Op1))
3128     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3129
3130   // Handle cases involving: rem X, (select Cond, Y, Z)
3131   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3132     return &I;
3133
3134   return 0;
3135 }
3136
3137 /// This function implements the transforms common to both integer remainder
3138 /// instructions (urem and srem). It is called by the visitors to those integer
3139 /// remainder instructions.
3140 /// @brief Common integer remainder transforms
3141 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3142   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3143
3144   if (Instruction *common = commonRemTransforms(I))
3145     return common;
3146
3147   // 0 % X == 0 for integer, we don't need to preserve faults!
3148   if (Constant *LHS = dyn_cast<Constant>(Op0))
3149     if (LHS->isNullValue())
3150       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3151
3152   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3153     // X % 0 == undef, we don't need to preserve faults!
3154     if (RHS->equalsInt(0))
3155       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3156     
3157     if (RHS->equalsInt(1))  // X % 1 == 0
3158       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3159
3160     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3161       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3162         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3163           return R;
3164       } else if (isa<PHINode>(Op0I)) {
3165         if (Instruction *NV = FoldOpIntoPhi(I))
3166           return NV;
3167       }
3168
3169       // See if we can fold away this rem instruction.
3170       if (SimplifyDemandedInstructionBits(I))
3171         return &I;
3172     }
3173   }
3174
3175   return 0;
3176 }
3177
3178 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3179   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3180
3181   if (Instruction *common = commonIRemTransforms(I))
3182     return common;
3183   
3184   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3185     // X urem C^2 -> X and C
3186     // Check to see if this is an unsigned remainder with an exact power of 2,
3187     // if so, convert to a bitwise and.
3188     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3189       if (C->getValue().isPowerOf2())
3190         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3191   }
3192
3193   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3194     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3195     if (RHSI->getOpcode() == Instruction::Shl &&
3196         isa<ConstantInt>(RHSI->getOperand(0))) {
3197       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3198         Constant *N1 = Constant::getAllOnesValue(I.getType());
3199         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3200                                                                    "tmp"), I);
3201         return BinaryOperator::CreateAnd(Op0, Add);
3202       }
3203     }
3204   }
3205
3206   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3207   // where C1&C2 are powers of two.
3208   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3209     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3210       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3211         // STO == 0 and SFO == 0 handled above.
3212         if ((STO->getValue().isPowerOf2()) && 
3213             (SFO->getValue().isPowerOf2())) {
3214           Value *TrueAnd = InsertNewInstBefore(
3215             BinaryOperator::CreateAnd(Op0, SubOne(STO),
3216                                       SI->getName()+".t"), I);
3217           Value *FalseAnd = InsertNewInstBefore(
3218             BinaryOperator::CreateAnd(Op0, SubOne(SFO),
3219                                       SI->getName()+".f"), I);
3220           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3221         }
3222       }
3223   }
3224   
3225   return 0;
3226 }
3227
3228 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3229   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3230
3231   // Handle the integer rem common cases
3232   if (Instruction *common = commonIRemTransforms(I))
3233     return common;
3234   
3235   if (Value *RHSNeg = dyn_castNegVal(Op1))
3236     if (!isa<Constant>(RHSNeg) ||
3237         (isa<ConstantInt>(RHSNeg) &&
3238          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3239       // X % -Y -> X % Y
3240       AddUsesToWorkList(I);
3241       I.setOperand(1, RHSNeg);
3242       return &I;
3243     }
3244
3245   // If the sign bits of both operands are zero (i.e. we can prove they are
3246   // unsigned inputs), turn this into a urem.
3247   if (I.getType()->isInteger()) {
3248     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3249     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3250       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3251       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3252     }
3253   }
3254
3255   // If it's a constant vector, flip any negative values positive.
3256   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3257     unsigned VWidth = RHSV->getNumOperands();
3258
3259     bool hasNegative = false;
3260     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3261       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3262         if (RHS->getValue().isNegative())
3263           hasNegative = true;
3264
3265     if (hasNegative) {
3266       std::vector<Constant *> Elts(VWidth);
3267       for (unsigned i = 0; i != VWidth; ++i) {
3268         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3269           if (RHS->getValue().isNegative())
3270             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3271           else
3272             Elts[i] = RHS;
3273         }
3274       }
3275
3276       Constant *NewRHSV = ConstantVector::get(Elts);
3277       if (NewRHSV != RHSV) {
3278         AddUsesToWorkList(I);
3279         I.setOperand(1, NewRHSV);
3280         return &I;
3281       }
3282     }
3283   }
3284
3285   return 0;
3286 }
3287
3288 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3289   return commonRemTransforms(I);
3290 }
3291
3292 // isOneBitSet - Return true if there is exactly one bit set in the specified
3293 // constant.
3294 static bool isOneBitSet(const ConstantInt *CI) {
3295   return CI->getValue().isPowerOf2();
3296 }
3297
3298 // isHighOnes - Return true if the constant is of the form 1+0+.
3299 // This is the same as lowones(~X).
3300 static bool isHighOnes(const ConstantInt *CI) {
3301   return (~CI->getValue() + 1).isPowerOf2();
3302 }
3303
3304 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3305 /// are carefully arranged to allow folding of expressions such as:
3306 ///
3307 ///      (A < B) | (A > B) --> (A != B)
3308 ///
3309 /// Note that this is only valid if the first and second predicates have the
3310 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3311 ///
3312 /// Three bits are used to represent the condition, as follows:
3313 ///   0  A > B
3314 ///   1  A == B
3315 ///   2  A < B
3316 ///
3317 /// <=>  Value  Definition
3318 /// 000     0   Always false
3319 /// 001     1   A >  B
3320 /// 010     2   A == B
3321 /// 011     3   A >= B
3322 /// 100     4   A <  B
3323 /// 101     5   A != B
3324 /// 110     6   A <= B
3325 /// 111     7   Always true
3326 ///  
3327 static unsigned getICmpCode(const ICmpInst *ICI) {
3328   switch (ICI->getPredicate()) {
3329     // False -> 0
3330   case ICmpInst::ICMP_UGT: return 1;  // 001
3331   case ICmpInst::ICMP_SGT: return 1;  // 001
3332   case ICmpInst::ICMP_EQ:  return 2;  // 010
3333   case ICmpInst::ICMP_UGE: return 3;  // 011
3334   case ICmpInst::ICMP_SGE: return 3;  // 011
3335   case ICmpInst::ICMP_ULT: return 4;  // 100
3336   case ICmpInst::ICMP_SLT: return 4;  // 100
3337   case ICmpInst::ICMP_NE:  return 5;  // 101
3338   case ICmpInst::ICMP_ULE: return 6;  // 110
3339   case ICmpInst::ICMP_SLE: return 6;  // 110
3340     // True -> 7
3341   default:
3342     llvm_unreachable("Invalid ICmp predicate!");
3343     return 0;
3344   }
3345 }
3346
3347 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3348 /// predicate into a three bit mask. It also returns whether it is an ordered
3349 /// predicate by reference.
3350 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3351   isOrdered = false;
3352   switch (CC) {
3353   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3354   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3355   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3356   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3357   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3358   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3359   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3360   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3361   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3362   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3363   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3364   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3365   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3366   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3367     // True -> 7
3368   default:
3369     // Not expecting FCMP_FALSE and FCMP_TRUE;
3370     llvm_unreachable("Unexpected FCmp predicate!");
3371     return 0;
3372   }
3373 }
3374
3375 /// getICmpValue - This is the complement of getICmpCode, which turns an
3376 /// opcode and two operands into either a constant true or false, or a brand 
3377 /// new ICmp instruction. The sign is passed in to determine which kind
3378 /// of predicate to use in the new icmp instruction.
3379 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3380                            LLVMContext *Context) {
3381   switch (code) {
3382   default: llvm_unreachable("Illegal ICmp code!");
3383   case  0: return ConstantInt::getFalse(*Context);
3384   case  1: 
3385     if (sign)
3386       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3387     else
3388       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3389   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3390   case  3: 
3391     if (sign)
3392       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3393     else
3394       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3395   case  4: 
3396     if (sign)
3397       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3398     else
3399       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3400   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3401   case  6: 
3402     if (sign)
3403       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3404     else
3405       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3406   case  7: return ConstantInt::getTrue(*Context);
3407   }
3408 }
3409
3410 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3411 /// opcode and two operands into either a FCmp instruction. isordered is passed
3412 /// in to determine which kind of predicate to use in the new fcmp instruction.
3413 static Value *getFCmpValue(bool isordered, unsigned code,
3414                            Value *LHS, Value *RHS, LLVMContext *Context) {
3415   switch (code) {
3416   default: llvm_unreachable("Illegal FCmp code!");
3417   case  0:
3418     if (isordered)
3419       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3420     else
3421       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3422   case  1: 
3423     if (isordered)
3424       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3425     else
3426       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3427   case  2: 
3428     if (isordered)
3429       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3430     else
3431       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3432   case  3: 
3433     if (isordered)
3434       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3435     else
3436       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3437   case  4: 
3438     if (isordered)
3439       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3440     else
3441       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3442   case  5: 
3443     if (isordered)
3444       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3445     else
3446       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3447   case  6: 
3448     if (isordered)
3449       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3450     else
3451       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3452   case  7: return ConstantInt::getTrue(*Context);
3453   }
3454 }
3455
3456 /// PredicatesFoldable - Return true if both predicates match sign or if at
3457 /// least one of them is an equality comparison (which is signless).
3458 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3459   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3460          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3461          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3462 }
3463
3464 namespace { 
3465 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3466 struct FoldICmpLogical {
3467   InstCombiner &IC;
3468   Value *LHS, *RHS;
3469   ICmpInst::Predicate pred;
3470   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3471     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3472       pred(ICI->getPredicate()) {}
3473   bool shouldApply(Value *V) const {
3474     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3475       if (PredicatesFoldable(pred, ICI->getPredicate()))
3476         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3477                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3478     return false;
3479   }
3480   Instruction *apply(Instruction &Log) const {
3481     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3482     if (ICI->getOperand(0) != LHS) {
3483       assert(ICI->getOperand(1) == LHS);
3484       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3485     }
3486
3487     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3488     unsigned LHSCode = getICmpCode(ICI);
3489     unsigned RHSCode = getICmpCode(RHSICI);
3490     unsigned Code;
3491     switch (Log.getOpcode()) {
3492     case Instruction::And: Code = LHSCode & RHSCode; break;
3493     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3494     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3495     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3496     }
3497
3498     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3499                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3500       
3501     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3502     if (Instruction *I = dyn_cast<Instruction>(RV))
3503       return I;
3504     // Otherwise, it's a constant boolean value...
3505     return IC.ReplaceInstUsesWith(Log, RV);
3506   }
3507 };
3508 } // end anonymous namespace
3509
3510 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3511 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3512 // guaranteed to be a binary operator.
3513 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3514                                     ConstantInt *OpRHS,
3515                                     ConstantInt *AndRHS,
3516                                     BinaryOperator &TheAnd) {
3517   Value *X = Op->getOperand(0);
3518   Constant *Together = 0;
3519   if (!Op->isShift())
3520     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3521
3522   switch (Op->getOpcode()) {
3523   case Instruction::Xor:
3524     if (Op->hasOneUse()) {
3525       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3526       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3527       InsertNewInstBefore(And, TheAnd);
3528       And->takeName(Op);
3529       return BinaryOperator::CreateXor(And, Together);
3530     }
3531     break;
3532   case Instruction::Or:
3533     if (Together == AndRHS) // (X | C) & C --> C
3534       return ReplaceInstUsesWith(TheAnd, AndRHS);
3535
3536     if (Op->hasOneUse() && Together != OpRHS) {
3537       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3538       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3539       InsertNewInstBefore(Or, TheAnd);
3540       Or->takeName(Op);
3541       return BinaryOperator::CreateAnd(Or, AndRHS);
3542     }
3543     break;
3544   case Instruction::Add:
3545     if (Op->hasOneUse()) {
3546       // Adding a one to a single bit bit-field should be turned into an XOR
3547       // of the bit.  First thing to check is to see if this AND is with a
3548       // single bit constant.
3549       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3550
3551       // If there is only one bit set...
3552       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3553         // Ok, at this point, we know that we are masking the result of the
3554         // ADD down to exactly one bit.  If the constant we are adding has
3555         // no bits set below this bit, then we can eliminate the ADD.
3556         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3557
3558         // Check to see if any bits below the one bit set in AndRHSV are set.
3559         if ((AddRHS & (AndRHSV-1)) == 0) {
3560           // If not, the only thing that can effect the output of the AND is
3561           // the bit specified by AndRHSV.  If that bit is set, the effect of
3562           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3563           // no effect.
3564           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3565             TheAnd.setOperand(0, X);
3566             return &TheAnd;
3567           } else {
3568             // Pull the XOR out of the AND.
3569             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3570             InsertNewInstBefore(NewAnd, TheAnd);
3571             NewAnd->takeName(Op);
3572             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3573           }
3574         }
3575       }
3576     }
3577     break;
3578
3579   case Instruction::Shl: {
3580     // We know that the AND will not produce any of the bits shifted in, so if
3581     // the anded constant includes them, clear them now!
3582     //
3583     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3584     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3585     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3586     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3587
3588     if (CI->getValue() == ShlMask) { 
3589     // Masking out bits that the shift already masks
3590       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3591     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3592       TheAnd.setOperand(1, CI);
3593       return &TheAnd;
3594     }
3595     break;
3596   }
3597   case Instruction::LShr:
3598   {
3599     // We know that the AND will not produce any of the bits shifted in, so if
3600     // the anded constant includes them, clear them now!  This only applies to
3601     // unsigned shifts, because a signed shr may bring in set bits!
3602     //
3603     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3604     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3605     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3606     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3607
3608     if (CI->getValue() == ShrMask) {   
3609     // Masking out bits that the shift already masks.
3610       return ReplaceInstUsesWith(TheAnd, Op);
3611     } else if (CI != AndRHS) {
3612       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3613       return &TheAnd;
3614     }
3615     break;
3616   }
3617   case Instruction::AShr:
3618     // Signed shr.
3619     // See if this is shifting in some sign extension, then masking it out
3620     // with an and.
3621     if (Op->hasOneUse()) {
3622       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3623       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3624       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3625       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3626       if (C == AndRHS) {          // Masking out bits shifted in.
3627         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3628         // Make the argument unsigned.
3629         Value *ShVal = Op->getOperand(0);
3630         ShVal = InsertNewInstBefore(
3631             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3632                                    Op->getName()), TheAnd);
3633         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3634       }
3635     }
3636     break;
3637   }
3638   return 0;
3639 }
3640
3641
3642 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3643 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3644 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3645 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3646 /// insert new instructions.
3647 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3648                                            bool isSigned, bool Inside, 
3649                                            Instruction &IB) {
3650   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3651             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3652          "Lo is not <= Hi in range emission code!");
3653     
3654   if (Inside) {
3655     if (Lo == Hi)  // Trivially false.
3656       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3657
3658     // V >= Min && V < Hi --> V < Hi
3659     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3660       ICmpInst::Predicate pred = (isSigned ? 
3661         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3662       return new ICmpInst(pred, V, Hi);
3663     }
3664
3665     // Emit V-Lo <u Hi-Lo
3666     Constant *NegLo = ConstantExpr::getNeg(Lo);
3667     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3668     InsertNewInstBefore(Add, IB);
3669     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3670     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3671   }
3672
3673   if (Lo == Hi)  // Trivially true.
3674     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3675
3676   // V < Min || V >= Hi -> V > Hi-1
3677   Hi = SubOne(cast<ConstantInt>(Hi));
3678   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3679     ICmpInst::Predicate pred = (isSigned ? 
3680         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3681     return new ICmpInst(pred, V, Hi);
3682   }
3683
3684   // Emit V-Lo >u Hi-1-Lo
3685   // Note that Hi has already had one subtracted from it, above.
3686   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3687   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3688   InsertNewInstBefore(Add, IB);
3689   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3690   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3691 }
3692
3693 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3694 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3695 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3696 // not, since all 1s are not contiguous.
3697 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3698   const APInt& V = Val->getValue();
3699   uint32_t BitWidth = Val->getType()->getBitWidth();
3700   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3701
3702   // look for the first zero bit after the run of ones
3703   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3704   // look for the first non-zero bit
3705   ME = V.getActiveBits(); 
3706   return true;
3707 }
3708
3709 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3710 /// where isSub determines whether the operator is a sub.  If we can fold one of
3711 /// the following xforms:
3712 /// 
3713 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3714 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3715 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3716 ///
3717 /// return (A +/- B).
3718 ///
3719 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3720                                         ConstantInt *Mask, bool isSub,
3721                                         Instruction &I) {
3722   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3723   if (!LHSI || LHSI->getNumOperands() != 2 ||
3724       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3725
3726   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3727
3728   switch (LHSI->getOpcode()) {
3729   default: return 0;
3730   case Instruction::And:
3731     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3732       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3733       if ((Mask->getValue().countLeadingZeros() + 
3734            Mask->getValue().countPopulation()) == 
3735           Mask->getValue().getBitWidth())
3736         break;
3737
3738       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3739       // part, we don't need any explicit masks to take them out of A.  If that
3740       // is all N is, ignore it.
3741       uint32_t MB = 0, ME = 0;
3742       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3743         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3744         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3745         if (MaskedValueIsZero(RHS, Mask))
3746           break;
3747       }
3748     }
3749     return 0;
3750   case Instruction::Or:
3751   case Instruction::Xor:
3752     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3753     if ((Mask->getValue().countLeadingZeros() + 
3754          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3755         && ConstantExpr::getAnd(N, Mask)->isNullValue())
3756       break;
3757     return 0;
3758   }
3759   
3760   Instruction *New;
3761   if (isSub)
3762     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3763   else
3764     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3765   return InsertNewInstBefore(New, I);
3766 }
3767
3768 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3769 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3770                                           ICmpInst *LHS, ICmpInst *RHS) {
3771   Value *Val, *Val2;
3772   ConstantInt *LHSCst, *RHSCst;
3773   ICmpInst::Predicate LHSCC, RHSCC;
3774   
3775   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3776   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3777                          m_ConstantInt(LHSCst))) ||
3778       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3779                          m_ConstantInt(RHSCst))))
3780     return 0;
3781   
3782   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3783   // where C is a power of 2
3784   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3785       LHSCst->getValue().isPowerOf2()) {
3786     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3787     InsertNewInstBefore(NewOr, I);
3788     return new ICmpInst(LHSCC, NewOr, LHSCst);
3789   }
3790   
3791   // From here on, we only handle:
3792   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3793   if (Val != Val2) return 0;
3794   
3795   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3796   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3797       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3798       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3799       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3800     return 0;
3801   
3802   // We can't fold (ugt x, C) & (sgt x, C2).
3803   if (!PredicatesFoldable(LHSCC, RHSCC))
3804     return 0;
3805     
3806   // Ensure that the larger constant is on the RHS.
3807   bool ShouldSwap;
3808   if (ICmpInst::isSignedPredicate(LHSCC) ||
3809       (ICmpInst::isEquality(LHSCC) && 
3810        ICmpInst::isSignedPredicate(RHSCC)))
3811     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3812   else
3813     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3814     
3815   if (ShouldSwap) {
3816     std::swap(LHS, RHS);
3817     std::swap(LHSCst, RHSCst);
3818     std::swap(LHSCC, RHSCC);
3819   }
3820
3821   // At this point, we know we have have two icmp instructions
3822   // comparing a value against two constants and and'ing the result
3823   // together.  Because of the above check, we know that we only have
3824   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3825   // (from the FoldICmpLogical check above), that the two constants 
3826   // are not equal and that the larger constant is on the RHS
3827   assert(LHSCst != RHSCst && "Compares not folded above?");
3828
3829   switch (LHSCC) {
3830   default: llvm_unreachable("Unknown integer condition code!");
3831   case ICmpInst::ICMP_EQ:
3832     switch (RHSCC) {
3833     default: llvm_unreachable("Unknown integer condition code!");
3834     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3835     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3836     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3837       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3838     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3839     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3840     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3841       return ReplaceInstUsesWith(I, LHS);
3842     }
3843   case ICmpInst::ICMP_NE:
3844     switch (RHSCC) {
3845     default: llvm_unreachable("Unknown integer condition code!");
3846     case ICmpInst::ICMP_ULT:
3847       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3848         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3849       break;                        // (X != 13 & X u< 15) -> no change
3850     case ICmpInst::ICMP_SLT:
3851       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3852         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3853       break;                        // (X != 13 & X s< 15) -> no change
3854     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3855     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3856     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3857       return ReplaceInstUsesWith(I, RHS);
3858     case ICmpInst::ICMP_NE:
3859       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3860         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3861         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3862                                                      Val->getName()+".off");
3863         InsertNewInstBefore(Add, I);
3864         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3865                             ConstantInt::get(Add->getType(), 1));
3866       }
3867       break;                        // (X != 13 & X != 15) -> no change
3868     }
3869     break;
3870   case ICmpInst::ICMP_ULT:
3871     switch (RHSCC) {
3872     default: llvm_unreachable("Unknown integer condition code!");
3873     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3874     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3875       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3876     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3877       break;
3878     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3879     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3880       return ReplaceInstUsesWith(I, LHS);
3881     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3882       break;
3883     }
3884     break;
3885   case ICmpInst::ICMP_SLT:
3886     switch (RHSCC) {
3887     default: llvm_unreachable("Unknown integer condition code!");
3888     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3889     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3890       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3891     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3892       break;
3893     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3894     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3895       return ReplaceInstUsesWith(I, LHS);
3896     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3897       break;
3898     }
3899     break;
3900   case ICmpInst::ICMP_UGT:
3901     switch (RHSCC) {
3902     default: llvm_unreachable("Unknown integer condition code!");
3903     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3904     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3905       return ReplaceInstUsesWith(I, RHS);
3906     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3907       break;
3908     case ICmpInst::ICMP_NE:
3909       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3910         return new ICmpInst(LHSCC, Val, RHSCst);
3911       break;                        // (X u> 13 & X != 15) -> no change
3912     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3913       return InsertRangeTest(Val, AddOne(LHSCst),
3914                              RHSCst, false, true, I);
3915     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3916       break;
3917     }
3918     break;
3919   case ICmpInst::ICMP_SGT:
3920     switch (RHSCC) {
3921     default: llvm_unreachable("Unknown integer condition code!");
3922     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3923     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3924       return ReplaceInstUsesWith(I, RHS);
3925     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3926       break;
3927     case ICmpInst::ICMP_NE:
3928       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3929         return new ICmpInst(LHSCC, Val, RHSCst);
3930       break;                        // (X s> 13 & X != 15) -> no change
3931     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3932       return InsertRangeTest(Val, AddOne(LHSCst),
3933                              RHSCst, true, true, I);
3934     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3935       break;
3936     }
3937     break;
3938   }
3939  
3940   return 0;
3941 }
3942
3943 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3944                                           FCmpInst *RHS) {
3945   
3946   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3947       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3948     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3949     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3950       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3951         // If either of the constants are nans, then the whole thing returns
3952         // false.
3953         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3954           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3955         return new FCmpInst(FCmpInst::FCMP_ORD,
3956                             LHS->getOperand(0), RHS->getOperand(0));
3957       }
3958     
3959     // Handle vector zeros.  This occurs because the canonical form of
3960     // "fcmp ord x,x" is "fcmp ord x, 0".
3961     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3962         isa<ConstantAggregateZero>(RHS->getOperand(1)))
3963       return new FCmpInst(FCmpInst::FCMP_ORD,
3964                           LHS->getOperand(0), RHS->getOperand(0));
3965     return 0;
3966   }
3967   
3968   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3969   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3970   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3971   
3972   
3973   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3974     // Swap RHS operands to match LHS.
3975     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3976     std::swap(Op1LHS, Op1RHS);
3977   }
3978   
3979   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3980     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3981     if (Op0CC == Op1CC)
3982       return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3983     
3984     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
3985       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3986     if (Op0CC == FCmpInst::FCMP_TRUE)
3987       return ReplaceInstUsesWith(I, RHS);
3988     if (Op1CC == FCmpInst::FCMP_TRUE)
3989       return ReplaceInstUsesWith(I, LHS);
3990     
3991     bool Op0Ordered;
3992     bool Op1Ordered;
3993     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3994     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3995     if (Op1Pred == 0) {
3996       std::swap(LHS, RHS);
3997       std::swap(Op0Pred, Op1Pred);
3998       std::swap(Op0Ordered, Op1Ordered);
3999     }
4000     if (Op0Pred == 0) {
4001       // uno && ueq -> uno && (uno || eq) -> ueq
4002       // ord && olt -> ord && (ord && lt) -> olt
4003       if (Op0Ordered == Op1Ordered)
4004         return ReplaceInstUsesWith(I, RHS);
4005       
4006       // uno && oeq -> uno && (ord && eq) -> false
4007       // uno && ord -> false
4008       if (!Op0Ordered)
4009         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4010       // ord && ueq -> ord && (uno || eq) -> oeq
4011       return cast<Instruction>(getFCmpValue(true, Op1Pred,
4012                                             Op0LHS, Op0RHS, Context));
4013     }
4014   }
4015
4016   return 0;
4017 }
4018
4019
4020 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4021   bool Changed = SimplifyCommutative(I);
4022   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4023
4024   if (isa<UndefValue>(Op1))                         // X & undef -> 0
4025     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4026
4027   // and X, X = X
4028   if (Op0 == Op1)
4029     return ReplaceInstUsesWith(I, Op1);
4030
4031   // See if we can simplify any instructions used by the instruction whose sole 
4032   // purpose is to compute bits we don't care about.
4033   if (SimplifyDemandedInstructionBits(I))
4034     return &I;
4035   if (isa<VectorType>(I.getType())) {
4036     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4037       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
4038         return ReplaceInstUsesWith(I, I.getOperand(0));
4039     } else if (isa<ConstantAggregateZero>(Op1)) {
4040       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4041     }
4042   }
4043
4044   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4045     const APInt& AndRHSMask = AndRHS->getValue();
4046     APInt NotAndRHS(~AndRHSMask);
4047
4048     // Optimize a variety of ((val OP C1) & C2) combinations...
4049     if (isa<BinaryOperator>(Op0)) {
4050       Instruction *Op0I = cast<Instruction>(Op0);
4051       Value *Op0LHS = Op0I->getOperand(0);
4052       Value *Op0RHS = Op0I->getOperand(1);
4053       switch (Op0I->getOpcode()) {
4054       case Instruction::Xor:
4055       case Instruction::Or:
4056         // If the mask is only needed on one incoming arm, push it up.
4057         if (Op0I->hasOneUse()) {
4058           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4059             // Not masking anything out for the LHS, move to RHS.
4060             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4061                                                    Op0RHS->getName()+".masked");
4062             InsertNewInstBefore(NewRHS, I);
4063             return BinaryOperator::Create(
4064                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4065           }
4066           if (!isa<Constant>(Op0RHS) &&
4067               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4068             // Not masking anything out for the RHS, move to LHS.
4069             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4070                                                    Op0LHS->getName()+".masked");
4071             InsertNewInstBefore(NewLHS, I);
4072             return BinaryOperator::Create(
4073                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4074           }
4075         }
4076
4077         break;
4078       case Instruction::Add:
4079         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4080         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4081         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4082         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4083           return BinaryOperator::CreateAnd(V, AndRHS);
4084         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4085           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4086         break;
4087
4088       case Instruction::Sub:
4089         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4090         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4091         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4092         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4093           return BinaryOperator::CreateAnd(V, AndRHS);
4094
4095         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4096         // has 1's for all bits that the subtraction with A might affect.
4097         if (Op0I->hasOneUse()) {
4098           uint32_t BitWidth = AndRHSMask.getBitWidth();
4099           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4100           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4101
4102           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4103           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4104               MaskedValueIsZero(Op0LHS, Mask)) {
4105             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4106             InsertNewInstBefore(NewNeg, I);
4107             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4108           }
4109         }
4110         break;
4111
4112       case Instruction::Shl:
4113       case Instruction::LShr:
4114         // (1 << x) & 1 --> zext(x == 0)
4115         // (1 >> x) & 1 --> zext(x == 0)
4116         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4117           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ,
4118                                     Op0RHS, Constant::getNullValue(I.getType()));
4119           InsertNewInstBefore(NewICmp, I);
4120           return new ZExtInst(NewICmp, I.getType());
4121         }
4122         break;
4123       }
4124
4125       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4126         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4127           return Res;
4128     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4129       // If this is an integer truncation or change from signed-to-unsigned, and
4130       // if the source is an and/or with immediate, transform it.  This
4131       // frequently occurs for bitfield accesses.
4132       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4133         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4134             CastOp->getNumOperands() == 2)
4135           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4136             if (CastOp->getOpcode() == Instruction::And) {
4137               // Change: and (cast (and X, C1) to T), C2
4138               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4139               // This will fold the two constants together, which may allow 
4140               // other simplifications.
4141               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4142                 CastOp->getOperand(0), I.getType(), 
4143                 CastOp->getName()+".shrunk");
4144               NewCast = InsertNewInstBefore(NewCast, I);
4145               // trunc_or_bitcast(C1)&C2
4146               Constant *C3 =
4147                       ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4148               C3 = ConstantExpr::getAnd(C3, AndRHS);
4149               return BinaryOperator::CreateAnd(NewCast, C3);
4150             } else if (CastOp->getOpcode() == Instruction::Or) {
4151               // Change: and (cast (or X, C1) to T), C2
4152               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4153               Constant *C3 =
4154                       ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4155               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4156                 // trunc(C1)&C2
4157                 return ReplaceInstUsesWith(I, AndRHS);
4158             }
4159           }
4160       }
4161     }
4162
4163     // Try to fold constant and into select arguments.
4164     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4165       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4166         return R;
4167     if (isa<PHINode>(Op0))
4168       if (Instruction *NV = FoldOpIntoPhi(I))
4169         return NV;
4170   }
4171
4172   Value *Op0NotVal = dyn_castNotVal(Op0);
4173   Value *Op1NotVal = dyn_castNotVal(Op1);
4174
4175   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4176     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4177
4178   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4179   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4180     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4181                                                I.getName()+".demorgan");
4182     InsertNewInstBefore(Or, I);
4183     return BinaryOperator::CreateNot(Or);
4184   }
4185   
4186   {
4187     Value *A = 0, *B = 0, *C = 0, *D = 0;
4188     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4189       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4190         return ReplaceInstUsesWith(I, Op1);
4191     
4192       // (A|B) & ~(A&B) -> A^B
4193       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4194         if ((A == C && B == D) || (A == D && B == C))
4195           return BinaryOperator::CreateXor(A, B);
4196       }
4197     }
4198     
4199     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4200       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4201         return ReplaceInstUsesWith(I, Op0);
4202
4203       // ~(A&B) & (A|B) -> A^B
4204       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4205         if ((A == C && B == D) || (A == D && B == C))
4206           return BinaryOperator::CreateXor(A, B);
4207       }
4208     }
4209     
4210     if (Op0->hasOneUse() &&
4211         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4212       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4213         I.swapOperands();     // Simplify below
4214         std::swap(Op0, Op1);
4215       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4216         cast<BinaryOperator>(Op0)->swapOperands();
4217         I.swapOperands();     // Simplify below
4218         std::swap(Op0, Op1);
4219       }
4220     }
4221
4222     if (Op1->hasOneUse() &&
4223         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4224       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4225         cast<BinaryOperator>(Op1)->swapOperands();
4226         std::swap(A, B);
4227       }
4228       if (A == Op0) {                                // A&(A^B) -> A & ~B
4229         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4230         InsertNewInstBefore(NotB, I);
4231         return BinaryOperator::CreateAnd(A, NotB);
4232       }
4233     }
4234
4235     // (A&((~A)|B)) -> A&B
4236     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4237         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4238       return BinaryOperator::CreateAnd(A, Op1);
4239     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4240         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4241       return BinaryOperator::CreateAnd(A, Op0);
4242   }
4243   
4244   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4245     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4246     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4247       return R;
4248
4249     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4250       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4251         return Res;
4252   }
4253
4254   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4255   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4256     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4257       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4258         const Type *SrcTy = Op0C->getOperand(0)->getType();
4259         if (SrcTy == Op1C->getOperand(0)->getType() &&
4260             SrcTy->isIntOrIntVector() &&
4261             // Only do this if the casts both really cause code to be generated.
4262             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4263                               I.getType(), TD) &&
4264             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4265                               I.getType(), TD)) {
4266           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4267                                                          Op1C->getOperand(0),
4268                                                          I.getName());
4269           InsertNewInstBefore(NewOp, I);
4270           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4271         }
4272       }
4273     
4274   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4275   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4276     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4277       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4278           SI0->getOperand(1) == SI1->getOperand(1) &&
4279           (SI0->hasOneUse() || SI1->hasOneUse())) {
4280         Instruction *NewOp =
4281           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4282                                                         SI1->getOperand(0),
4283                                                         SI0->getName()), I);
4284         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4285                                       SI1->getOperand(1));
4286       }
4287   }
4288
4289   // If and'ing two fcmp, try combine them into one.
4290   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4291     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4292       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4293         return Res;
4294   }
4295
4296   return Changed ? &I : 0;
4297 }
4298
4299 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4300 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4301 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4302 /// the expression came from the corresponding "byte swapped" byte in some other
4303 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4304 /// we know that the expression deposits the low byte of %X into the high byte
4305 /// of the bswap result and that all other bytes are zero.  This expression is
4306 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4307 /// match.
4308 ///
4309 /// This function returns true if the match was unsuccessful and false if so.
4310 /// On entry to the function the "OverallLeftShift" is a signed integer value
4311 /// indicating the number of bytes that the subexpression is later shifted.  For
4312 /// example, if the expression is later right shifted by 16 bits, the
4313 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4314 /// byte of ByteValues is actually being set.
4315 ///
4316 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4317 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4318 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4319 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4320 /// always in the local (OverallLeftShift) coordinate space.
4321 ///
4322 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4323                               SmallVector<Value*, 8> &ByteValues) {
4324   if (Instruction *I = dyn_cast<Instruction>(V)) {
4325     // If this is an or instruction, it may be an inner node of the bswap.
4326     if (I->getOpcode() == Instruction::Or) {
4327       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4328                                ByteValues) ||
4329              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4330                                ByteValues);
4331     }
4332   
4333     // If this is a logical shift by a constant multiple of 8, recurse with
4334     // OverallLeftShift and ByteMask adjusted.
4335     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4336       unsigned ShAmt = 
4337         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4338       // Ensure the shift amount is defined and of a byte value.
4339       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4340         return true;
4341
4342       unsigned ByteShift = ShAmt >> 3;
4343       if (I->getOpcode() == Instruction::Shl) {
4344         // X << 2 -> collect(X, +2)
4345         OverallLeftShift += ByteShift;
4346         ByteMask >>= ByteShift;
4347       } else {
4348         // X >>u 2 -> collect(X, -2)
4349         OverallLeftShift -= ByteShift;
4350         ByteMask <<= ByteShift;
4351         ByteMask &= (~0U >> (32-ByteValues.size()));
4352       }
4353
4354       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4355       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4356
4357       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4358                                ByteValues);
4359     }
4360
4361     // If this is a logical 'and' with a mask that clears bytes, clear the
4362     // corresponding bytes in ByteMask.
4363     if (I->getOpcode() == Instruction::And &&
4364         isa<ConstantInt>(I->getOperand(1))) {
4365       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4366       unsigned NumBytes = ByteValues.size();
4367       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4368       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4369       
4370       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4371         // If this byte is masked out by a later operation, we don't care what
4372         // the and mask is.
4373         if ((ByteMask & (1 << i)) == 0)
4374           continue;
4375         
4376         // If the AndMask is all zeros for this byte, clear the bit.
4377         APInt MaskB = AndMask & Byte;
4378         if (MaskB == 0) {
4379           ByteMask &= ~(1U << i);
4380           continue;
4381         }
4382         
4383         // If the AndMask is not all ones for this byte, it's not a bytezap.
4384         if (MaskB != Byte)
4385           return true;
4386
4387         // Otherwise, this byte is kept.
4388       }
4389
4390       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4391                                ByteValues);
4392     }
4393   }
4394   
4395   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4396   // the input value to the bswap.  Some observations: 1) if more than one byte
4397   // is demanded from this input, then it could not be successfully assembled
4398   // into a byteswap.  At least one of the two bytes would not be aligned with
4399   // their ultimate destination.
4400   if (!isPowerOf2_32(ByteMask)) return true;
4401   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4402   
4403   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4404   // is demanded, it needs to go into byte 0 of the result.  This means that the
4405   // byte needs to be shifted until it lands in the right byte bucket.  The
4406   // shift amount depends on the position: if the byte is coming from the high
4407   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4408   // low part, it must be shifted left.
4409   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4410   if (InputByteNo < ByteValues.size()/2) {
4411     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4412       return true;
4413   } else {
4414     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4415       return true;
4416   }
4417   
4418   // If the destination byte value is already defined, the values are or'd
4419   // together, which isn't a bswap (unless it's an or of the same bits).
4420   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4421     return true;
4422   ByteValues[DestByteNo] = V;
4423   return false;
4424 }
4425
4426 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4427 /// If so, insert the new bswap intrinsic and return it.
4428 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4429   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4430   if (!ITy || ITy->getBitWidth() % 16 || 
4431       // ByteMask only allows up to 32-byte values.
4432       ITy->getBitWidth() > 32*8) 
4433     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4434   
4435   /// ByteValues - For each byte of the result, we keep track of which value
4436   /// defines each byte.
4437   SmallVector<Value*, 8> ByteValues;
4438   ByteValues.resize(ITy->getBitWidth()/8);
4439     
4440   // Try to find all the pieces corresponding to the bswap.
4441   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4442   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4443     return 0;
4444   
4445   // Check to see if all of the bytes come from the same value.
4446   Value *V = ByteValues[0];
4447   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4448   
4449   // Check to make sure that all of the bytes come from the same value.
4450   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4451     if (ByteValues[i] != V)
4452       return 0;
4453   const Type *Tys[] = { ITy };
4454   Module *M = I.getParent()->getParent()->getParent();
4455   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4456   return CallInst::Create(F, V);
4457 }
4458
4459 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4460 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4461 /// we can simplify this expression to "cond ? C : D or B".
4462 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4463                                          Value *C, Value *D,
4464                                          LLVMContext *Context) {
4465   // If A is not a select of -1/0, this cannot match.
4466   Value *Cond = 0;
4467   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4468     return 0;
4469
4470   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4471   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4472     return SelectInst::Create(Cond, C, B);
4473   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4474     return SelectInst::Create(Cond, C, B);
4475   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4476   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4477     return SelectInst::Create(Cond, C, D);
4478   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4479     return SelectInst::Create(Cond, C, D);
4480   return 0;
4481 }
4482
4483 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4484 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4485                                          ICmpInst *LHS, ICmpInst *RHS) {
4486   Value *Val, *Val2;
4487   ConstantInt *LHSCst, *RHSCst;
4488   ICmpInst::Predicate LHSCC, RHSCC;
4489   
4490   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4491   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4492              m_ConstantInt(LHSCst))) ||
4493       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4494              m_ConstantInt(RHSCst))))
4495     return 0;
4496   
4497   // From here on, we only handle:
4498   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4499   if (Val != Val2) return 0;
4500   
4501   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4502   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4503       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4504       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4505       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4506     return 0;
4507   
4508   // We can't fold (ugt x, C) | (sgt x, C2).
4509   if (!PredicatesFoldable(LHSCC, RHSCC))
4510     return 0;
4511   
4512   // Ensure that the larger constant is on the RHS.
4513   bool ShouldSwap;
4514   if (ICmpInst::isSignedPredicate(LHSCC) ||
4515       (ICmpInst::isEquality(LHSCC) && 
4516        ICmpInst::isSignedPredicate(RHSCC)))
4517     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4518   else
4519     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4520   
4521   if (ShouldSwap) {
4522     std::swap(LHS, RHS);
4523     std::swap(LHSCst, RHSCst);
4524     std::swap(LHSCC, RHSCC);
4525   }
4526   
4527   // At this point, we know we have have two icmp instructions
4528   // comparing a value against two constants and or'ing the result
4529   // together.  Because of the above check, we know that we only have
4530   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4531   // FoldICmpLogical check above), that the two constants are not
4532   // equal.
4533   assert(LHSCst != RHSCst && "Compares not folded above?");
4534
4535   switch (LHSCC) {
4536   default: llvm_unreachable("Unknown integer condition code!");
4537   case ICmpInst::ICMP_EQ:
4538     switch (RHSCC) {
4539     default: llvm_unreachable("Unknown integer condition code!");
4540     case ICmpInst::ICMP_EQ:
4541       if (LHSCst == SubOne(RHSCst)) {
4542         // (X == 13 | X == 14) -> X-13 <u 2
4543         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4544         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4545                                                      Val->getName()+".off");
4546         InsertNewInstBefore(Add, I);
4547         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4548         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4549       }
4550       break;                         // (X == 13 | X == 15) -> no change
4551     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4552     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4553       break;
4554     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4555     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4556     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4557       return ReplaceInstUsesWith(I, RHS);
4558     }
4559     break;
4560   case ICmpInst::ICMP_NE:
4561     switch (RHSCC) {
4562     default: llvm_unreachable("Unknown integer condition code!");
4563     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4564     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4565     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4566       return ReplaceInstUsesWith(I, LHS);
4567     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4568     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4569     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4570       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4571     }
4572     break;
4573   case ICmpInst::ICMP_ULT:
4574     switch (RHSCC) {
4575     default: llvm_unreachable("Unknown integer condition code!");
4576     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4577       break;
4578     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4579       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4580       // this can cause overflow.
4581       if (RHSCst->isMaxValue(false))
4582         return ReplaceInstUsesWith(I, LHS);
4583       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4584                              false, false, I);
4585     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4586       break;
4587     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4588     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4589       return ReplaceInstUsesWith(I, RHS);
4590     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4591       break;
4592     }
4593     break;
4594   case ICmpInst::ICMP_SLT:
4595     switch (RHSCC) {
4596     default: llvm_unreachable("Unknown integer condition code!");
4597     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4598       break;
4599     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4600       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4601       // this can cause overflow.
4602       if (RHSCst->isMaxValue(true))
4603         return ReplaceInstUsesWith(I, LHS);
4604       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4605                              true, false, I);
4606     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4607       break;
4608     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4609     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4610       return ReplaceInstUsesWith(I, RHS);
4611     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4612       break;
4613     }
4614     break;
4615   case ICmpInst::ICMP_UGT:
4616     switch (RHSCC) {
4617     default: llvm_unreachable("Unknown integer condition code!");
4618     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4619     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4620       return ReplaceInstUsesWith(I, LHS);
4621     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4622       break;
4623     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4624     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4625       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4626     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4627       break;
4628     }
4629     break;
4630   case ICmpInst::ICMP_SGT:
4631     switch (RHSCC) {
4632     default: llvm_unreachable("Unknown integer condition code!");
4633     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4634     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4635       return ReplaceInstUsesWith(I, LHS);
4636     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4637       break;
4638     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4639     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4640       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4641     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4642       break;
4643     }
4644     break;
4645   }
4646   return 0;
4647 }
4648
4649 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4650                                          FCmpInst *RHS) {
4651   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4652       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4653       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4654     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4655       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4656         // If either of the constants are nans, then the whole thing returns
4657         // true.
4658         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4659           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4660         
4661         // Otherwise, no need to compare the two constants, compare the
4662         // rest.
4663         return new FCmpInst(FCmpInst::FCMP_UNO,
4664                             LHS->getOperand(0), RHS->getOperand(0));
4665       }
4666     
4667     // Handle vector zeros.  This occurs because the canonical form of
4668     // "fcmp uno x,x" is "fcmp uno x, 0".
4669     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4670         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4671       return new FCmpInst(FCmpInst::FCMP_UNO,
4672                           LHS->getOperand(0), RHS->getOperand(0));
4673     
4674     return 0;
4675   }
4676   
4677   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4678   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4679   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4680   
4681   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4682     // Swap RHS operands to match LHS.
4683     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4684     std::swap(Op1LHS, Op1RHS);
4685   }
4686   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4687     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4688     if (Op0CC == Op1CC)
4689       return new FCmpInst((FCmpInst::Predicate)Op0CC,
4690                           Op0LHS, Op0RHS);
4691     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4692       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4693     if (Op0CC == FCmpInst::FCMP_FALSE)
4694       return ReplaceInstUsesWith(I, RHS);
4695     if (Op1CC == FCmpInst::FCMP_FALSE)
4696       return ReplaceInstUsesWith(I, LHS);
4697     bool Op0Ordered;
4698     bool Op1Ordered;
4699     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4700     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4701     if (Op0Ordered == Op1Ordered) {
4702       // If both are ordered or unordered, return a new fcmp with
4703       // or'ed predicates.
4704       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4705                                Op0LHS, Op0RHS, Context);
4706       if (Instruction *I = dyn_cast<Instruction>(RV))
4707         return I;
4708       // Otherwise, it's a constant boolean value...
4709       return ReplaceInstUsesWith(I, RV);
4710     }
4711   }
4712   return 0;
4713 }
4714
4715 /// FoldOrWithConstants - This helper function folds:
4716 ///
4717 ///     ((A | B) & C1) | (B & C2)
4718 ///
4719 /// into:
4720 /// 
4721 ///     (A & C1) | B
4722 ///
4723 /// when the XOR of the two constants is "all ones" (-1).
4724 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4725                                                Value *A, Value *B, Value *C) {
4726   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4727   if (!CI1) return 0;
4728
4729   Value *V1 = 0;
4730   ConstantInt *CI2 = 0;
4731   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4732
4733   APInt Xor = CI1->getValue() ^ CI2->getValue();
4734   if (!Xor.isAllOnesValue()) return 0;
4735
4736   if (V1 == A || V1 == B) {
4737     Instruction *NewOp =
4738       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4739     return BinaryOperator::CreateOr(NewOp, V1);
4740   }
4741
4742   return 0;
4743 }
4744
4745 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4746   bool Changed = SimplifyCommutative(I);
4747   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4748
4749   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4750     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4751
4752   // or X, X = X
4753   if (Op0 == Op1)
4754     return ReplaceInstUsesWith(I, Op0);
4755
4756   // See if we can simplify any instructions used by the instruction whose sole 
4757   // purpose is to compute bits we don't care about.
4758   if (SimplifyDemandedInstructionBits(I))
4759     return &I;
4760   if (isa<VectorType>(I.getType())) {
4761     if (isa<ConstantAggregateZero>(Op1)) {
4762       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4763     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4764       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4765         return ReplaceInstUsesWith(I, I.getOperand(1));
4766     }
4767   }
4768
4769   // or X, -1 == -1
4770   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4771     ConstantInt *C1 = 0; Value *X = 0;
4772     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4773     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
4774         isOnlyUse(Op0)) {
4775       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4776       InsertNewInstBefore(Or, I);
4777       Or->takeName(Op0);
4778       return BinaryOperator::CreateAnd(Or, 
4779                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4780     }
4781
4782     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4783     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
4784         isOnlyUse(Op0)) {
4785       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4786       InsertNewInstBefore(Or, I);
4787       Or->takeName(Op0);
4788       return BinaryOperator::CreateXor(Or,
4789                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4790     }
4791
4792     // Try to fold constant and into select arguments.
4793     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4794       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4795         return R;
4796     if (isa<PHINode>(Op0))
4797       if (Instruction *NV = FoldOpIntoPhi(I))
4798         return NV;
4799   }
4800
4801   Value *A = 0, *B = 0;
4802   ConstantInt *C1 = 0, *C2 = 0;
4803
4804   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4805     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4806       return ReplaceInstUsesWith(I, Op1);
4807   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4808     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4809       return ReplaceInstUsesWith(I, Op0);
4810
4811   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4812   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4813   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4814       match(Op1, m_Or(m_Value(), m_Value())) ||
4815       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4816        match(Op1, m_Shift(m_Value(), m_Value())))) {
4817     if (Instruction *BSwap = MatchBSwap(I))
4818       return BSwap;
4819   }
4820   
4821   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4822   if (Op0->hasOneUse() &&
4823       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4824       MaskedValueIsZero(Op1, C1->getValue())) {
4825     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4826     InsertNewInstBefore(NOr, I);
4827     NOr->takeName(Op0);
4828     return BinaryOperator::CreateXor(NOr, C1);
4829   }
4830
4831   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4832   if (Op1->hasOneUse() &&
4833       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4834       MaskedValueIsZero(Op0, C1->getValue())) {
4835     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4836     InsertNewInstBefore(NOr, I);
4837     NOr->takeName(Op0);
4838     return BinaryOperator::CreateXor(NOr, C1);
4839   }
4840
4841   // (A & C)|(B & D)
4842   Value *C = 0, *D = 0;
4843   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4844       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4845     Value *V1 = 0, *V2 = 0, *V3 = 0;
4846     C1 = dyn_cast<ConstantInt>(C);
4847     C2 = dyn_cast<ConstantInt>(D);
4848     if (C1 && C2) {  // (A & C1)|(B & C2)
4849       // If we have: ((V + N) & C1) | (V & C2)
4850       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4851       // replace with V+N.
4852       if (C1->getValue() == ~C2->getValue()) {
4853         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4854             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4855           // Add commutes, try both ways.
4856           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4857             return ReplaceInstUsesWith(I, A);
4858           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4859             return ReplaceInstUsesWith(I, A);
4860         }
4861         // Or commutes, try both ways.
4862         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4863             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4864           // Add commutes, try both ways.
4865           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4866             return ReplaceInstUsesWith(I, B);
4867           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4868             return ReplaceInstUsesWith(I, B);
4869         }
4870       }
4871       V1 = 0; V2 = 0; V3 = 0;
4872     }
4873     
4874     // Check to see if we have any common things being and'ed.  If so, find the
4875     // terms for V1 & (V2|V3).
4876     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4877       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4878         V1 = A, V2 = C, V3 = D;
4879       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4880         V1 = A, V2 = B, V3 = C;
4881       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4882         V1 = C, V2 = A, V3 = D;
4883       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4884         V1 = C, V2 = A, V3 = B;
4885       
4886       if (V1) {
4887         Value *Or =
4888           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4889         return BinaryOperator::CreateAnd(V1, Or);
4890       }
4891     }
4892
4893     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4894     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4895       return Match;
4896     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4897       return Match;
4898     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4899       return Match;
4900     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4901       return Match;
4902
4903     // ((A&~B)|(~A&B)) -> A^B
4904     if ((match(C, m_Not(m_Specific(D))) &&
4905          match(B, m_Not(m_Specific(A)))))
4906       return BinaryOperator::CreateXor(A, D);
4907     // ((~B&A)|(~A&B)) -> A^B
4908     if ((match(A, m_Not(m_Specific(D))) &&
4909          match(B, m_Not(m_Specific(C)))))
4910       return BinaryOperator::CreateXor(C, D);
4911     // ((A&~B)|(B&~A)) -> A^B
4912     if ((match(C, m_Not(m_Specific(B))) &&
4913          match(D, m_Not(m_Specific(A)))))
4914       return BinaryOperator::CreateXor(A, B);
4915     // ((~B&A)|(B&~A)) -> A^B
4916     if ((match(A, m_Not(m_Specific(B))) &&
4917          match(D, m_Not(m_Specific(C)))))
4918       return BinaryOperator::CreateXor(C, B);
4919   }
4920   
4921   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4922   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4923     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4924       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4925           SI0->getOperand(1) == SI1->getOperand(1) &&
4926           (SI0->hasOneUse() || SI1->hasOneUse())) {
4927         Instruction *NewOp =
4928         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4929                                                      SI1->getOperand(0),
4930                                                      SI0->getName()), I);
4931         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4932                                       SI1->getOperand(1));
4933       }
4934   }
4935
4936   // ((A|B)&1)|(B&-2) -> (A&1) | B
4937   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4938       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4939     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4940     if (Ret) return Ret;
4941   }
4942   // (B&-2)|((A|B)&1) -> (A&1) | B
4943   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4944       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4945     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4946     if (Ret) return Ret;
4947   }
4948
4949   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4950     if (A == Op1)   // ~A | A == -1
4951       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4952   } else {
4953     A = 0;
4954   }
4955   // Note, A is still live here!
4956   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4957     if (Op0 == B)
4958       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4959
4960     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4961     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4962       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4963                                               I.getName()+".demorgan"), I);
4964       return BinaryOperator::CreateNot(And);
4965     }
4966   }
4967
4968   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4969   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4970     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4971       return R;
4972
4973     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4974       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4975         return Res;
4976   }
4977     
4978   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4979   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4980     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4981       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4982         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4983             !isa<ICmpInst>(Op1C->getOperand(0))) {
4984           const Type *SrcTy = Op0C->getOperand(0)->getType();
4985           if (SrcTy == Op1C->getOperand(0)->getType() &&
4986               SrcTy->isIntOrIntVector() &&
4987               // Only do this if the casts both really cause code to be
4988               // generated.
4989               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4990                                 I.getType(), TD) &&
4991               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4992                                 I.getType(), TD)) {
4993             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4994                                                           Op1C->getOperand(0),
4995                                                           I.getName());
4996             InsertNewInstBefore(NewOp, I);
4997             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4998           }
4999         }
5000       }
5001   }
5002   
5003     
5004   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
5005   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
5006     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5007       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5008         return Res;
5009   }
5010
5011   return Changed ? &I : 0;
5012 }
5013
5014 namespace {
5015
5016 // XorSelf - Implements: X ^ X --> 0
5017 struct XorSelf {
5018   Value *RHS;
5019   XorSelf(Value *rhs) : RHS(rhs) {}
5020   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5021   Instruction *apply(BinaryOperator &Xor) const {
5022     return &Xor;
5023   }
5024 };
5025
5026 }
5027
5028 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5029   bool Changed = SimplifyCommutative(I);
5030   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5031
5032   if (isa<UndefValue>(Op1)) {
5033     if (isa<UndefValue>(Op0))
5034       // Handle undef ^ undef -> 0 special case. This is a common
5035       // idiom (misuse).
5036       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5037     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5038   }
5039
5040   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5041   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5042     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5043     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5044   }
5045   
5046   // See if we can simplify any instructions used by the instruction whose sole 
5047   // purpose is to compute bits we don't care about.
5048   if (SimplifyDemandedInstructionBits(I))
5049     return &I;
5050   if (isa<VectorType>(I.getType()))
5051     if (isa<ConstantAggregateZero>(Op1))
5052       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5053
5054   // Is this a ~ operation?
5055   if (Value *NotOp = dyn_castNotVal(&I)) {
5056     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5057     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5058     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5059       if (Op0I->getOpcode() == Instruction::And || 
5060           Op0I->getOpcode() == Instruction::Or) {
5061         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5062         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5063           Instruction *NotY =
5064             BinaryOperator::CreateNot(Op0I->getOperand(1),
5065                                       Op0I->getOperand(1)->getName()+".not");
5066           InsertNewInstBefore(NotY, I);
5067           if (Op0I->getOpcode() == Instruction::And)
5068             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5069           else
5070             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5071         }
5072       }
5073     }
5074   }
5075   
5076   
5077   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5078     if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
5079       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5080       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5081         return new ICmpInst(ICI->getInversePredicate(),
5082                             ICI->getOperand(0), ICI->getOperand(1));
5083
5084       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5085         return new FCmpInst(FCI->getInversePredicate(),
5086                             FCI->getOperand(0), FCI->getOperand(1));
5087     }
5088
5089     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5090     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5091       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5092         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5093           Instruction::CastOps Opcode = Op0C->getOpcode();
5094           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5095             if (RHS == ConstantExpr::getCast(Opcode, 
5096                                              ConstantInt::getTrue(*Context),
5097                                              Op0C->getDestTy())) {
5098               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5099                                      CI->getOpcode(), CI->getInversePredicate(),
5100                                      CI->getOperand(0), CI->getOperand(1)), I);
5101               NewCI->takeName(CI);
5102               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5103             }
5104           }
5105         }
5106       }
5107     }
5108
5109     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5110       // ~(c-X) == X-c-1 == X+(-c-1)
5111       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5112         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5113           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5114           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5115                                       ConstantInt::get(I.getType(), 1));
5116           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5117         }
5118           
5119       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5120         if (Op0I->getOpcode() == Instruction::Add) {
5121           // ~(X-c) --> (-c-1)-X
5122           if (RHS->isAllOnesValue()) {
5123             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5124             return BinaryOperator::CreateSub(
5125                            ConstantExpr::getSub(NegOp0CI,
5126                                       ConstantInt::get(I.getType(), 1)),
5127                                       Op0I->getOperand(0));
5128           } else if (RHS->getValue().isSignBit()) {
5129             // (X + C) ^ signbit -> (X + C + signbit)
5130             Constant *C = ConstantInt::get(*Context,
5131                                            RHS->getValue() + Op0CI->getValue());
5132             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5133
5134           }
5135         } else if (Op0I->getOpcode() == Instruction::Or) {
5136           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5137           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5138             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5139             // Anything in both C1 and C2 is known to be zero, remove it from
5140             // NewRHS.
5141             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5142             NewRHS = ConstantExpr::getAnd(NewRHS, 
5143                                        ConstantExpr::getNot(CommonBits));
5144             AddToWorkList(Op0I);
5145             I.setOperand(0, Op0I->getOperand(0));
5146             I.setOperand(1, NewRHS);
5147             return &I;
5148           }
5149         }
5150       }
5151     }
5152
5153     // Try to fold constant and into select arguments.
5154     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5155       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5156         return R;
5157     if (isa<PHINode>(Op0))
5158       if (Instruction *NV = FoldOpIntoPhi(I))
5159         return NV;
5160   }
5161
5162   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5163     if (X == Op1)
5164       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5165
5166   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5167     if (X == Op0)
5168       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5169
5170   
5171   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5172   if (Op1I) {
5173     Value *A, *B;
5174     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5175       if (A == Op0) {              // B^(B|A) == (A|B)^B
5176         Op1I->swapOperands();
5177         I.swapOperands();
5178         std::swap(Op0, Op1);
5179       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5180         I.swapOperands();     // Simplified below.
5181         std::swap(Op0, Op1);
5182       }
5183     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5184       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5185     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5186       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5187     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
5188                Op1I->hasOneUse()){
5189       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5190         Op1I->swapOperands();
5191         std::swap(A, B);
5192       }
5193       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5194         I.swapOperands();     // Simplified below.
5195         std::swap(Op0, Op1);
5196       }
5197     }
5198   }
5199   
5200   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5201   if (Op0I) {
5202     Value *A, *B;
5203     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5204         Op0I->hasOneUse()) {
5205       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5206         std::swap(A, B);
5207       if (B == Op1) {                                // (A|B)^B == A & ~B
5208         Instruction *NotB =
5209           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5210         return BinaryOperator::CreateAnd(A, NotB);
5211       }
5212     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5213       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5214     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5215       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5216     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
5217                Op0I->hasOneUse()){
5218       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5219         std::swap(A, B);
5220       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5221           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5222         Instruction *N =
5223           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5224         return BinaryOperator::CreateAnd(N, Op1);
5225       }
5226     }
5227   }
5228   
5229   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5230   if (Op0I && Op1I && Op0I->isShift() && 
5231       Op0I->getOpcode() == Op1I->getOpcode() && 
5232       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5233       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5234     Instruction *NewOp =
5235       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5236                                                     Op1I->getOperand(0),
5237                                                     Op0I->getName()), I);
5238     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5239                                   Op1I->getOperand(1));
5240   }
5241     
5242   if (Op0I && Op1I) {
5243     Value *A, *B, *C, *D;
5244     // (A & B)^(A | B) -> A ^ B
5245     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5246         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5247       if ((A == C && B == D) || (A == D && B == C)) 
5248         return BinaryOperator::CreateXor(A, B);
5249     }
5250     // (A | B)^(A & B) -> A ^ B
5251     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5252         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5253       if ((A == C && B == D) || (A == D && B == C)) 
5254         return BinaryOperator::CreateXor(A, B);
5255     }
5256     
5257     // (A & B)^(C & D)
5258     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5259         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5260         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5261       // (X & Y)^(X & Y) -> (Y^Z) & X
5262       Value *X = 0, *Y = 0, *Z = 0;
5263       if (A == C)
5264         X = A, Y = B, Z = D;
5265       else if (A == D)
5266         X = A, Y = B, Z = C;
5267       else if (B == C)
5268         X = B, Y = A, Z = D;
5269       else if (B == D)
5270         X = B, Y = A, Z = C;
5271       
5272       if (X) {
5273         Instruction *NewOp =
5274         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5275         return BinaryOperator::CreateAnd(NewOp, X);
5276       }
5277     }
5278   }
5279     
5280   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5281   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5282     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5283       return R;
5284
5285   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5286   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5287     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5288       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5289         const Type *SrcTy = Op0C->getOperand(0)->getType();
5290         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5291             // Only do this if the casts both really cause code to be generated.
5292             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5293                               I.getType(), TD) &&
5294             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5295                               I.getType(), TD)) {
5296           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5297                                                          Op1C->getOperand(0),
5298                                                          I.getName());
5299           InsertNewInstBefore(NewOp, I);
5300           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5301         }
5302       }
5303   }
5304
5305   return Changed ? &I : 0;
5306 }
5307
5308 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5309                                    LLVMContext *Context) {
5310   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5311 }
5312
5313 static bool HasAddOverflow(ConstantInt *Result,
5314                            ConstantInt *In1, ConstantInt *In2,
5315                            bool IsSigned) {
5316   if (IsSigned)
5317     if (In2->getValue().isNegative())
5318       return Result->getValue().sgt(In1->getValue());
5319     else
5320       return Result->getValue().slt(In1->getValue());
5321   else
5322     return Result->getValue().ult(In1->getValue());
5323 }
5324
5325 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5326 /// overflowed for this type.
5327 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5328                             Constant *In2, LLVMContext *Context,
5329                             bool IsSigned = false) {
5330   Result = ConstantExpr::getAdd(In1, In2);
5331
5332   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5333     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5334       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5335       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5336                          ExtractElement(In1, Idx, Context),
5337                          ExtractElement(In2, Idx, Context),
5338                          IsSigned))
5339         return true;
5340     }
5341     return false;
5342   }
5343
5344   return HasAddOverflow(cast<ConstantInt>(Result),
5345                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5346                         IsSigned);
5347 }
5348
5349 static bool HasSubOverflow(ConstantInt *Result,
5350                            ConstantInt *In1, ConstantInt *In2,
5351                            bool IsSigned) {
5352   if (IsSigned)
5353     if (In2->getValue().isNegative())
5354       return Result->getValue().slt(In1->getValue());
5355     else
5356       return Result->getValue().sgt(In1->getValue());
5357   else
5358     return Result->getValue().ugt(In1->getValue());
5359 }
5360
5361 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5362 /// overflowed for this type.
5363 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5364                             Constant *In2, LLVMContext *Context,
5365                             bool IsSigned = false) {
5366   Result = ConstantExpr::getSub(In1, In2);
5367
5368   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5369     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5370       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5371       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5372                          ExtractElement(In1, Idx, Context),
5373                          ExtractElement(In2, Idx, Context),
5374                          IsSigned))
5375         return true;
5376     }
5377     return false;
5378   }
5379
5380   return HasSubOverflow(cast<ConstantInt>(Result),
5381                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5382                         IsSigned);
5383 }
5384
5385 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5386 /// code necessary to compute the offset from the base pointer (without adding
5387 /// in the base pointer).  Return the result as a signed integer of intptr size.
5388 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5389   TargetData &TD = *IC.getTargetData();
5390   gep_type_iterator GTI = gep_type_begin(GEP);
5391   const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
5392   LLVMContext *Context = IC.getContext();
5393   Value *Result = Constant::getNullValue(IntPtrTy);
5394
5395   // Build a mask for high order bits.
5396   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5397   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5398
5399   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5400        ++i, ++GTI) {
5401     Value *Op = *i;
5402     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5403     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5404       if (OpC->isZero()) continue;
5405       
5406       // Handle a struct index, which adds its field offset to the pointer.
5407       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5408         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5409         
5410         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5411           Result = 
5412              ConstantInt::get(*Context, 
5413                               RC->getValue() + APInt(IntPtrWidth, Size));
5414         else
5415           Result = IC.InsertNewInstBefore(
5416                    BinaryOperator::CreateAdd(Result,
5417                                         ConstantInt::get(IntPtrTy, Size),
5418                                              GEP->getName()+".offs"), I);
5419         continue;
5420       }
5421       
5422       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5423       Constant *OC =
5424               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5425       Scale = ConstantExpr::getMul(OC, Scale);
5426       if (Constant *RC = dyn_cast<Constant>(Result))
5427         Result = ConstantExpr::getAdd(RC, Scale);
5428       else {
5429         // Emit an add instruction.
5430         Result = IC.InsertNewInstBefore(
5431            BinaryOperator::CreateAdd(Result, Scale,
5432                                      GEP->getName()+".offs"), I);
5433       }
5434       continue;
5435     }
5436     // Convert to correct type.
5437     if (Op->getType() != IntPtrTy) {
5438       if (Constant *OpC = dyn_cast<Constant>(Op))
5439         Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
5440       else
5441         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5442                                                                 true,
5443                                                       Op->getName()+".c"), I);
5444     }
5445     if (Size != 1) {
5446       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5447       if (Constant *OpC = dyn_cast<Constant>(Op))
5448         Op = ConstantExpr::getMul(OpC, Scale);
5449       else    // We'll let instcombine(mul) convert this to a shl if possible.
5450         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5451                                                   GEP->getName()+".idx"), I);
5452     }
5453
5454     // Emit an add instruction.
5455     if (isa<Constant>(Op) && isa<Constant>(Result))
5456       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5457                                     cast<Constant>(Result));
5458     else
5459       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5460                                                   GEP->getName()+".offs"), I);
5461   }
5462   return Result;
5463 }
5464
5465
5466 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5467 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5468 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5469 /// be complex, and scales are involved.  The above expression would also be
5470 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5471 /// This later form is less amenable to optimization though, and we are allowed
5472 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5473 ///
5474 /// If we can't emit an optimized form for this expression, this returns null.
5475 /// 
5476 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5477                                           InstCombiner &IC) {
5478   TargetData &TD = *IC.getTargetData();
5479   gep_type_iterator GTI = gep_type_begin(GEP);
5480
5481   // Check to see if this gep only has a single variable index.  If so, and if
5482   // any constant indices are a multiple of its scale, then we can compute this
5483   // in terms of the scale of the variable index.  For example, if the GEP
5484   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5485   // because the expression will cross zero at the same point.
5486   unsigned i, e = GEP->getNumOperands();
5487   int64_t Offset = 0;
5488   for (i = 1; i != e; ++i, ++GTI) {
5489     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5490       // Compute the aggregate offset of constant indices.
5491       if (CI->isZero()) continue;
5492
5493       // Handle a struct index, which adds its field offset to the pointer.
5494       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5495         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5496       } else {
5497         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5498         Offset += Size*CI->getSExtValue();
5499       }
5500     } else {
5501       // Found our variable index.
5502       break;
5503     }
5504   }
5505   
5506   // If there are no variable indices, we must have a constant offset, just
5507   // evaluate it the general way.
5508   if (i == e) return 0;
5509   
5510   Value *VariableIdx = GEP->getOperand(i);
5511   // Determine the scale factor of the variable element.  For example, this is
5512   // 4 if the variable index is into an array of i32.
5513   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5514   
5515   // Verify that there are no other variable indices.  If so, emit the hard way.
5516   for (++i, ++GTI; i != e; ++i, ++GTI) {
5517     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5518     if (!CI) return 0;
5519    
5520     // Compute the aggregate offset of constant indices.
5521     if (CI->isZero()) continue;
5522     
5523     // Handle a struct index, which adds its field offset to the pointer.
5524     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5525       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5526     } else {
5527       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5528       Offset += Size*CI->getSExtValue();
5529     }
5530   }
5531   
5532   // Okay, we know we have a single variable index, which must be a
5533   // pointer/array/vector index.  If there is no offset, life is simple, return
5534   // the index.
5535   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5536   if (Offset == 0) {
5537     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5538     // we don't need to bother extending: the extension won't affect where the
5539     // computation crosses zero.
5540     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5541       VariableIdx = new TruncInst(VariableIdx, 
5542                                   TD.getIntPtrType(VariableIdx->getContext()),
5543                                   VariableIdx->getName(), &I);
5544     return VariableIdx;
5545   }
5546   
5547   // Otherwise, there is an index.  The computation we will do will be modulo
5548   // the pointer size, so get it.
5549   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5550   
5551   Offset &= PtrSizeMask;
5552   VariableScale &= PtrSizeMask;
5553
5554   // To do this transformation, any constant index must be a multiple of the
5555   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5556   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5557   // multiple of the variable scale.
5558   int64_t NewOffs = Offset / (int64_t)VariableScale;
5559   if (Offset != NewOffs*(int64_t)VariableScale)
5560     return 0;
5561
5562   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5563   const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
5564   if (VariableIdx->getType() != IntPtrTy)
5565     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5566                                               true /*SExt*/, 
5567                                               VariableIdx->getName(), &I);
5568   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5569   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5570 }
5571
5572
5573 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5574 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5575 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5576                                        ICmpInst::Predicate Cond,
5577                                        Instruction &I) {
5578   // Look through bitcasts.
5579   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5580     RHS = BCI->getOperand(0);
5581
5582   Value *PtrBase = GEPLHS->getOperand(0);
5583   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5584     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5585     // This transformation (ignoring the base and scales) is valid because we
5586     // know pointers can't overflow since the gep is inbounds.  See if we can
5587     // output an optimized form.
5588     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5589     
5590     // If not, synthesize the offset the hard way.
5591     if (Offset == 0)
5592       Offset = EmitGEPOffset(GEPLHS, I, *this);
5593     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5594                         Constant::getNullValue(Offset->getType()));
5595   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5596     // If the base pointers are different, but the indices are the same, just
5597     // compare the base pointer.
5598     if (PtrBase != GEPRHS->getOperand(0)) {
5599       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5600       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5601                         GEPRHS->getOperand(0)->getType();
5602       if (IndicesTheSame)
5603         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5604           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5605             IndicesTheSame = false;
5606             break;
5607           }
5608
5609       // If all indices are the same, just compare the base pointers.
5610       if (IndicesTheSame)
5611         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5612                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5613
5614       // Otherwise, the base pointers are different and the indices are
5615       // different, bail out.
5616       return 0;
5617     }
5618
5619     // If one of the GEPs has all zero indices, recurse.
5620     bool AllZeros = true;
5621     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5622       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5623           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5624         AllZeros = false;
5625         break;
5626       }
5627     if (AllZeros)
5628       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5629                           ICmpInst::getSwappedPredicate(Cond), I);
5630
5631     // If the other GEP has all zero indices, recurse.
5632     AllZeros = true;
5633     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5634       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5635           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5636         AllZeros = false;
5637         break;
5638       }
5639     if (AllZeros)
5640       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5641
5642     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5643       // If the GEPs only differ by one index, compare it.
5644       unsigned NumDifferences = 0;  // Keep track of # differences.
5645       unsigned DiffOperand = 0;     // The operand that differs.
5646       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5647         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5648           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5649                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5650             // Irreconcilable differences.
5651             NumDifferences = 2;
5652             break;
5653           } else {
5654             if (NumDifferences++) break;
5655             DiffOperand = i;
5656           }
5657         }
5658
5659       if (NumDifferences == 0)   // SAME GEP?
5660         return ReplaceInstUsesWith(I, // No comparison is needed here.
5661                                    ConstantInt::get(Type::getInt1Ty(*Context),
5662                                              ICmpInst::isTrueWhenEqual(Cond)));
5663
5664       else if (NumDifferences == 1) {
5665         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5666         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5667         // Make sure we do a signed comparison here.
5668         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5669       }
5670     }
5671
5672     // Only lower this if the icmp is the only user of the GEP or if we expect
5673     // the result to fold to a constant!
5674     if (TD &&
5675         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5676         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5677       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5678       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5679       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5680       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5681     }
5682   }
5683   return 0;
5684 }
5685
5686 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5687 ///
5688 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5689                                                 Instruction *LHSI,
5690                                                 Constant *RHSC) {
5691   if (!isa<ConstantFP>(RHSC)) return 0;
5692   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5693   
5694   // Get the width of the mantissa.  We don't want to hack on conversions that
5695   // might lose information from the integer, e.g. "i64 -> float"
5696   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5697   if (MantissaWidth == -1) return 0;  // Unknown.
5698   
5699   // Check to see that the input is converted from an integer type that is small
5700   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5701   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5702   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5703   
5704   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5705   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5706   if (LHSUnsigned)
5707     ++InputSize;
5708   
5709   // If the conversion would lose info, don't hack on this.
5710   if ((int)InputSize > MantissaWidth)
5711     return 0;
5712   
5713   // Otherwise, we can potentially simplify the comparison.  We know that it
5714   // will always come through as an integer value and we know the constant is
5715   // not a NAN (it would have been previously simplified).
5716   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5717   
5718   ICmpInst::Predicate Pred;
5719   switch (I.getPredicate()) {
5720   default: llvm_unreachable("Unexpected predicate!");
5721   case FCmpInst::FCMP_UEQ:
5722   case FCmpInst::FCMP_OEQ:
5723     Pred = ICmpInst::ICMP_EQ;
5724     break;
5725   case FCmpInst::FCMP_UGT:
5726   case FCmpInst::FCMP_OGT:
5727     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5728     break;
5729   case FCmpInst::FCMP_UGE:
5730   case FCmpInst::FCMP_OGE:
5731     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5732     break;
5733   case FCmpInst::FCMP_ULT:
5734   case FCmpInst::FCMP_OLT:
5735     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5736     break;
5737   case FCmpInst::FCMP_ULE:
5738   case FCmpInst::FCMP_OLE:
5739     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5740     break;
5741   case FCmpInst::FCMP_UNE:
5742   case FCmpInst::FCMP_ONE:
5743     Pred = ICmpInst::ICMP_NE;
5744     break;
5745   case FCmpInst::FCMP_ORD:
5746     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5747   case FCmpInst::FCMP_UNO:
5748     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5749   }
5750   
5751   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5752   
5753   // Now we know that the APFloat is a normal number, zero or inf.
5754   
5755   // See if the FP constant is too large for the integer.  For example,
5756   // comparing an i8 to 300.0.
5757   unsigned IntWidth = IntTy->getScalarSizeInBits();
5758   
5759   if (!LHSUnsigned) {
5760     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5761     // and large values.
5762     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5763     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5764                           APFloat::rmNearestTiesToEven);
5765     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5766       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5767           Pred == ICmpInst::ICMP_SLE)
5768         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5769       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5770     }
5771   } else {
5772     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5773     // +INF and large values.
5774     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5775     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5776                           APFloat::rmNearestTiesToEven);
5777     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5778       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5779           Pred == ICmpInst::ICMP_ULE)
5780         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5781       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5782     }
5783   }
5784   
5785   if (!LHSUnsigned) {
5786     // See if the RHS value is < SignedMin.
5787     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5788     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5789                           APFloat::rmNearestTiesToEven);
5790     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5791       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5792           Pred == ICmpInst::ICMP_SGE)
5793         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5794       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5795     }
5796   }
5797
5798   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5799   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5800   // casting the FP value to the integer value and back, checking for equality.
5801   // Don't do this for zero, because -0.0 is not fractional.
5802   Constant *RHSInt = LHSUnsigned
5803     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5804     : ConstantExpr::getFPToSI(RHSC, IntTy);
5805   if (!RHS.isZero()) {
5806     bool Equal = LHSUnsigned
5807       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5808       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5809     if (!Equal) {
5810       // If we had a comparison against a fractional value, we have to adjust
5811       // the compare predicate and sometimes the value.  RHSC is rounded towards
5812       // zero at this point.
5813       switch (Pred) {
5814       default: llvm_unreachable("Unexpected integer comparison!");
5815       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5816         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5817       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5818         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5819       case ICmpInst::ICMP_ULE:
5820         // (float)int <= 4.4   --> int <= 4
5821         // (float)int <= -4.4  --> false
5822         if (RHS.isNegative())
5823           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5824         break;
5825       case ICmpInst::ICMP_SLE:
5826         // (float)int <= 4.4   --> int <= 4
5827         // (float)int <= -4.4  --> int < -4
5828         if (RHS.isNegative())
5829           Pred = ICmpInst::ICMP_SLT;
5830         break;
5831       case ICmpInst::ICMP_ULT:
5832         // (float)int < -4.4   --> false
5833         // (float)int < 4.4    --> int <= 4
5834         if (RHS.isNegative())
5835           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5836         Pred = ICmpInst::ICMP_ULE;
5837         break;
5838       case ICmpInst::ICMP_SLT:
5839         // (float)int < -4.4   --> int < -4
5840         // (float)int < 4.4    --> int <= 4
5841         if (!RHS.isNegative())
5842           Pred = ICmpInst::ICMP_SLE;
5843         break;
5844       case ICmpInst::ICMP_UGT:
5845         // (float)int > 4.4    --> int > 4
5846         // (float)int > -4.4   --> true
5847         if (RHS.isNegative())
5848           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5849         break;
5850       case ICmpInst::ICMP_SGT:
5851         // (float)int > 4.4    --> int > 4
5852         // (float)int > -4.4   --> int >= -4
5853         if (RHS.isNegative())
5854           Pred = ICmpInst::ICMP_SGE;
5855         break;
5856       case ICmpInst::ICMP_UGE:
5857         // (float)int >= -4.4   --> true
5858         // (float)int >= 4.4    --> int > 4
5859         if (!RHS.isNegative())
5860           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5861         Pred = ICmpInst::ICMP_UGT;
5862         break;
5863       case ICmpInst::ICMP_SGE:
5864         // (float)int >= -4.4   --> int >= -4
5865         // (float)int >= 4.4    --> int > 4
5866         if (!RHS.isNegative())
5867           Pred = ICmpInst::ICMP_SGT;
5868         break;
5869       }
5870     }
5871   }
5872
5873   // Lower this FP comparison into an appropriate integer version of the
5874   // comparison.
5875   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5876 }
5877
5878 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5879   bool Changed = SimplifyCompare(I);
5880   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5881
5882   // Fold trivial predicates.
5883   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5884     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5885   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5886     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5887   
5888   // Simplify 'fcmp pred X, X'
5889   if (Op0 == Op1) {
5890     switch (I.getPredicate()) {
5891     default: llvm_unreachable("Unknown predicate!");
5892     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5893     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5894     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5895       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5896     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5897     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5898     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5899       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5900       
5901     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5902     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5903     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5904     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5905       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5906       I.setPredicate(FCmpInst::FCMP_UNO);
5907       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5908       return &I;
5909       
5910     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5911     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5912     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5913     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5914       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5915       I.setPredicate(FCmpInst::FCMP_ORD);
5916       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5917       return &I;
5918     }
5919   }
5920     
5921   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5922     return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
5923
5924   // Handle fcmp with constant RHS
5925   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5926     // If the constant is a nan, see if we can fold the comparison based on it.
5927     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5928       if (CFP->getValueAPF().isNaN()) {
5929         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5930           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5931         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5932                "Comparison must be either ordered or unordered!");
5933         // True if unordered.
5934         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5935       }
5936     }
5937     
5938     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5939       switch (LHSI->getOpcode()) {
5940       case Instruction::PHI:
5941         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5942         // block.  If in the same block, we're encouraging jump threading.  If
5943         // not, we are just pessimizing the code by making an i1 phi.
5944         if (LHSI->getParent() == I.getParent())
5945           if (Instruction *NV = FoldOpIntoPhi(I))
5946             return NV;
5947         break;
5948       case Instruction::SIToFP:
5949       case Instruction::UIToFP:
5950         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5951           return NV;
5952         break;
5953       case Instruction::Select:
5954         // If either operand of the select is a constant, we can fold the
5955         // comparison into the select arms, which will cause one to be
5956         // constant folded and the select turned into a bitwise or.
5957         Value *Op1 = 0, *Op2 = 0;
5958         if (LHSI->hasOneUse()) {
5959           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5960             // Fold the known value into the constant operand.
5961             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5962             // Insert a new FCmp of the other select operand.
5963             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5964                                                       LHSI->getOperand(2), RHSC,
5965                                                       I.getName()), I);
5966           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5967             // Fold the known value into the constant operand.
5968             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5969             // Insert a new FCmp of the other select operand.
5970             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5971                                                       LHSI->getOperand(1), RHSC,
5972                                                       I.getName()), I);
5973           }
5974         }
5975
5976         if (Op1)
5977           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5978         break;
5979       }
5980   }
5981
5982   return Changed ? &I : 0;
5983 }
5984
5985 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5986   bool Changed = SimplifyCompare(I);
5987   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5988   const Type *Ty = Op0->getType();
5989
5990   // icmp X, X
5991   if (Op0 == Op1)
5992     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
5993                                                    I.isTrueWhenEqual()));
5994
5995   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5996     return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
5997   
5998   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5999   // addresses never equal each other!  We already know that Op0 != Op1.
6000   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
6001        isa<ConstantPointerNull>(Op0)) &&
6002       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
6003        isa<ConstantPointerNull>(Op1)))
6004     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
6005                                                    !I.isTrueWhenEqual()));
6006
6007   // icmp's with boolean values can always be turned into bitwise operations
6008   if (Ty == Type::getInt1Ty(*Context)) {
6009     switch (I.getPredicate()) {
6010     default: llvm_unreachable("Invalid icmp instruction!");
6011     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
6012       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
6013       InsertNewInstBefore(Xor, I);
6014       return BinaryOperator::CreateNot(Xor);
6015     }
6016     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6017       return BinaryOperator::CreateXor(Op0, Op1);
6018
6019     case ICmpInst::ICMP_UGT:
6020       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6021       // FALL THROUGH
6022     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6023       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
6024       InsertNewInstBefore(Not, I);
6025       return BinaryOperator::CreateAnd(Not, Op1);
6026     }
6027     case ICmpInst::ICMP_SGT:
6028       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6029       // FALL THROUGH
6030     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6031       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6032       InsertNewInstBefore(Not, I);
6033       return BinaryOperator::CreateAnd(Not, Op0);
6034     }
6035     case ICmpInst::ICMP_UGE:
6036       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6037       // FALL THROUGH
6038     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6039       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
6040       InsertNewInstBefore(Not, I);
6041       return BinaryOperator::CreateOr(Not, Op1);
6042     }
6043     case ICmpInst::ICMP_SGE:
6044       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6045       // FALL THROUGH
6046     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6047       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6048       InsertNewInstBefore(Not, I);
6049       return BinaryOperator::CreateOr(Not, Op0);
6050     }
6051     }
6052   }
6053
6054   unsigned BitWidth = 0;
6055   if (TD)
6056     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6057   else if (Ty->isIntOrIntVector())
6058     BitWidth = Ty->getScalarSizeInBits();
6059
6060   bool isSignBit = false;
6061
6062   // See if we are doing a comparison with a constant.
6063   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6064     Value *A = 0, *B = 0;
6065     
6066     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6067     if (I.isEquality() && CI->isNullValue() &&
6068         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6069       // (icmp cond A B) if cond is equality
6070       return new ICmpInst(I.getPredicate(), A, B);
6071     }
6072     
6073     // If we have an icmp le or icmp ge instruction, turn it into the
6074     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6075     // them being folded in the code below.
6076     switch (I.getPredicate()) {
6077     default: break;
6078     case ICmpInst::ICMP_ULE:
6079       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6080         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6081       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
6082                           AddOne(CI));
6083     case ICmpInst::ICMP_SLE:
6084       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6085         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6086       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6087                           AddOne(CI));
6088     case ICmpInst::ICMP_UGE:
6089       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6090         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6091       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
6092                           SubOne(CI));
6093     case ICmpInst::ICMP_SGE:
6094       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6095         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6096       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6097                           SubOne(CI));
6098     }
6099     
6100     // If this comparison is a normal comparison, it demands all
6101     // bits, if it is a sign bit comparison, it only demands the sign bit.
6102     bool UnusedBit;
6103     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6104   }
6105
6106   // See if we can fold the comparison based on range information we can get
6107   // by checking whether bits are known to be zero or one in the input.
6108   if (BitWidth != 0) {
6109     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6110     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6111
6112     if (SimplifyDemandedBits(I.getOperandUse(0),
6113                              isSignBit ? APInt::getSignBit(BitWidth)
6114                                        : APInt::getAllOnesValue(BitWidth),
6115                              Op0KnownZero, Op0KnownOne, 0))
6116       return &I;
6117     if (SimplifyDemandedBits(I.getOperandUse(1),
6118                              APInt::getAllOnesValue(BitWidth),
6119                              Op1KnownZero, Op1KnownOne, 0))
6120       return &I;
6121
6122     // Given the known and unknown bits, compute a range that the LHS could be
6123     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6124     // EQ and NE we use unsigned values.
6125     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6126     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6127     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6128       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6129                                              Op0Min, Op0Max);
6130       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6131                                              Op1Min, Op1Max);
6132     } else {
6133       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6134                                                Op0Min, Op0Max);
6135       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6136                                                Op1Min, Op1Max);
6137     }
6138
6139     // If Min and Max are known to be the same, then SimplifyDemandedBits
6140     // figured out that the LHS is a constant.  Just constant fold this now so
6141     // that code below can assume that Min != Max.
6142     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6143       return new ICmpInst(I.getPredicate(),
6144                           ConstantInt::get(*Context, Op0Min), Op1);
6145     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6146       return new ICmpInst(I.getPredicate(), Op0,
6147                           ConstantInt::get(*Context, Op1Min));
6148
6149     // Based on the range information we know about the LHS, see if we can
6150     // simplify this comparison.  For example, (x&4) < 8  is always true.
6151     switch (I.getPredicate()) {
6152     default: llvm_unreachable("Unknown icmp opcode!");
6153     case ICmpInst::ICMP_EQ:
6154       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6155         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6156       break;
6157     case ICmpInst::ICMP_NE:
6158       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6159         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6160       break;
6161     case ICmpInst::ICMP_ULT:
6162       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6163         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6164       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6165         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6166       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6167         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6168       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6169         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6170           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6171                               SubOne(CI));
6172
6173         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6174         if (CI->isMinValue(true))
6175           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6176                            Constant::getAllOnesValue(Op0->getType()));
6177       }
6178       break;
6179     case ICmpInst::ICMP_UGT:
6180       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6181         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6182       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6183         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6184
6185       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6186         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6187       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6188         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6189           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6190                               AddOne(CI));
6191
6192         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6193         if (CI->isMaxValue(true))
6194           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6195                               Constant::getNullValue(Op0->getType()));
6196       }
6197       break;
6198     case ICmpInst::ICMP_SLT:
6199       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6200         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6201       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6202         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6203       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6204         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6205       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6206         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6207           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6208                               SubOne(CI));
6209       }
6210       break;
6211     case ICmpInst::ICMP_SGT:
6212       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6213         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6214       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6215         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6216
6217       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6218         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6219       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6220         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6221           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6222                               AddOne(CI));
6223       }
6224       break;
6225     case ICmpInst::ICMP_SGE:
6226       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6227       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6228         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6229       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6230         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6231       break;
6232     case ICmpInst::ICMP_SLE:
6233       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6234       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6235         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6236       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6237         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6238       break;
6239     case ICmpInst::ICMP_UGE:
6240       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6241       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6242         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6243       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6244         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6245       break;
6246     case ICmpInst::ICMP_ULE:
6247       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6248       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6249         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6250       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6251         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6252       break;
6253     }
6254
6255     // Turn a signed comparison into an unsigned one if both operands
6256     // are known to have the same sign.
6257     if (I.isSignedPredicate() &&
6258         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6259          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6260       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6261   }
6262
6263   // Test if the ICmpInst instruction is used exclusively by a select as
6264   // part of a minimum or maximum operation. If so, refrain from doing
6265   // any other folding. This helps out other analyses which understand
6266   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6267   // and CodeGen. And in this case, at least one of the comparison
6268   // operands has at least one user besides the compare (the select),
6269   // which would often largely negate the benefit of folding anyway.
6270   if (I.hasOneUse())
6271     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6272       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6273           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6274         return 0;
6275
6276   // See if we are doing a comparison between a constant and an instruction that
6277   // can be folded into the comparison.
6278   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6279     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6280     // instruction, see if that instruction also has constants so that the 
6281     // instruction can be folded into the icmp 
6282     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6283       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6284         return Res;
6285   }
6286
6287   // Handle icmp with constant (but not simple integer constant) RHS
6288   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6289     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6290       switch (LHSI->getOpcode()) {
6291       case Instruction::GetElementPtr:
6292         if (RHSC->isNullValue()) {
6293           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6294           bool isAllZeros = true;
6295           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6296             if (!isa<Constant>(LHSI->getOperand(i)) ||
6297                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6298               isAllZeros = false;
6299               break;
6300             }
6301           if (isAllZeros)
6302             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6303                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6304         }
6305         break;
6306
6307       case Instruction::PHI:
6308         // Only fold icmp into the PHI if the phi and fcmp are in the same
6309         // block.  If in the same block, we're encouraging jump threading.  If
6310         // not, we are just pessimizing the code by making an i1 phi.
6311         if (LHSI->getParent() == I.getParent())
6312           if (Instruction *NV = FoldOpIntoPhi(I))
6313             return NV;
6314         break;
6315       case Instruction::Select: {
6316         // If either operand of the select is a constant, we can fold the
6317         // comparison into the select arms, which will cause one to be
6318         // constant folded and the select turned into a bitwise or.
6319         Value *Op1 = 0, *Op2 = 0;
6320         if (LHSI->hasOneUse()) {
6321           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6322             // Fold the known value into the constant operand.
6323             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6324             // Insert a new ICmp of the other select operand.
6325             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6326                                                    LHSI->getOperand(2), RHSC,
6327                                                    I.getName()), I);
6328           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6329             // Fold the known value into the constant operand.
6330             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6331             // Insert a new ICmp of the other select operand.
6332             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6333                                                    LHSI->getOperand(1), RHSC,
6334                                                    I.getName()), I);
6335           }
6336         }
6337
6338         if (Op1)
6339           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6340         break;
6341       }
6342       case Instruction::Malloc:
6343         // If we have (malloc != null), and if the malloc has a single use, we
6344         // can assume it is successful and remove the malloc.
6345         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6346           AddToWorkList(LHSI);
6347           return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
6348                                                          !I.isTrueWhenEqual()));
6349         }
6350         break;
6351       }
6352   }
6353
6354   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6355   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6356     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6357       return NI;
6358   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6359     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6360                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6361       return NI;
6362
6363   // Test to see if the operands of the icmp are casted versions of other
6364   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6365   // now.
6366   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6367     if (isa<PointerType>(Op0->getType()) && 
6368         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6369       // We keep moving the cast from the left operand over to the right
6370       // operand, where it can often be eliminated completely.
6371       Op0 = CI->getOperand(0);
6372
6373       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6374       // so eliminate it as well.
6375       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6376         Op1 = CI2->getOperand(0);
6377
6378       // If Op1 is a constant, we can fold the cast into the constant.
6379       if (Op0->getType() != Op1->getType()) {
6380         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6381           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6382         } else {
6383           // Otherwise, cast the RHS right before the icmp
6384           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6385         }
6386       }
6387       return new ICmpInst(I.getPredicate(), Op0, Op1);
6388     }
6389   }
6390   
6391   if (isa<CastInst>(Op0)) {
6392     // Handle the special case of: icmp (cast bool to X), <cst>
6393     // This comes up when you have code like
6394     //   int X = A < B;
6395     //   if (X) ...
6396     // For generality, we handle any zero-extension of any operand comparison
6397     // with a constant or another cast from the same type.
6398     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6399       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6400         return R;
6401   }
6402   
6403   // See if it's the same type of instruction on the left and right.
6404   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6405     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6406       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6407           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6408         switch (Op0I->getOpcode()) {
6409         default: break;
6410         case Instruction::Add:
6411         case Instruction::Sub:
6412         case Instruction::Xor:
6413           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6414             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6415                                 Op1I->getOperand(0));
6416           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6417           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6418             if (CI->getValue().isSignBit()) {
6419               ICmpInst::Predicate Pred = I.isSignedPredicate()
6420                                              ? I.getUnsignedPredicate()
6421                                              : I.getSignedPredicate();
6422               return new ICmpInst(Pred, Op0I->getOperand(0),
6423                                   Op1I->getOperand(0));
6424             }
6425             
6426             if (CI->getValue().isMaxSignedValue()) {
6427               ICmpInst::Predicate Pred = I.isSignedPredicate()
6428                                              ? I.getUnsignedPredicate()
6429                                              : I.getSignedPredicate();
6430               Pred = I.getSwappedPredicate(Pred);
6431               return new ICmpInst(Pred, Op0I->getOperand(0),
6432                                   Op1I->getOperand(0));
6433             }
6434           }
6435           break;
6436         case Instruction::Mul:
6437           if (!I.isEquality())
6438             break;
6439
6440           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6441             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6442             // Mask = -1 >> count-trailing-zeros(Cst).
6443             if (!CI->isZero() && !CI->isOne()) {
6444               const APInt &AP = CI->getValue();
6445               ConstantInt *Mask = ConstantInt::get(*Context, 
6446                                       APInt::getLowBitsSet(AP.getBitWidth(),
6447                                                            AP.getBitWidth() -
6448                                                       AP.countTrailingZeros()));
6449               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6450                                                             Mask);
6451               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6452                                                             Mask);
6453               InsertNewInstBefore(And1, I);
6454               InsertNewInstBefore(And2, I);
6455               return new ICmpInst(I.getPredicate(), And1, And2);
6456             }
6457           }
6458           break;
6459         }
6460       }
6461     }
6462   }
6463   
6464   // ~x < ~y --> y < x
6465   { Value *A, *B;
6466     if (match(Op0, m_Not(m_Value(A))) &&
6467         match(Op1, m_Not(m_Value(B))))
6468       return new ICmpInst(I.getPredicate(), B, A);
6469   }
6470   
6471   if (I.isEquality()) {
6472     Value *A, *B, *C, *D;
6473     
6474     // -x == -y --> x == y
6475     if (match(Op0, m_Neg(m_Value(A))) &&
6476         match(Op1, m_Neg(m_Value(B))))
6477       return new ICmpInst(I.getPredicate(), A, B);
6478     
6479     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6480       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6481         Value *OtherVal = A == Op1 ? B : A;
6482         return new ICmpInst(I.getPredicate(), OtherVal,
6483                             Constant::getNullValue(A->getType()));
6484       }
6485
6486       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6487         // A^c1 == C^c2 --> A == C^(c1^c2)
6488         ConstantInt *C1, *C2;
6489         if (match(B, m_ConstantInt(C1)) &&
6490             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6491           Constant *NC = 
6492                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6493           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6494           return new ICmpInst(I.getPredicate(), A,
6495                               InsertNewInstBefore(Xor, I));
6496         }
6497         
6498         // A^B == A^D -> B == D
6499         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6500         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6501         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6502         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6503       }
6504     }
6505     
6506     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6507         (A == Op0 || B == Op0)) {
6508       // A == (A^B)  ->  B == 0
6509       Value *OtherVal = A == Op0 ? B : A;
6510       return new ICmpInst(I.getPredicate(), OtherVal,
6511                           Constant::getNullValue(A->getType()));
6512     }
6513
6514     // (A-B) == A  ->  B == 0
6515     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6516       return new ICmpInst(I.getPredicate(), B, 
6517                           Constant::getNullValue(B->getType()));
6518
6519     // A == (A-B)  ->  B == 0
6520     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6521       return new ICmpInst(I.getPredicate(), B,
6522                           Constant::getNullValue(B->getType()));
6523     
6524     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6525     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6526         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6527         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6528       Value *X = 0, *Y = 0, *Z = 0;
6529       
6530       if (A == C) {
6531         X = B; Y = D; Z = A;
6532       } else if (A == D) {
6533         X = B; Y = C; Z = A;
6534       } else if (B == C) {
6535         X = A; Y = D; Z = B;
6536       } else if (B == D) {
6537         X = A; Y = C; Z = B;
6538       }
6539       
6540       if (X) {   // Build (X^Y) & Z
6541         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6542         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6543         I.setOperand(0, Op1);
6544         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6545         return &I;
6546       }
6547     }
6548   }
6549   return Changed ? &I : 0;
6550 }
6551
6552
6553 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6554 /// and CmpRHS are both known to be integer constants.
6555 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6556                                           ConstantInt *DivRHS) {
6557   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6558   const APInt &CmpRHSV = CmpRHS->getValue();
6559   
6560   // FIXME: If the operand types don't match the type of the divide 
6561   // then don't attempt this transform. The code below doesn't have the
6562   // logic to deal with a signed divide and an unsigned compare (and
6563   // vice versa). This is because (x /s C1) <s C2  produces different 
6564   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6565   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6566   // work. :(  The if statement below tests that condition and bails 
6567   // if it finds it. 
6568   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6569   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6570     return 0;
6571   if (DivRHS->isZero())
6572     return 0; // The ProdOV computation fails on divide by zero.
6573   if (DivIsSigned && DivRHS->isAllOnesValue())
6574     return 0; // The overflow computation also screws up here
6575   if (DivRHS->isOne())
6576     return 0; // Not worth bothering, and eliminates some funny cases
6577               // with INT_MIN.
6578
6579   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6580   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6581   // C2 (CI). By solving for X we can turn this into a range check 
6582   // instead of computing a divide. 
6583   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6584
6585   // Determine if the product overflows by seeing if the product is
6586   // not equal to the divide. Make sure we do the same kind of divide
6587   // as in the LHS instruction that we're folding. 
6588   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6589                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6590
6591   // Get the ICmp opcode
6592   ICmpInst::Predicate Pred = ICI.getPredicate();
6593
6594   // Figure out the interval that is being checked.  For example, a comparison
6595   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6596   // Compute this interval based on the constants involved and the signedness of
6597   // the compare/divide.  This computes a half-open interval, keeping track of
6598   // whether either value in the interval overflows.  After analysis each
6599   // overflow variable is set to 0 if it's corresponding bound variable is valid
6600   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6601   int LoOverflow = 0, HiOverflow = 0;
6602   Constant *LoBound = 0, *HiBound = 0;
6603   
6604   if (!DivIsSigned) {  // udiv
6605     // e.g. X/5 op 3  --> [15, 20)
6606     LoBound = Prod;
6607     HiOverflow = LoOverflow = ProdOV;
6608     if (!HiOverflow)
6609       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6610   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6611     if (CmpRHSV == 0) {       // (X / pos) op 0
6612       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6613       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6614       HiBound = DivRHS;
6615     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6616       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6617       HiOverflow = LoOverflow = ProdOV;
6618       if (!HiOverflow)
6619         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6620     } else {                       // (X / pos) op neg
6621       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6622       HiBound = AddOne(Prod);
6623       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6624       if (!LoOverflow) {
6625         ConstantInt* DivNeg =
6626                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6627         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6628                                      true) ? -1 : 0;
6629        }
6630     }
6631   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6632     if (CmpRHSV == 0) {       // (X / neg) op 0
6633       // e.g. X/-5 op 0  --> [-4, 5)
6634       LoBound = AddOne(DivRHS);
6635       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6636       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6637         HiOverflow = 1;            // [INTMIN+1, overflow)
6638         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6639       }
6640     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6641       // e.g. X/-5 op 3  --> [-19, -14)
6642       HiBound = AddOne(Prod);
6643       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6644       if (!LoOverflow)
6645         LoOverflow = AddWithOverflow(LoBound, HiBound,
6646                                      DivRHS, Context, true) ? -1 : 0;
6647     } else {                       // (X / neg) op neg
6648       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6649       LoOverflow = HiOverflow = ProdOV;
6650       if (!HiOverflow)
6651         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6652     }
6653     
6654     // Dividing by a negative swaps the condition.  LT <-> GT
6655     Pred = ICmpInst::getSwappedPredicate(Pred);
6656   }
6657
6658   Value *X = DivI->getOperand(0);
6659   switch (Pred) {
6660   default: llvm_unreachable("Unhandled icmp opcode!");
6661   case ICmpInst::ICMP_EQ:
6662     if (LoOverflow && HiOverflow)
6663       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6664     else if (HiOverflow)
6665       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6666                           ICmpInst::ICMP_UGE, X, LoBound);
6667     else if (LoOverflow)
6668       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6669                           ICmpInst::ICMP_ULT, X, HiBound);
6670     else
6671       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6672   case ICmpInst::ICMP_NE:
6673     if (LoOverflow && HiOverflow)
6674       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6675     else if (HiOverflow)
6676       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6677                           ICmpInst::ICMP_ULT, X, LoBound);
6678     else if (LoOverflow)
6679       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6680                           ICmpInst::ICMP_UGE, X, HiBound);
6681     else
6682       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6683   case ICmpInst::ICMP_ULT:
6684   case ICmpInst::ICMP_SLT:
6685     if (LoOverflow == +1)   // Low bound is greater than input range.
6686       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6687     if (LoOverflow == -1)   // Low bound is less than input range.
6688       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6689     return new ICmpInst(Pred, X, LoBound);
6690   case ICmpInst::ICMP_UGT:
6691   case ICmpInst::ICMP_SGT:
6692     if (HiOverflow == +1)       // High bound greater than input range.
6693       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6694     else if (HiOverflow == -1)  // High bound less than input range.
6695       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6696     if (Pred == ICmpInst::ICMP_UGT)
6697       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6698     else
6699       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6700   }
6701 }
6702
6703
6704 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6705 ///
6706 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6707                                                           Instruction *LHSI,
6708                                                           ConstantInt *RHS) {
6709   const APInt &RHSV = RHS->getValue();
6710   
6711   switch (LHSI->getOpcode()) {
6712   case Instruction::Trunc:
6713     if (ICI.isEquality() && LHSI->hasOneUse()) {
6714       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6715       // of the high bits truncated out of x are known.
6716       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6717              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6718       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6719       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6720       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6721       
6722       // If all the high bits are known, we can do this xform.
6723       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6724         // Pull in the high bits from known-ones set.
6725         APInt NewRHS(RHS->getValue());
6726         NewRHS.zext(SrcBits);
6727         NewRHS |= KnownOne;
6728         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6729                             ConstantInt::get(*Context, NewRHS));
6730       }
6731     }
6732     break;
6733       
6734   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6735     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6736       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6737       // fold the xor.
6738       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6739           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6740         Value *CompareVal = LHSI->getOperand(0);
6741         
6742         // If the sign bit of the XorCST is not set, there is no change to
6743         // the operation, just stop using the Xor.
6744         if (!XorCST->getValue().isNegative()) {
6745           ICI.setOperand(0, CompareVal);
6746           AddToWorkList(LHSI);
6747           return &ICI;
6748         }
6749         
6750         // Was the old condition true if the operand is positive?
6751         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6752         
6753         // If so, the new one isn't.
6754         isTrueIfPositive ^= true;
6755         
6756         if (isTrueIfPositive)
6757           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6758                               SubOne(RHS));
6759         else
6760           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6761                               AddOne(RHS));
6762       }
6763
6764       if (LHSI->hasOneUse()) {
6765         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6766         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6767           const APInt &SignBit = XorCST->getValue();
6768           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6769                                          ? ICI.getUnsignedPredicate()
6770                                          : ICI.getSignedPredicate();
6771           return new ICmpInst(Pred, LHSI->getOperand(0),
6772                               ConstantInt::get(*Context, RHSV ^ SignBit));
6773         }
6774
6775         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6776         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6777           const APInt &NotSignBit = XorCST->getValue();
6778           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6779                                          ? ICI.getUnsignedPredicate()
6780                                          : ICI.getSignedPredicate();
6781           Pred = ICI.getSwappedPredicate(Pred);
6782           return new ICmpInst(Pred, LHSI->getOperand(0),
6783                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
6784         }
6785       }
6786     }
6787     break;
6788   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6789     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6790         LHSI->getOperand(0)->hasOneUse()) {
6791       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6792       
6793       // If the LHS is an AND of a truncating cast, we can widen the
6794       // and/compare to be the input width without changing the value
6795       // produced, eliminating a cast.
6796       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6797         // We can do this transformation if either the AND constant does not
6798         // have its sign bit set or if it is an equality comparison. 
6799         // Extending a relational comparison when we're checking the sign
6800         // bit would not work.
6801         if (Cast->hasOneUse() &&
6802             (ICI.isEquality() ||
6803              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6804           uint32_t BitWidth = 
6805             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6806           APInt NewCST = AndCST->getValue();
6807           NewCST.zext(BitWidth);
6808           APInt NewCI = RHSV;
6809           NewCI.zext(BitWidth);
6810           Instruction *NewAnd = 
6811             BinaryOperator::CreateAnd(Cast->getOperand(0),
6812                            ConstantInt::get(*Context, NewCST), LHSI->getName());
6813           InsertNewInstBefore(NewAnd, ICI);
6814           return new ICmpInst(ICI.getPredicate(), NewAnd,
6815                               ConstantInt::get(*Context, NewCI));
6816         }
6817       }
6818       
6819       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6820       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6821       // happens a LOT in code produced by the C front-end, for bitfield
6822       // access.
6823       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6824       if (Shift && !Shift->isShift())
6825         Shift = 0;
6826       
6827       ConstantInt *ShAmt;
6828       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6829       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6830       const Type *AndTy = AndCST->getType();          // Type of the and.
6831       
6832       // We can fold this as long as we can't shift unknown bits
6833       // into the mask.  This can only happen with signed shift
6834       // rights, as they sign-extend.
6835       if (ShAmt) {
6836         bool CanFold = Shift->isLogicalShift();
6837         if (!CanFold) {
6838           // To test for the bad case of the signed shr, see if any
6839           // of the bits shifted in could be tested after the mask.
6840           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6841           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6842           
6843           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6844           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6845                AndCST->getValue()) == 0)
6846             CanFold = true;
6847         }
6848         
6849         if (CanFold) {
6850           Constant *NewCst;
6851           if (Shift->getOpcode() == Instruction::Shl)
6852             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6853           else
6854             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6855           
6856           // Check to see if we are shifting out any of the bits being
6857           // compared.
6858           if (ConstantExpr::get(Shift->getOpcode(),
6859                                        NewCst, ShAmt) != RHS) {
6860             // If we shifted bits out, the fold is not going to work out.
6861             // As a special case, check to see if this means that the
6862             // result is always true or false now.
6863             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6864               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6865             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6866               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6867           } else {
6868             ICI.setOperand(1, NewCst);
6869             Constant *NewAndCST;
6870             if (Shift->getOpcode() == Instruction::Shl)
6871               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6872             else
6873               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6874             LHSI->setOperand(1, NewAndCST);
6875             LHSI->setOperand(0, Shift->getOperand(0));
6876             AddToWorkList(Shift); // Shift is dead.
6877             AddUsesToWorkList(ICI);
6878             return &ICI;
6879           }
6880         }
6881       }
6882       
6883       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6884       // preferable because it allows the C<<Y expression to be hoisted out
6885       // of a loop if Y is invariant and X is not.
6886       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6887           ICI.isEquality() && !Shift->isArithmeticShift() &&
6888           !isa<Constant>(Shift->getOperand(0))) {
6889         // Compute C << Y.
6890         Value *NS;
6891         if (Shift->getOpcode() == Instruction::LShr) {
6892           NS = BinaryOperator::CreateShl(AndCST, 
6893                                          Shift->getOperand(1), "tmp");
6894         } else {
6895           // Insert a logical shift.
6896           NS = BinaryOperator::CreateLShr(AndCST,
6897                                           Shift->getOperand(1), "tmp");
6898         }
6899         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6900         
6901         // Compute X & (C << Y).
6902         Instruction *NewAnd = 
6903           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6904         InsertNewInstBefore(NewAnd, ICI);
6905         
6906         ICI.setOperand(0, NewAnd);
6907         return &ICI;
6908       }
6909     }
6910     break;
6911     
6912   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6913     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6914     if (!ShAmt) break;
6915     
6916     uint32_t TypeBits = RHSV.getBitWidth();
6917     
6918     // Check that the shift amount is in range.  If not, don't perform
6919     // undefined shifts.  When the shift is visited it will be
6920     // simplified.
6921     if (ShAmt->uge(TypeBits))
6922       break;
6923     
6924     if (ICI.isEquality()) {
6925       // If we are comparing against bits always shifted out, the
6926       // comparison cannot succeed.
6927       Constant *Comp =
6928         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6929                                                                  ShAmt);
6930       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6931         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6932         Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6933         return ReplaceInstUsesWith(ICI, Cst);
6934       }
6935       
6936       if (LHSI->hasOneUse()) {
6937         // Otherwise strength reduce the shift into an and.
6938         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6939         Constant *Mask =
6940           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
6941                                                        TypeBits-ShAmtVal));
6942         
6943         Instruction *AndI =
6944           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6945                                     Mask, LHSI->getName()+".mask");
6946         Value *And = InsertNewInstBefore(AndI, ICI);
6947         return new ICmpInst(ICI.getPredicate(), And,
6948                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6949       }
6950     }
6951     
6952     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6953     bool TrueIfSigned = false;
6954     if (LHSI->hasOneUse() &&
6955         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6956       // (X << 31) <s 0  --> (X&1) != 0
6957       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6958                                            (TypeBits-ShAmt->getZExtValue()-1));
6959       Instruction *AndI =
6960         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6961                                   Mask, LHSI->getName()+".mask");
6962       Value *And = InsertNewInstBefore(AndI, ICI);
6963       
6964       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6965                           And, Constant::getNullValue(And->getType()));
6966     }
6967     break;
6968   }
6969     
6970   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6971   case Instruction::AShr: {
6972     // Only handle equality comparisons of shift-by-constant.
6973     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6974     if (!ShAmt || !ICI.isEquality()) break;
6975
6976     // Check that the shift amount is in range.  If not, don't perform
6977     // undefined shifts.  When the shift is visited it will be
6978     // simplified.
6979     uint32_t TypeBits = RHSV.getBitWidth();
6980     if (ShAmt->uge(TypeBits))
6981       break;
6982     
6983     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6984       
6985     // If we are comparing against bits always shifted out, the
6986     // comparison cannot succeed.
6987     APInt Comp = RHSV << ShAmtVal;
6988     if (LHSI->getOpcode() == Instruction::LShr)
6989       Comp = Comp.lshr(ShAmtVal);
6990     else
6991       Comp = Comp.ashr(ShAmtVal);
6992     
6993     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6994       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6995       Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6996       return ReplaceInstUsesWith(ICI, Cst);
6997     }
6998     
6999     // Otherwise, check to see if the bits shifted out are known to be zero.
7000     // If so, we can compare against the unshifted value:
7001     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
7002     if (LHSI->hasOneUse() &&
7003         MaskedValueIsZero(LHSI->getOperand(0), 
7004                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7005       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
7006                           ConstantExpr::getShl(RHS, ShAmt));
7007     }
7008       
7009     if (LHSI->hasOneUse()) {
7010       // Otherwise strength reduce the shift into an and.
7011       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7012       Constant *Mask = ConstantInt::get(*Context, Val);
7013       
7014       Instruction *AndI =
7015         BinaryOperator::CreateAnd(LHSI->getOperand(0),
7016                                   Mask, LHSI->getName()+".mask");
7017       Value *And = InsertNewInstBefore(AndI, ICI);
7018       return new ICmpInst(ICI.getPredicate(), And,
7019                           ConstantExpr::getShl(RHS, ShAmt));
7020     }
7021     break;
7022   }
7023     
7024   case Instruction::SDiv:
7025   case Instruction::UDiv:
7026     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7027     // Fold this div into the comparison, producing a range check. 
7028     // Determine, based on the divide type, what the range is being 
7029     // checked.  If there is an overflow on the low or high side, remember 
7030     // it, otherwise compute the range [low, hi) bounding the new value.
7031     // See: InsertRangeTest above for the kinds of replacements possible.
7032     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7033       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7034                                           DivRHS))
7035         return R;
7036     break;
7037
7038   case Instruction::Add:
7039     // Fold: icmp pred (add, X, C1), C2
7040
7041     if (!ICI.isEquality()) {
7042       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7043       if (!LHSC) break;
7044       const APInt &LHSV = LHSC->getValue();
7045
7046       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7047                             .subtract(LHSV);
7048
7049       if (ICI.isSignedPredicate()) {
7050         if (CR.getLower().isSignBit()) {
7051           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7052                               ConstantInt::get(*Context, CR.getUpper()));
7053         } else if (CR.getUpper().isSignBit()) {
7054           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7055                               ConstantInt::get(*Context, CR.getLower()));
7056         }
7057       } else {
7058         if (CR.getLower().isMinValue()) {
7059           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7060                               ConstantInt::get(*Context, CR.getUpper()));
7061         } else if (CR.getUpper().isMinValue()) {
7062           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7063                               ConstantInt::get(*Context, CR.getLower()));
7064         }
7065       }
7066     }
7067     break;
7068   }
7069   
7070   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7071   if (ICI.isEquality()) {
7072     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7073     
7074     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7075     // the second operand is a constant, simplify a bit.
7076     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7077       switch (BO->getOpcode()) {
7078       case Instruction::SRem:
7079         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7080         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7081           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7082           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7083             Instruction *NewRem =
7084               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7085                                          BO->getName());
7086             InsertNewInstBefore(NewRem, ICI);
7087             return new ICmpInst(ICI.getPredicate(), NewRem,
7088                                 Constant::getNullValue(BO->getType()));
7089           }
7090         }
7091         break;
7092       case Instruction::Add:
7093         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7094         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7095           if (BO->hasOneUse())
7096             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7097                                 ConstantExpr::getSub(RHS, BOp1C));
7098         } else if (RHSV == 0) {
7099           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7100           // efficiently invertible, or if the add has just this one use.
7101           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7102           
7103           if (Value *NegVal = dyn_castNegVal(BOp1))
7104             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7105           else if (Value *NegVal = dyn_castNegVal(BOp0))
7106             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7107           else if (BO->hasOneUse()) {
7108             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
7109             InsertNewInstBefore(Neg, ICI);
7110             Neg->takeName(BO);
7111             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7112           }
7113         }
7114         break;
7115       case Instruction::Xor:
7116         // For the xor case, we can xor two constants together, eliminating
7117         // the explicit xor.
7118         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7119           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
7120                               ConstantExpr::getXor(RHS, BOC));
7121         
7122         // FALLTHROUGH
7123       case Instruction::Sub:
7124         // Replace (([sub|xor] A, B) != 0) with (A != B)
7125         if (RHSV == 0)
7126           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7127                               BO->getOperand(1));
7128         break;
7129         
7130       case Instruction::Or:
7131         // If bits are being or'd in that are not present in the constant we
7132         // are comparing against, then the comparison could never succeed!
7133         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7134           Constant *NotCI = ConstantExpr::getNot(RHS);
7135           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7136             return ReplaceInstUsesWith(ICI,
7137                                        ConstantInt::get(Type::getInt1Ty(*Context), 
7138                                        isICMP_NE));
7139         }
7140         break;
7141         
7142       case Instruction::And:
7143         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7144           // If bits are being compared against that are and'd out, then the
7145           // comparison can never succeed!
7146           if ((RHSV & ~BOC->getValue()) != 0)
7147             return ReplaceInstUsesWith(ICI,
7148                                        ConstantInt::get(Type::getInt1Ty(*Context),
7149                                        isICMP_NE));
7150           
7151           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7152           if (RHS == BOC && RHSV.isPowerOf2())
7153             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7154                                 ICmpInst::ICMP_NE, LHSI,
7155                                 Constant::getNullValue(RHS->getType()));
7156           
7157           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7158           if (BOC->getValue().isSignBit()) {
7159             Value *X = BO->getOperand(0);
7160             Constant *Zero = Constant::getNullValue(X->getType());
7161             ICmpInst::Predicate pred = isICMP_NE ? 
7162               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7163             return new ICmpInst(pred, X, Zero);
7164           }
7165           
7166           // ((X & ~7) == 0) --> X < 8
7167           if (RHSV == 0 && isHighOnes(BOC)) {
7168             Value *X = BO->getOperand(0);
7169             Constant *NegX = ConstantExpr::getNeg(BOC);
7170             ICmpInst::Predicate pred = isICMP_NE ? 
7171               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7172             return new ICmpInst(pred, X, NegX);
7173           }
7174         }
7175       default: break;
7176       }
7177     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7178       // Handle icmp {eq|ne} <intrinsic>, intcst.
7179       if (II->getIntrinsicID() == Intrinsic::bswap) {
7180         AddToWorkList(II);
7181         ICI.setOperand(0, II->getOperand(1));
7182         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7183         return &ICI;
7184       }
7185     }
7186   }
7187   return 0;
7188 }
7189
7190 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7191 /// We only handle extending casts so far.
7192 ///
7193 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7194   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7195   Value *LHSCIOp        = LHSCI->getOperand(0);
7196   const Type *SrcTy     = LHSCIOp->getType();
7197   const Type *DestTy    = LHSCI->getType();
7198   Value *RHSCIOp;
7199
7200   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7201   // integer type is the same size as the pointer type.
7202   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7203       TD->getPointerSizeInBits() ==
7204          cast<IntegerType>(DestTy)->getBitWidth()) {
7205     Value *RHSOp = 0;
7206     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7207       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7208     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7209       RHSOp = RHSC->getOperand(0);
7210       // If the pointer types don't match, insert a bitcast.
7211       if (LHSCIOp->getType() != RHSOp->getType())
7212         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7213     }
7214
7215     if (RHSOp)
7216       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7217   }
7218   
7219   // The code below only handles extension cast instructions, so far.
7220   // Enforce this.
7221   if (LHSCI->getOpcode() != Instruction::ZExt &&
7222       LHSCI->getOpcode() != Instruction::SExt)
7223     return 0;
7224
7225   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7226   bool isSignedCmp = ICI.isSignedPredicate();
7227
7228   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7229     // Not an extension from the same type?
7230     RHSCIOp = CI->getOperand(0);
7231     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7232       return 0;
7233     
7234     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7235     // and the other is a zext), then we can't handle this.
7236     if (CI->getOpcode() != LHSCI->getOpcode())
7237       return 0;
7238
7239     // Deal with equality cases early.
7240     if (ICI.isEquality())
7241       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7242
7243     // A signed comparison of sign extended values simplifies into a
7244     // signed comparison.
7245     if (isSignedCmp && isSignedExt)
7246       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7247
7248     // The other three cases all fold into an unsigned comparison.
7249     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7250   }
7251
7252   // If we aren't dealing with a constant on the RHS, exit early
7253   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7254   if (!CI)
7255     return 0;
7256
7257   // Compute the constant that would happen if we truncated to SrcTy then
7258   // reextended to DestTy.
7259   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7260   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7261                                                 Res1, DestTy);
7262
7263   // If the re-extended constant didn't change...
7264   if (Res2 == CI) {
7265     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7266     // For example, we might have:
7267     //    %A = sext i16 %X to i32
7268     //    %B = icmp ugt i32 %A, 1330
7269     // It is incorrect to transform this into 
7270     //    %B = icmp ugt i16 %X, 1330
7271     // because %A may have negative value. 
7272     //
7273     // However, we allow this when the compare is EQ/NE, because they are
7274     // signless.
7275     if (isSignedExt == isSignedCmp || ICI.isEquality())
7276       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7277     return 0;
7278   }
7279
7280   // The re-extended constant changed so the constant cannot be represented 
7281   // in the shorter type. Consequently, we cannot emit a simple comparison.
7282
7283   // First, handle some easy cases. We know the result cannot be equal at this
7284   // point so handle the ICI.isEquality() cases
7285   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7286     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7287   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7288     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7289
7290   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7291   // should have been folded away previously and not enter in here.
7292   Value *Result;
7293   if (isSignedCmp) {
7294     // We're performing a signed comparison.
7295     if (cast<ConstantInt>(CI)->getValue().isNegative())
7296       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7297     else
7298       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7299   } else {
7300     // We're performing an unsigned comparison.
7301     if (isSignedExt) {
7302       // We're performing an unsigned comp with a sign extended value.
7303       // This is true if the input is >= 0. [aka >s -1]
7304       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7305       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT,
7306                                    LHSCIOp, NegOne, ICI.getName()), ICI);
7307     } else {
7308       // Unsigned extend & unsigned compare -> always true.
7309       Result = ConstantInt::getTrue(*Context);
7310     }
7311   }
7312
7313   // Finally, return the value computed.
7314   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7315       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7316     return ReplaceInstUsesWith(ICI, Result);
7317
7318   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7319           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7320          "ICmp should be folded!");
7321   if (Constant *CI = dyn_cast<Constant>(Result))
7322     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7323   return BinaryOperator::CreateNot(Result);
7324 }
7325
7326 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7327   return commonShiftTransforms(I);
7328 }
7329
7330 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7331   return commonShiftTransforms(I);
7332 }
7333
7334 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7335   if (Instruction *R = commonShiftTransforms(I))
7336     return R;
7337   
7338   Value *Op0 = I.getOperand(0);
7339   
7340   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7341   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7342     if (CSI->isAllOnesValue())
7343       return ReplaceInstUsesWith(I, CSI);
7344
7345   // See if we can turn a signed shr into an unsigned shr.
7346   if (MaskedValueIsZero(Op0,
7347                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7348     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7349
7350   // Arithmetic shifting an all-sign-bit value is a no-op.
7351   unsigned NumSignBits = ComputeNumSignBits(Op0);
7352   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7353     return ReplaceInstUsesWith(I, Op0);
7354
7355   return 0;
7356 }
7357
7358 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7359   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7360   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7361
7362   // shl X, 0 == X and shr X, 0 == X
7363   // shl 0, X == 0 and shr 0, X == 0
7364   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7365       Op0 == Constant::getNullValue(Op0->getType()))
7366     return ReplaceInstUsesWith(I, Op0);
7367   
7368   if (isa<UndefValue>(Op0)) {            
7369     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7370       return ReplaceInstUsesWith(I, Op0);
7371     else                                    // undef << X -> 0, undef >>u X -> 0
7372       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7373   }
7374   if (isa<UndefValue>(Op1)) {
7375     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7376       return ReplaceInstUsesWith(I, Op0);          
7377     else                                     // X << undef, X >>u undef -> 0
7378       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7379   }
7380
7381   // See if we can fold away this shift.
7382   if (SimplifyDemandedInstructionBits(I))
7383     return &I;
7384
7385   // Try to fold constant and into select arguments.
7386   if (isa<Constant>(Op0))
7387     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7388       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7389         return R;
7390
7391   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7392     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7393       return Res;
7394   return 0;
7395 }
7396
7397 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7398                                                BinaryOperator &I) {
7399   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7400
7401   // See if we can simplify any instructions used by the instruction whose sole 
7402   // purpose is to compute bits we don't care about.
7403   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7404   
7405   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7406   // a signed shift.
7407   //
7408   if (Op1->uge(TypeBits)) {
7409     if (I.getOpcode() != Instruction::AShr)
7410       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7411     else {
7412       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7413       return &I;
7414     }
7415   }
7416   
7417   // ((X*C1) << C2) == (X * (C1 << C2))
7418   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7419     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7420       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7421         return BinaryOperator::CreateMul(BO->getOperand(0),
7422                                         ConstantExpr::getShl(BOOp, Op1));
7423   
7424   // Try to fold constant and into select arguments.
7425   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7426     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7427       return R;
7428   if (isa<PHINode>(Op0))
7429     if (Instruction *NV = FoldOpIntoPhi(I))
7430       return NV;
7431   
7432   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7433   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7434     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7435     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7436     // place.  Don't try to do this transformation in this case.  Also, we
7437     // require that the input operand is a shift-by-constant so that we have
7438     // confidence that the shifts will get folded together.  We could do this
7439     // xform in more cases, but it is unlikely to be profitable.
7440     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7441         isa<ConstantInt>(TrOp->getOperand(1))) {
7442       // Okay, we'll do this xform.  Make the shift of shift.
7443       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7444       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7445                                                 I.getName());
7446       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7447
7448       // For logical shifts, the truncation has the effect of making the high
7449       // part of the register be zeros.  Emulate this by inserting an AND to
7450       // clear the top bits as needed.  This 'and' will usually be zapped by
7451       // other xforms later if dead.
7452       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7453       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7454       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7455       
7456       // The mask we constructed says what the trunc would do if occurring
7457       // between the shifts.  We want to know the effect *after* the second
7458       // shift.  We know that it is a logical shift by a constant, so adjust the
7459       // mask as appropriate.
7460       if (I.getOpcode() == Instruction::Shl)
7461         MaskV <<= Op1->getZExtValue();
7462       else {
7463         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7464         MaskV = MaskV.lshr(Op1->getZExtValue());
7465       }
7466
7467       Instruction *And =
7468         BinaryOperator::CreateAnd(NSh, ConstantInt::get(*Context, MaskV), 
7469                                   TI->getName());
7470       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7471
7472       // Return the value truncated to the interesting size.
7473       return new TruncInst(And, I.getType());
7474     }
7475   }
7476   
7477   if (Op0->hasOneUse()) {
7478     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7479       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7480       Value *V1, *V2;
7481       ConstantInt *CC;
7482       switch (Op0BO->getOpcode()) {
7483         default: break;
7484         case Instruction::Add:
7485         case Instruction::And:
7486         case Instruction::Or:
7487         case Instruction::Xor: {
7488           // These operators commute.
7489           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7490           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7491               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7492                     m_Specific(Op1)))){
7493             Instruction *YS = BinaryOperator::CreateShl(
7494                                             Op0BO->getOperand(0), Op1,
7495                                             Op0BO->getName());
7496             InsertNewInstBefore(YS, I); // (Y << C)
7497             Instruction *X = 
7498               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7499                                      Op0BO->getOperand(1)->getName());
7500             InsertNewInstBefore(X, I);  // (X + (Y << C))
7501             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7502             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7503                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7504           }
7505           
7506           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7507           Value *Op0BOOp1 = Op0BO->getOperand(1);
7508           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7509               match(Op0BOOp1, 
7510                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7511                           m_ConstantInt(CC))) &&
7512               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7513             Instruction *YS = BinaryOperator::CreateShl(
7514                                                      Op0BO->getOperand(0), Op1,
7515                                                      Op0BO->getName());
7516             InsertNewInstBefore(YS, I); // (Y << C)
7517             Instruction *XM =
7518               BinaryOperator::CreateAnd(V1,
7519                                         ConstantExpr::getShl(CC, Op1),
7520                                         V1->getName()+".mask");
7521             InsertNewInstBefore(XM, I); // X & (CC << C)
7522             
7523             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7524           }
7525         }
7526           
7527         // FALL THROUGH.
7528         case Instruction::Sub: {
7529           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7530           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7531               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7532                     m_Specific(Op1)))) {
7533             Instruction *YS = BinaryOperator::CreateShl(
7534                                                      Op0BO->getOperand(1), Op1,
7535                                                      Op0BO->getName());
7536             InsertNewInstBefore(YS, I); // (Y << C)
7537             Instruction *X =
7538               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7539                                      Op0BO->getOperand(0)->getName());
7540             InsertNewInstBefore(X, I);  // (X + (Y << C))
7541             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7542             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7543                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7544           }
7545           
7546           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7547           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7548               match(Op0BO->getOperand(0),
7549                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7550                           m_ConstantInt(CC))) && V2 == Op1 &&
7551               cast<BinaryOperator>(Op0BO->getOperand(0))
7552                   ->getOperand(0)->hasOneUse()) {
7553             Instruction *YS = BinaryOperator::CreateShl(
7554                                                      Op0BO->getOperand(1), Op1,
7555                                                      Op0BO->getName());
7556             InsertNewInstBefore(YS, I); // (Y << C)
7557             Instruction *XM =
7558               BinaryOperator::CreateAnd(V1, 
7559                                         ConstantExpr::getShl(CC, Op1),
7560                                         V1->getName()+".mask");
7561             InsertNewInstBefore(XM, I); // X & (CC << C)
7562             
7563             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7564           }
7565           
7566           break;
7567         }
7568       }
7569       
7570       
7571       // If the operand is an bitwise operator with a constant RHS, and the
7572       // shift is the only use, we can pull it out of the shift.
7573       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7574         bool isValid = true;     // Valid only for And, Or, Xor
7575         bool highBitSet = false; // Transform if high bit of constant set?
7576         
7577         switch (Op0BO->getOpcode()) {
7578           default: isValid = false; break;   // Do not perform transform!
7579           case Instruction::Add:
7580             isValid = isLeftShift;
7581             break;
7582           case Instruction::Or:
7583           case Instruction::Xor:
7584             highBitSet = false;
7585             break;
7586           case Instruction::And:
7587             highBitSet = true;
7588             break;
7589         }
7590         
7591         // If this is a signed shift right, and the high bit is modified
7592         // by the logical operation, do not perform the transformation.
7593         // The highBitSet boolean indicates the value of the high bit of
7594         // the constant which would cause it to be modified for this
7595         // operation.
7596         //
7597         if (isValid && I.getOpcode() == Instruction::AShr)
7598           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7599         
7600         if (isValid) {
7601           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7602           
7603           Instruction *NewShift =
7604             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7605           InsertNewInstBefore(NewShift, I);
7606           NewShift->takeName(Op0BO);
7607           
7608           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7609                                         NewRHS);
7610         }
7611       }
7612     }
7613   }
7614   
7615   // Find out if this is a shift of a shift by a constant.
7616   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7617   if (ShiftOp && !ShiftOp->isShift())
7618     ShiftOp = 0;
7619   
7620   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7621     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7622     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7623     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7624     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7625     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7626     Value *X = ShiftOp->getOperand(0);
7627     
7628     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7629     
7630     const IntegerType *Ty = cast<IntegerType>(I.getType());
7631     
7632     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7633     if (I.getOpcode() == ShiftOp->getOpcode()) {
7634       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7635       // saturates.
7636       if (AmtSum >= TypeBits) {
7637         if (I.getOpcode() != Instruction::AShr)
7638           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7639         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7640       }
7641       
7642       return BinaryOperator::Create(I.getOpcode(), X,
7643                                     ConstantInt::get(Ty, AmtSum));
7644     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7645                I.getOpcode() == Instruction::AShr) {
7646       if (AmtSum >= TypeBits)
7647         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7648       
7649       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7650       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7651     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7652                I.getOpcode() == Instruction::LShr) {
7653       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7654       if (AmtSum >= TypeBits)
7655         AmtSum = TypeBits-1;
7656       
7657       Instruction *Shift =
7658         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7659       InsertNewInstBefore(Shift, I);
7660
7661       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7662       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7663     }
7664     
7665     // Okay, if we get here, one shift must be left, and the other shift must be
7666     // right.  See if the amounts are equal.
7667     if (ShiftAmt1 == ShiftAmt2) {
7668       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7669       if (I.getOpcode() == Instruction::Shl) {
7670         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7671         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7672       }
7673       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7674       if (I.getOpcode() == Instruction::LShr) {
7675         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7676         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7677       }
7678       // We can simplify ((X << C) >>s C) into a trunc + sext.
7679       // NOTE: we could do this for any C, but that would make 'unusual' integer
7680       // types.  For now, just stick to ones well-supported by the code
7681       // generators.
7682       const Type *SExtType = 0;
7683       switch (Ty->getBitWidth() - ShiftAmt1) {
7684       case 1  :
7685       case 8  :
7686       case 16 :
7687       case 32 :
7688       case 64 :
7689       case 128:
7690         SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7691         break;
7692       default: break;
7693       }
7694       if (SExtType) {
7695         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7696         InsertNewInstBefore(NewTrunc, I);
7697         return new SExtInst(NewTrunc, Ty);
7698       }
7699       // Otherwise, we can't handle it yet.
7700     } else if (ShiftAmt1 < ShiftAmt2) {
7701       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7702       
7703       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7704       if (I.getOpcode() == Instruction::Shl) {
7705         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7706                ShiftOp->getOpcode() == Instruction::AShr);
7707         Instruction *Shift =
7708           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7709         InsertNewInstBefore(Shift, I);
7710         
7711         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7712         return BinaryOperator::CreateAnd(Shift,
7713                                          ConstantInt::get(*Context, Mask));
7714       }
7715       
7716       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7717       if (I.getOpcode() == Instruction::LShr) {
7718         assert(ShiftOp->getOpcode() == Instruction::Shl);
7719         Instruction *Shift =
7720           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7721         InsertNewInstBefore(Shift, I);
7722         
7723         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7724         return BinaryOperator::CreateAnd(Shift,
7725                                          ConstantInt::get(*Context, Mask));
7726       }
7727       
7728       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7729     } else {
7730       assert(ShiftAmt2 < ShiftAmt1);
7731       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7732
7733       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7734       if (I.getOpcode() == Instruction::Shl) {
7735         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7736                ShiftOp->getOpcode() == Instruction::AShr);
7737         Instruction *Shift =
7738           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7739                                  ConstantInt::get(Ty, ShiftDiff));
7740         InsertNewInstBefore(Shift, I);
7741         
7742         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7743         return BinaryOperator::CreateAnd(Shift,
7744                                          ConstantInt::get(*Context, Mask));
7745       }
7746       
7747       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7748       if (I.getOpcode() == Instruction::LShr) {
7749         assert(ShiftOp->getOpcode() == Instruction::Shl);
7750         Instruction *Shift =
7751           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7752         InsertNewInstBefore(Shift, I);
7753         
7754         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7755         return BinaryOperator::CreateAnd(Shift,
7756                                          ConstantInt::get(*Context, Mask));
7757       }
7758       
7759       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7760     }
7761   }
7762   return 0;
7763 }
7764
7765
7766 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7767 /// expression.  If so, decompose it, returning some value X, such that Val is
7768 /// X*Scale+Offset.
7769 ///
7770 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7771                                         int &Offset, LLVMContext *Context) {
7772   assert(Val->getType() == Type::getInt32Ty(*Context) && "Unexpected allocation size type!");
7773   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7774     Offset = CI->getZExtValue();
7775     Scale  = 0;
7776     return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7777   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7778     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7779       if (I->getOpcode() == Instruction::Shl) {
7780         // This is a value scaled by '1 << the shift amt'.
7781         Scale = 1U << RHS->getZExtValue();
7782         Offset = 0;
7783         return I->getOperand(0);
7784       } else if (I->getOpcode() == Instruction::Mul) {
7785         // This value is scaled by 'RHS'.
7786         Scale = RHS->getZExtValue();
7787         Offset = 0;
7788         return I->getOperand(0);
7789       } else if (I->getOpcode() == Instruction::Add) {
7790         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7791         // where C1 is divisible by C2.
7792         unsigned SubScale;
7793         Value *SubVal = 
7794           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7795                                     Offset, Context);
7796         Offset += RHS->getZExtValue();
7797         Scale = SubScale;
7798         return SubVal;
7799       }
7800     }
7801   }
7802
7803   // Otherwise, we can't look past this.
7804   Scale = 1;
7805   Offset = 0;
7806   return Val;
7807 }
7808
7809
7810 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7811 /// try to eliminate the cast by moving the type information into the alloc.
7812 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7813                                                    AllocationInst &AI) {
7814   const PointerType *PTy = cast<PointerType>(CI.getType());
7815   
7816   // Remove any uses of AI that are dead.
7817   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7818   
7819   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7820     Instruction *User = cast<Instruction>(*UI++);
7821     if (isInstructionTriviallyDead(User)) {
7822       while (UI != E && *UI == User)
7823         ++UI; // If this instruction uses AI more than once, don't break UI.
7824       
7825       ++NumDeadInst;
7826       DEBUG(errs() << "IC: DCE: " << *User << '\n');
7827       EraseInstFromFunction(*User);
7828     }
7829   }
7830
7831   // This requires TargetData to get the alloca alignment and size information.
7832   if (!TD) return 0;
7833
7834   // Get the type really allocated and the type casted to.
7835   const Type *AllocElTy = AI.getAllocatedType();
7836   const Type *CastElTy = PTy->getElementType();
7837   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7838
7839   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7840   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7841   if (CastElTyAlign < AllocElTyAlign) return 0;
7842
7843   // If the allocation has multiple uses, only promote it if we are strictly
7844   // increasing the alignment of the resultant allocation.  If we keep it the
7845   // same, we open the door to infinite loops of various kinds.  (A reference
7846   // from a dbg.declare doesn't count as a use for this purpose.)
7847   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7848       CastElTyAlign == AllocElTyAlign) return 0;
7849
7850   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7851   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7852   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7853
7854   // See if we can satisfy the modulus by pulling a scale out of the array
7855   // size argument.
7856   unsigned ArraySizeScale;
7857   int ArrayOffset;
7858   Value *NumElements = // See if the array size is a decomposable linear expr.
7859     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7860                               ArrayOffset, Context);
7861  
7862   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7863   // do the xform.
7864   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7865       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7866
7867   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7868   Value *Amt = 0;
7869   if (Scale == 1) {
7870     Amt = NumElements;
7871   } else {
7872     // If the allocation size is constant, form a constant mul expression
7873     Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7874     if (isa<ConstantInt>(NumElements))
7875       Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
7876                                  cast<ConstantInt>(Amt));
7877     // otherwise multiply the amount and the number of elements
7878     else {
7879       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7880       Amt = InsertNewInstBefore(Tmp, AI);
7881     }
7882   }
7883   
7884   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7885     Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7886     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7887     Amt = InsertNewInstBefore(Tmp, AI);
7888   }
7889   
7890   AllocationInst *New;
7891   if (isa<MallocInst>(AI))
7892     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7893   else
7894     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7895   InsertNewInstBefore(New, AI);
7896   New->takeName(&AI);
7897   
7898   // If the allocation has one real use plus a dbg.declare, just remove the
7899   // declare.
7900   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7901     EraseInstFromFunction(*DI);
7902   }
7903   // If the allocation has multiple real uses, insert a cast and change all
7904   // things that used it to use the new cast.  This will also hack on CI, but it
7905   // will die soon.
7906   else if (!AI.hasOneUse()) {
7907     AddUsesToWorkList(AI);
7908     // New is the allocation instruction, pointer typed. AI is the original
7909     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7910     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7911     InsertNewInstBefore(NewCast, AI);
7912     AI.replaceAllUsesWith(NewCast);
7913   }
7914   return ReplaceInstUsesWith(CI, New);
7915 }
7916
7917 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7918 /// and return it as type Ty without inserting any new casts and without
7919 /// changing the computed value.  This is used by code that tries to decide
7920 /// whether promoting or shrinking integer operations to wider or smaller types
7921 /// will allow us to eliminate a truncate or extend.
7922 ///
7923 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7924 /// extension operation if Ty is larger.
7925 ///
7926 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7927 /// should return true if trunc(V) can be computed by computing V in the smaller
7928 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7929 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7930 /// efficiently truncated.
7931 ///
7932 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7933 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7934 /// the final result.
7935 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7936                                               unsigned CastOpc,
7937                                               int &NumCastsRemoved){
7938   // We can always evaluate constants in another type.
7939   if (isa<Constant>(V))
7940     return true;
7941   
7942   Instruction *I = dyn_cast<Instruction>(V);
7943   if (!I) return false;
7944   
7945   const Type *OrigTy = V->getType();
7946   
7947   // If this is an extension or truncate, we can often eliminate it.
7948   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7949     // If this is a cast from the destination type, we can trivially eliminate
7950     // it, and this will remove a cast overall.
7951     if (I->getOperand(0)->getType() == Ty) {
7952       // If the first operand is itself a cast, and is eliminable, do not count
7953       // this as an eliminable cast.  We would prefer to eliminate those two
7954       // casts first.
7955       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7956         ++NumCastsRemoved;
7957       return true;
7958     }
7959   }
7960
7961   // We can't extend or shrink something that has multiple uses: doing so would
7962   // require duplicating the instruction in general, which isn't profitable.
7963   if (!I->hasOneUse()) return false;
7964
7965   unsigned Opc = I->getOpcode();
7966   switch (Opc) {
7967   case Instruction::Add:
7968   case Instruction::Sub:
7969   case Instruction::Mul:
7970   case Instruction::And:
7971   case Instruction::Or:
7972   case Instruction::Xor:
7973     // These operators can all arbitrarily be extended or truncated.
7974     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7975                                       NumCastsRemoved) &&
7976            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7977                                       NumCastsRemoved);
7978
7979   case Instruction::UDiv:
7980   case Instruction::URem: {
7981     // UDiv and URem can be truncated if all the truncated bits are zero.
7982     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7983     uint32_t BitWidth = Ty->getScalarSizeInBits();
7984     if (BitWidth < OrigBitWidth) {
7985       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7986       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7987           MaskedValueIsZero(I->getOperand(1), Mask)) {
7988         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7989                                           NumCastsRemoved) &&
7990                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7991                                           NumCastsRemoved);
7992       }
7993     }
7994     break;
7995   }
7996   case Instruction::Shl:
7997     // If we are truncating the result of this SHL, and if it's a shift of a
7998     // constant amount, we can always perform a SHL in a smaller type.
7999     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8000       uint32_t BitWidth = Ty->getScalarSizeInBits();
8001       if (BitWidth < OrigTy->getScalarSizeInBits() &&
8002           CI->getLimitedValue(BitWidth) < BitWidth)
8003         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8004                                           NumCastsRemoved);
8005     }
8006     break;
8007   case Instruction::LShr:
8008     // If this is a truncate of a logical shr, we can truncate it to a smaller
8009     // lshr iff we know that the bits we would otherwise be shifting in are
8010     // already zeros.
8011     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8012       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8013       uint32_t BitWidth = Ty->getScalarSizeInBits();
8014       if (BitWidth < OrigBitWidth &&
8015           MaskedValueIsZero(I->getOperand(0),
8016             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8017           CI->getLimitedValue(BitWidth) < BitWidth) {
8018         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8019                                           NumCastsRemoved);
8020       }
8021     }
8022     break;
8023   case Instruction::ZExt:
8024   case Instruction::SExt:
8025   case Instruction::Trunc:
8026     // If this is the same kind of case as our original (e.g. zext+zext), we
8027     // can safely replace it.  Note that replacing it does not reduce the number
8028     // of casts in the input.
8029     if (Opc == CastOpc)
8030       return true;
8031
8032     // sext (zext ty1), ty2 -> zext ty2
8033     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8034       return true;
8035     break;
8036   case Instruction::Select: {
8037     SelectInst *SI = cast<SelectInst>(I);
8038     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8039                                       NumCastsRemoved) &&
8040            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8041                                       NumCastsRemoved);
8042   }
8043   case Instruction::PHI: {
8044     // We can change a phi if we can change all operands.
8045     PHINode *PN = cast<PHINode>(I);
8046     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8047       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8048                                       NumCastsRemoved))
8049         return false;
8050     return true;
8051   }
8052   default:
8053     // TODO: Can handle more cases here.
8054     break;
8055   }
8056   
8057   return false;
8058 }
8059
8060 /// EvaluateInDifferentType - Given an expression that 
8061 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8062 /// evaluate the expression.
8063 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8064                                              bool isSigned) {
8065   if (Constant *C = dyn_cast<Constant>(V))
8066     return ConstantExpr::getIntegerCast(C, Ty,
8067                                                isSigned /*Sext or ZExt*/);
8068
8069   // Otherwise, it must be an instruction.
8070   Instruction *I = cast<Instruction>(V);
8071   Instruction *Res = 0;
8072   unsigned Opc = I->getOpcode();
8073   switch (Opc) {
8074   case Instruction::Add:
8075   case Instruction::Sub:
8076   case Instruction::Mul:
8077   case Instruction::And:
8078   case Instruction::Or:
8079   case Instruction::Xor:
8080   case Instruction::AShr:
8081   case Instruction::LShr:
8082   case Instruction::Shl:
8083   case Instruction::UDiv:
8084   case Instruction::URem: {
8085     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8086     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8087     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8088     break;
8089   }    
8090   case Instruction::Trunc:
8091   case Instruction::ZExt:
8092   case Instruction::SExt:
8093     // If the source type of the cast is the type we're trying for then we can
8094     // just return the source.  There's no need to insert it because it is not
8095     // new.
8096     if (I->getOperand(0)->getType() == Ty)
8097       return I->getOperand(0);
8098     
8099     // Otherwise, must be the same type of cast, so just reinsert a new one.
8100     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8101                            Ty);
8102     break;
8103   case Instruction::Select: {
8104     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8105     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8106     Res = SelectInst::Create(I->getOperand(0), True, False);
8107     break;
8108   }
8109   case Instruction::PHI: {
8110     PHINode *OPN = cast<PHINode>(I);
8111     PHINode *NPN = PHINode::Create(Ty);
8112     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8113       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8114       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8115     }
8116     Res = NPN;
8117     break;
8118   }
8119   default: 
8120     // TODO: Can handle more cases here.
8121     llvm_unreachable("Unreachable!");
8122     break;
8123   }
8124   
8125   Res->takeName(I);
8126   return InsertNewInstBefore(Res, *I);
8127 }
8128
8129 /// @brief Implement the transforms common to all CastInst visitors.
8130 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8131   Value *Src = CI.getOperand(0);
8132
8133   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8134   // eliminate it now.
8135   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8136     if (Instruction::CastOps opc = 
8137         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8138       // The first cast (CSrc) is eliminable so we need to fix up or replace
8139       // the second cast (CI). CSrc will then have a good chance of being dead.
8140       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8141     }
8142   }
8143
8144   // If we are casting a select then fold the cast into the select
8145   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8146     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8147       return NV;
8148
8149   // If we are casting a PHI then fold the cast into the PHI
8150   if (isa<PHINode>(Src))
8151     if (Instruction *NV = FoldOpIntoPhi(CI))
8152       return NV;
8153   
8154   return 0;
8155 }
8156
8157 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8158 /// or not there is a sequence of GEP indices into the type that will land us at
8159 /// the specified offset.  If so, fill them into NewIndices and return the
8160 /// resultant element type, otherwise return null.
8161 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8162                                        SmallVectorImpl<Value*> &NewIndices,
8163                                        const TargetData *TD,
8164                                        LLVMContext *Context) {
8165   if (!TD) return 0;
8166   if (!Ty->isSized()) return 0;
8167   
8168   // Start with the index over the outer type.  Note that the type size
8169   // might be zero (even if the offset isn't zero) if the indexed type
8170   // is something like [0 x {int, int}]
8171   const Type *IntPtrTy = TD->getIntPtrType(*Context);
8172   int64_t FirstIdx = 0;
8173   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8174     FirstIdx = Offset/TySize;
8175     Offset -= FirstIdx*TySize;
8176     
8177     // Handle hosts where % returns negative instead of values [0..TySize).
8178     if (Offset < 0) {
8179       --FirstIdx;
8180       Offset += TySize;
8181       assert(Offset >= 0);
8182     }
8183     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8184   }
8185   
8186   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8187     
8188   // Index into the types.  If we fail, set OrigBase to null.
8189   while (Offset) {
8190     // Indexing into tail padding between struct/array elements.
8191     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8192       return 0;
8193     
8194     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8195       const StructLayout *SL = TD->getStructLayout(STy);
8196       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8197              "Offset must stay within the indexed type");
8198       
8199       unsigned Elt = SL->getElementContainingOffset(Offset);
8200       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8201       
8202       Offset -= SL->getElementOffset(Elt);
8203       Ty = STy->getElementType(Elt);
8204     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8205       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8206       assert(EltSize && "Cannot index into a zero-sized array");
8207       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8208       Offset %= EltSize;
8209       Ty = AT->getElementType();
8210     } else {
8211       // Otherwise, we can't index into the middle of this atomic type, bail.
8212       return 0;
8213     }
8214   }
8215   
8216   return Ty;
8217 }
8218
8219 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8220 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8221   Value *Src = CI.getOperand(0);
8222   
8223   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8224     // If casting the result of a getelementptr instruction with no offset, turn
8225     // this into a cast of the original pointer!
8226     if (GEP->hasAllZeroIndices()) {
8227       // Changing the cast operand is usually not a good idea but it is safe
8228       // here because the pointer operand is being replaced with another 
8229       // pointer operand so the opcode doesn't need to change.
8230       AddToWorkList(GEP);
8231       CI.setOperand(0, GEP->getOperand(0));
8232       return &CI;
8233     }
8234     
8235     // If the GEP has a single use, and the base pointer is a bitcast, and the
8236     // GEP computes a constant offset, see if we can convert these three
8237     // instructions into fewer.  This typically happens with unions and other
8238     // non-type-safe code.
8239     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8240       if (GEP->hasAllConstantIndices()) {
8241         // We are guaranteed to get a constant from EmitGEPOffset.
8242         ConstantInt *OffsetV =
8243                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8244         int64_t Offset = OffsetV->getSExtValue();
8245         
8246         // Get the base pointer input of the bitcast, and the type it points to.
8247         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8248         const Type *GEPIdxTy =
8249           cast<PointerType>(OrigBase->getType())->getElementType();
8250         SmallVector<Value*, 8> NewIndices;
8251         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8252           // If we were able to index down into an element, create the GEP
8253           // and bitcast the result.  This eliminates one bitcast, potentially
8254           // two.
8255           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8256                                                         NewIndices.begin(),
8257                                                         NewIndices.end(), "");
8258           InsertNewInstBefore(NGEP, CI);
8259           NGEP->takeName(GEP);
8260           if (cast<GEPOperator>(GEP)->isInBounds())
8261             cast<GEPOperator>(NGEP)->setIsInBounds(true);
8262           
8263           if (isa<BitCastInst>(CI))
8264             return new BitCastInst(NGEP, CI.getType());
8265           assert(isa<PtrToIntInst>(CI));
8266           return new PtrToIntInst(NGEP, CI.getType());
8267         }
8268       }      
8269     }
8270   }
8271     
8272   return commonCastTransforms(CI);
8273 }
8274
8275 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8276 /// type like i42.  We don't want to introduce operations on random non-legal
8277 /// integer types where they don't already exist in the code.  In the future,
8278 /// we should consider making this based off target-data, so that 32-bit targets
8279 /// won't get i64 operations etc.
8280 static bool isSafeIntegerType(const Type *Ty) {
8281   switch (Ty->getPrimitiveSizeInBits()) {
8282   case 8:
8283   case 16:
8284   case 32:
8285   case 64:
8286     return true;
8287   default: 
8288     return false;
8289   }
8290 }
8291
8292 /// commonIntCastTransforms - This function implements the common transforms
8293 /// for trunc, zext, and sext.
8294 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8295   if (Instruction *Result = commonCastTransforms(CI))
8296     return Result;
8297
8298   Value *Src = CI.getOperand(0);
8299   const Type *SrcTy = Src->getType();
8300   const Type *DestTy = CI.getType();
8301   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8302   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8303
8304   // See if we can simplify any instructions used by the LHS whose sole 
8305   // purpose is to compute bits we don't care about.
8306   if (SimplifyDemandedInstructionBits(CI))
8307     return &CI;
8308
8309   // If the source isn't an instruction or has more than one use then we
8310   // can't do anything more. 
8311   Instruction *SrcI = dyn_cast<Instruction>(Src);
8312   if (!SrcI || !Src->hasOneUse())
8313     return 0;
8314
8315   // Attempt to propagate the cast into the instruction for int->int casts.
8316   int NumCastsRemoved = 0;
8317   // Only do this if the dest type is a simple type, don't convert the
8318   // expression tree to something weird like i93 unless the source is also
8319   // strange.
8320   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8321        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8322       CanEvaluateInDifferentType(SrcI, DestTy,
8323                                  CI.getOpcode(), NumCastsRemoved)) {
8324     // If this cast is a truncate, evaluting in a different type always
8325     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8326     // we need to do an AND to maintain the clear top-part of the computation,
8327     // so we require that the input have eliminated at least one cast.  If this
8328     // is a sign extension, we insert two new casts (to do the extension) so we
8329     // require that two casts have been eliminated.
8330     bool DoXForm = false;
8331     bool JustReplace = false;
8332     switch (CI.getOpcode()) {
8333     default:
8334       // All the others use floating point so we shouldn't actually 
8335       // get here because of the check above.
8336       llvm_unreachable("Unknown cast type");
8337     case Instruction::Trunc:
8338       DoXForm = true;
8339       break;
8340     case Instruction::ZExt: {
8341       DoXForm = NumCastsRemoved >= 1;
8342       if (!DoXForm && 0) {
8343         // If it's unnecessary to issue an AND to clear the high bits, it's
8344         // always profitable to do this xform.
8345         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8346         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8347         if (MaskedValueIsZero(TryRes, Mask))
8348           return ReplaceInstUsesWith(CI, TryRes);
8349         
8350         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8351           if (TryI->use_empty())
8352             EraseInstFromFunction(*TryI);
8353       }
8354       break;
8355     }
8356     case Instruction::SExt: {
8357       DoXForm = NumCastsRemoved >= 2;
8358       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8359         // If we do not have to emit the truncate + sext pair, then it's always
8360         // profitable to do this xform.
8361         //
8362         // It's not safe to eliminate the trunc + sext pair if one of the
8363         // eliminated cast is a truncate. e.g.
8364         // t2 = trunc i32 t1 to i16
8365         // t3 = sext i16 t2 to i32
8366         // !=
8367         // i32 t1
8368         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8369         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8370         if (NumSignBits > (DestBitSize - SrcBitSize))
8371           return ReplaceInstUsesWith(CI, TryRes);
8372         
8373         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8374           if (TryI->use_empty())
8375             EraseInstFromFunction(*TryI);
8376       }
8377       break;
8378     }
8379     }
8380     
8381     if (DoXForm) {
8382       DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8383             " to avoid cast: " << CI);
8384       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8385                                            CI.getOpcode() == Instruction::SExt);
8386       if (JustReplace)
8387         // Just replace this cast with the result.
8388         return ReplaceInstUsesWith(CI, Res);
8389
8390       assert(Res->getType() == DestTy);
8391       switch (CI.getOpcode()) {
8392       default: llvm_unreachable("Unknown cast type!");
8393       case Instruction::Trunc:
8394         // Just replace this cast with the result.
8395         return ReplaceInstUsesWith(CI, Res);
8396       case Instruction::ZExt: {
8397         assert(SrcBitSize < DestBitSize && "Not a zext?");
8398
8399         // If the high bits are already zero, just replace this cast with the
8400         // result.
8401         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8402         if (MaskedValueIsZero(Res, Mask))
8403           return ReplaceInstUsesWith(CI, Res);
8404
8405         // We need to emit an AND to clear the high bits.
8406         Constant *C = ConstantInt::get(*Context, 
8407                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8408         return BinaryOperator::CreateAnd(Res, C);
8409       }
8410       case Instruction::SExt: {
8411         // If the high bits are already filled with sign bit, just replace this
8412         // cast with the result.
8413         unsigned NumSignBits = ComputeNumSignBits(Res);
8414         if (NumSignBits > (DestBitSize - SrcBitSize))
8415           return ReplaceInstUsesWith(CI, Res);
8416
8417         // We need to emit a cast to truncate, then a cast to sext.
8418         return CastInst::Create(Instruction::SExt,
8419             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8420                              CI), DestTy);
8421       }
8422       }
8423     }
8424   }
8425   
8426   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8427   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8428
8429   switch (SrcI->getOpcode()) {
8430   case Instruction::Add:
8431   case Instruction::Mul:
8432   case Instruction::And:
8433   case Instruction::Or:
8434   case Instruction::Xor:
8435     // If we are discarding information, rewrite.
8436     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8437       // Don't insert two casts unless at least one can be eliminated.
8438       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8439           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8440         Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8441         Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8442         return BinaryOperator::Create(
8443             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8444       }
8445     }
8446
8447     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8448     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8449         SrcI->getOpcode() == Instruction::Xor &&
8450         Op1 == ConstantInt::getTrue(*Context) &&
8451         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8452       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8453       return BinaryOperator::CreateXor(New,
8454                                       ConstantInt::get(CI.getType(), 1));
8455     }
8456     break;
8457
8458   case Instruction::Shl: {
8459     // Canonicalize trunc inside shl, if we can.
8460     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8461     if (CI && DestBitSize < SrcBitSize &&
8462         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8463       Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8464       Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8465       return BinaryOperator::CreateShl(Op0c, Op1c);
8466     }
8467     break;
8468   }
8469   }
8470   return 0;
8471 }
8472
8473 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8474   if (Instruction *Result = commonIntCastTransforms(CI))
8475     return Result;
8476   
8477   Value *Src = CI.getOperand(0);
8478   const Type *Ty = CI.getType();
8479   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8480   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8481
8482   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8483   if (DestBitWidth == 1) {
8484     Constant *One = ConstantInt::get(Src->getType(), 1);
8485     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8486     Value *Zero = Constant::getNullValue(Src->getType());
8487     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8488   }
8489
8490   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8491   ConstantInt *ShAmtV = 0;
8492   Value *ShiftOp = 0;
8493   if (Src->hasOneUse() &&
8494       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8495     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8496     
8497     // Get a mask for the bits shifting in.
8498     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8499     if (MaskedValueIsZero(ShiftOp, Mask)) {
8500       if (ShAmt >= DestBitWidth)        // All zeros.
8501         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8502       
8503       // Okay, we can shrink this.  Truncate the input, then return a new
8504       // shift.
8505       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8506       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8507       return BinaryOperator::CreateLShr(V1, V2);
8508     }
8509   }
8510   
8511   return 0;
8512 }
8513
8514 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8515 /// in order to eliminate the icmp.
8516 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8517                                              bool DoXform) {
8518   // If we are just checking for a icmp eq of a single bit and zext'ing it
8519   // to an integer, then shift the bit to the appropriate place and then
8520   // cast to integer to avoid the comparison.
8521   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8522     const APInt &Op1CV = Op1C->getValue();
8523       
8524     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8525     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8526     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8527         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8528       if (!DoXform) return ICI;
8529
8530       Value *In = ICI->getOperand(0);
8531       Value *Sh = ConstantInt::get(In->getType(),
8532                                    In->getType()->getScalarSizeInBits()-1);
8533       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8534                                                         In->getName()+".lobit"),
8535                                CI);
8536       if (In->getType() != CI.getType())
8537         In = CastInst::CreateIntegerCast(In, CI.getType(),
8538                                          false/*ZExt*/, "tmp", &CI);
8539
8540       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8541         Constant *One = ConstantInt::get(In->getType(), 1);
8542         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8543                                                          In->getName()+".not"),
8544                                  CI);
8545       }
8546
8547       return ReplaceInstUsesWith(CI, In);
8548     }
8549       
8550       
8551       
8552     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8553     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8554     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8555     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8556     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8557     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8558     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8559     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8560     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8561         // This only works for EQ and NE
8562         ICI->isEquality()) {
8563       // If Op1C some other power of two, convert:
8564       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8565       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8566       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8567       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8568         
8569       APInt KnownZeroMask(~KnownZero);
8570       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8571         if (!DoXform) return ICI;
8572
8573         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8574         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8575           // (X&4) == 2 --> false
8576           // (X&4) != 2 --> true
8577           Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8578           Res = ConstantExpr::getZExt(Res, CI.getType());
8579           return ReplaceInstUsesWith(CI, Res);
8580         }
8581           
8582         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8583         Value *In = ICI->getOperand(0);
8584         if (ShiftAmt) {
8585           // Perform a logical shr by shiftamt.
8586           // Insert the shift to put the result in the low bit.
8587           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8588                               ConstantInt::get(In->getType(), ShiftAmt),
8589                                                    In->getName()+".lobit"), CI);
8590         }
8591           
8592         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8593           Constant *One = ConstantInt::get(In->getType(), 1);
8594           In = BinaryOperator::CreateXor(In, One, "tmp");
8595           InsertNewInstBefore(cast<Instruction>(In), CI);
8596         }
8597           
8598         if (CI.getType() == In->getType())
8599           return ReplaceInstUsesWith(CI, In);
8600         else
8601           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8602       }
8603     }
8604   }
8605
8606   return 0;
8607 }
8608
8609 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8610   // If one of the common conversion will work ..
8611   if (Instruction *Result = commonIntCastTransforms(CI))
8612     return Result;
8613
8614   Value *Src = CI.getOperand(0);
8615
8616   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8617   // types and if the sizes are just right we can convert this into a logical
8618   // 'and' which will be much cheaper than the pair of casts.
8619   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8620     // Get the sizes of the types involved.  We know that the intermediate type
8621     // will be smaller than A or C, but don't know the relation between A and C.
8622     Value *A = CSrc->getOperand(0);
8623     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8624     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8625     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8626     // If we're actually extending zero bits, then if
8627     // SrcSize <  DstSize: zext(a & mask)
8628     // SrcSize == DstSize: a & mask
8629     // SrcSize  > DstSize: trunc(a) & mask
8630     if (SrcSize < DstSize) {
8631       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8632       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8633       Instruction *And =
8634         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8635       InsertNewInstBefore(And, CI);
8636       return new ZExtInst(And, CI.getType());
8637     } else if (SrcSize == DstSize) {
8638       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8639       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8640                                                            AndValue));
8641     } else if (SrcSize > DstSize) {
8642       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8643       InsertNewInstBefore(Trunc, CI);
8644       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8645       return BinaryOperator::CreateAnd(Trunc, 
8646                                        ConstantInt::get(Trunc->getType(),
8647                                                                AndValue));
8648     }
8649   }
8650
8651   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8652     return transformZExtICmp(ICI, CI);
8653
8654   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8655   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8656     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8657     // of the (zext icmp) will be transformed.
8658     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8659     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8660     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8661         (transformZExtICmp(LHS, CI, false) ||
8662          transformZExtICmp(RHS, CI, false))) {
8663       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8664       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8665       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8666     }
8667   }
8668
8669   // zext(trunc(t) & C) -> (t & zext(C)).
8670   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8671     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8672       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8673         Value *TI0 = TI->getOperand(0);
8674         if (TI0->getType() == CI.getType())
8675           return
8676             BinaryOperator::CreateAnd(TI0,
8677                                 ConstantExpr::getZExt(C, CI.getType()));
8678       }
8679
8680   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8681   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8682     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8683       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8684         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8685             And->getOperand(1) == C)
8686           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8687             Value *TI0 = TI->getOperand(0);
8688             if (TI0->getType() == CI.getType()) {
8689               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8690               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8691               InsertNewInstBefore(NewAnd, *And);
8692               return BinaryOperator::CreateXor(NewAnd, ZC);
8693             }
8694           }
8695
8696   return 0;
8697 }
8698
8699 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8700   if (Instruction *I = commonIntCastTransforms(CI))
8701     return I;
8702   
8703   Value *Src = CI.getOperand(0);
8704   
8705   // Canonicalize sign-extend from i1 to a select.
8706   if (Src->getType() == Type::getInt1Ty(*Context))
8707     return SelectInst::Create(Src,
8708                               Constant::getAllOnesValue(CI.getType()),
8709                               Constant::getNullValue(CI.getType()));
8710
8711   // See if the value being truncated is already sign extended.  If so, just
8712   // eliminate the trunc/sext pair.
8713   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8714     Value *Op = cast<User>(Src)->getOperand(0);
8715     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8716     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8717     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8718     unsigned NumSignBits = ComputeNumSignBits(Op);
8719
8720     if (OpBits == DestBits) {
8721       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8722       // bits, it is already ready.
8723       if (NumSignBits > DestBits-MidBits)
8724         return ReplaceInstUsesWith(CI, Op);
8725     } else if (OpBits < DestBits) {
8726       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8727       // bits, just sext from i32.
8728       if (NumSignBits > OpBits-MidBits)
8729         return new SExtInst(Op, CI.getType(), "tmp");
8730     } else {
8731       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8732       // bits, just truncate to i32.
8733       if (NumSignBits > OpBits-MidBits)
8734         return new TruncInst(Op, CI.getType(), "tmp");
8735     }
8736   }
8737
8738   // If the input is a shl/ashr pair of a same constant, then this is a sign
8739   // extension from a smaller value.  If we could trust arbitrary bitwidth
8740   // integers, we could turn this into a truncate to the smaller bit and then
8741   // use a sext for the whole extension.  Since we don't, look deeper and check
8742   // for a truncate.  If the source and dest are the same type, eliminate the
8743   // trunc and extend and just do shifts.  For example, turn:
8744   //   %a = trunc i32 %i to i8
8745   //   %b = shl i8 %a, 6
8746   //   %c = ashr i8 %b, 6
8747   //   %d = sext i8 %c to i32
8748   // into:
8749   //   %a = shl i32 %i, 30
8750   //   %d = ashr i32 %a, 30
8751   Value *A = 0;
8752   ConstantInt *BA = 0, *CA = 0;
8753   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8754                         m_ConstantInt(CA))) &&
8755       BA == CA && isa<TruncInst>(A)) {
8756     Value *I = cast<TruncInst>(A)->getOperand(0);
8757     if (I->getType() == CI.getType()) {
8758       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8759       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8760       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8761       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8762       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8763                                                         CI.getName()), CI);
8764       return BinaryOperator::CreateAShr(I, ShAmtV);
8765     }
8766   }
8767   
8768   return 0;
8769 }
8770
8771 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8772 /// in the specified FP type without changing its value.
8773 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8774                               LLVMContext *Context) {
8775   bool losesInfo;
8776   APFloat F = CFP->getValueAPF();
8777   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8778   if (!losesInfo)
8779     return ConstantFP::get(*Context, F);
8780   return 0;
8781 }
8782
8783 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8784 /// through it until we get the source value.
8785 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8786   if (Instruction *I = dyn_cast<Instruction>(V))
8787     if (I->getOpcode() == Instruction::FPExt)
8788       return LookThroughFPExtensions(I->getOperand(0), Context);
8789   
8790   // If this value is a constant, return the constant in the smallest FP type
8791   // that can accurately represent it.  This allows us to turn
8792   // (float)((double)X+2.0) into x+2.0f.
8793   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8794     if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8795       return V;  // No constant folding of this.
8796     // See if the value can be truncated to float and then reextended.
8797     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8798       return V;
8799     if (CFP->getType() == Type::getDoubleTy(*Context))
8800       return V;  // Won't shrink.
8801     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8802       return V;
8803     // Don't try to shrink to various long double types.
8804   }
8805   
8806   return V;
8807 }
8808
8809 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8810   if (Instruction *I = commonCastTransforms(CI))
8811     return I;
8812   
8813   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8814   // smaller than the destination type, we can eliminate the truncate by doing
8815   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8816   // many builtins (sqrt, etc).
8817   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8818   if (OpI && OpI->hasOneUse()) {
8819     switch (OpI->getOpcode()) {
8820     default: break;
8821     case Instruction::FAdd:
8822     case Instruction::FSub:
8823     case Instruction::FMul:
8824     case Instruction::FDiv:
8825     case Instruction::FRem:
8826       const Type *SrcTy = OpI->getType();
8827       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8828       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8829       if (LHSTrunc->getType() != SrcTy && 
8830           RHSTrunc->getType() != SrcTy) {
8831         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8832         // If the source types were both smaller than the destination type of
8833         // the cast, do this xform.
8834         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8835             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8836           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8837                                       CI.getType(), CI);
8838           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8839                                       CI.getType(), CI);
8840           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8841         }
8842       }
8843       break;  
8844     }
8845   }
8846   return 0;
8847 }
8848
8849 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8850   return commonCastTransforms(CI);
8851 }
8852
8853 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8854   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8855   if (OpI == 0)
8856     return commonCastTransforms(FI);
8857
8858   // fptoui(uitofp(X)) --> X
8859   // fptoui(sitofp(X)) --> X
8860   // This is safe if the intermediate type has enough bits in its mantissa to
8861   // accurately represent all values of X.  For example, do not do this with
8862   // i64->float->i64.  This is also safe for sitofp case, because any negative
8863   // 'X' value would cause an undefined result for the fptoui. 
8864   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8865       OpI->getOperand(0)->getType() == FI.getType() &&
8866       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8867                     OpI->getType()->getFPMantissaWidth())
8868     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8869
8870   return commonCastTransforms(FI);
8871 }
8872
8873 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8874   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8875   if (OpI == 0)
8876     return commonCastTransforms(FI);
8877   
8878   // fptosi(sitofp(X)) --> X
8879   // fptosi(uitofp(X)) --> X
8880   // This is safe if the intermediate type has enough bits in its mantissa to
8881   // accurately represent all values of X.  For example, do not do this with
8882   // i64->float->i64.  This is also safe for sitofp case, because any negative
8883   // 'X' value would cause an undefined result for the fptoui. 
8884   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8885       OpI->getOperand(0)->getType() == FI.getType() &&
8886       (int)FI.getType()->getScalarSizeInBits() <=
8887                     OpI->getType()->getFPMantissaWidth())
8888     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8889   
8890   return commonCastTransforms(FI);
8891 }
8892
8893 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8894   return commonCastTransforms(CI);
8895 }
8896
8897 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8898   return commonCastTransforms(CI);
8899 }
8900
8901 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8902   // If the destination integer type is smaller than the intptr_t type for
8903   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8904   // trunc to be exposed to other transforms.  Don't do this for extending
8905   // ptrtoint's, because we don't know if the target sign or zero extends its
8906   // pointers.
8907   if (TD &&
8908       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8909     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8910                                              TD->getIntPtrType(CI.getContext()),
8911                                                     "tmp"), CI);
8912     return new TruncInst(P, CI.getType());
8913   }
8914   
8915   return commonPointerCastTransforms(CI);
8916 }
8917
8918 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8919   // If the source integer type is larger than the intptr_t type for
8920   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8921   // allows the trunc to be exposed to other transforms.  Don't do this for
8922   // extending inttoptr's, because we don't know if the target sign or zero
8923   // extends to pointers.
8924   if (TD &&
8925       CI.getOperand(0)->getType()->getScalarSizeInBits() >
8926       TD->getPointerSizeInBits()) {
8927     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8928                                              TD->getIntPtrType(CI.getContext()),
8929                                                  "tmp"), CI);
8930     return new IntToPtrInst(P, CI.getType());
8931   }
8932   
8933   if (Instruction *I = commonCastTransforms(CI))
8934     return I;
8935
8936   return 0;
8937 }
8938
8939 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8940   // If the operands are integer typed then apply the integer transforms,
8941   // otherwise just apply the common ones.
8942   Value *Src = CI.getOperand(0);
8943   const Type *SrcTy = Src->getType();
8944   const Type *DestTy = CI.getType();
8945
8946   if (isa<PointerType>(SrcTy)) {
8947     if (Instruction *I = commonPointerCastTransforms(CI))
8948       return I;
8949   } else {
8950     if (Instruction *Result = commonCastTransforms(CI))
8951       return Result;
8952   }
8953
8954
8955   // Get rid of casts from one type to the same type. These are useless and can
8956   // be replaced by the operand.
8957   if (DestTy == Src->getType())
8958     return ReplaceInstUsesWith(CI, Src);
8959
8960   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8961     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8962     const Type *DstElTy = DstPTy->getElementType();
8963     const Type *SrcElTy = SrcPTy->getElementType();
8964     
8965     // If the address spaces don't match, don't eliminate the bitcast, which is
8966     // required for changing types.
8967     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8968       return 0;
8969     
8970     // If we are casting a malloc or alloca to a pointer to a type of the same
8971     // size, rewrite the allocation instruction to allocate the "right" type.
8972     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8973       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8974         return V;
8975     
8976     // If the source and destination are pointers, and this cast is equivalent
8977     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8978     // This can enhance SROA and other transforms that want type-safe pointers.
8979     Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8980     unsigned NumZeros = 0;
8981     while (SrcElTy != DstElTy && 
8982            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8983            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8984       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8985       ++NumZeros;
8986     }
8987
8988     // If we found a path from the src to dest, create the getelementptr now.
8989     if (SrcElTy == DstElTy) {
8990       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8991       Instruction *GEP = GetElementPtrInst::Create(Src,
8992                                                    Idxs.begin(), Idxs.end(), "",
8993                                                    ((Instruction*) NULL));
8994       cast<GEPOperator>(GEP)->setIsInBounds(true);
8995       return GEP;
8996     }
8997   }
8998
8999   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9000     if (DestVTy->getNumElements() == 1) {
9001       if (!isa<VectorType>(SrcTy)) {
9002         Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
9003                                        DestVTy->getElementType(), CI);
9004         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
9005                                          Constant::getNullValue(Type::getInt32Ty(*Context)));
9006       }
9007       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9008     }
9009   }
9010
9011   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9012     if (SrcVTy->getNumElements() == 1) {
9013       if (!isa<VectorType>(DestTy)) {
9014         Instruction *Elem =
9015           ExtractElementInst::Create(Src, Constant::getNullValue(Type::getInt32Ty(*Context)));
9016         InsertNewInstBefore(Elem, CI);
9017         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9018       }
9019     }
9020   }
9021
9022   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9023     if (SVI->hasOneUse()) {
9024       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9025       // a bitconvert to a vector with the same # elts.
9026       if (isa<VectorType>(DestTy) && 
9027           cast<VectorType>(DestTy)->getNumElements() ==
9028                 SVI->getType()->getNumElements() &&
9029           SVI->getType()->getNumElements() ==
9030             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9031         CastInst *Tmp;
9032         // If either of the operands is a cast from CI.getType(), then
9033         // evaluating the shuffle in the casted destination's type will allow
9034         // us to eliminate at least one cast.
9035         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9036              Tmp->getOperand(0)->getType() == DestTy) ||
9037             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9038              Tmp->getOperand(0)->getType() == DestTy)) {
9039           Value *LHS = InsertCastBefore(Instruction::BitCast,
9040                                         SVI->getOperand(0), DestTy, CI);
9041           Value *RHS = InsertCastBefore(Instruction::BitCast,
9042                                         SVI->getOperand(1), DestTy, CI);
9043           // Return a new shuffle vector.  Use the same element ID's, as we
9044           // know the vector types match #elts.
9045           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9046         }
9047       }
9048     }
9049   }
9050   return 0;
9051 }
9052
9053 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9054 ///   %C = or %A, %B
9055 ///   %D = select %cond, %C, %A
9056 /// into:
9057 ///   %C = select %cond, %B, 0
9058 ///   %D = or %A, %C
9059 ///
9060 /// Assuming that the specified instruction is an operand to the select, return
9061 /// a bitmask indicating which operands of this instruction are foldable if they
9062 /// equal the other incoming value of the select.
9063 ///
9064 static unsigned GetSelectFoldableOperands(Instruction *I) {
9065   switch (I->getOpcode()) {
9066   case Instruction::Add:
9067   case Instruction::Mul:
9068   case Instruction::And:
9069   case Instruction::Or:
9070   case Instruction::Xor:
9071     return 3;              // Can fold through either operand.
9072   case Instruction::Sub:   // Can only fold on the amount subtracted.
9073   case Instruction::Shl:   // Can only fold on the shift amount.
9074   case Instruction::LShr:
9075   case Instruction::AShr:
9076     return 1;
9077   default:
9078     return 0;              // Cannot fold
9079   }
9080 }
9081
9082 /// GetSelectFoldableConstant - For the same transformation as the previous
9083 /// function, return the identity constant that goes into the select.
9084 static Constant *GetSelectFoldableConstant(Instruction *I,
9085                                            LLVMContext *Context) {
9086   switch (I->getOpcode()) {
9087   default: llvm_unreachable("This cannot happen!");
9088   case Instruction::Add:
9089   case Instruction::Sub:
9090   case Instruction::Or:
9091   case Instruction::Xor:
9092   case Instruction::Shl:
9093   case Instruction::LShr:
9094   case Instruction::AShr:
9095     return Constant::getNullValue(I->getType());
9096   case Instruction::And:
9097     return Constant::getAllOnesValue(I->getType());
9098   case Instruction::Mul:
9099     return ConstantInt::get(I->getType(), 1);
9100   }
9101 }
9102
9103 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9104 /// have the same opcode and only one use each.  Try to simplify this.
9105 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9106                                           Instruction *FI) {
9107   if (TI->getNumOperands() == 1) {
9108     // If this is a non-volatile load or a cast from the same type,
9109     // merge.
9110     if (TI->isCast()) {
9111       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9112         return 0;
9113     } else {
9114       return 0;  // unknown unary op.
9115     }
9116
9117     // Fold this by inserting a select from the input values.
9118     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9119                                           FI->getOperand(0), SI.getName()+".v");
9120     InsertNewInstBefore(NewSI, SI);
9121     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9122                             TI->getType());
9123   }
9124
9125   // Only handle binary operators here.
9126   if (!isa<BinaryOperator>(TI))
9127     return 0;
9128
9129   // Figure out if the operations have any operands in common.
9130   Value *MatchOp, *OtherOpT, *OtherOpF;
9131   bool MatchIsOpZero;
9132   if (TI->getOperand(0) == FI->getOperand(0)) {
9133     MatchOp  = TI->getOperand(0);
9134     OtherOpT = TI->getOperand(1);
9135     OtherOpF = FI->getOperand(1);
9136     MatchIsOpZero = true;
9137   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9138     MatchOp  = TI->getOperand(1);
9139     OtherOpT = TI->getOperand(0);
9140     OtherOpF = FI->getOperand(0);
9141     MatchIsOpZero = false;
9142   } else if (!TI->isCommutative()) {
9143     return 0;
9144   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9145     MatchOp  = TI->getOperand(0);
9146     OtherOpT = TI->getOperand(1);
9147     OtherOpF = FI->getOperand(0);
9148     MatchIsOpZero = true;
9149   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9150     MatchOp  = TI->getOperand(1);
9151     OtherOpT = TI->getOperand(0);
9152     OtherOpF = FI->getOperand(1);
9153     MatchIsOpZero = true;
9154   } else {
9155     return 0;
9156   }
9157
9158   // If we reach here, they do have operations in common.
9159   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9160                                          OtherOpF, SI.getName()+".v");
9161   InsertNewInstBefore(NewSI, SI);
9162
9163   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9164     if (MatchIsOpZero)
9165       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9166     else
9167       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9168   }
9169   llvm_unreachable("Shouldn't get here");
9170   return 0;
9171 }
9172
9173 static bool isSelect01(Constant *C1, Constant *C2) {
9174   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9175   if (!C1I)
9176     return false;
9177   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9178   if (!C2I)
9179     return false;
9180   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9181 }
9182
9183 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9184 /// facilitate further optimization.
9185 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9186                                             Value *FalseVal) {
9187   // See the comment above GetSelectFoldableOperands for a description of the
9188   // transformation we are doing here.
9189   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9190     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9191         !isa<Constant>(FalseVal)) {
9192       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9193         unsigned OpToFold = 0;
9194         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9195           OpToFold = 1;
9196         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9197           OpToFold = 2;
9198         }
9199
9200         if (OpToFold) {
9201           Constant *C = GetSelectFoldableConstant(TVI, Context);
9202           Value *OOp = TVI->getOperand(2-OpToFold);
9203           // Avoid creating select between 2 constants unless it's selecting
9204           // between 0 and 1.
9205           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9206             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9207             InsertNewInstBefore(NewSel, SI);
9208             NewSel->takeName(TVI);
9209             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9210               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9211             llvm_unreachable("Unknown instruction!!");
9212           }
9213         }
9214       }
9215     }
9216   }
9217
9218   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9219     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9220         !isa<Constant>(TrueVal)) {
9221       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9222         unsigned OpToFold = 0;
9223         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9224           OpToFold = 1;
9225         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9226           OpToFold = 2;
9227         }
9228
9229         if (OpToFold) {
9230           Constant *C = GetSelectFoldableConstant(FVI, Context);
9231           Value *OOp = FVI->getOperand(2-OpToFold);
9232           // Avoid creating select between 2 constants unless it's selecting
9233           // between 0 and 1.
9234           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9235             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9236             InsertNewInstBefore(NewSel, SI);
9237             NewSel->takeName(FVI);
9238             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9239               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9240             llvm_unreachable("Unknown instruction!!");
9241           }
9242         }
9243       }
9244     }
9245   }
9246
9247   return 0;
9248 }
9249
9250 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9251 /// ICmpInst as its first operand.
9252 ///
9253 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9254                                                    ICmpInst *ICI) {
9255   bool Changed = false;
9256   ICmpInst::Predicate Pred = ICI->getPredicate();
9257   Value *CmpLHS = ICI->getOperand(0);
9258   Value *CmpRHS = ICI->getOperand(1);
9259   Value *TrueVal = SI.getTrueValue();
9260   Value *FalseVal = SI.getFalseValue();
9261
9262   // Check cases where the comparison is with a constant that
9263   // can be adjusted to fit the min/max idiom. We may edit ICI in
9264   // place here, so make sure the select is the only user.
9265   if (ICI->hasOneUse())
9266     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9267       switch (Pred) {
9268       default: break;
9269       case ICmpInst::ICMP_ULT:
9270       case ICmpInst::ICMP_SLT: {
9271         // X < MIN ? T : F  -->  F
9272         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9273           return ReplaceInstUsesWith(SI, FalseVal);
9274         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9275         Constant *AdjustedRHS = SubOne(CI);
9276         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9277             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9278           Pred = ICmpInst::getSwappedPredicate(Pred);
9279           CmpRHS = AdjustedRHS;
9280           std::swap(FalseVal, TrueVal);
9281           ICI->setPredicate(Pred);
9282           ICI->setOperand(1, CmpRHS);
9283           SI.setOperand(1, TrueVal);
9284           SI.setOperand(2, FalseVal);
9285           Changed = true;
9286         }
9287         break;
9288       }
9289       case ICmpInst::ICMP_UGT:
9290       case ICmpInst::ICMP_SGT: {
9291         // X > MAX ? T : F  -->  F
9292         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9293           return ReplaceInstUsesWith(SI, FalseVal);
9294         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9295         Constant *AdjustedRHS = AddOne(CI);
9296         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9297             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9298           Pred = ICmpInst::getSwappedPredicate(Pred);
9299           CmpRHS = AdjustedRHS;
9300           std::swap(FalseVal, TrueVal);
9301           ICI->setPredicate(Pred);
9302           ICI->setOperand(1, CmpRHS);
9303           SI.setOperand(1, TrueVal);
9304           SI.setOperand(2, FalseVal);
9305           Changed = true;
9306         }
9307         break;
9308       }
9309       }
9310
9311       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9312       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9313       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9314       if (match(TrueVal, m_ConstantInt<-1>()) &&
9315           match(FalseVal, m_ConstantInt<0>()))
9316         Pred = ICI->getPredicate();
9317       else if (match(TrueVal, m_ConstantInt<0>()) &&
9318                match(FalseVal, m_ConstantInt<-1>()))
9319         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9320       
9321       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9322         // If we are just checking for a icmp eq of a single bit and zext'ing it
9323         // to an integer, then shift the bit to the appropriate place and then
9324         // cast to integer to avoid the comparison.
9325         const APInt &Op1CV = CI->getValue();
9326     
9327         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9328         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9329         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9330             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9331           Value *In = ICI->getOperand(0);
9332           Value *Sh = ConstantInt::get(In->getType(),
9333                                        In->getType()->getScalarSizeInBits()-1);
9334           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9335                                                         In->getName()+".lobit"),
9336                                    *ICI);
9337           if (In->getType() != SI.getType())
9338             In = CastInst::CreateIntegerCast(In, SI.getType(),
9339                                              true/*SExt*/, "tmp", ICI);
9340     
9341           if (Pred == ICmpInst::ICMP_SGT)
9342             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9343                                        In->getName()+".not"), *ICI);
9344     
9345           return ReplaceInstUsesWith(SI, In);
9346         }
9347       }
9348     }
9349
9350   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9351     // Transform (X == Y) ? X : Y  -> Y
9352     if (Pred == ICmpInst::ICMP_EQ)
9353       return ReplaceInstUsesWith(SI, FalseVal);
9354     // Transform (X != Y) ? X : Y  -> X
9355     if (Pred == ICmpInst::ICMP_NE)
9356       return ReplaceInstUsesWith(SI, TrueVal);
9357     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9358
9359   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9360     // Transform (X == Y) ? Y : X  -> X
9361     if (Pred == ICmpInst::ICMP_EQ)
9362       return ReplaceInstUsesWith(SI, FalseVal);
9363     // Transform (X != Y) ? Y : X  -> Y
9364     if (Pred == ICmpInst::ICMP_NE)
9365       return ReplaceInstUsesWith(SI, TrueVal);
9366     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9367   }
9368
9369   /// NOTE: if we wanted to, this is where to detect integer ABS
9370
9371   return Changed ? &SI : 0;
9372 }
9373
9374 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9375   Value *CondVal = SI.getCondition();
9376   Value *TrueVal = SI.getTrueValue();
9377   Value *FalseVal = SI.getFalseValue();
9378
9379   // select true, X, Y  -> X
9380   // select false, X, Y -> Y
9381   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9382     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9383
9384   // select C, X, X -> X
9385   if (TrueVal == FalseVal)
9386     return ReplaceInstUsesWith(SI, TrueVal);
9387
9388   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9389     return ReplaceInstUsesWith(SI, FalseVal);
9390   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9391     return ReplaceInstUsesWith(SI, TrueVal);
9392   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9393     if (isa<Constant>(TrueVal))
9394       return ReplaceInstUsesWith(SI, TrueVal);
9395     else
9396       return ReplaceInstUsesWith(SI, FalseVal);
9397   }
9398
9399   if (SI.getType() == Type::getInt1Ty(*Context)) {
9400     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9401       if (C->getZExtValue()) {
9402         // Change: A = select B, true, C --> A = or B, C
9403         return BinaryOperator::CreateOr(CondVal, FalseVal);
9404       } else {
9405         // Change: A = select B, false, C --> A = and !B, C
9406         Value *NotCond =
9407           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9408                                              "not."+CondVal->getName()), SI);
9409         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9410       }
9411     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9412       if (C->getZExtValue() == false) {
9413         // Change: A = select B, C, false --> A = and B, C
9414         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9415       } else {
9416         // Change: A = select B, C, true --> A = or !B, C
9417         Value *NotCond =
9418           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9419                                              "not."+CondVal->getName()), SI);
9420         return BinaryOperator::CreateOr(NotCond, TrueVal);
9421       }
9422     }
9423     
9424     // select a, b, a  -> a&b
9425     // select a, a, b  -> a|b
9426     if (CondVal == TrueVal)
9427       return BinaryOperator::CreateOr(CondVal, FalseVal);
9428     else if (CondVal == FalseVal)
9429       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9430   }
9431
9432   // Selecting between two integer constants?
9433   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9434     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9435       // select C, 1, 0 -> zext C to int
9436       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9437         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9438       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9439         // select C, 0, 1 -> zext !C to int
9440         Value *NotCond =
9441           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9442                                                "not."+CondVal->getName()), SI);
9443         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9444       }
9445
9446       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9447         // If one of the constants is zero (we know they can't both be) and we
9448         // have an icmp instruction with zero, and we have an 'and' with the
9449         // non-constant value, eliminate this whole mess.  This corresponds to
9450         // cases like this: ((X & 27) ? 27 : 0)
9451         if (TrueValC->isZero() || FalseValC->isZero())
9452           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9453               cast<Constant>(IC->getOperand(1))->isNullValue())
9454             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9455               if (ICA->getOpcode() == Instruction::And &&
9456                   isa<ConstantInt>(ICA->getOperand(1)) &&
9457                   (ICA->getOperand(1) == TrueValC ||
9458                    ICA->getOperand(1) == FalseValC) &&
9459                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9460                 // Okay, now we know that everything is set up, we just don't
9461                 // know whether we have a icmp_ne or icmp_eq and whether the 
9462                 // true or false val is the zero.
9463                 bool ShouldNotVal = !TrueValC->isZero();
9464                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9465                 Value *V = ICA;
9466                 if (ShouldNotVal)
9467                   V = InsertNewInstBefore(BinaryOperator::Create(
9468                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9469                 return ReplaceInstUsesWith(SI, V);
9470               }
9471       }
9472     }
9473
9474   // See if we are selecting two values based on a comparison of the two values.
9475   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9476     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9477       // Transform (X == Y) ? X : Y  -> Y
9478       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9479         // This is not safe in general for floating point:  
9480         // consider X== -0, Y== +0.
9481         // It becomes safe if either operand is a nonzero constant.
9482         ConstantFP *CFPt, *CFPf;
9483         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9484               !CFPt->getValueAPF().isZero()) ||
9485             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9486              !CFPf->getValueAPF().isZero()))
9487         return ReplaceInstUsesWith(SI, FalseVal);
9488       }
9489       // Transform (X != Y) ? X : Y  -> X
9490       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9491         return ReplaceInstUsesWith(SI, TrueVal);
9492       // NOTE: if we wanted to, this is where to detect MIN/MAX
9493
9494     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9495       // Transform (X == Y) ? Y : X  -> X
9496       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9497         // This is not safe in general for floating point:  
9498         // consider X== -0, Y== +0.
9499         // It becomes safe if either operand is a nonzero constant.
9500         ConstantFP *CFPt, *CFPf;
9501         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9502               !CFPt->getValueAPF().isZero()) ||
9503             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9504              !CFPf->getValueAPF().isZero()))
9505           return ReplaceInstUsesWith(SI, FalseVal);
9506       }
9507       // Transform (X != Y) ? Y : X  -> Y
9508       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9509         return ReplaceInstUsesWith(SI, TrueVal);
9510       // NOTE: if we wanted to, this is where to detect MIN/MAX
9511     }
9512     // NOTE: if we wanted to, this is where to detect ABS
9513   }
9514
9515   // See if we are selecting two values based on a comparison of the two values.
9516   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9517     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9518       return Result;
9519
9520   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9521     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9522       if (TI->hasOneUse() && FI->hasOneUse()) {
9523         Instruction *AddOp = 0, *SubOp = 0;
9524
9525         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9526         if (TI->getOpcode() == FI->getOpcode())
9527           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9528             return IV;
9529
9530         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9531         // even legal for FP.
9532         if ((TI->getOpcode() == Instruction::Sub &&
9533              FI->getOpcode() == Instruction::Add) ||
9534             (TI->getOpcode() == Instruction::FSub &&
9535              FI->getOpcode() == Instruction::FAdd)) {
9536           AddOp = FI; SubOp = TI;
9537         } else if ((FI->getOpcode() == Instruction::Sub &&
9538                     TI->getOpcode() == Instruction::Add) ||
9539                    (FI->getOpcode() == Instruction::FSub &&
9540                     TI->getOpcode() == Instruction::FAdd)) {
9541           AddOp = TI; SubOp = FI;
9542         }
9543
9544         if (AddOp) {
9545           Value *OtherAddOp = 0;
9546           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9547             OtherAddOp = AddOp->getOperand(1);
9548           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9549             OtherAddOp = AddOp->getOperand(0);
9550           }
9551
9552           if (OtherAddOp) {
9553             // So at this point we know we have (Y -> OtherAddOp):
9554             //        select C, (add X, Y), (sub X, Z)
9555             Value *NegVal;  // Compute -Z
9556             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9557               NegVal = ConstantExpr::getNeg(C);
9558             } else {
9559               NegVal = InsertNewInstBefore(
9560                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
9561                                               "tmp"), SI);
9562             }
9563
9564             Value *NewTrueOp = OtherAddOp;
9565             Value *NewFalseOp = NegVal;
9566             if (AddOp != TI)
9567               std::swap(NewTrueOp, NewFalseOp);
9568             Instruction *NewSel =
9569               SelectInst::Create(CondVal, NewTrueOp,
9570                                  NewFalseOp, SI.getName() + ".p");
9571
9572             NewSel = InsertNewInstBefore(NewSel, SI);
9573             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9574           }
9575         }
9576       }
9577
9578   // See if we can fold the select into one of our operands.
9579   if (SI.getType()->isInteger()) {
9580     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9581     if (FoldI)
9582       return FoldI;
9583   }
9584
9585   if (BinaryOperator::isNot(CondVal)) {
9586     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9587     SI.setOperand(1, FalseVal);
9588     SI.setOperand(2, TrueVal);
9589     return &SI;
9590   }
9591
9592   return 0;
9593 }
9594
9595 /// EnforceKnownAlignment - If the specified pointer points to an object that
9596 /// we control, modify the object's alignment to PrefAlign. This isn't
9597 /// often possible though. If alignment is important, a more reliable approach
9598 /// is to simply align all global variables and allocation instructions to
9599 /// their preferred alignment from the beginning.
9600 ///
9601 static unsigned EnforceKnownAlignment(Value *V,
9602                                       unsigned Align, unsigned PrefAlign) {
9603
9604   User *U = dyn_cast<User>(V);
9605   if (!U) return Align;
9606
9607   switch (Operator::getOpcode(U)) {
9608   default: break;
9609   case Instruction::BitCast:
9610     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9611   case Instruction::GetElementPtr: {
9612     // If all indexes are zero, it is just the alignment of the base pointer.
9613     bool AllZeroOperands = true;
9614     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9615       if (!isa<Constant>(*i) ||
9616           !cast<Constant>(*i)->isNullValue()) {
9617         AllZeroOperands = false;
9618         break;
9619       }
9620
9621     if (AllZeroOperands) {
9622       // Treat this like a bitcast.
9623       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9624     }
9625     break;
9626   }
9627   }
9628
9629   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9630     // If there is a large requested alignment and we can, bump up the alignment
9631     // of the global.
9632     if (!GV->isDeclaration()) {
9633       if (GV->getAlignment() >= PrefAlign)
9634         Align = GV->getAlignment();
9635       else {
9636         GV->setAlignment(PrefAlign);
9637         Align = PrefAlign;
9638       }
9639     }
9640   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9641     // If there is a requested alignment and if this is an alloca, round up.  We
9642     // don't do this for malloc, because some systems can't respect the request.
9643     if (isa<AllocaInst>(AI)) {
9644       if (AI->getAlignment() >= PrefAlign)
9645         Align = AI->getAlignment();
9646       else {
9647         AI->setAlignment(PrefAlign);
9648         Align = PrefAlign;
9649       }
9650     }
9651   }
9652
9653   return Align;
9654 }
9655
9656 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9657 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9658 /// and it is more than the alignment of the ultimate object, see if we can
9659 /// increase the alignment of the ultimate object, making this check succeed.
9660 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9661                                                   unsigned PrefAlign) {
9662   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9663                       sizeof(PrefAlign) * CHAR_BIT;
9664   APInt Mask = APInt::getAllOnesValue(BitWidth);
9665   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9666   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9667   unsigned TrailZ = KnownZero.countTrailingOnes();
9668   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9669
9670   if (PrefAlign > Align)
9671     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9672   
9673     // We don't need to make any adjustment.
9674   return Align;
9675 }
9676
9677 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9678   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9679   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9680   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9681   unsigned CopyAlign = MI->getAlignment();
9682
9683   if (CopyAlign < MinAlign) {
9684     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9685                                              MinAlign, false));
9686     return MI;
9687   }
9688   
9689   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9690   // load/store.
9691   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9692   if (MemOpLength == 0) return 0;
9693   
9694   // Source and destination pointer types are always "i8*" for intrinsic.  See
9695   // if the size is something we can handle with a single primitive load/store.
9696   // A single load+store correctly handles overlapping memory in the memmove
9697   // case.
9698   unsigned Size = MemOpLength->getZExtValue();
9699   if (Size == 0) return MI;  // Delete this mem transfer.
9700   
9701   if (Size > 8 || (Size&(Size-1)))
9702     return 0;  // If not 1/2/4/8 bytes, exit.
9703   
9704   // Use an integer load+store unless we can find something better.
9705   Type *NewPtrTy =
9706                 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9707   
9708   // Memcpy forces the use of i8* for the source and destination.  That means
9709   // that if you're using memcpy to move one double around, you'll get a cast
9710   // from double* to i8*.  We'd much rather use a double load+store rather than
9711   // an i64 load+store, here because this improves the odds that the source or
9712   // dest address will be promotable.  See if we can find a better type than the
9713   // integer datatype.
9714   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9715     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9716     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9717       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9718       // down through these levels if so.
9719       while (!SrcETy->isSingleValueType()) {
9720         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9721           if (STy->getNumElements() == 1)
9722             SrcETy = STy->getElementType(0);
9723           else
9724             break;
9725         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9726           if (ATy->getNumElements() == 1)
9727             SrcETy = ATy->getElementType();
9728           else
9729             break;
9730         } else
9731           break;
9732       }
9733       
9734       if (SrcETy->isSingleValueType())
9735         NewPtrTy = PointerType::getUnqual(SrcETy);
9736     }
9737   }
9738   
9739   
9740   // If the memcpy/memmove provides better alignment info than we can
9741   // infer, use it.
9742   SrcAlign = std::max(SrcAlign, CopyAlign);
9743   DstAlign = std::max(DstAlign, CopyAlign);
9744   
9745   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9746   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9747   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9748   InsertNewInstBefore(L, *MI);
9749   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9750
9751   // Set the size of the copy to 0, it will be deleted on the next iteration.
9752   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9753   return MI;
9754 }
9755
9756 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9757   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9758   if (MI->getAlignment() < Alignment) {
9759     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9760                                              Alignment, false));
9761     return MI;
9762   }
9763   
9764   // Extract the length and alignment and fill if they are constant.
9765   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9766   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9767   if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9768     return 0;
9769   uint64_t Len = LenC->getZExtValue();
9770   Alignment = MI->getAlignment();
9771   
9772   // If the length is zero, this is a no-op
9773   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9774   
9775   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9776   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9777     const Type *ITy = IntegerType::get(*Context, Len*8);  // n=1 -> i8.
9778     
9779     Value *Dest = MI->getDest();
9780     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9781
9782     // Alignment 0 is identity for alignment 1 for memset, but not store.
9783     if (Alignment == 0) Alignment = 1;
9784     
9785     // Extract the fill value and store.
9786     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9787     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9788                                       Dest, false, Alignment), *MI);
9789     
9790     // Set the size of the copy to 0, it will be deleted on the next iteration.
9791     MI->setLength(Constant::getNullValue(LenC->getType()));
9792     return MI;
9793   }
9794
9795   return 0;
9796 }
9797
9798
9799 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9800 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9801 /// the heavy lifting.
9802 ///
9803 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9804   // If the caller function is nounwind, mark the call as nounwind, even if the
9805   // callee isn't.
9806   if (CI.getParent()->getParent()->doesNotThrow() &&
9807       !CI.doesNotThrow()) {
9808     CI.setDoesNotThrow();
9809     return &CI;
9810   }
9811   
9812   
9813   
9814   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9815   if (!II) return visitCallSite(&CI);
9816   
9817   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9818   // visitCallSite.
9819   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9820     bool Changed = false;
9821
9822     // memmove/cpy/set of zero bytes is a noop.
9823     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9824       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9825
9826       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9827         if (CI->getZExtValue() == 1) {
9828           // Replace the instruction with just byte operations.  We would
9829           // transform other cases to loads/stores, but we don't know if
9830           // alignment is sufficient.
9831         }
9832     }
9833
9834     // If we have a memmove and the source operation is a constant global,
9835     // then the source and dest pointers can't alias, so we can change this
9836     // into a call to memcpy.
9837     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9838       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9839         if (GVSrc->isConstant()) {
9840           Module *M = CI.getParent()->getParent()->getParent();
9841           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9842           const Type *Tys[1];
9843           Tys[0] = CI.getOperand(3)->getType();
9844           CI.setOperand(0, 
9845                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9846           Changed = true;
9847         }
9848
9849       // memmove(x,x,size) -> noop.
9850       if (MMI->getSource() == MMI->getDest())
9851         return EraseInstFromFunction(CI);
9852     }
9853
9854     // If we can determine a pointer alignment that is bigger than currently
9855     // set, update the alignment.
9856     if (isa<MemTransferInst>(MI)) {
9857       if (Instruction *I = SimplifyMemTransfer(MI))
9858         return I;
9859     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9860       if (Instruction *I = SimplifyMemSet(MSI))
9861         return I;
9862     }
9863           
9864     if (Changed) return II;
9865   }
9866   
9867   switch (II->getIntrinsicID()) {
9868   default: break;
9869   case Intrinsic::bswap:
9870     // bswap(bswap(x)) -> x
9871     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9872       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9873         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9874     break;
9875   case Intrinsic::ppc_altivec_lvx:
9876   case Intrinsic::ppc_altivec_lvxl:
9877   case Intrinsic::x86_sse_loadu_ps:
9878   case Intrinsic::x86_sse2_loadu_pd:
9879   case Intrinsic::x86_sse2_loadu_dq:
9880     // Turn PPC lvx     -> load if the pointer is known aligned.
9881     // Turn X86 loadups -> load if the pointer is known aligned.
9882     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9883       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9884                                    PointerType::getUnqual(II->getType()),
9885                                        CI);
9886       return new LoadInst(Ptr);
9887     }
9888     break;
9889   case Intrinsic::ppc_altivec_stvx:
9890   case Intrinsic::ppc_altivec_stvxl:
9891     // Turn stvx -> store if the pointer is known aligned.
9892     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9893       const Type *OpPtrTy = 
9894         PointerType::getUnqual(II->getOperand(1)->getType());
9895       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9896       return new StoreInst(II->getOperand(1), Ptr);
9897     }
9898     break;
9899   case Intrinsic::x86_sse_storeu_ps:
9900   case Intrinsic::x86_sse2_storeu_pd:
9901   case Intrinsic::x86_sse2_storeu_dq:
9902     // Turn X86 storeu -> store if the pointer is known aligned.
9903     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9904       const Type *OpPtrTy = 
9905         PointerType::getUnqual(II->getOperand(2)->getType());
9906       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9907       return new StoreInst(II->getOperand(2), Ptr);
9908     }
9909     break;
9910     
9911   case Intrinsic::x86_sse_cvttss2si: {
9912     // These intrinsics only demands the 0th element of its input vector.  If
9913     // we can simplify the input based on that, do so now.
9914     unsigned VWidth =
9915       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9916     APInt DemandedElts(VWidth, 1);
9917     APInt UndefElts(VWidth, 0);
9918     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9919                                               UndefElts)) {
9920       II->setOperand(1, V);
9921       return II;
9922     }
9923     break;
9924   }
9925     
9926   case Intrinsic::ppc_altivec_vperm:
9927     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9928     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9929       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9930       
9931       // Check that all of the elements are integer constants or undefs.
9932       bool AllEltsOk = true;
9933       for (unsigned i = 0; i != 16; ++i) {
9934         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9935             !isa<UndefValue>(Mask->getOperand(i))) {
9936           AllEltsOk = false;
9937           break;
9938         }
9939       }
9940       
9941       if (AllEltsOk) {
9942         // Cast the input vectors to byte vectors.
9943         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9944         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9945         Value *Result = UndefValue::get(Op0->getType());
9946         
9947         // Only extract each element once.
9948         Value *ExtractedElts[32];
9949         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9950         
9951         for (unsigned i = 0; i != 16; ++i) {
9952           if (isa<UndefValue>(Mask->getOperand(i)))
9953             continue;
9954           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9955           Idx &= 31;  // Match the hardware behavior.
9956           
9957           if (ExtractedElts[Idx] == 0) {
9958             Instruction *Elt = 
9959               ExtractElementInst::Create(Idx < 16 ? Op0 : Op1, 
9960                   ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false), "tmp");
9961             InsertNewInstBefore(Elt, CI);
9962             ExtractedElts[Idx] = Elt;
9963           }
9964         
9965           // Insert this value into the result vector.
9966           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9967                                ConstantInt::get(Type::getInt32Ty(*Context), i, false), 
9968                                "tmp");
9969           InsertNewInstBefore(cast<Instruction>(Result), CI);
9970         }
9971         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9972       }
9973     }
9974     break;
9975
9976   case Intrinsic::stackrestore: {
9977     // If the save is right next to the restore, remove the restore.  This can
9978     // happen when variable allocas are DCE'd.
9979     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9980       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9981         BasicBlock::iterator BI = SS;
9982         if (&*++BI == II)
9983           return EraseInstFromFunction(CI);
9984       }
9985     }
9986     
9987     // Scan down this block to see if there is another stack restore in the
9988     // same block without an intervening call/alloca.
9989     BasicBlock::iterator BI = II;
9990     TerminatorInst *TI = II->getParent()->getTerminator();
9991     bool CannotRemove = false;
9992     for (++BI; &*BI != TI; ++BI) {
9993       if (isa<AllocaInst>(BI)) {
9994         CannotRemove = true;
9995         break;
9996       }
9997       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9998         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9999           // If there is a stackrestore below this one, remove this one.
10000           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10001             return EraseInstFromFunction(CI);
10002           // Otherwise, ignore the intrinsic.
10003         } else {
10004           // If we found a non-intrinsic call, we can't remove the stack
10005           // restore.
10006           CannotRemove = true;
10007           break;
10008         }
10009       }
10010     }
10011     
10012     // If the stack restore is in a return/unwind block and if there are no
10013     // allocas or calls between the restore and the return, nuke the restore.
10014     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10015       return EraseInstFromFunction(CI);
10016     break;
10017   }
10018   }
10019
10020   return visitCallSite(II);
10021 }
10022
10023 // InvokeInst simplification
10024 //
10025 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10026   return visitCallSite(&II);
10027 }
10028
10029 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10030 /// passed through the varargs area, we can eliminate the use of the cast.
10031 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10032                                          const CastInst * const CI,
10033                                          const TargetData * const TD,
10034                                          const int ix) {
10035   if (!CI->isLosslessCast())
10036     return false;
10037
10038   // The size of ByVal arguments is derived from the type, so we
10039   // can't change to a type with a different size.  If the size were
10040   // passed explicitly we could avoid this check.
10041   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10042     return true;
10043
10044   const Type* SrcTy = 
10045             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10046   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10047   if (!SrcTy->isSized() || !DstTy->isSized())
10048     return false;
10049   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10050     return false;
10051   return true;
10052 }
10053
10054 // visitCallSite - Improvements for call and invoke instructions.
10055 //
10056 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10057   bool Changed = false;
10058
10059   // If the callee is a constexpr cast of a function, attempt to move the cast
10060   // to the arguments of the call/invoke.
10061   if (transformConstExprCastCall(CS)) return 0;
10062
10063   Value *Callee = CS.getCalledValue();
10064
10065   if (Function *CalleeF = dyn_cast<Function>(Callee))
10066     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10067       Instruction *OldCall = CS.getInstruction();
10068       // If the call and callee calling conventions don't match, this call must
10069       // be unreachable, as the call is undefined.
10070       new StoreInst(ConstantInt::getTrue(*Context),
10071                 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), 
10072                                   OldCall);
10073       if (!OldCall->use_empty())
10074         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10075       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10076         return EraseInstFromFunction(*OldCall);
10077       return 0;
10078     }
10079
10080   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10081     // This instruction is not reachable, just remove it.  We insert a store to
10082     // undef so that we know that this code is not reachable, despite the fact
10083     // that we can't modify the CFG here.
10084     new StoreInst(ConstantInt::getTrue(*Context),
10085                UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
10086                   CS.getInstruction());
10087
10088     if (!CS.getInstruction()->use_empty())
10089       CS.getInstruction()->
10090         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10091
10092     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10093       // Don't break the CFG, insert a dummy cond branch.
10094       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10095                          ConstantInt::getTrue(*Context), II);
10096     }
10097     return EraseInstFromFunction(*CS.getInstruction());
10098   }
10099
10100   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10101     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10102       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10103         return transformCallThroughTrampoline(CS);
10104
10105   const PointerType *PTy = cast<PointerType>(Callee->getType());
10106   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10107   if (FTy->isVarArg()) {
10108     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10109     // See if we can optimize any arguments passed through the varargs area of
10110     // the call.
10111     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10112            E = CS.arg_end(); I != E; ++I, ++ix) {
10113       CastInst *CI = dyn_cast<CastInst>(*I);
10114       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10115         *I = CI->getOperand(0);
10116         Changed = true;
10117       }
10118     }
10119   }
10120
10121   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10122     // Inline asm calls cannot throw - mark them 'nounwind'.
10123     CS.setDoesNotThrow();
10124     Changed = true;
10125   }
10126
10127   return Changed ? CS.getInstruction() : 0;
10128 }
10129
10130 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10131 // attempt to move the cast to the arguments of the call/invoke.
10132 //
10133 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10134   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10135   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10136   if (CE->getOpcode() != Instruction::BitCast || 
10137       !isa<Function>(CE->getOperand(0)))
10138     return false;
10139   Function *Callee = cast<Function>(CE->getOperand(0));
10140   Instruction *Caller = CS.getInstruction();
10141   const AttrListPtr &CallerPAL = CS.getAttributes();
10142
10143   // Okay, this is a cast from a function to a different type.  Unless doing so
10144   // would cause a type conversion of one of our arguments, change this call to
10145   // be a direct call with arguments casted to the appropriate types.
10146   //
10147   const FunctionType *FT = Callee->getFunctionType();
10148   const Type *OldRetTy = Caller->getType();
10149   const Type *NewRetTy = FT->getReturnType();
10150
10151   if (isa<StructType>(NewRetTy))
10152     return false; // TODO: Handle multiple return values.
10153
10154   // Check to see if we are changing the return type...
10155   if (OldRetTy != NewRetTy) {
10156     if (Callee->isDeclaration() &&
10157         // Conversion is ok if changing from one pointer type to another or from
10158         // a pointer to an integer of the same size.
10159         !((isa<PointerType>(OldRetTy) || !TD ||
10160            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10161           (isa<PointerType>(NewRetTy) || !TD ||
10162            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10163       return false;   // Cannot transform this return value.
10164
10165     if (!Caller->use_empty() &&
10166         // void -> non-void is handled specially
10167         NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
10168       return false;   // Cannot transform this return value.
10169
10170     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10171       Attributes RAttrs = CallerPAL.getRetAttributes();
10172       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10173         return false;   // Attribute not compatible with transformed value.
10174     }
10175
10176     // If the callsite is an invoke instruction, and the return value is used by
10177     // a PHI node in a successor, we cannot change the return type of the call
10178     // because there is no place to put the cast instruction (without breaking
10179     // the critical edge).  Bail out in this case.
10180     if (!Caller->use_empty())
10181       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10182         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10183              UI != E; ++UI)
10184           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10185             if (PN->getParent() == II->getNormalDest() ||
10186                 PN->getParent() == II->getUnwindDest())
10187               return false;
10188   }
10189
10190   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10191   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10192
10193   CallSite::arg_iterator AI = CS.arg_begin();
10194   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10195     const Type *ParamTy = FT->getParamType(i);
10196     const Type *ActTy = (*AI)->getType();
10197
10198     if (!CastInst::isCastable(ActTy, ParamTy))
10199       return false;   // Cannot transform this parameter value.
10200
10201     if (CallerPAL.getParamAttributes(i + 1) 
10202         & Attribute::typeIncompatible(ParamTy))
10203       return false;   // Attribute not compatible with transformed value.
10204
10205     // Converting from one pointer type to another or between a pointer and an
10206     // integer of the same size is safe even if we do not have a body.
10207     bool isConvertible = ActTy == ParamTy ||
10208       (TD && ((isa<PointerType>(ParamTy) ||
10209       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10210               (isa<PointerType>(ActTy) ||
10211               ActTy == TD->getIntPtrType(Caller->getContext()))));
10212     if (Callee->isDeclaration() && !isConvertible) return false;
10213   }
10214
10215   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10216       Callee->isDeclaration())
10217     return false;   // Do not delete arguments unless we have a function body.
10218
10219   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10220       !CallerPAL.isEmpty())
10221     // In this case we have more arguments than the new function type, but we
10222     // won't be dropping them.  Check that these extra arguments have attributes
10223     // that are compatible with being a vararg call argument.
10224     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10225       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10226         break;
10227       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10228       if (PAttrs & Attribute::VarArgsIncompatible)
10229         return false;
10230     }
10231
10232   // Okay, we decided that this is a safe thing to do: go ahead and start
10233   // inserting cast instructions as necessary...
10234   std::vector<Value*> Args;
10235   Args.reserve(NumActualArgs);
10236   SmallVector<AttributeWithIndex, 8> attrVec;
10237   attrVec.reserve(NumCommonArgs);
10238
10239   // Get any return attributes.
10240   Attributes RAttrs = CallerPAL.getRetAttributes();
10241
10242   // If the return value is not being used, the type may not be compatible
10243   // with the existing attributes.  Wipe out any problematic attributes.
10244   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10245
10246   // Add the new return attributes.
10247   if (RAttrs)
10248     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10249
10250   AI = CS.arg_begin();
10251   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10252     const Type *ParamTy = FT->getParamType(i);
10253     if ((*AI)->getType() == ParamTy) {
10254       Args.push_back(*AI);
10255     } else {
10256       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10257           false, ParamTy, false);
10258       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10259       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10260     }
10261
10262     // Add any parameter attributes.
10263     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10264       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10265   }
10266
10267   // If the function takes more arguments than the call was taking, add them
10268   // now...
10269   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10270     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10271
10272   // If we are removing arguments to the function, emit an obnoxious warning...
10273   if (FT->getNumParams() < NumActualArgs) {
10274     if (!FT->isVarArg()) {
10275       errs() << "WARNING: While resolving call to function '"
10276              << Callee->getName() << "' arguments were dropped!\n";
10277     } else {
10278       // Add all of the arguments in their promoted form to the arg list...
10279       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10280         const Type *PTy = getPromotedType((*AI)->getType());
10281         if (PTy != (*AI)->getType()) {
10282           // Must promote to pass through va_arg area!
10283           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10284                                                                 PTy, false);
10285           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10286           InsertNewInstBefore(Cast, *Caller);
10287           Args.push_back(Cast);
10288         } else {
10289           Args.push_back(*AI);
10290         }
10291
10292         // Add any parameter attributes.
10293         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10294           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10295       }
10296     }
10297   }
10298
10299   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10300     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10301
10302   if (NewRetTy == Type::getVoidTy(*Context))
10303     Caller->setName("");   // Void type should not have a name.
10304
10305   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10306                                                      attrVec.end());
10307
10308   Instruction *NC;
10309   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10310     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10311                             Args.begin(), Args.end(),
10312                             Caller->getName(), Caller);
10313     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10314     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10315   } else {
10316     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10317                           Caller->getName(), Caller);
10318     CallInst *CI = cast<CallInst>(Caller);
10319     if (CI->isTailCall())
10320       cast<CallInst>(NC)->setTailCall();
10321     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10322     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10323   }
10324
10325   // Insert a cast of the return type as necessary.
10326   Value *NV = NC;
10327   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10328     if (NV->getType() != Type::getVoidTy(*Context)) {
10329       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10330                                                             OldRetTy, false);
10331       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10332
10333       // If this is an invoke instruction, we should insert it after the first
10334       // non-phi, instruction in the normal successor block.
10335       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10336         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10337         InsertNewInstBefore(NC, *I);
10338       } else {
10339         // Otherwise, it's a call, just insert cast right after the call instr
10340         InsertNewInstBefore(NC, *Caller);
10341       }
10342       AddUsersToWorkList(*Caller);
10343     } else {
10344       NV = UndefValue::get(Caller->getType());
10345     }
10346   }
10347
10348   if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10349     Caller->replaceAllUsesWith(NV);
10350   Caller->eraseFromParent();
10351   RemoveFromWorkList(Caller);
10352   return true;
10353 }
10354
10355 // transformCallThroughTrampoline - Turn a call to a function created by the
10356 // init_trampoline intrinsic into a direct call to the underlying function.
10357 //
10358 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10359   Value *Callee = CS.getCalledValue();
10360   const PointerType *PTy = cast<PointerType>(Callee->getType());
10361   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10362   const AttrListPtr &Attrs = CS.getAttributes();
10363
10364   // If the call already has the 'nest' attribute somewhere then give up -
10365   // otherwise 'nest' would occur twice after splicing in the chain.
10366   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10367     return 0;
10368
10369   IntrinsicInst *Tramp =
10370     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10371
10372   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10373   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10374   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10375
10376   const AttrListPtr &NestAttrs = NestF->getAttributes();
10377   if (!NestAttrs.isEmpty()) {
10378     unsigned NestIdx = 1;
10379     const Type *NestTy = 0;
10380     Attributes NestAttr = Attribute::None;
10381
10382     // Look for a parameter marked with the 'nest' attribute.
10383     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10384          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10385       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10386         // Record the parameter type and any other attributes.
10387         NestTy = *I;
10388         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10389         break;
10390       }
10391
10392     if (NestTy) {
10393       Instruction *Caller = CS.getInstruction();
10394       std::vector<Value*> NewArgs;
10395       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10396
10397       SmallVector<AttributeWithIndex, 8> NewAttrs;
10398       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10399
10400       // Insert the nest argument into the call argument list, which may
10401       // mean appending it.  Likewise for attributes.
10402
10403       // Add any result attributes.
10404       if (Attributes Attr = Attrs.getRetAttributes())
10405         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10406
10407       {
10408         unsigned Idx = 1;
10409         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10410         do {
10411           if (Idx == NestIdx) {
10412             // Add the chain argument and attributes.
10413             Value *NestVal = Tramp->getOperand(3);
10414             if (NestVal->getType() != NestTy)
10415               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10416             NewArgs.push_back(NestVal);
10417             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10418           }
10419
10420           if (I == E)
10421             break;
10422
10423           // Add the original argument and attributes.
10424           NewArgs.push_back(*I);
10425           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10426             NewAttrs.push_back
10427               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10428
10429           ++Idx, ++I;
10430         } while (1);
10431       }
10432
10433       // Add any function attributes.
10434       if (Attributes Attr = Attrs.getFnAttributes())
10435         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10436
10437       // The trampoline may have been bitcast to a bogus type (FTy).
10438       // Handle this by synthesizing a new function type, equal to FTy
10439       // with the chain parameter inserted.
10440
10441       std::vector<const Type*> NewTypes;
10442       NewTypes.reserve(FTy->getNumParams()+1);
10443
10444       // Insert the chain's type into the list of parameter types, which may
10445       // mean appending it.
10446       {
10447         unsigned Idx = 1;
10448         FunctionType::param_iterator I = FTy->param_begin(),
10449           E = FTy->param_end();
10450
10451         do {
10452           if (Idx == NestIdx)
10453             // Add the chain's type.
10454             NewTypes.push_back(NestTy);
10455
10456           if (I == E)
10457             break;
10458
10459           // Add the original type.
10460           NewTypes.push_back(*I);
10461
10462           ++Idx, ++I;
10463         } while (1);
10464       }
10465
10466       // Replace the trampoline call with a direct call.  Let the generic
10467       // code sort out any function type mismatches.
10468       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10469                                                 FTy->isVarArg());
10470       Constant *NewCallee =
10471         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10472         NestF : ConstantExpr::getBitCast(NestF, 
10473                                          PointerType::getUnqual(NewFTy));
10474       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10475                                                    NewAttrs.end());
10476
10477       Instruction *NewCaller;
10478       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10479         NewCaller = InvokeInst::Create(NewCallee,
10480                                        II->getNormalDest(), II->getUnwindDest(),
10481                                        NewArgs.begin(), NewArgs.end(),
10482                                        Caller->getName(), Caller);
10483         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10484         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10485       } else {
10486         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10487                                      Caller->getName(), Caller);
10488         if (cast<CallInst>(Caller)->isTailCall())
10489           cast<CallInst>(NewCaller)->setTailCall();
10490         cast<CallInst>(NewCaller)->
10491           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10492         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10493       }
10494       if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10495         Caller->replaceAllUsesWith(NewCaller);
10496       Caller->eraseFromParent();
10497       RemoveFromWorkList(Caller);
10498       return 0;
10499     }
10500   }
10501
10502   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10503   // parameter, there is no need to adjust the argument list.  Let the generic
10504   // code sort out any function type mismatches.
10505   Constant *NewCallee =
10506     NestF->getType() == PTy ? NestF : 
10507                               ConstantExpr::getBitCast(NestF, PTy);
10508   CS.setCalledFunction(NewCallee);
10509   return CS.getInstruction();
10510 }
10511
10512 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10513 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10514 /// and a single binop.
10515 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10516   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10517   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10518   unsigned Opc = FirstInst->getOpcode();
10519   Value *LHSVal = FirstInst->getOperand(0);
10520   Value *RHSVal = FirstInst->getOperand(1);
10521     
10522   const Type *LHSType = LHSVal->getType();
10523   const Type *RHSType = RHSVal->getType();
10524   
10525   // Scan to see if all operands are the same opcode, all have one use, and all
10526   // kill their operands (i.e. the operands have one use).
10527   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10528     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10529     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10530         // Verify type of the LHS matches so we don't fold cmp's of different
10531         // types or GEP's with different index types.
10532         I->getOperand(0)->getType() != LHSType ||
10533         I->getOperand(1)->getType() != RHSType)
10534       return 0;
10535
10536     // If they are CmpInst instructions, check their predicates
10537     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10538       if (cast<CmpInst>(I)->getPredicate() !=
10539           cast<CmpInst>(FirstInst)->getPredicate())
10540         return 0;
10541     
10542     // Keep track of which operand needs a phi node.
10543     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10544     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10545   }
10546   
10547   // Otherwise, this is safe to transform!
10548   
10549   Value *InLHS = FirstInst->getOperand(0);
10550   Value *InRHS = FirstInst->getOperand(1);
10551   PHINode *NewLHS = 0, *NewRHS = 0;
10552   if (LHSVal == 0) {
10553     NewLHS = PHINode::Create(LHSType,
10554                              FirstInst->getOperand(0)->getName() + ".pn");
10555     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10556     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10557     InsertNewInstBefore(NewLHS, PN);
10558     LHSVal = NewLHS;
10559   }
10560   
10561   if (RHSVal == 0) {
10562     NewRHS = PHINode::Create(RHSType,
10563                              FirstInst->getOperand(1)->getName() + ".pn");
10564     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10565     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10566     InsertNewInstBefore(NewRHS, PN);
10567     RHSVal = NewRHS;
10568   }
10569   
10570   // Add all operands to the new PHIs.
10571   if (NewLHS || NewRHS) {
10572     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10573       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10574       if (NewLHS) {
10575         Value *NewInLHS = InInst->getOperand(0);
10576         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10577       }
10578       if (NewRHS) {
10579         Value *NewInRHS = InInst->getOperand(1);
10580         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10581       }
10582     }
10583   }
10584     
10585   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10586     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10587   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10588   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10589                          LHSVal, RHSVal);
10590 }
10591
10592 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10593   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10594   
10595   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10596                                         FirstInst->op_end());
10597   // This is true if all GEP bases are allocas and if all indices into them are
10598   // constants.
10599   bool AllBasePointersAreAllocas = true;
10600   
10601   // Scan to see if all operands are the same opcode, all have one use, and all
10602   // kill their operands (i.e. the operands have one use).
10603   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10604     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10605     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10606       GEP->getNumOperands() != FirstInst->getNumOperands())
10607       return 0;
10608
10609     // Keep track of whether or not all GEPs are of alloca pointers.
10610     if (AllBasePointersAreAllocas &&
10611         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10612          !GEP->hasAllConstantIndices()))
10613       AllBasePointersAreAllocas = false;
10614     
10615     // Compare the operand lists.
10616     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10617       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10618         continue;
10619       
10620       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10621       // if one of the PHIs has a constant for the index.  The index may be
10622       // substantially cheaper to compute for the constants, so making it a
10623       // variable index could pessimize the path.  This also handles the case
10624       // for struct indices, which must always be constant.
10625       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10626           isa<ConstantInt>(GEP->getOperand(op)))
10627         return 0;
10628       
10629       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10630         return 0;
10631       FixedOperands[op] = 0;  // Needs a PHI.
10632     }
10633   }
10634   
10635   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10636   // bother doing this transformation.  At best, this will just save a bit of
10637   // offset calculation, but all the predecessors will have to materialize the
10638   // stack address into a register anyway.  We'd actually rather *clone* the
10639   // load up into the predecessors so that we have a load of a gep of an alloca,
10640   // which can usually all be folded into the load.
10641   if (AllBasePointersAreAllocas)
10642     return 0;
10643   
10644   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10645   // that is variable.
10646   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10647   
10648   bool HasAnyPHIs = false;
10649   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10650     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10651     Value *FirstOp = FirstInst->getOperand(i);
10652     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10653                                      FirstOp->getName()+".pn");
10654     InsertNewInstBefore(NewPN, PN);
10655     
10656     NewPN->reserveOperandSpace(e);
10657     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10658     OperandPhis[i] = NewPN;
10659     FixedOperands[i] = NewPN;
10660     HasAnyPHIs = true;
10661   }
10662
10663   
10664   // Add all operands to the new PHIs.
10665   if (HasAnyPHIs) {
10666     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10667       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10668       BasicBlock *InBB = PN.getIncomingBlock(i);
10669       
10670       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10671         if (PHINode *OpPhi = OperandPhis[op])
10672           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10673     }
10674   }
10675   
10676   Value *Base = FixedOperands[0];
10677   GetElementPtrInst *GEP =
10678     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10679                               FixedOperands.end());
10680   if (cast<GEPOperator>(FirstInst)->isInBounds())
10681     cast<GEPOperator>(GEP)->setIsInBounds(true);
10682   return GEP;
10683 }
10684
10685
10686 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10687 /// sink the load out of the block that defines it.  This means that it must be
10688 /// obvious the value of the load is not changed from the point of the load to
10689 /// the end of the block it is in.
10690 ///
10691 /// Finally, it is safe, but not profitable, to sink a load targetting a
10692 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10693 /// to a register.
10694 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10695   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10696   
10697   for (++BBI; BBI != E; ++BBI)
10698     if (BBI->mayWriteToMemory())
10699       return false;
10700   
10701   // Check for non-address taken alloca.  If not address-taken already, it isn't
10702   // profitable to do this xform.
10703   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10704     bool isAddressTaken = false;
10705     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10706          UI != E; ++UI) {
10707       if (isa<LoadInst>(UI)) continue;
10708       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10709         // If storing TO the alloca, then the address isn't taken.
10710         if (SI->getOperand(1) == AI) continue;
10711       }
10712       isAddressTaken = true;
10713       break;
10714     }
10715     
10716     if (!isAddressTaken && AI->isStaticAlloca())
10717       return false;
10718   }
10719   
10720   // If this load is a load from a GEP with a constant offset from an alloca,
10721   // then we don't want to sink it.  In its present form, it will be
10722   // load [constant stack offset].  Sinking it will cause us to have to
10723   // materialize the stack addresses in each predecessor in a register only to
10724   // do a shared load from register in the successor.
10725   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10726     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10727       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10728         return false;
10729   
10730   return true;
10731 }
10732
10733
10734 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10735 // operator and they all are only used by the PHI, PHI together their
10736 // inputs, and do the operation once, to the result of the PHI.
10737 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10738   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10739
10740   // Scan the instruction, looking for input operations that can be folded away.
10741   // If all input operands to the phi are the same instruction (e.g. a cast from
10742   // the same type or "+42") we can pull the operation through the PHI, reducing
10743   // code size and simplifying code.
10744   Constant *ConstantOp = 0;
10745   const Type *CastSrcTy = 0;
10746   bool isVolatile = false;
10747   if (isa<CastInst>(FirstInst)) {
10748     CastSrcTy = FirstInst->getOperand(0)->getType();
10749   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10750     // Can fold binop, compare or shift here if the RHS is a constant, 
10751     // otherwise call FoldPHIArgBinOpIntoPHI.
10752     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10753     if (ConstantOp == 0)
10754       return FoldPHIArgBinOpIntoPHI(PN);
10755   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10756     isVolatile = LI->isVolatile();
10757     // We can't sink the load if the loaded value could be modified between the
10758     // load and the PHI.
10759     if (LI->getParent() != PN.getIncomingBlock(0) ||
10760         !isSafeAndProfitableToSinkLoad(LI))
10761       return 0;
10762     
10763     // If the PHI is of volatile loads and the load block has multiple
10764     // successors, sinking it would remove a load of the volatile value from
10765     // the path through the other successor.
10766     if (isVolatile &&
10767         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10768       return 0;
10769     
10770   } else if (isa<GetElementPtrInst>(FirstInst)) {
10771     return FoldPHIArgGEPIntoPHI(PN);
10772   } else {
10773     return 0;  // Cannot fold this operation.
10774   }
10775
10776   // Check to see if all arguments are the same operation.
10777   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10778     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10779     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10780     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10781       return 0;
10782     if (CastSrcTy) {
10783       if (I->getOperand(0)->getType() != CastSrcTy)
10784         return 0;  // Cast operation must match.
10785     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10786       // We can't sink the load if the loaded value could be modified between 
10787       // the load and the PHI.
10788       if (LI->isVolatile() != isVolatile ||
10789           LI->getParent() != PN.getIncomingBlock(i) ||
10790           !isSafeAndProfitableToSinkLoad(LI))
10791         return 0;
10792       
10793       // If the PHI is of volatile loads and the load block has multiple
10794       // successors, sinking it would remove a load of the volatile value from
10795       // the path through the other successor.
10796       if (isVolatile &&
10797           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10798         return 0;
10799       
10800     } else if (I->getOperand(1) != ConstantOp) {
10801       return 0;
10802     }
10803   }
10804
10805   // Okay, they are all the same operation.  Create a new PHI node of the
10806   // correct type, and PHI together all of the LHS's of the instructions.
10807   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10808                                    PN.getName()+".in");
10809   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10810
10811   Value *InVal = FirstInst->getOperand(0);
10812   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10813
10814   // Add all operands to the new PHI.
10815   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10816     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10817     if (NewInVal != InVal)
10818       InVal = 0;
10819     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10820   }
10821
10822   Value *PhiVal;
10823   if (InVal) {
10824     // The new PHI unions all of the same values together.  This is really
10825     // common, so we handle it intelligently here for compile-time speed.
10826     PhiVal = InVal;
10827     delete NewPN;
10828   } else {
10829     InsertNewInstBefore(NewPN, PN);
10830     PhiVal = NewPN;
10831   }
10832
10833   // Insert and return the new operation.
10834   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10835     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10836   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10837     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10838   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10839     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10840                            PhiVal, ConstantOp);
10841   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10842   
10843   // If this was a volatile load that we are merging, make sure to loop through
10844   // and mark all the input loads as non-volatile.  If we don't do this, we will
10845   // insert a new volatile load and the old ones will not be deletable.
10846   if (isVolatile)
10847     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10848       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10849   
10850   return new LoadInst(PhiVal, "", isVolatile);
10851 }
10852
10853 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10854 /// that is dead.
10855 static bool DeadPHICycle(PHINode *PN,
10856                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10857   if (PN->use_empty()) return true;
10858   if (!PN->hasOneUse()) return false;
10859
10860   // Remember this node, and if we find the cycle, return.
10861   if (!PotentiallyDeadPHIs.insert(PN))
10862     return true;
10863   
10864   // Don't scan crazily complex things.
10865   if (PotentiallyDeadPHIs.size() == 16)
10866     return false;
10867
10868   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10869     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10870
10871   return false;
10872 }
10873
10874 /// PHIsEqualValue - Return true if this phi node is always equal to
10875 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10876 ///   z = some value; x = phi (y, z); y = phi (x, z)
10877 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10878                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10879   // See if we already saw this PHI node.
10880   if (!ValueEqualPHIs.insert(PN))
10881     return true;
10882   
10883   // Don't scan crazily complex things.
10884   if (ValueEqualPHIs.size() == 16)
10885     return false;
10886  
10887   // Scan the operands to see if they are either phi nodes or are equal to
10888   // the value.
10889   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10890     Value *Op = PN->getIncomingValue(i);
10891     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10892       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10893         return false;
10894     } else if (Op != NonPhiInVal)
10895       return false;
10896   }
10897   
10898   return true;
10899 }
10900
10901
10902 // PHINode simplification
10903 //
10904 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10905   // If LCSSA is around, don't mess with Phi nodes
10906   if (MustPreserveLCSSA) return 0;
10907   
10908   if (Value *V = PN.hasConstantValue())
10909     return ReplaceInstUsesWith(PN, V);
10910
10911   // If all PHI operands are the same operation, pull them through the PHI,
10912   // reducing code size.
10913   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10914       isa<Instruction>(PN.getIncomingValue(1)) &&
10915       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10916       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10917       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10918       // than themselves more than once.
10919       PN.getIncomingValue(0)->hasOneUse())
10920     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10921       return Result;
10922
10923   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10924   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10925   // PHI)... break the cycle.
10926   if (PN.hasOneUse()) {
10927     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10928     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10929       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10930       PotentiallyDeadPHIs.insert(&PN);
10931       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10932         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10933     }
10934    
10935     // If this phi has a single use, and if that use just computes a value for
10936     // the next iteration of a loop, delete the phi.  This occurs with unused
10937     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10938     // common case here is good because the only other things that catch this
10939     // are induction variable analysis (sometimes) and ADCE, which is only run
10940     // late.
10941     if (PHIUser->hasOneUse() &&
10942         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10943         PHIUser->use_back() == &PN) {
10944       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10945     }
10946   }
10947
10948   // We sometimes end up with phi cycles that non-obviously end up being the
10949   // same value, for example:
10950   //   z = some value; x = phi (y, z); y = phi (x, z)
10951   // where the phi nodes don't necessarily need to be in the same block.  Do a
10952   // quick check to see if the PHI node only contains a single non-phi value, if
10953   // so, scan to see if the phi cycle is actually equal to that value.
10954   {
10955     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10956     // Scan for the first non-phi operand.
10957     while (InValNo != NumOperandVals && 
10958            isa<PHINode>(PN.getIncomingValue(InValNo)))
10959       ++InValNo;
10960
10961     if (InValNo != NumOperandVals) {
10962       Value *NonPhiInVal = PN.getOperand(InValNo);
10963       
10964       // Scan the rest of the operands to see if there are any conflicts, if so
10965       // there is no need to recursively scan other phis.
10966       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10967         Value *OpVal = PN.getIncomingValue(InValNo);
10968         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10969           break;
10970       }
10971       
10972       // If we scanned over all operands, then we have one unique value plus
10973       // phi values.  Scan PHI nodes to see if they all merge in each other or
10974       // the value.
10975       if (InValNo == NumOperandVals) {
10976         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10977         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10978           return ReplaceInstUsesWith(PN, NonPhiInVal);
10979       }
10980     }
10981   }
10982   return 0;
10983 }
10984
10985 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10986                                    Instruction *InsertPoint,
10987                                    InstCombiner *IC) {
10988   unsigned PtrSize = DTy->getScalarSizeInBits();
10989   unsigned VTySize = V->getType()->getScalarSizeInBits();
10990   // We must cast correctly to the pointer type. Ensure that we
10991   // sign extend the integer value if it is smaller as this is
10992   // used for address computation.
10993   Instruction::CastOps opcode = 
10994      (VTySize < PtrSize ? Instruction::SExt :
10995       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10996   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10997 }
10998
10999
11000 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11001   Value *PtrOp = GEP.getOperand(0);
11002   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
11003   // If so, eliminate the noop.
11004   if (GEP.getNumOperands() == 1)
11005     return ReplaceInstUsesWith(GEP, PtrOp);
11006
11007   if (isa<UndefValue>(GEP.getOperand(0)))
11008     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
11009
11010   bool HasZeroPointerIndex = false;
11011   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11012     HasZeroPointerIndex = C->isNullValue();
11013
11014   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11015     return ReplaceInstUsesWith(GEP, PtrOp);
11016
11017   // Eliminate unneeded casts for indices.
11018   if (TD) {
11019     bool MadeChange = false;
11020     unsigned PtrSize = TD->getPointerSizeInBits();
11021     
11022     gep_type_iterator GTI = gep_type_begin(GEP);
11023     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11024          I != E; ++I, ++GTI) {
11025       if (!isa<SequentialType>(*GTI)) continue;
11026       
11027       // If we are using a wider index than needed for this platform, shrink it
11028       // to what we need.  If narrower, sign-extend it to what we need.  This
11029       // explicit cast can make subsequent optimizations more obvious.
11030       unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
11031       
11032       if (OpBits == PtrSize)
11033         continue;
11034       
11035       Instruction::CastOps Opc =
11036         OpBits > PtrSize ? Instruction::Trunc : Instruction::SExt;
11037       *I = InsertCastBefore(Opc, *I, TD->getIntPtrType(GEP.getContext()), GEP);
11038       MadeChange = true;
11039     }
11040     if (MadeChange) return &GEP;
11041   }
11042
11043   // Combine Indices - If the source pointer to this getelementptr instruction
11044   // is a getelementptr instruction, combine the indices of the two
11045   // getelementptr instructions into a single instruction.
11046   //
11047   SmallVector<Value*, 8> SrcGEPOperands;
11048   bool BothInBounds = cast<GEPOperator>(&GEP)->isInBounds();
11049   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
11050     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11051     if (!Src->isInBounds())
11052       BothInBounds = false;
11053   }
11054
11055   if (!SrcGEPOperands.empty()) {
11056     // Note that if our source is a gep chain itself that we wait for that
11057     // chain to be resolved before we perform this transformation.  This
11058     // avoids us creating a TON of code in some cases.
11059     //
11060     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11061         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11062       return 0;   // Wait until our source is folded to completion.
11063
11064     SmallVector<Value*, 8> Indices;
11065
11066     // Find out whether the last index in the source GEP is a sequential idx.
11067     bool EndsWithSequential = false;
11068     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11069            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11070       EndsWithSequential = !isa<StructType>(*I);
11071
11072     // Can we combine the two pointer arithmetics offsets?
11073     if (EndsWithSequential) {
11074       // Replace: gep (gep %P, long B), long A, ...
11075       // With:    T = long A+B; gep %P, T, ...
11076       //
11077       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11078       if (SO1 == Constant::getNullValue(SO1->getType())) {
11079         Sum = GO1;
11080       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11081         Sum = SO1;
11082       } else {
11083         // If they aren't the same type, convert both to an integer of the
11084         // target's pointer size.
11085         if (SO1->getType() != GO1->getType()) {
11086           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11087             SO1 =
11088                 ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
11089           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11090             GO1 =
11091                 ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
11092           } else if (TD) {
11093             unsigned PS = TD->getPointerSizeInBits();
11094             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11095               // Convert GO1 to SO1's type.
11096               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11097
11098             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11099               // Convert SO1 to GO1's type.
11100               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11101             } else {
11102               const Type *PT = TD->getIntPtrType(GEP.getContext());
11103               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11104               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11105             }
11106           }
11107         }
11108         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11109           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
11110         else {
11111           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11112           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11113         }
11114       }
11115
11116       // Recycle the GEP we already have if possible.
11117       if (SrcGEPOperands.size() == 2) {
11118         GEP.setOperand(0, SrcGEPOperands[0]);
11119         GEP.setOperand(1, Sum);
11120         return &GEP;
11121       }
11122       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11123                      SrcGEPOperands.end()-1);
11124       Indices.push_back(Sum);
11125       Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11126     } else if (isa<Constant>(*GEP.idx_begin()) &&
11127                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11128                SrcGEPOperands.size() != 1) {
11129       // Otherwise we can do the fold if the first index of the GEP is a zero
11130       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11131                      SrcGEPOperands.end());
11132       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11133     }
11134
11135     if (!Indices.empty()) {
11136       GetElementPtrInst *NewGEP =
11137         GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11138                                   Indices.end(), GEP.getName());
11139       if (BothInBounds)
11140         cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11141       return NewGEP;
11142     }
11143
11144   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11145     if (!isa<PointerType>(X->getType())) {
11146       // Not interesting.  Source pointer must be a cast from pointer.
11147     } else if (HasZeroPointerIndex) {
11148       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11149       // into     : GEP [10 x i8]* X, i32 0, ...
11150       //
11151       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11152       //           into     : GEP i8* X, ...
11153       // 
11154       // This occurs when the program declares an array extern like "int X[];"
11155       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11156       const PointerType *XTy = cast<PointerType>(X->getType());
11157       if (const ArrayType *CATy =
11158           dyn_cast<ArrayType>(CPTy->getElementType())) {
11159         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11160         if (CATy->getElementType() == XTy->getElementType()) {
11161           // -> GEP i8* X, ...
11162           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11163           GetElementPtrInst *NewGEP =
11164             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11165                                       GEP.getName());
11166           if (cast<GEPOperator>(&GEP)->isInBounds())
11167             cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11168           return NewGEP;
11169         } else if (const ArrayType *XATy =
11170                  dyn_cast<ArrayType>(XTy->getElementType())) {
11171           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11172           if (CATy->getElementType() == XATy->getElementType()) {
11173             // -> GEP [10 x i8]* X, i32 0, ...
11174             // At this point, we know that the cast source type is a pointer
11175             // to an array of the same type as the destination pointer
11176             // array.  Because the array type is never stepped over (there
11177             // is a leading zero) we can fold the cast into this GEP.
11178             GEP.setOperand(0, X);
11179             return &GEP;
11180           }
11181         }
11182       }
11183     } else if (GEP.getNumOperands() == 2) {
11184       // Transform things like:
11185       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11186       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11187       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11188       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11189       if (TD && isa<ArrayType>(SrcElTy) &&
11190           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11191           TD->getTypeAllocSize(ResElTy)) {
11192         Value *Idx[2];
11193         Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11194         Idx[1] = GEP.getOperand(1);
11195         GetElementPtrInst *NewGEP =
11196           GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11197         if (cast<GEPOperator>(&GEP)->isInBounds())
11198           cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11199         Value *V = InsertNewInstBefore(NewGEP, GEP);
11200         // V and GEP are both pointer types --> BitCast
11201         return new BitCastInst(V, GEP.getType());
11202       }
11203       
11204       // Transform things like:
11205       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11206       //   (where tmp = 8*tmp2) into:
11207       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11208       
11209       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
11210         uint64_t ArrayEltSize =
11211             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11212         
11213         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11214         // allow either a mul, shift, or constant here.
11215         Value *NewIdx = 0;
11216         ConstantInt *Scale = 0;
11217         if (ArrayEltSize == 1) {
11218           NewIdx = GEP.getOperand(1);
11219           Scale = 
11220                ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11221         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11222           NewIdx = ConstantInt::get(CI->getType(), 1);
11223           Scale = CI;
11224         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11225           if (Inst->getOpcode() == Instruction::Shl &&
11226               isa<ConstantInt>(Inst->getOperand(1))) {
11227             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11228             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11229             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11230                                      1ULL << ShAmtVal);
11231             NewIdx = Inst->getOperand(0);
11232           } else if (Inst->getOpcode() == Instruction::Mul &&
11233                      isa<ConstantInt>(Inst->getOperand(1))) {
11234             Scale = cast<ConstantInt>(Inst->getOperand(1));
11235             NewIdx = Inst->getOperand(0);
11236           }
11237         }
11238         
11239         // If the index will be to exactly the right offset with the scale taken
11240         // out, perform the transformation. Note, we don't know whether Scale is
11241         // signed or not. We'll use unsigned version of division/modulo
11242         // operation after making sure Scale doesn't have the sign bit set.
11243         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11244             Scale->getZExtValue() % ArrayEltSize == 0) {
11245           Scale = ConstantInt::get(Scale->getType(),
11246                                    Scale->getZExtValue() / ArrayEltSize);
11247           if (Scale->getZExtValue() != 1) {
11248             Constant *C =
11249                    ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11250                                                        false /*ZExt*/);
11251             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11252             NewIdx = InsertNewInstBefore(Sc, GEP);
11253           }
11254
11255           // Insert the new GEP instruction.
11256           Value *Idx[2];
11257           Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11258           Idx[1] = NewIdx;
11259           Instruction *NewGEP =
11260             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11261           if (cast<GEPOperator>(&GEP)->isInBounds())
11262             cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11263           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11264           // The NewGEP must be pointer typed, so must the old one -> BitCast
11265           return new BitCastInst(NewGEP, GEP.getType());
11266         }
11267       }
11268     }
11269   }
11270   
11271   /// See if we can simplify:
11272   ///   X = bitcast A to B*
11273   ///   Y = gep X, <...constant indices...>
11274   /// into a gep of the original struct.  This is important for SROA and alias
11275   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11276   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11277     if (TD &&
11278         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11279       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11280       // a constant back from EmitGEPOffset.
11281       ConstantInt *OffsetV =
11282                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11283       int64_t Offset = OffsetV->getSExtValue();
11284       
11285       // If this GEP instruction doesn't move the pointer, just replace the GEP
11286       // with a bitcast of the real input to the dest type.
11287       if (Offset == 0) {
11288         // If the bitcast is of an allocation, and the allocation will be
11289         // converted to match the type of the cast, don't touch this.
11290         if (isa<AllocationInst>(BCI->getOperand(0))) {
11291           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11292           if (Instruction *I = visitBitCast(*BCI)) {
11293             if (I != BCI) {
11294               I->takeName(BCI);
11295               BCI->getParent()->getInstList().insert(BCI, I);
11296               ReplaceInstUsesWith(*BCI, I);
11297             }
11298             return &GEP;
11299           }
11300         }
11301         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11302       }
11303       
11304       // Otherwise, if the offset is non-zero, we need to find out if there is a
11305       // field at Offset in 'A's type.  If so, we can pull the cast through the
11306       // GEP.
11307       SmallVector<Value*, 8> NewIndices;
11308       const Type *InTy =
11309         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11310       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11311         Instruction *NGEP =
11312            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11313                                      NewIndices.end());
11314         if (NGEP->getType() == GEP.getType()) return NGEP;
11315         if (cast<GEPOperator>(&GEP)->isInBounds())
11316           cast<GEPOperator>(NGEP)->setIsInBounds(true);
11317         InsertNewInstBefore(NGEP, GEP);
11318         NGEP->takeName(&GEP);
11319         return new BitCastInst(NGEP, GEP.getType());
11320       }
11321     }
11322   }    
11323     
11324   return 0;
11325 }
11326
11327 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11328   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11329   if (AI.isArrayAllocation()) {  // Check C != 1
11330     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11331       const Type *NewTy = 
11332         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11333       AllocationInst *New = 0;
11334
11335       // Create and insert the replacement instruction...
11336       if (isa<MallocInst>(AI))
11337         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11338       else {
11339         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11340         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11341       }
11342
11343       InsertNewInstBefore(New, AI);
11344
11345       // Scan to the end of the allocation instructions, to skip over a block of
11346       // allocas if possible...also skip interleaved debug info
11347       //
11348       BasicBlock::iterator It = New;
11349       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11350
11351       // Now that I is pointing to the first non-allocation-inst in the block,
11352       // insert our getelementptr instruction...
11353       //
11354       Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11355       Value *Idx[2];
11356       Idx[0] = NullIdx;
11357       Idx[1] = NullIdx;
11358       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11359                                            New->getName()+".sub", It);
11360       cast<GEPOperator>(V)->setIsInBounds(true);
11361
11362       // Now make everything use the getelementptr instead of the original
11363       // allocation.
11364       return ReplaceInstUsesWith(AI, V);
11365     } else if (isa<UndefValue>(AI.getArraySize())) {
11366       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11367     }
11368   }
11369
11370   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11371     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11372     // Note that we only do this for alloca's, because malloc should allocate
11373     // and return a unique pointer, even for a zero byte allocation.
11374     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11375       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11376
11377     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11378     if (AI.getAlignment() == 0)
11379       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11380   }
11381
11382   return 0;
11383 }
11384
11385 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11386   Value *Op = FI.getOperand(0);
11387
11388   // free undef -> unreachable.
11389   if (isa<UndefValue>(Op)) {
11390     // Insert a new store to null because we cannot modify the CFG here.
11391     new StoreInst(ConstantInt::getTrue(*Context),
11392            UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
11393     return EraseInstFromFunction(FI);
11394   }
11395   
11396   // If we have 'free null' delete the instruction.  This can happen in stl code
11397   // when lots of inlining happens.
11398   if (isa<ConstantPointerNull>(Op))
11399     return EraseInstFromFunction(FI);
11400   
11401   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11402   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11403     FI.setOperand(0, CI->getOperand(0));
11404     return &FI;
11405   }
11406   
11407   // Change free (gep X, 0,0,0,0) into free(X)
11408   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11409     if (GEPI->hasAllZeroIndices()) {
11410       AddToWorkList(GEPI);
11411       FI.setOperand(0, GEPI->getOperand(0));
11412       return &FI;
11413     }
11414   }
11415   
11416   // Change free(malloc) into nothing, if the malloc has a single use.
11417   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11418     if (MI->hasOneUse()) {
11419       EraseInstFromFunction(FI);
11420       return EraseInstFromFunction(*MI);
11421     }
11422
11423   return 0;
11424 }
11425
11426
11427 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11428 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11429                                         const TargetData *TD) {
11430   User *CI = cast<User>(LI.getOperand(0));
11431   Value *CastOp = CI->getOperand(0);
11432   LLVMContext *Context = IC.getContext();
11433
11434   if (TD) {
11435     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11436       // Instead of loading constant c string, use corresponding integer value
11437       // directly if string length is small enough.
11438       std::string Str;
11439       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11440         unsigned len = Str.length();
11441         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11442         unsigned numBits = Ty->getPrimitiveSizeInBits();
11443         // Replace LI with immediate integer store.
11444         if ((numBits >> 3) == len + 1) {
11445           APInt StrVal(numBits, 0);
11446           APInt SingleChar(numBits, 0);
11447           if (TD->isLittleEndian()) {
11448             for (signed i = len-1; i >= 0; i--) {
11449               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11450               StrVal = (StrVal << 8) | SingleChar;
11451             }
11452           } else {
11453             for (unsigned i = 0; i < len; i++) {
11454               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11455               StrVal = (StrVal << 8) | SingleChar;
11456             }
11457             // Append NULL at the end.
11458             SingleChar = 0;
11459             StrVal = (StrVal << 8) | SingleChar;
11460           }
11461           Value *NL = ConstantInt::get(*Context, StrVal);
11462           return IC.ReplaceInstUsesWith(LI, NL);
11463         }
11464       }
11465     }
11466   }
11467
11468   const PointerType *DestTy = cast<PointerType>(CI->getType());
11469   const Type *DestPTy = DestTy->getElementType();
11470   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11471
11472     // If the address spaces don't match, don't eliminate the cast.
11473     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11474       return 0;
11475
11476     const Type *SrcPTy = SrcTy->getElementType();
11477
11478     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11479          isa<VectorType>(DestPTy)) {
11480       // If the source is an array, the code below will not succeed.  Check to
11481       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11482       // constants.
11483       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11484         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11485           if (ASrcTy->getNumElements() != 0) {
11486             Value *Idxs[2];
11487             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
11488             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11489             SrcTy = cast<PointerType>(CastOp->getType());
11490             SrcPTy = SrcTy->getElementType();
11491           }
11492
11493       if (IC.getTargetData() &&
11494           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11495             isa<VectorType>(SrcPTy)) &&
11496           // Do not allow turning this into a load of an integer, which is then
11497           // casted to a pointer, this pessimizes pointer analysis a lot.
11498           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11499           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11500                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11501
11502         // Okay, we are casting from one integer or pointer type to another of
11503         // the same size.  Instead of casting the pointer before the load, cast
11504         // the result of the loaded value.
11505         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11506                                                              CI->getName(),
11507                                                          LI.isVolatile()),LI);
11508         // Now cast the result of the load.
11509         return new BitCastInst(NewLoad, LI.getType());
11510       }
11511     }
11512   }
11513   return 0;
11514 }
11515
11516 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11517   Value *Op = LI.getOperand(0);
11518
11519   // Attempt to improve the alignment.
11520   if (TD) {
11521     unsigned KnownAlign =
11522       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11523     if (KnownAlign >
11524         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11525                                   LI.getAlignment()))
11526       LI.setAlignment(KnownAlign);
11527   }
11528
11529   // load (cast X) --> cast (load X) iff safe
11530   if (isa<CastInst>(Op))
11531     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11532       return Res;
11533
11534   // None of the following transforms are legal for volatile loads.
11535   if (LI.isVolatile()) return 0;
11536   
11537   // Do really simple store-to-load forwarding and load CSE, to catch cases
11538   // where there are several consequtive memory accesses to the same location,
11539   // separated by a few arithmetic operations.
11540   BasicBlock::iterator BBI = &LI;
11541   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11542     return ReplaceInstUsesWith(LI, AvailableVal);
11543
11544   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11545     const Value *GEPI0 = GEPI->getOperand(0);
11546     // TODO: Consider a target hook for valid address spaces for this xform.
11547     if (isa<ConstantPointerNull>(GEPI0) &&
11548         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11549       // Insert a new store to null instruction before the load to indicate
11550       // that this code is not reachable.  We do this instead of inserting
11551       // an unreachable instruction directly because we cannot modify the
11552       // CFG.
11553       new StoreInst(UndefValue::get(LI.getType()),
11554                     Constant::getNullValue(Op->getType()), &LI);
11555       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11556     }
11557   } 
11558
11559   if (Constant *C = dyn_cast<Constant>(Op)) {
11560     // load null/undef -> undef
11561     // TODO: Consider a target hook for valid address spaces for this xform.
11562     if (isa<UndefValue>(C) || (C->isNullValue() && 
11563         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11564       // Insert a new store to null instruction before the load to indicate that
11565       // this code is not reachable.  We do this instead of inserting an
11566       // unreachable instruction directly because we cannot modify the CFG.
11567       new StoreInst(UndefValue::get(LI.getType()),
11568                     Constant::getNullValue(Op->getType()), &LI);
11569       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11570     }
11571
11572     // Instcombine load (constant global) into the value loaded.
11573     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11574       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11575         return ReplaceInstUsesWith(LI, GV->getInitializer());
11576
11577     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11578     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11579       if (CE->getOpcode() == Instruction::GetElementPtr) {
11580         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11581           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11582             if (Constant *V = 
11583                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11584                                                       *Context))
11585               return ReplaceInstUsesWith(LI, V);
11586         if (CE->getOperand(0)->isNullValue()) {
11587           // Insert a new store to null instruction before the load to indicate
11588           // that this code is not reachable.  We do this instead of inserting
11589           // an unreachable instruction directly because we cannot modify the
11590           // CFG.
11591           new StoreInst(UndefValue::get(LI.getType()),
11592                         Constant::getNullValue(Op->getType()), &LI);
11593           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11594         }
11595
11596       } else if (CE->isCast()) {
11597         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11598           return Res;
11599       }
11600     }
11601   }
11602     
11603   // If this load comes from anywhere in a constant global, and if the global
11604   // is all undef or zero, we know what it loads.
11605   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11606     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11607       if (GV->getInitializer()->isNullValue())
11608         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11609       else if (isa<UndefValue>(GV->getInitializer()))
11610         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11611     }
11612   }
11613
11614   if (Op->hasOneUse()) {
11615     // Change select and PHI nodes to select values instead of addresses: this
11616     // helps alias analysis out a lot, allows many others simplifications, and
11617     // exposes redundancy in the code.
11618     //
11619     // Note that we cannot do the transformation unless we know that the
11620     // introduced loads cannot trap!  Something like this is valid as long as
11621     // the condition is always false: load (select bool %C, int* null, int* %G),
11622     // but it would not be valid if we transformed it to load from null
11623     // unconditionally.
11624     //
11625     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11626       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11627       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11628           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11629         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11630                                      SI->getOperand(1)->getName()+".val"), LI);
11631         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11632                                      SI->getOperand(2)->getName()+".val"), LI);
11633         return SelectInst::Create(SI->getCondition(), V1, V2);
11634       }
11635
11636       // load (select (cond, null, P)) -> load P
11637       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11638         if (C->isNullValue()) {
11639           LI.setOperand(0, SI->getOperand(2));
11640           return &LI;
11641         }
11642
11643       // load (select (cond, P, null)) -> load P
11644       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11645         if (C->isNullValue()) {
11646           LI.setOperand(0, SI->getOperand(1));
11647           return &LI;
11648         }
11649     }
11650   }
11651   return 0;
11652 }
11653
11654 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11655 /// when possible.  This makes it generally easy to do alias analysis and/or
11656 /// SROA/mem2reg of the memory object.
11657 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11658   User *CI = cast<User>(SI.getOperand(1));
11659   Value *CastOp = CI->getOperand(0);
11660
11661   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11662   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11663   if (SrcTy == 0) return 0;
11664   
11665   const Type *SrcPTy = SrcTy->getElementType();
11666
11667   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11668     return 0;
11669   
11670   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11671   /// to its first element.  This allows us to handle things like:
11672   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11673   /// on 32-bit hosts.
11674   SmallVector<Value*, 4> NewGEPIndices;
11675   
11676   // If the source is an array, the code below will not succeed.  Check to
11677   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11678   // constants.
11679   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11680     // Index through pointer.
11681     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11682     NewGEPIndices.push_back(Zero);
11683     
11684     while (1) {
11685       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11686         if (!STy->getNumElements()) /* Struct can be empty {} */
11687           break;
11688         NewGEPIndices.push_back(Zero);
11689         SrcPTy = STy->getElementType(0);
11690       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11691         NewGEPIndices.push_back(Zero);
11692         SrcPTy = ATy->getElementType();
11693       } else {
11694         break;
11695       }
11696     }
11697     
11698     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11699   }
11700
11701   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11702     return 0;
11703   
11704   // If the pointers point into different address spaces or if they point to
11705   // values with different sizes, we can't do the transformation.
11706   if (!IC.getTargetData() ||
11707       SrcTy->getAddressSpace() != 
11708         cast<PointerType>(CI->getType())->getAddressSpace() ||
11709       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11710       IC.getTargetData()->getTypeSizeInBits(DestPTy))
11711     return 0;
11712
11713   // Okay, we are casting from one integer or pointer type to another of
11714   // the same size.  Instead of casting the pointer before 
11715   // the store, cast the value to be stored.
11716   Value *NewCast;
11717   Value *SIOp0 = SI.getOperand(0);
11718   Instruction::CastOps opcode = Instruction::BitCast;
11719   const Type* CastSrcTy = SIOp0->getType();
11720   const Type* CastDstTy = SrcPTy;
11721   if (isa<PointerType>(CastDstTy)) {
11722     if (CastSrcTy->isInteger())
11723       opcode = Instruction::IntToPtr;
11724   } else if (isa<IntegerType>(CastDstTy)) {
11725     if (isa<PointerType>(SIOp0->getType()))
11726       opcode = Instruction::PtrToInt;
11727   }
11728   
11729   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11730   // emit a GEP to index into its first field.
11731   if (!NewGEPIndices.empty()) {
11732     if (Constant *C = dyn_cast<Constant>(CastOp))
11733       CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0], 
11734                                               NewGEPIndices.size());
11735     else
11736       CastOp = IC.InsertNewInstBefore(
11737               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11738                                         NewGEPIndices.end()), SI);
11739     cast<GEPOperator>(CastOp)->setIsInBounds(true);
11740   }
11741   
11742   if (Constant *C = dyn_cast<Constant>(SIOp0))
11743     NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11744   else
11745     NewCast = IC.InsertNewInstBefore(
11746       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11747       SI);
11748   return new StoreInst(NewCast, CastOp);
11749 }
11750
11751 /// equivalentAddressValues - Test if A and B will obviously have the same
11752 /// value. This includes recognizing that %t0 and %t1 will have the same
11753 /// value in code like this:
11754 ///   %t0 = getelementptr \@a, 0, 3
11755 ///   store i32 0, i32* %t0
11756 ///   %t1 = getelementptr \@a, 0, 3
11757 ///   %t2 = load i32* %t1
11758 ///
11759 static bool equivalentAddressValues(Value *A, Value *B) {
11760   // Test if the values are trivially equivalent.
11761   if (A == B) return true;
11762   
11763   // Test if the values come form identical arithmetic instructions.
11764   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11765   // its only used to compare two uses within the same basic block, which
11766   // means that they'll always either have the same value or one of them
11767   // will have an undefined value.
11768   if (isa<BinaryOperator>(A) ||
11769       isa<CastInst>(A) ||
11770       isa<PHINode>(A) ||
11771       isa<GetElementPtrInst>(A))
11772     if (Instruction *BI = dyn_cast<Instruction>(B))
11773       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
11774         return true;
11775   
11776   // Otherwise they may not be equivalent.
11777   return false;
11778 }
11779
11780 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11781 // return the llvm.dbg.declare.
11782 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11783   if (!V->hasNUses(2))
11784     return 0;
11785   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11786        UI != E; ++UI) {
11787     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11788       return DI;
11789     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11790       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11791         return DI;
11792       }
11793   }
11794   return 0;
11795 }
11796
11797 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11798   Value *Val = SI.getOperand(0);
11799   Value *Ptr = SI.getOperand(1);
11800
11801   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11802     EraseInstFromFunction(SI);
11803     ++NumCombined;
11804     return 0;
11805   }
11806   
11807   // If the RHS is an alloca with a single use, zapify the store, making the
11808   // alloca dead.
11809   // If the RHS is an alloca with a two uses, the other one being a 
11810   // llvm.dbg.declare, zapify the store and the declare, making the
11811   // alloca dead.  We must do this to prevent declare's from affecting
11812   // codegen.
11813   if (!SI.isVolatile()) {
11814     if (Ptr->hasOneUse()) {
11815       if (isa<AllocaInst>(Ptr)) {
11816         EraseInstFromFunction(SI);
11817         ++NumCombined;
11818         return 0;
11819       }
11820       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11821         if (isa<AllocaInst>(GEP->getOperand(0))) {
11822           if (GEP->getOperand(0)->hasOneUse()) {
11823             EraseInstFromFunction(SI);
11824             ++NumCombined;
11825             return 0;
11826           }
11827           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11828             EraseInstFromFunction(*DI);
11829             EraseInstFromFunction(SI);
11830             ++NumCombined;
11831             return 0;
11832           }
11833         }
11834       }
11835     }
11836     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11837       EraseInstFromFunction(*DI);
11838       EraseInstFromFunction(SI);
11839       ++NumCombined;
11840       return 0;
11841     }
11842   }
11843
11844   // Attempt to improve the alignment.
11845   if (TD) {
11846     unsigned KnownAlign =
11847       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11848     if (KnownAlign >
11849         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11850                                   SI.getAlignment()))
11851       SI.setAlignment(KnownAlign);
11852   }
11853
11854   // Do really simple DSE, to catch cases where there are several consecutive
11855   // stores to the same location, separated by a few arithmetic operations. This
11856   // situation often occurs with bitfield accesses.
11857   BasicBlock::iterator BBI = &SI;
11858   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11859        --ScanInsts) {
11860     --BBI;
11861     // Don't count debug info directives, lest they affect codegen,
11862     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11863     // It is necessary for correctness to skip those that feed into a
11864     // llvm.dbg.declare, as these are not present when debugging is off.
11865     if (isa<DbgInfoIntrinsic>(BBI) ||
11866         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11867       ScanInsts++;
11868       continue;
11869     }    
11870     
11871     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11872       // Prev store isn't volatile, and stores to the same location?
11873       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11874                                                           SI.getOperand(1))) {
11875         ++NumDeadStore;
11876         ++BBI;
11877         EraseInstFromFunction(*PrevSI);
11878         continue;
11879       }
11880       break;
11881     }
11882     
11883     // If this is a load, we have to stop.  However, if the loaded value is from
11884     // the pointer we're loading and is producing the pointer we're storing,
11885     // then *this* store is dead (X = load P; store X -> P).
11886     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11887       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11888           !SI.isVolatile()) {
11889         EraseInstFromFunction(SI);
11890         ++NumCombined;
11891         return 0;
11892       }
11893       // Otherwise, this is a load from some other location.  Stores before it
11894       // may not be dead.
11895       break;
11896     }
11897     
11898     // Don't skip over loads or things that can modify memory.
11899     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11900       break;
11901   }
11902   
11903   
11904   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11905
11906   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11907   if (isa<ConstantPointerNull>(Ptr) &&
11908       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11909     if (!isa<UndefValue>(Val)) {
11910       SI.setOperand(0, UndefValue::get(Val->getType()));
11911       if (Instruction *U = dyn_cast<Instruction>(Val))
11912         AddToWorkList(U);  // Dropped a use.
11913       ++NumCombined;
11914     }
11915     return 0;  // Do not modify these!
11916   }
11917
11918   // store undef, Ptr -> noop
11919   if (isa<UndefValue>(Val)) {
11920     EraseInstFromFunction(SI);
11921     ++NumCombined;
11922     return 0;
11923   }
11924
11925   // If the pointer destination is a cast, see if we can fold the cast into the
11926   // source instead.
11927   if (isa<CastInst>(Ptr))
11928     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11929       return Res;
11930   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11931     if (CE->isCast())
11932       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11933         return Res;
11934
11935   
11936   // If this store is the last instruction in the basic block (possibly
11937   // excepting debug info instructions and the pointer bitcasts that feed
11938   // into them), and if the block ends with an unconditional branch, try
11939   // to move it to the successor block.
11940   BBI = &SI; 
11941   do {
11942     ++BBI;
11943   } while (isa<DbgInfoIntrinsic>(BBI) ||
11944            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11945   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11946     if (BI->isUnconditional())
11947       if (SimplifyStoreAtEndOfBlock(SI))
11948         return 0;  // xform done!
11949   
11950   return 0;
11951 }
11952
11953 /// SimplifyStoreAtEndOfBlock - Turn things like:
11954 ///   if () { *P = v1; } else { *P = v2 }
11955 /// into a phi node with a store in the successor.
11956 ///
11957 /// Simplify things like:
11958 ///   *P = v1; if () { *P = v2; }
11959 /// into a phi node with a store in the successor.
11960 ///
11961 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11962   BasicBlock *StoreBB = SI.getParent();
11963   
11964   // Check to see if the successor block has exactly two incoming edges.  If
11965   // so, see if the other predecessor contains a store to the same location.
11966   // if so, insert a PHI node (if needed) and move the stores down.
11967   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11968   
11969   // Determine whether Dest has exactly two predecessors and, if so, compute
11970   // the other predecessor.
11971   pred_iterator PI = pred_begin(DestBB);
11972   BasicBlock *OtherBB = 0;
11973   if (*PI != StoreBB)
11974     OtherBB = *PI;
11975   ++PI;
11976   if (PI == pred_end(DestBB))
11977     return false;
11978   
11979   if (*PI != StoreBB) {
11980     if (OtherBB)
11981       return false;
11982     OtherBB = *PI;
11983   }
11984   if (++PI != pred_end(DestBB))
11985     return false;
11986
11987   // Bail out if all the relevant blocks aren't distinct (this can happen,
11988   // for example, if SI is in an infinite loop)
11989   if (StoreBB == DestBB || OtherBB == DestBB)
11990     return false;
11991
11992   // Verify that the other block ends in a branch and is not otherwise empty.
11993   BasicBlock::iterator BBI = OtherBB->getTerminator();
11994   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11995   if (!OtherBr || BBI == OtherBB->begin())
11996     return false;
11997   
11998   // If the other block ends in an unconditional branch, check for the 'if then
11999   // else' case.  there is an instruction before the branch.
12000   StoreInst *OtherStore = 0;
12001   if (OtherBr->isUnconditional()) {
12002     --BBI;
12003     // Skip over debugging info.
12004     while (isa<DbgInfoIntrinsic>(BBI) ||
12005            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12006       if (BBI==OtherBB->begin())
12007         return false;
12008       --BBI;
12009     }
12010     // If this isn't a store, or isn't a store to the same location, bail out.
12011     OtherStore = dyn_cast<StoreInst>(BBI);
12012     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12013       return false;
12014   } else {
12015     // Otherwise, the other block ended with a conditional branch. If one of the
12016     // destinations is StoreBB, then we have the if/then case.
12017     if (OtherBr->getSuccessor(0) != StoreBB && 
12018         OtherBr->getSuccessor(1) != StoreBB)
12019       return false;
12020     
12021     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12022     // if/then triangle.  See if there is a store to the same ptr as SI that
12023     // lives in OtherBB.
12024     for (;; --BBI) {
12025       // Check to see if we find the matching store.
12026       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12027         if (OtherStore->getOperand(1) != SI.getOperand(1))
12028           return false;
12029         break;
12030       }
12031       // If we find something that may be using or overwriting the stored
12032       // value, or if we run out of instructions, we can't do the xform.
12033       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12034           BBI == OtherBB->begin())
12035         return false;
12036     }
12037     
12038     // In order to eliminate the store in OtherBr, we have to
12039     // make sure nothing reads or overwrites the stored value in
12040     // StoreBB.
12041     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12042       // FIXME: This should really be AA driven.
12043       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12044         return false;
12045     }
12046   }
12047   
12048   // Insert a PHI node now if we need it.
12049   Value *MergedVal = OtherStore->getOperand(0);
12050   if (MergedVal != SI.getOperand(0)) {
12051     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12052     PN->reserveOperandSpace(2);
12053     PN->addIncoming(SI.getOperand(0), SI.getParent());
12054     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12055     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12056   }
12057   
12058   // Advance to a place where it is safe to insert the new store and
12059   // insert it.
12060   BBI = DestBB->getFirstNonPHI();
12061   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12062                                     OtherStore->isVolatile()), *BBI);
12063   
12064   // Nuke the old stores.
12065   EraseInstFromFunction(SI);
12066   EraseInstFromFunction(*OtherStore);
12067   ++NumCombined;
12068   return true;
12069 }
12070
12071
12072 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12073   // Change br (not X), label True, label False to: br X, label False, True
12074   Value *X = 0;
12075   BasicBlock *TrueDest;
12076   BasicBlock *FalseDest;
12077   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
12078       !isa<Constant>(X)) {
12079     // Swap Destinations and condition...
12080     BI.setCondition(X);
12081     BI.setSuccessor(0, FalseDest);
12082     BI.setSuccessor(1, TrueDest);
12083     return &BI;
12084   }
12085
12086   // Cannonicalize fcmp_one -> fcmp_oeq
12087   FCmpInst::Predicate FPred; Value *Y;
12088   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12089                              TrueDest, FalseDest)))
12090     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12091          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12092       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12093       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12094       Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12095       NewSCC->takeName(I);
12096       // Swap Destinations and condition...
12097       BI.setCondition(NewSCC);
12098       BI.setSuccessor(0, FalseDest);
12099       BI.setSuccessor(1, TrueDest);
12100       RemoveFromWorkList(I);
12101       I->eraseFromParent();
12102       AddToWorkList(NewSCC);
12103       return &BI;
12104     }
12105
12106   // Cannonicalize icmp_ne -> icmp_eq
12107   ICmpInst::Predicate IPred;
12108   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12109                       TrueDest, FalseDest)))
12110     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12111          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12112          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12113       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12114       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12115       Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12116       NewSCC->takeName(I);
12117       // Swap Destinations and condition...
12118       BI.setCondition(NewSCC);
12119       BI.setSuccessor(0, FalseDest);
12120       BI.setSuccessor(1, TrueDest);
12121       RemoveFromWorkList(I);
12122       I->eraseFromParent();;
12123       AddToWorkList(NewSCC);
12124       return &BI;
12125     }
12126
12127   return 0;
12128 }
12129
12130 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12131   Value *Cond = SI.getCondition();
12132   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12133     if (I->getOpcode() == Instruction::Add)
12134       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12135         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12136         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12137           SI.setOperand(i,
12138                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12139                                                 AddRHS));
12140         SI.setOperand(0, I->getOperand(0));
12141         AddToWorkList(I);
12142         return &SI;
12143       }
12144   }
12145   return 0;
12146 }
12147
12148 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12149   Value *Agg = EV.getAggregateOperand();
12150
12151   if (!EV.hasIndices())
12152     return ReplaceInstUsesWith(EV, Agg);
12153
12154   if (Constant *C = dyn_cast<Constant>(Agg)) {
12155     if (isa<UndefValue>(C))
12156       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12157       
12158     if (isa<ConstantAggregateZero>(C))
12159       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12160
12161     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12162       // Extract the element indexed by the first index out of the constant
12163       Value *V = C->getOperand(*EV.idx_begin());
12164       if (EV.getNumIndices() > 1)
12165         // Extract the remaining indices out of the constant indexed by the
12166         // first index
12167         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12168       else
12169         return ReplaceInstUsesWith(EV, V);
12170     }
12171     return 0; // Can't handle other constants
12172   } 
12173   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12174     // We're extracting from an insertvalue instruction, compare the indices
12175     const unsigned *exti, *exte, *insi, *inse;
12176     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12177          exte = EV.idx_end(), inse = IV->idx_end();
12178          exti != exte && insi != inse;
12179          ++exti, ++insi) {
12180       if (*insi != *exti)
12181         // The insert and extract both reference distinctly different elements.
12182         // This means the extract is not influenced by the insert, and we can
12183         // replace the aggregate operand of the extract with the aggregate
12184         // operand of the insert. i.e., replace
12185         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12186         // %E = extractvalue { i32, { i32 } } %I, 0
12187         // with
12188         // %E = extractvalue { i32, { i32 } } %A, 0
12189         return ExtractValueInst::Create(IV->getAggregateOperand(),
12190                                         EV.idx_begin(), EV.idx_end());
12191     }
12192     if (exti == exte && insi == inse)
12193       // Both iterators are at the end: Index lists are identical. Replace
12194       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12195       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12196       // with "i32 42"
12197       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12198     if (exti == exte) {
12199       // The extract list is a prefix of the insert list. i.e. replace
12200       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12201       // %E = extractvalue { i32, { i32 } } %I, 1
12202       // with
12203       // %X = extractvalue { i32, { i32 } } %A, 1
12204       // %E = insertvalue { i32 } %X, i32 42, 0
12205       // by switching the order of the insert and extract (though the
12206       // insertvalue should be left in, since it may have other uses).
12207       Value *NewEV = InsertNewInstBefore(
12208         ExtractValueInst::Create(IV->getAggregateOperand(),
12209                                  EV.idx_begin(), EV.idx_end()),
12210         EV);
12211       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12212                                      insi, inse);
12213     }
12214     if (insi == inse)
12215       // The insert list is a prefix of the extract list
12216       // We can simply remove the common indices from the extract and make it
12217       // operate on the inserted value instead of the insertvalue result.
12218       // i.e., replace
12219       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12220       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12221       // with
12222       // %E extractvalue { i32 } { i32 42 }, 0
12223       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12224                                       exti, exte);
12225   }
12226   // Can't simplify extracts from other values. Note that nested extracts are
12227   // already simplified implicitely by the above (extract ( extract (insert) )
12228   // will be translated into extract ( insert ( extract ) ) first and then just
12229   // the value inserted, if appropriate).
12230   return 0;
12231 }
12232
12233 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12234 /// is to leave as a vector operation.
12235 static bool CheapToScalarize(Value *V, bool isConstant) {
12236   if (isa<ConstantAggregateZero>(V)) 
12237     return true;
12238   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12239     if (isConstant) return true;
12240     // If all elts are the same, we can extract.
12241     Constant *Op0 = C->getOperand(0);
12242     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12243       if (C->getOperand(i) != Op0)
12244         return false;
12245     return true;
12246   }
12247   Instruction *I = dyn_cast<Instruction>(V);
12248   if (!I) return false;
12249   
12250   // Insert element gets simplified to the inserted element or is deleted if
12251   // this is constant idx extract element and its a constant idx insertelt.
12252   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12253       isa<ConstantInt>(I->getOperand(2)))
12254     return true;
12255   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12256     return true;
12257   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12258     if (BO->hasOneUse() &&
12259         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12260          CheapToScalarize(BO->getOperand(1), isConstant)))
12261       return true;
12262   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12263     if (CI->hasOneUse() &&
12264         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12265          CheapToScalarize(CI->getOperand(1), isConstant)))
12266       return true;
12267   
12268   return false;
12269 }
12270
12271 /// Read and decode a shufflevector mask.
12272 ///
12273 /// It turns undef elements into values that are larger than the number of
12274 /// elements in the input.
12275 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12276   unsigned NElts = SVI->getType()->getNumElements();
12277   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12278     return std::vector<unsigned>(NElts, 0);
12279   if (isa<UndefValue>(SVI->getOperand(2)))
12280     return std::vector<unsigned>(NElts, 2*NElts);
12281
12282   std::vector<unsigned> Result;
12283   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12284   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12285     if (isa<UndefValue>(*i))
12286       Result.push_back(NElts*2);  // undef -> 8
12287     else
12288       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12289   return Result;
12290 }
12291
12292 /// FindScalarElement - Given a vector and an element number, see if the scalar
12293 /// value is already around as a register, for example if it were inserted then
12294 /// extracted from the vector.
12295 static Value *FindScalarElement(Value *V, unsigned EltNo,
12296                                 LLVMContext *Context) {
12297   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12298   const VectorType *PTy = cast<VectorType>(V->getType());
12299   unsigned Width = PTy->getNumElements();
12300   if (EltNo >= Width)  // Out of range access.
12301     return UndefValue::get(PTy->getElementType());
12302   
12303   if (isa<UndefValue>(V))
12304     return UndefValue::get(PTy->getElementType());
12305   else if (isa<ConstantAggregateZero>(V))
12306     return Constant::getNullValue(PTy->getElementType());
12307   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12308     return CP->getOperand(EltNo);
12309   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12310     // If this is an insert to a variable element, we don't know what it is.
12311     if (!isa<ConstantInt>(III->getOperand(2))) 
12312       return 0;
12313     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12314     
12315     // If this is an insert to the element we are looking for, return the
12316     // inserted value.
12317     if (EltNo == IIElt) 
12318       return III->getOperand(1);
12319     
12320     // Otherwise, the insertelement doesn't modify the value, recurse on its
12321     // vector input.
12322     return FindScalarElement(III->getOperand(0), EltNo, Context);
12323   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12324     unsigned LHSWidth =
12325       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12326     unsigned InEl = getShuffleMask(SVI)[EltNo];
12327     if (InEl < LHSWidth)
12328       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12329     else if (InEl < LHSWidth*2)
12330       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12331     else
12332       return UndefValue::get(PTy->getElementType());
12333   }
12334   
12335   // Otherwise, we don't know.
12336   return 0;
12337 }
12338
12339 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12340   // If vector val is undef, replace extract with scalar undef.
12341   if (isa<UndefValue>(EI.getOperand(0)))
12342     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12343
12344   // If vector val is constant 0, replace extract with scalar 0.
12345   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12346     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12347   
12348   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12349     // If vector val is constant with all elements the same, replace EI with
12350     // that element. When the elements are not identical, we cannot replace yet
12351     // (we do that below, but only when the index is constant).
12352     Constant *op0 = C->getOperand(0);
12353     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12354       if (C->getOperand(i) != op0) {
12355         op0 = 0; 
12356         break;
12357       }
12358     if (op0)
12359       return ReplaceInstUsesWith(EI, op0);
12360   }
12361   
12362   // If extracting a specified index from the vector, see if we can recursively
12363   // find a previously computed scalar that was inserted into the vector.
12364   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12365     unsigned IndexVal = IdxC->getZExtValue();
12366     unsigned VectorWidth = 
12367       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12368       
12369     // If this is extracting an invalid index, turn this into undef, to avoid
12370     // crashing the code below.
12371     if (IndexVal >= VectorWidth)
12372       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12373     
12374     // This instruction only demands the single element from the input vector.
12375     // If the input vector has a single use, simplify it based on this use
12376     // property.
12377     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12378       APInt UndefElts(VectorWidth, 0);
12379       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12380       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12381                                                 DemandedMask, UndefElts)) {
12382         EI.setOperand(0, V);
12383         return &EI;
12384       }
12385     }
12386     
12387     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12388       return ReplaceInstUsesWith(EI, Elt);
12389     
12390     // If the this extractelement is directly using a bitcast from a vector of
12391     // the same number of elements, see if we can find the source element from
12392     // it.  In this case, we will end up needing to bitcast the scalars.
12393     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12394       if (const VectorType *VT = 
12395               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12396         if (VT->getNumElements() == VectorWidth)
12397           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12398                                              IndexVal, Context))
12399             return new BitCastInst(Elt, EI.getType());
12400     }
12401   }
12402   
12403   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12404     if (I->hasOneUse()) {
12405       // Push extractelement into predecessor operation if legal and
12406       // profitable to do so
12407       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12408         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12409         if (CheapToScalarize(BO, isConstantElt)) {
12410           ExtractElementInst *newEI0 = 
12411             ExtractElementInst::Create(BO->getOperand(0), EI.getOperand(1),
12412                                    EI.getName()+".lhs");
12413           ExtractElementInst *newEI1 =
12414             ExtractElementInst::Create(BO->getOperand(1), EI.getOperand(1),
12415                                    EI.getName()+".rhs");
12416           InsertNewInstBefore(newEI0, EI);
12417           InsertNewInstBefore(newEI1, EI);
12418           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12419         }
12420       } else if (isa<LoadInst>(I)) {
12421         unsigned AS = 
12422           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12423         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12424                                   PointerType::get(EI.getType(), AS),*I);
12425         GetElementPtrInst *GEP =
12426           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12427         cast<GEPOperator>(GEP)->setIsInBounds(true);
12428         InsertNewInstBefore(GEP, *I);
12429         LoadInst* Load = new LoadInst(GEP, "tmp");
12430         InsertNewInstBefore(Load, *I);
12431         return ReplaceInstUsesWith(EI, Load);
12432       }
12433     }
12434     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12435       // Extracting the inserted element?
12436       if (IE->getOperand(2) == EI.getOperand(1))
12437         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12438       // If the inserted and extracted elements are constants, they must not
12439       // be the same value, extract from the pre-inserted value instead.
12440       if (isa<Constant>(IE->getOperand(2)) &&
12441           isa<Constant>(EI.getOperand(1))) {
12442         AddUsesToWorkList(EI);
12443         EI.setOperand(0, IE->getOperand(0));
12444         return &EI;
12445       }
12446     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12447       // If this is extracting an element from a shufflevector, figure out where
12448       // it came from and extract from the appropriate input element instead.
12449       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12450         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12451         Value *Src;
12452         unsigned LHSWidth =
12453           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12454
12455         if (SrcIdx < LHSWidth)
12456           Src = SVI->getOperand(0);
12457         else if (SrcIdx < LHSWidth*2) {
12458           SrcIdx -= LHSWidth;
12459           Src = SVI->getOperand(1);
12460         } else {
12461           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12462         }
12463         return ExtractElementInst::Create(Src,
12464                          ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx, false));
12465       }
12466     }
12467     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12468   }
12469   return 0;
12470 }
12471
12472 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12473 /// elements from either LHS or RHS, return the shuffle mask and true. 
12474 /// Otherwise, return false.
12475 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12476                                          std::vector<Constant*> &Mask,
12477                                          LLVMContext *Context) {
12478   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12479          "Invalid CollectSingleShuffleElements");
12480   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12481
12482   if (isa<UndefValue>(V)) {
12483     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12484     return true;
12485   } else if (V == LHS) {
12486     for (unsigned i = 0; i != NumElts; ++i)
12487       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12488     return true;
12489   } else if (V == RHS) {
12490     for (unsigned i = 0; i != NumElts; ++i)
12491       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12492     return true;
12493   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12494     // If this is an insert of an extract from some other vector, include it.
12495     Value *VecOp    = IEI->getOperand(0);
12496     Value *ScalarOp = IEI->getOperand(1);
12497     Value *IdxOp    = IEI->getOperand(2);
12498     
12499     if (!isa<ConstantInt>(IdxOp))
12500       return false;
12501     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12502     
12503     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12504       // Okay, we can handle this if the vector we are insertinting into is
12505       // transitively ok.
12506       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12507         // If so, update the mask to reflect the inserted undef.
12508         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12509         return true;
12510       }      
12511     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12512       if (isa<ConstantInt>(EI->getOperand(1)) &&
12513           EI->getOperand(0)->getType() == V->getType()) {
12514         unsigned ExtractedIdx =
12515           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12516         
12517         // This must be extracting from either LHS or RHS.
12518         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12519           // Okay, we can handle this if the vector we are insertinting into is
12520           // transitively ok.
12521           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12522             // If so, update the mask to reflect the inserted value.
12523             if (EI->getOperand(0) == LHS) {
12524               Mask[InsertedIdx % NumElts] = 
12525                  ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12526             } else {
12527               assert(EI->getOperand(0) == RHS);
12528               Mask[InsertedIdx % NumElts] = 
12529                 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12530               
12531             }
12532             return true;
12533           }
12534         }
12535       }
12536     }
12537   }
12538   // TODO: Handle shufflevector here!
12539   
12540   return false;
12541 }
12542
12543 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12544 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12545 /// that computes V and the LHS value of the shuffle.
12546 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12547                                      Value *&RHS, LLVMContext *Context) {
12548   assert(isa<VectorType>(V->getType()) && 
12549          (RHS == 0 || V->getType() == RHS->getType()) &&
12550          "Invalid shuffle!");
12551   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12552
12553   if (isa<UndefValue>(V)) {
12554     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12555     return V;
12556   } else if (isa<ConstantAggregateZero>(V)) {
12557     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12558     return V;
12559   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12560     // If this is an insert of an extract from some other vector, include it.
12561     Value *VecOp    = IEI->getOperand(0);
12562     Value *ScalarOp = IEI->getOperand(1);
12563     Value *IdxOp    = IEI->getOperand(2);
12564     
12565     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12566       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12567           EI->getOperand(0)->getType() == V->getType()) {
12568         unsigned ExtractedIdx =
12569           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12570         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12571         
12572         // Either the extracted from or inserted into vector must be RHSVec,
12573         // otherwise we'd end up with a shuffle of three inputs.
12574         if (EI->getOperand(0) == RHS || RHS == 0) {
12575           RHS = EI->getOperand(0);
12576           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12577           Mask[InsertedIdx % NumElts] = 
12578             ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12579           return V;
12580         }
12581         
12582         if (VecOp == RHS) {
12583           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12584                                             RHS, Context);
12585           // Everything but the extracted element is replaced with the RHS.
12586           for (unsigned i = 0; i != NumElts; ++i) {
12587             if (i != InsertedIdx)
12588               Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12589           }
12590           return V;
12591         }
12592         
12593         // If this insertelement is a chain that comes from exactly these two
12594         // vectors, return the vector and the effective shuffle.
12595         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12596                                          Context))
12597           return EI->getOperand(0);
12598         
12599       }
12600     }
12601   }
12602   // TODO: Handle shufflevector here!
12603   
12604   // Otherwise, can't do anything fancy.  Return an identity vector.
12605   for (unsigned i = 0; i != NumElts; ++i)
12606     Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12607   return V;
12608 }
12609
12610 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12611   Value *VecOp    = IE.getOperand(0);
12612   Value *ScalarOp = IE.getOperand(1);
12613   Value *IdxOp    = IE.getOperand(2);
12614   
12615   // Inserting an undef or into an undefined place, remove this.
12616   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12617     ReplaceInstUsesWith(IE, VecOp);
12618   
12619   // If the inserted element was extracted from some other vector, and if the 
12620   // indexes are constant, try to turn this into a shufflevector operation.
12621   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12622     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12623         EI->getOperand(0)->getType() == IE.getType()) {
12624       unsigned NumVectorElts = IE.getType()->getNumElements();
12625       unsigned ExtractedIdx =
12626         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12627       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12628       
12629       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12630         return ReplaceInstUsesWith(IE, VecOp);
12631       
12632       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12633         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12634       
12635       // If we are extracting a value from a vector, then inserting it right
12636       // back into the same place, just use the input vector.
12637       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12638         return ReplaceInstUsesWith(IE, VecOp);      
12639       
12640       // We could theoretically do this for ANY input.  However, doing so could
12641       // turn chains of insertelement instructions into a chain of shufflevector
12642       // instructions, and right now we do not merge shufflevectors.  As such,
12643       // only do this in a situation where it is clear that there is benefit.
12644       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12645         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12646         // the values of VecOp, except then one read from EIOp0.
12647         // Build a new shuffle mask.
12648         std::vector<Constant*> Mask;
12649         if (isa<UndefValue>(VecOp))
12650           Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
12651         else {
12652           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12653           Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
12654                                                        NumVectorElts));
12655         } 
12656         Mask[InsertedIdx] = 
12657                            ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12658         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12659                                      ConstantVector::get(Mask));
12660       }
12661       
12662       // If this insertelement isn't used by some other insertelement, turn it
12663       // (and any insertelements it points to), into one big shuffle.
12664       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12665         std::vector<Constant*> Mask;
12666         Value *RHS = 0;
12667         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12668         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12669         // We now have a shuffle of LHS, RHS, Mask.
12670         return new ShuffleVectorInst(LHS, RHS,
12671                                      ConstantVector::get(Mask));
12672       }
12673     }
12674   }
12675
12676   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12677   APInt UndefElts(VWidth, 0);
12678   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12679   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12680     return &IE;
12681
12682   return 0;
12683 }
12684
12685
12686 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12687   Value *LHS = SVI.getOperand(0);
12688   Value *RHS = SVI.getOperand(1);
12689   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12690
12691   bool MadeChange = false;
12692
12693   // Undefined shuffle mask -> undefined value.
12694   if (isa<UndefValue>(SVI.getOperand(2)))
12695     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12696
12697   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12698
12699   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12700     return 0;
12701
12702   APInt UndefElts(VWidth, 0);
12703   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12704   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12705     LHS = SVI.getOperand(0);
12706     RHS = SVI.getOperand(1);
12707     MadeChange = true;
12708   }
12709   
12710   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12711   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12712   if (LHS == RHS || isa<UndefValue>(LHS)) {
12713     if (isa<UndefValue>(LHS) && LHS == RHS) {
12714       // shuffle(undef,undef,mask) -> undef.
12715       return ReplaceInstUsesWith(SVI, LHS);
12716     }
12717     
12718     // Remap any references to RHS to use LHS.
12719     std::vector<Constant*> Elts;
12720     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12721       if (Mask[i] >= 2*e)
12722         Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12723       else {
12724         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12725             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12726           Mask[i] = 2*e;     // Turn into undef.
12727           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12728         } else {
12729           Mask[i] = Mask[i] % e;  // Force to LHS.
12730           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12731         }
12732       }
12733     }
12734     SVI.setOperand(0, SVI.getOperand(1));
12735     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12736     SVI.setOperand(2, ConstantVector::get(Elts));
12737     LHS = SVI.getOperand(0);
12738     RHS = SVI.getOperand(1);
12739     MadeChange = true;
12740   }
12741   
12742   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12743   bool isLHSID = true, isRHSID = true;
12744     
12745   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12746     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12747     // Is this an identity shuffle of the LHS value?
12748     isLHSID &= (Mask[i] == i);
12749       
12750     // Is this an identity shuffle of the RHS value?
12751     isRHSID &= (Mask[i]-e == i);
12752   }
12753
12754   // Eliminate identity shuffles.
12755   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12756   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12757   
12758   // If the LHS is a shufflevector itself, see if we can combine it with this
12759   // one without producing an unusual shuffle.  Here we are really conservative:
12760   // we are absolutely afraid of producing a shuffle mask not in the input
12761   // program, because the code gen may not be smart enough to turn a merged
12762   // shuffle into two specific shuffles: it may produce worse code.  As such,
12763   // we only merge two shuffles if the result is one of the two input shuffle
12764   // masks.  In this case, merging the shuffles just removes one instruction,
12765   // which we know is safe.  This is good for things like turning:
12766   // (splat(splat)) -> splat.
12767   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12768     if (isa<UndefValue>(RHS)) {
12769       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12770
12771       std::vector<unsigned> NewMask;
12772       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12773         if (Mask[i] >= 2*e)
12774           NewMask.push_back(2*e);
12775         else
12776           NewMask.push_back(LHSMask[Mask[i]]);
12777       
12778       // If the result mask is equal to the src shuffle or this shuffle mask, do
12779       // the replacement.
12780       if (NewMask == LHSMask || NewMask == Mask) {
12781         unsigned LHSInNElts =
12782           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12783         std::vector<Constant*> Elts;
12784         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12785           if (NewMask[i] >= LHSInNElts*2) {
12786             Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12787           } else {
12788             Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12789           }
12790         }
12791         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12792                                      LHSSVI->getOperand(1),
12793                                      ConstantVector::get(Elts));
12794       }
12795     }
12796   }
12797
12798   return MadeChange ? &SVI : 0;
12799 }
12800
12801
12802
12803
12804 /// TryToSinkInstruction - Try to move the specified instruction from its
12805 /// current block into the beginning of DestBlock, which can only happen if it's
12806 /// safe to move the instruction past all of the instructions between it and the
12807 /// end of its block.
12808 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12809   assert(I->hasOneUse() && "Invariants didn't hold!");
12810
12811   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12812   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12813     return false;
12814
12815   // Do not sink alloca instructions out of the entry block.
12816   if (isa<AllocaInst>(I) && I->getParent() ==
12817         &DestBlock->getParent()->getEntryBlock())
12818     return false;
12819
12820   // We can only sink load instructions if there is nothing between the load and
12821   // the end of block that could change the value.
12822   if (I->mayReadFromMemory()) {
12823     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12824          Scan != E; ++Scan)
12825       if (Scan->mayWriteToMemory())
12826         return false;
12827   }
12828
12829   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12830
12831   CopyPrecedingStopPoint(I, InsertPos);
12832   I->moveBefore(InsertPos);
12833   ++NumSunkInst;
12834   return true;
12835 }
12836
12837
12838 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12839 /// all reachable code to the worklist.
12840 ///
12841 /// This has a couple of tricks to make the code faster and more powerful.  In
12842 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12843 /// them to the worklist (this significantly speeds up instcombine on code where
12844 /// many instructions are dead or constant).  Additionally, if we find a branch
12845 /// whose condition is a known constant, we only visit the reachable successors.
12846 ///
12847 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12848                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12849                                        InstCombiner &IC,
12850                                        const TargetData *TD) {
12851   SmallVector<BasicBlock*, 256> Worklist;
12852   Worklist.push_back(BB);
12853
12854   while (!Worklist.empty()) {
12855     BB = Worklist.back();
12856     Worklist.pop_back();
12857     
12858     // We have now visited this block!  If we've already been here, ignore it.
12859     if (!Visited.insert(BB)) continue;
12860
12861     DbgInfoIntrinsic *DBI_Prev = NULL;
12862     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12863       Instruction *Inst = BBI++;
12864       
12865       // DCE instruction if trivially dead.
12866       if (isInstructionTriviallyDead(Inst)) {
12867         ++NumDeadInst;
12868         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
12869         Inst->eraseFromParent();
12870         continue;
12871       }
12872       
12873       // ConstantProp instruction if trivially constant.
12874       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12875         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12876                      << *Inst << '\n');
12877         Inst->replaceAllUsesWith(C);
12878         ++NumConstProp;
12879         Inst->eraseFromParent();
12880         continue;
12881       }
12882      
12883       // If there are two consecutive llvm.dbg.stoppoint calls then
12884       // it is likely that the optimizer deleted code in between these
12885       // two intrinsics. 
12886       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12887       if (DBI_Next) {
12888         if (DBI_Prev
12889             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12890             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12891           IC.RemoveFromWorkList(DBI_Prev);
12892           DBI_Prev->eraseFromParent();
12893         }
12894         DBI_Prev = DBI_Next;
12895       } else {
12896         DBI_Prev = 0;
12897       }
12898
12899       IC.AddToWorkList(Inst);
12900     }
12901
12902     // Recursively visit successors.  If this is a branch or switch on a
12903     // constant, only visit the reachable successor.
12904     TerminatorInst *TI = BB->getTerminator();
12905     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12906       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12907         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12908         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12909         Worklist.push_back(ReachableBB);
12910         continue;
12911       }
12912     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12913       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12914         // See if this is an explicit destination.
12915         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12916           if (SI->getCaseValue(i) == Cond) {
12917             BasicBlock *ReachableBB = SI->getSuccessor(i);
12918             Worklist.push_back(ReachableBB);
12919             continue;
12920           }
12921         
12922         // Otherwise it is the default destination.
12923         Worklist.push_back(SI->getSuccessor(0));
12924         continue;
12925       }
12926     }
12927     
12928     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12929       Worklist.push_back(TI->getSuccessor(i));
12930   }
12931 }
12932
12933 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12934   bool Changed = false;
12935   TD = getAnalysisIfAvailable<TargetData>();
12936   
12937   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12938         << F.getNameStr() << "\n");
12939
12940   {
12941     // Do a depth-first traversal of the function, populate the worklist with
12942     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12943     // track of which blocks we visit.
12944     SmallPtrSet<BasicBlock*, 64> Visited;
12945     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12946
12947     // Do a quick scan over the function.  If we find any blocks that are
12948     // unreachable, remove any instructions inside of them.  This prevents
12949     // the instcombine code from having to deal with some bad special cases.
12950     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12951       if (!Visited.count(BB)) {
12952         Instruction *Term = BB->getTerminator();
12953         while (Term != BB->begin()) {   // Remove instrs bottom-up
12954           BasicBlock::iterator I = Term; --I;
12955
12956           DEBUG(errs() << "IC: DCE: " << *I << '\n');
12957           // A debug intrinsic shouldn't force another iteration if we weren't
12958           // going to do one without it.
12959           if (!isa<DbgInfoIntrinsic>(I)) {
12960             ++NumDeadInst;
12961             Changed = true;
12962           }
12963           if (!I->use_empty())
12964             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12965           I->eraseFromParent();
12966         }
12967       }
12968   }
12969
12970   while (!Worklist.empty()) {
12971     Instruction *I = RemoveOneFromWorkList();
12972     if (I == 0) continue;  // skip null values.
12973
12974     // Check to see if we can DCE the instruction.
12975     if (isInstructionTriviallyDead(I)) {
12976       // Add operands to the worklist.
12977       if (I->getNumOperands() < 4)
12978         AddUsesToWorkList(*I);
12979       ++NumDeadInst;
12980
12981       DEBUG(errs() << "IC: DCE: " << *I << '\n');
12982
12983       I->eraseFromParent();
12984       RemoveFromWorkList(I);
12985       Changed = true;
12986       continue;
12987     }
12988
12989     // Instruction isn't dead, see if we can constant propagate it.
12990     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12991       DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
12992
12993       // Add operands to the worklist.
12994       AddUsesToWorkList(*I);
12995       ReplaceInstUsesWith(*I, C);
12996
12997       ++NumConstProp;
12998       I->eraseFromParent();
12999       RemoveFromWorkList(I);
13000       Changed = true;
13001       continue;
13002     }
13003
13004     if (TD) {
13005       // See if we can constant fold its operands.
13006       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13007         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
13008           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
13009                                   F.getContext(), TD))
13010             if (NewC != CE) {
13011               i->set(NewC);
13012               Changed = true;
13013             }
13014     }
13015
13016     // See if we can trivially sink this instruction to a successor basic block.
13017     if (I->hasOneUse()) {
13018       BasicBlock *BB = I->getParent();
13019       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13020       if (UserParent != BB) {
13021         bool UserIsSuccessor = false;
13022         // See if the user is one of our successors.
13023         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13024           if (*SI == UserParent) {
13025             UserIsSuccessor = true;
13026             break;
13027           }
13028
13029         // If the user is one of our immediate successors, and if that successor
13030         // only has us as a predecessors (we'd have to split the critical edge
13031         // otherwise), we can keep going.
13032         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13033             next(pred_begin(UserParent)) == pred_end(UserParent))
13034           // Okay, the CFG is simple enough, try to sink this instruction.
13035           Changed |= TryToSinkInstruction(I, UserParent);
13036       }
13037     }
13038
13039     // Now that we have an instruction, try combining it to simplify it...
13040 #ifndef NDEBUG
13041     std::string OrigI;
13042 #endif
13043     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
13044     if (Instruction *Result = visit(*I)) {
13045       ++NumCombined;
13046       // Should we replace the old instruction with a new one?
13047       if (Result != I) {
13048         DEBUG(errs() << "IC: Old = " << *I << '\n'
13049                      << "    New = " << *Result << '\n');
13050
13051         // Everything uses the new instruction now.
13052         I->replaceAllUsesWith(Result);
13053
13054         // Push the new instruction and any users onto the worklist.
13055         AddToWorkList(Result);
13056         AddUsersToWorkList(*Result);
13057
13058         // Move the name to the new instruction first.
13059         Result->takeName(I);
13060
13061         // Insert the new instruction into the basic block...
13062         BasicBlock *InstParent = I->getParent();
13063         BasicBlock::iterator InsertPos = I;
13064
13065         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13066           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13067             ++InsertPos;
13068
13069         InstParent->getInstList().insert(InsertPos, Result);
13070
13071         // Make sure that we reprocess all operands now that we reduced their
13072         // use counts.
13073         AddUsesToWorkList(*I);
13074
13075         // Instructions can end up on the worklist more than once.  Make sure
13076         // we do not process an instruction that has been deleted.
13077         RemoveFromWorkList(I);
13078
13079         // Erase the old instruction.
13080         InstParent->getInstList().erase(I);
13081       } else {
13082 #ifndef NDEBUG
13083         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13084                      << "    New = " << *I << '\n');
13085 #endif
13086
13087         // If the instruction was modified, it's possible that it is now dead.
13088         // if so, remove it.
13089         if (isInstructionTriviallyDead(I)) {
13090           // Make sure we process all operands now that we are reducing their
13091           // use counts.
13092           AddUsesToWorkList(*I);
13093
13094           // Instructions may end up in the worklist more than once.  Erase all
13095           // occurrences of this instruction.
13096           RemoveFromWorkList(I);
13097           I->eraseFromParent();
13098         } else {
13099           AddToWorkList(I);
13100           AddUsersToWorkList(*I);
13101         }
13102       }
13103       Changed = true;
13104     }
13105   }
13106
13107   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13108     
13109   // Do an explicit clear, this shrinks the map if needed.
13110   WorklistMap.clear();
13111   return Changed;
13112 }
13113
13114
13115 bool InstCombiner::runOnFunction(Function &F) {
13116   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13117   Context = &F.getContext();
13118   
13119   bool EverMadeChange = false;
13120
13121   // Iterate while there is work to do.
13122   unsigned Iteration = 0;
13123   while (DoOneIteration(F, Iteration++))
13124     EverMadeChange = true;
13125   return EverMadeChange;
13126 }
13127
13128 FunctionPass *llvm::createInstructionCombiningPass() {
13129   return new InstCombiner();
13130 }