Remove check which is duplicated in
[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/Analysis/ConstantFolding.h"
44 #include "llvm/Analysis/ValueTracking.h"
45 #include "llvm/Target/TargetData.h"
46 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
47 #include "llvm/Transforms/Utils/Local.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/ConstantRange.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/GetElementPtrTypeIterator.h"
53 #include "llvm/Support/InstVisitor.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Support/PatternMatch.h"
56 #include "llvm/Support/Compiler.h"
57 #include "llvm/ADT/DenseMap.h"
58 #include "llvm/ADT/SmallVector.h"
59 #include "llvm/ADT/SmallPtrSet.h"
60 #include "llvm/ADT/Statistic.h"
61 #include "llvm/ADT/STLExtras.h"
62 #include <algorithm>
63 #include <climits>
64 #include <sstream>
65 using namespace llvm;
66 using namespace llvm::PatternMatch;
67
68 STATISTIC(NumCombined , "Number of insts combined");
69 STATISTIC(NumConstProp, "Number of constant folds");
70 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
71 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
72 STATISTIC(NumSunkInst , "Number of instructions sunk");
73
74 namespace {
75   class VISIBILITY_HIDDEN InstCombiner
76     : public FunctionPass,
77       public InstVisitor<InstCombiner, Instruction*> {
78     // Worklist of all of the instructions that need to be simplified.
79     SmallVector<Instruction*, 256> Worklist;
80     DenseMap<Instruction*, unsigned> WorklistMap;
81     TargetData *TD;
82     bool MustPreserveLCSSA;
83   public:
84     static char ID; // Pass identification, replacement for typeid
85     InstCombiner() : FunctionPass(&ID) {}
86
87     LLVMContext *getContext() { return Context; }
88
89     /// AddToWorkList - Add the specified instruction to the worklist if it
90     /// isn't already in it.
91     void AddToWorkList(Instruction *I) {
92       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
93         Worklist.push_back(I);
94     }
95     
96     // RemoveFromWorkList - remove I from the worklist if it exists.
97     void RemoveFromWorkList(Instruction *I) {
98       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
99       if (It == WorklistMap.end()) return; // Not in worklist.
100       
101       // Don't bother moving everything down, just null out the slot.
102       Worklist[It->second] = 0;
103       
104       WorklistMap.erase(It);
105     }
106     
107     Instruction *RemoveOneFromWorkList() {
108       Instruction *I = Worklist.back();
109       Worklist.pop_back();
110       WorklistMap.erase(I);
111       return I;
112     }
113
114     
115     /// AddUsersToWorkList - When an instruction is simplified, add all users of
116     /// the instruction to the work lists because they might get more simplified
117     /// now.
118     ///
119     void AddUsersToWorkList(Value &I) {
120       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
121            UI != UE; ++UI)
122         AddToWorkList(cast<Instruction>(*UI));
123     }
124
125     /// AddUsesToWorkList - When an instruction is simplified, add operands to
126     /// the work lists because they might get more simplified now.
127     ///
128     void AddUsesToWorkList(Instruction &I) {
129       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
130         if (Instruction *Op = dyn_cast<Instruction>(*i))
131           AddToWorkList(Op);
132     }
133     
134     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
135     /// dead.  Add all of its operands to the worklist, turning them into
136     /// undef's to reduce the number of uses of those instructions.
137     ///
138     /// Return the specified operand before it is turned into an undef.
139     ///
140     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
141       Value *R = I.getOperand(op);
142       
143       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
144         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
145           AddToWorkList(Op);
146           // Set the operand to undef to drop the use.
147           *i = Context->getUndef(Op->getType());
148         }
149       
150       return R;
151     }
152
153   public:
154     virtual bool runOnFunction(Function &F);
155     
156     bool DoOneIteration(Function &F, unsigned ItNum);
157
158     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
159       AU.addRequired<TargetData>();
160       AU.addPreservedID(LCSSAID);
161       AU.setPreservesCFG();
162     }
163
164     TargetData &getTargetData() const { return *TD; }
165
166     // Visitation implementation - Implement instruction combining for different
167     // instruction types.  The semantics are as follows:
168     // Return Value:
169     //    null        - No change was made
170     //     I          - Change was made, I is still valid, I may be dead though
171     //   otherwise    - Change was made, replace I with returned instruction
172     //
173     Instruction *visitAdd(BinaryOperator &I);
174     Instruction *visitFAdd(BinaryOperator &I);
175     Instruction *visitSub(BinaryOperator &I);
176     Instruction *visitFSub(BinaryOperator &I);
177     Instruction *visitMul(BinaryOperator &I);
178     Instruction *visitFMul(BinaryOperator &I);
179     Instruction *visitURem(BinaryOperator &I);
180     Instruction *visitSRem(BinaryOperator &I);
181     Instruction *visitFRem(BinaryOperator &I);
182     bool SimplifyDivRemOfSelect(BinaryOperator &I);
183     Instruction *commonRemTransforms(BinaryOperator &I);
184     Instruction *commonIRemTransforms(BinaryOperator &I);
185     Instruction *commonDivTransforms(BinaryOperator &I);
186     Instruction *commonIDivTransforms(BinaryOperator &I);
187     Instruction *visitUDiv(BinaryOperator &I);
188     Instruction *visitSDiv(BinaryOperator &I);
189     Instruction *visitFDiv(BinaryOperator &I);
190     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
191     Instruction *visitAnd(BinaryOperator &I);
192     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
193     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
194                                      Value *A, Value *B, Value *C);
195     Instruction *visitOr (BinaryOperator &I);
196     Instruction *visitXor(BinaryOperator &I);
197     Instruction *visitShl(BinaryOperator &I);
198     Instruction *visitAShr(BinaryOperator &I);
199     Instruction *visitLShr(BinaryOperator &I);
200     Instruction *commonShiftTransforms(BinaryOperator &I);
201     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
202                                       Constant *RHSC);
203     Instruction *visitFCmpInst(FCmpInst &I);
204     Instruction *visitICmpInst(ICmpInst &I);
205     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
206     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
207                                                 Instruction *LHS,
208                                                 ConstantInt *RHS);
209     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
210                                 ConstantInt *DivRHS);
211
212     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
213                              ICmpInst::Predicate Cond, Instruction &I);
214     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
215                                      BinaryOperator &I);
216     Instruction *commonCastTransforms(CastInst &CI);
217     Instruction *commonIntCastTransforms(CastInst &CI);
218     Instruction *commonPointerCastTransforms(CastInst &CI);
219     Instruction *visitTrunc(TruncInst &CI);
220     Instruction *visitZExt(ZExtInst &CI);
221     Instruction *visitSExt(SExtInst &CI);
222     Instruction *visitFPTrunc(FPTruncInst &CI);
223     Instruction *visitFPExt(CastInst &CI);
224     Instruction *visitFPToUI(FPToUIInst &FI);
225     Instruction *visitFPToSI(FPToSIInst &FI);
226     Instruction *visitUIToFP(CastInst &CI);
227     Instruction *visitSIToFP(CastInst &CI);
228     Instruction *visitPtrToInt(PtrToIntInst &CI);
229     Instruction *visitIntToPtr(IntToPtrInst &CI);
230     Instruction *visitBitCast(BitCastInst &CI);
231     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
232                                 Instruction *FI);
233     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
234     Instruction *visitSelectInst(SelectInst &SI);
235     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
236     Instruction *visitCallInst(CallInst &CI);
237     Instruction *visitInvokeInst(InvokeInst &II);
238     Instruction *visitPHINode(PHINode &PN);
239     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
240     Instruction *visitAllocationInst(AllocationInst &AI);
241     Instruction *visitFreeInst(FreeInst &FI);
242     Instruction *visitLoadInst(LoadInst &LI);
243     Instruction *visitStoreInst(StoreInst &SI);
244     Instruction *visitBranchInst(BranchInst &BI);
245     Instruction *visitSwitchInst(SwitchInst &SI);
246     Instruction *visitInsertElementInst(InsertElementInst &IE);
247     Instruction *visitExtractElementInst(ExtractElementInst &EI);
248     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
249     Instruction *visitExtractValueInst(ExtractValueInst &EV);
250
251     // visitInstruction - Specify what to return for unhandled instructions...
252     Instruction *visitInstruction(Instruction &I) { return 0; }
253
254   private:
255     Instruction *visitCallSite(CallSite CS);
256     bool transformConstExprCastCall(CallSite CS);
257     Instruction *transformCallThroughTrampoline(CallSite CS);
258     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
259                                    bool DoXform = true);
260     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
261     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
262
263
264   public:
265     // InsertNewInstBefore - insert an instruction New before instruction Old
266     // in the program.  Add the new instruction to the worklist.
267     //
268     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
269       assert(New && New->getParent() == 0 &&
270              "New instruction already inserted into a basic block!");
271       BasicBlock *BB = Old.getParent();
272       BB->getInstList().insert(&Old, New);  // Insert inst
273       AddToWorkList(New);
274       return New;
275     }
276
277     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
278     /// This also adds the cast to the worklist.  Finally, this returns the
279     /// cast.
280     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
281                             Instruction &Pos) {
282       if (V->getType() == Ty) return V;
283
284       if (Constant *CV = dyn_cast<Constant>(V))
285         return Context->getConstantExprCast(opc, CV, Ty);
286       
287       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
288       AddToWorkList(C);
289       return C;
290     }
291         
292     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
293       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
294     }
295
296
297     // ReplaceInstUsesWith - This method is to be used when an instruction is
298     // found to be dead, replacable with another preexisting expression.  Here
299     // we add all uses of I to the worklist, replace all uses of I with the new
300     // value, then return I, so that the inst combiner will know that I was
301     // modified.
302     //
303     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
304       AddUsersToWorkList(I);         // Add all modified instrs to worklist
305       if (&I != V) {
306         I.replaceAllUsesWith(V);
307         return &I;
308       } else {
309         // If we are replacing the instruction with itself, this must be in a
310         // segment of unreachable code, so just clobber the instruction.
311         I.replaceAllUsesWith(Context->getUndef(I.getType()));
312         return &I;
313       }
314     }
315
316     // EraseInstFromFunction - When dealing with an instruction that has side
317     // effects or produces a void value, we can't rely on DCE to delete the
318     // instruction.  Instead, visit methods should return the value returned by
319     // this function.
320     Instruction *EraseInstFromFunction(Instruction &I) {
321       assert(I.use_empty() && "Cannot erase instruction that is used!");
322       AddUsesToWorkList(I);
323       RemoveFromWorkList(&I);
324       I.eraseFromParent();
325       return 0;  // Don't do anything with FI
326     }
327         
328     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
329                            APInt &KnownOne, unsigned Depth = 0) const {
330       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
331     }
332     
333     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
334                            unsigned Depth = 0) const {
335       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
336     }
337     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
338       return llvm::ComputeNumSignBits(Op, TD, Depth);
339     }
340
341   private:
342
343     /// SimplifyCommutative - This performs a few simplifications for 
344     /// commutative operators.
345     bool SimplifyCommutative(BinaryOperator &I);
346
347     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
348     /// most-complex to least-complex order.
349     bool SimplifyCompare(CmpInst &I);
350
351     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
352     /// based on the demanded bits.
353     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
354                                    APInt& KnownZero, APInt& KnownOne,
355                                    unsigned Depth);
356     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
357                               APInt& KnownZero, APInt& KnownOne,
358                               unsigned Depth=0);
359         
360     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
361     /// SimplifyDemandedBits knows about.  See if the instruction has any
362     /// properties that allow us to simplify its operands.
363     bool SimplifyDemandedInstructionBits(Instruction &Inst);
364         
365     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
366                                       APInt& UndefElts, unsigned Depth = 0);
367       
368     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
369     // PHI node as operand #0, see if we can fold the instruction into the PHI
370     // (which is only possible if all operands to the PHI are constants).
371     Instruction *FoldOpIntoPhi(Instruction &I);
372
373     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
374     // operator and they all are only used by the PHI, PHI together their
375     // inputs, and do the operation once, to the result of the PHI.
376     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
377     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
378     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
379
380     
381     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
382                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
383     
384     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
385                               bool isSub, Instruction &I);
386     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
387                                  bool isSigned, bool Inside, Instruction &IB);
388     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
389     Instruction *MatchBSwap(BinaryOperator &I);
390     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
391     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
392     Instruction *SimplifyMemSet(MemSetInst *MI);
393
394
395     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
396
397     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
398                                     unsigned CastOpc, int &NumCastsRemoved);
399     unsigned GetOrEnforceKnownAlignment(Value *V,
400                                         unsigned PrefAlign = 0);
401
402   };
403 }
404
405 char InstCombiner::ID = 0;
406 static RegisterPass<InstCombiner>
407 X("instcombine", "Combine redundant instructions");
408
409 // getComplexity:  Assign a complexity or rank value to LLVM Values...
410 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
411 static unsigned getComplexity(Value *V) {
412   if (isa<Instruction>(V)) {
413     if (BinaryOperator::isNeg(V) || BinaryOperator::isFNeg(V) ||
414         BinaryOperator::isNot(V))
415       return 3;
416     return 4;
417   }
418   if (isa<Argument>(V)) return 3;
419   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
420 }
421
422 // isOnlyUse - Return true if this instruction will be deleted if we stop using
423 // it.
424 static bool isOnlyUse(Value *V) {
425   return V->hasOneUse() || isa<Constant>(V);
426 }
427
428 // getPromotedType - Return the specified type promoted as it would be to pass
429 // though a va_arg area...
430 static const Type *getPromotedType(const Type *Ty) {
431   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
432     if (ITy->getBitWidth() < 32)
433       return Type::Int32Ty;
434   }
435   return Ty;
436 }
437
438 /// getBitCastOperand - If the specified operand is a CastInst, a constant
439 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
440 /// operand value, otherwise return null.
441 static Value *getBitCastOperand(Value *V) {
442   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
443     // BitCastInst?
444     return I->getOperand(0);
445   else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
446     // GetElementPtrInst?
447     if (GEP->hasAllZeroIndices())
448       return GEP->getOperand(0);
449   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
450     if (CE->getOpcode() == Instruction::BitCast)
451       // BitCast ConstantExp?
452       return CE->getOperand(0);
453     else if (CE->getOpcode() == Instruction::GetElementPtr) {
454       // GetElementPtr ConstantExp?
455       for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
456            I != E; ++I) {
457         ConstantInt *CI = dyn_cast<ConstantInt>(I);
458         if (!CI || !CI->isZero())
459           // Any non-zero indices? Not cast-like.
460           return 0;
461       }
462       // All-zero indices? This is just like casting.
463       return CE->getOperand(0);
464     }
465   }
466   return 0;
467 }
468
469 /// This function is a wrapper around CastInst::isEliminableCastPair. It
470 /// simply extracts arguments and returns what that function returns.
471 static Instruction::CastOps 
472 isEliminableCastPair(
473   const CastInst *CI, ///< The first cast instruction
474   unsigned opcode,       ///< The opcode of the second cast instruction
475   const Type *DstTy,     ///< The target type for the second cast instruction
476   TargetData *TD         ///< The target data for pointer size
477 ) {
478   
479   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
480   const Type *MidTy = CI->getType();                  // B from above
481
482   // Get the opcodes of the two Cast instructions
483   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
484   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
485
486   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
487                                                 DstTy, TD->getIntPtrType());
488   
489   // We don't want to form an inttoptr or ptrtoint that converts to an integer
490   // type that differs from the pointer size.
491   if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
492       (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
493     Res = 0;
494   
495   return Instruction::CastOps(Res);
496 }
497
498 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
499 /// in any code being generated.  It does not require codegen if V is simple
500 /// enough or if the cast can be folded into other casts.
501 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
502                               const Type *Ty, TargetData *TD) {
503   if (V->getType() == Ty || isa<Constant>(V)) return false;
504   
505   // If this is another cast that can be eliminated, it isn't codegen either.
506   if (const CastInst *CI = dyn_cast<CastInst>(V))
507     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
508       return false;
509   return true;
510 }
511
512 // SimplifyCommutative - This performs a few simplifications for commutative
513 // operators:
514 //
515 //  1. Order operands such that they are listed from right (least complex) to
516 //     left (most complex).  This puts constants before unary operators before
517 //     binary operators.
518 //
519 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
520 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
521 //
522 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
523   bool Changed = false;
524   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
525     Changed = !I.swapOperands();
526
527   if (!I.isAssociative()) return Changed;
528   Instruction::BinaryOps Opcode = I.getOpcode();
529   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
530     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
531       if (isa<Constant>(I.getOperand(1))) {
532         Constant *Folded = Context->getConstantExpr(I.getOpcode(),
533                                              cast<Constant>(I.getOperand(1)),
534                                              cast<Constant>(Op->getOperand(1)));
535         I.setOperand(0, Op->getOperand(0));
536         I.setOperand(1, Folded);
537         return true;
538       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
539         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
540             isOnlyUse(Op) && isOnlyUse(Op1)) {
541           Constant *C1 = cast<Constant>(Op->getOperand(1));
542           Constant *C2 = cast<Constant>(Op1->getOperand(1));
543
544           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
545           Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
546           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
547                                                     Op1->getOperand(0),
548                                                     Op1->getName(), &I);
549           AddToWorkList(New);
550           I.setOperand(0, New);
551           I.setOperand(1, Folded);
552           return true;
553         }
554     }
555   return Changed;
556 }
557
558 /// SimplifyCompare - For a CmpInst this function just orders the operands
559 /// so that theyare listed from right (least complex) to left (most complex).
560 /// This puts constants before unary operators before binary operators.
561 bool InstCombiner::SimplifyCompare(CmpInst &I) {
562   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
563     return false;
564   I.swapOperands();
565   // Compare instructions are not associative so there's nothing else we can do.
566   return true;
567 }
568
569 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
570 // if the LHS is a constant zero (which is the 'negate' form).
571 //
572 static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
573   if (BinaryOperator::isNeg(V))
574     return BinaryOperator::getNegArgument(V);
575
576   // Constants can be considered to be negated values if they can be folded.
577   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
578     return Context->getConstantExprNeg(C);
579
580   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
581     if (C->getType()->getElementType()->isInteger())
582       return Context->getConstantExprNeg(C);
583
584   return 0;
585 }
586
587 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
588 // instruction if the LHS is a constant negative zero (which is the 'negate'
589 // form).
590 //
591 static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
592   if (BinaryOperator::isFNeg(V))
593     return BinaryOperator::getFNegArgument(V);
594
595   // Constants can be considered to be negated values if they can be folded.
596   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
597     return Context->getConstantExprFNeg(C);
598
599   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
600     if (C->getType()->getElementType()->isFloatingPoint())
601       return Context->getConstantExprFNeg(C);
602
603   return 0;
604 }
605
606 static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
607   if (BinaryOperator::isNot(V))
608     return BinaryOperator::getNotArgument(V);
609
610   // Constants can be considered to be not'ed values...
611   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
612     return Context->getConstantInt(~C->getValue());
613   return 0;
614 }
615
616 // dyn_castFoldableMul - If this value is a multiply that can be folded into
617 // other computations (because it has a constant operand), return the
618 // non-constant operand of the multiply, and set CST to point to the multiplier.
619 // Otherwise, return null.
620 //
621 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
622                                          LLVMContext *Context) {
623   if (V->hasOneUse() && V->getType()->isInteger())
624     if (Instruction *I = dyn_cast<Instruction>(V)) {
625       if (I->getOpcode() == Instruction::Mul)
626         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
627           return I->getOperand(0);
628       if (I->getOpcode() == Instruction::Shl)
629         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
630           // The multiplier is really 1 << CST.
631           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
632           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
633           CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
634           return I->getOperand(0);
635         }
636     }
637   return 0;
638 }
639
640 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
641 /// expression, return it.
642 static User *dyn_castGetElementPtr(Value *V) {
643   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
644   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
645     if (CE->getOpcode() == Instruction::GetElementPtr)
646       return cast<User>(V);
647   return false;
648 }
649
650 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
651 /// opcode value. Otherwise return UserOp1.
652 static unsigned getOpcode(const Value *V) {
653   if (const Instruction *I = dyn_cast<Instruction>(V))
654     return I->getOpcode();
655   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
656     return CE->getOpcode();
657   // Use UserOp1 to mean there's no opcode.
658   return Instruction::UserOp1;
659 }
660
661 /// AddOne - Add one to a ConstantInt
662 static Constant *AddOne(Constant *C, LLVMContext *Context) {
663   return Context->getConstantExprAdd(C, 
664     Context->getConstantInt(C->getType(), 1));
665 }
666 /// SubOne - Subtract one from a ConstantInt
667 static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
668   return Context->getConstantExprSub(C, 
669     Context->getConstantInt(C->getType(), 1));
670 }
671 /// MultiplyOverflows - True if the multiply can not be expressed in an int
672 /// this size.
673 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
674                               LLVMContext *Context) {
675   uint32_t W = C1->getBitWidth();
676   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
677   if (sign) {
678     LHSExt.sext(W * 2);
679     RHSExt.sext(W * 2);
680   } else {
681     LHSExt.zext(W * 2);
682     RHSExt.zext(W * 2);
683   }
684
685   APInt MulExt = LHSExt * RHSExt;
686
687   if (sign) {
688     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
689     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
690     return MulExt.slt(Min) || MulExt.sgt(Max);
691   } else 
692     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
693 }
694
695
696 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
697 /// specified instruction is a constant integer.  If so, check to see if there
698 /// are any bits set in the constant that are not demanded.  If so, shrink the
699 /// constant and return true.
700 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
701                                    APInt Demanded, LLVMContext *Context) {
702   assert(I && "No instruction?");
703   assert(OpNo < I->getNumOperands() && "Operand index too large");
704
705   // If the operand is not a constant integer, nothing to do.
706   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
707   if (!OpC) return false;
708
709   // If there are no bits set that aren't demanded, nothing to do.
710   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
711   if ((~Demanded & OpC->getValue()) == 0)
712     return false;
713
714   // This instruction is producing bits that are not demanded. Shrink the RHS.
715   Demanded &= OpC->getValue();
716   I->setOperand(OpNo, Context->getConstantInt(Demanded));
717   return true;
718 }
719
720 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
721 // set of known zero and one bits, compute the maximum and minimum values that
722 // could have the specified known zero and known one bits, returning them in
723 // min/max.
724 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
725                                                    const APInt& KnownOne,
726                                                    APInt& Min, APInt& Max) {
727   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
728          KnownZero.getBitWidth() == Min.getBitWidth() &&
729          KnownZero.getBitWidth() == Max.getBitWidth() &&
730          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
731   APInt UnknownBits = ~(KnownZero|KnownOne);
732
733   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
734   // bit if it is unknown.
735   Min = KnownOne;
736   Max = KnownOne|UnknownBits;
737   
738   if (UnknownBits.isNegative()) { // Sign bit is unknown
739     Min.set(Min.getBitWidth()-1);
740     Max.clear(Max.getBitWidth()-1);
741   }
742 }
743
744 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
745 // a set of known zero and one bits, compute the maximum and minimum values that
746 // could have the specified known zero and known one bits, returning them in
747 // min/max.
748 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
749                                                      const APInt &KnownOne,
750                                                      APInt &Min, APInt &Max) {
751   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
752          KnownZero.getBitWidth() == Min.getBitWidth() &&
753          KnownZero.getBitWidth() == Max.getBitWidth() &&
754          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
755   APInt UnknownBits = ~(KnownZero|KnownOne);
756   
757   // The minimum value is when the unknown bits are all zeros.
758   Min = KnownOne;
759   // The maximum value is when the unknown bits are all ones.
760   Max = KnownOne|UnknownBits;
761 }
762
763 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
764 /// SimplifyDemandedBits knows about.  See if the instruction has any
765 /// properties that allow us to simplify its operands.
766 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
767   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
768   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
769   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
770   
771   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
772                                      KnownZero, KnownOne, 0);
773   if (V == 0) return false;
774   if (V == &Inst) return true;
775   ReplaceInstUsesWith(Inst, V);
776   return true;
777 }
778
779 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
780 /// specified instruction operand if possible, updating it in place.  It returns
781 /// true if it made any change and false otherwise.
782 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
783                                         APInt &KnownZero, APInt &KnownOne,
784                                         unsigned Depth) {
785   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
786                                           KnownZero, KnownOne, Depth);
787   if (NewVal == 0) return false;
788   U.set(NewVal);
789   return true;
790 }
791
792
793 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
794 /// value based on the demanded bits.  When this function is called, it is known
795 /// that only the bits set in DemandedMask of the result of V are ever used
796 /// downstream. Consequently, depending on the mask and V, it may be possible
797 /// to replace V with a constant or one of its operands. In such cases, this
798 /// function does the replacement and returns true. In all other cases, it
799 /// returns false after analyzing the expression and setting KnownOne and known
800 /// to be one in the expression.  KnownZero contains all the bits that are known
801 /// to be zero in the expression. These are provided to potentially allow the
802 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
803 /// the expression. KnownOne and KnownZero always follow the invariant that 
804 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
805 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
806 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
807 /// and KnownOne must all be the same.
808 ///
809 /// This returns null if it did not change anything and it permits no
810 /// simplification.  This returns V itself if it did some simplification of V's
811 /// operands based on the information about what bits are demanded. This returns
812 /// some other non-null value if it found out that V is equal to another value
813 /// in the context where the specified bits are demanded, but not for all users.
814 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
815                                              APInt &KnownZero, APInt &KnownOne,
816                                              unsigned Depth) {
817   assert(V != 0 && "Null pointer of Value???");
818   assert(Depth <= 6 && "Limit Search Depth");
819   uint32_t BitWidth = DemandedMask.getBitWidth();
820   const Type *VTy = V->getType();
821   assert((TD || !isa<PointerType>(VTy)) &&
822          "SimplifyDemandedBits needs to know bit widths!");
823   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
824          (!VTy->isIntOrIntVector() ||
825           VTy->getScalarSizeInBits() == BitWidth) &&
826          KnownZero.getBitWidth() == BitWidth &&
827          KnownOne.getBitWidth() == BitWidth &&
828          "Value *V, DemandedMask, KnownZero and KnownOne "
829          "must have same BitWidth");
830   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
831     // We know all of the bits for a constant!
832     KnownOne = CI->getValue() & DemandedMask;
833     KnownZero = ~KnownOne & DemandedMask;
834     return 0;
835   }
836   if (isa<ConstantPointerNull>(V)) {
837     // We know all of the bits for a constant!
838     KnownOne.clear();
839     KnownZero = DemandedMask;
840     return 0;
841   }
842
843   KnownZero.clear();
844   KnownOne.clear();
845   if (DemandedMask == 0) {   // Not demanding any bits from V.
846     if (isa<UndefValue>(V))
847       return 0;
848     return Context->getUndef(VTy);
849   }
850   
851   if (Depth == 6)        // Limit search depth.
852     return 0;
853   
854   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
855   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
856
857   Instruction *I = dyn_cast<Instruction>(V);
858   if (!I) {
859     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
860     return 0;        // Only analyze instructions.
861   }
862
863   // If there are multiple uses of this value and we aren't at the root, then
864   // we can't do any simplifications of the operands, because DemandedMask
865   // only reflects the bits demanded by *one* of the users.
866   if (Depth != 0 && !I->hasOneUse()) {
867     // Despite the fact that we can't simplify this instruction in all User's
868     // context, we can at least compute the knownzero/knownone bits, and we can
869     // do simplifications that apply to *just* the one user if we know that
870     // this instruction has a simpler value in that context.
871     if (I->getOpcode() == Instruction::And) {
872       // If either the LHS or the RHS are Zero, the result is zero.
873       ComputeMaskedBits(I->getOperand(1), DemandedMask,
874                         RHSKnownZero, RHSKnownOne, Depth+1);
875       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
876                         LHSKnownZero, LHSKnownOne, Depth+1);
877       
878       // If all of the demanded bits are known 1 on one side, return the other.
879       // These bits cannot contribute to the result of the 'and' in this
880       // context.
881       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
882           (DemandedMask & ~LHSKnownZero))
883         return I->getOperand(0);
884       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
885           (DemandedMask & ~RHSKnownZero))
886         return I->getOperand(1);
887       
888       // If all of the demanded bits in the inputs are known zeros, return zero.
889       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
890         return Context->getNullValue(VTy);
891       
892     } else if (I->getOpcode() == Instruction::Or) {
893       // We can simplify (X|Y) -> X or Y in the user's context if we know that
894       // only bits from X or Y are demanded.
895       
896       // If either the LHS or the RHS are One, the result is One.
897       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
898                         RHSKnownZero, RHSKnownOne, Depth+1);
899       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
900                         LHSKnownZero, LHSKnownOne, Depth+1);
901       
902       // If all of the demanded bits are known zero on one side, return the
903       // other.  These bits cannot contribute to the result of the 'or' in this
904       // context.
905       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
906           (DemandedMask & ~LHSKnownOne))
907         return I->getOperand(0);
908       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
909           (DemandedMask & ~RHSKnownOne))
910         return I->getOperand(1);
911       
912       // If all of the potentially set bits on one side are known to be set on
913       // the other side, just use the 'other' side.
914       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
915           (DemandedMask & (~RHSKnownZero)))
916         return I->getOperand(0);
917       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
918           (DemandedMask & (~LHSKnownZero)))
919         return I->getOperand(1);
920     }
921     
922     // Compute the KnownZero/KnownOne bits to simplify things downstream.
923     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
924     return 0;
925   }
926   
927   // If this is the root being simplified, allow it to have multiple uses,
928   // just set the DemandedMask to all bits so that we can try to simplify the
929   // operands.  This allows visitTruncInst (for example) to simplify the
930   // operand of a trunc without duplicating all the logic below.
931   if (Depth == 0 && !V->hasOneUse())
932     DemandedMask = APInt::getAllOnesValue(BitWidth);
933   
934   switch (I->getOpcode()) {
935   default:
936     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
937     break;
938   case Instruction::And:
939     // If either the LHS or the RHS are Zero, the result is zero.
940     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
941                              RHSKnownZero, RHSKnownOne, Depth+1) ||
942         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
943                              LHSKnownZero, LHSKnownOne, Depth+1))
944       return I;
945     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
946     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
947
948     // If all of the demanded bits are known 1 on one side, return the other.
949     // These bits cannot contribute to the result of the 'and'.
950     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
951         (DemandedMask & ~LHSKnownZero))
952       return I->getOperand(0);
953     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
954         (DemandedMask & ~RHSKnownZero))
955       return I->getOperand(1);
956     
957     // If all of the demanded bits in the inputs are known zeros, return zero.
958     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
959       return Context->getNullValue(VTy);
960       
961     // If the RHS is a constant, see if we can simplify it.
962     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
963       return I;
964       
965     // Output known-1 bits are only known if set in both the LHS & RHS.
966     RHSKnownOne &= LHSKnownOne;
967     // Output known-0 are known to be clear if zero in either the LHS | RHS.
968     RHSKnownZero |= LHSKnownZero;
969     break;
970   case Instruction::Or:
971     // If either the LHS or the RHS are One, the result is One.
972     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
973                              RHSKnownZero, RHSKnownOne, Depth+1) ||
974         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
975                              LHSKnownZero, LHSKnownOne, Depth+1))
976       return I;
977     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
978     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
979     
980     // If all of the demanded bits are known zero on one side, return the other.
981     // These bits cannot contribute to the result of the 'or'.
982     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
983         (DemandedMask & ~LHSKnownOne))
984       return I->getOperand(0);
985     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
986         (DemandedMask & ~RHSKnownOne))
987       return I->getOperand(1);
988
989     // If all of the potentially set bits on one side are known to be set on
990     // the other side, just use the 'other' side.
991     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
992         (DemandedMask & (~RHSKnownZero)))
993       return I->getOperand(0);
994     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
995         (DemandedMask & (~LHSKnownZero)))
996       return I->getOperand(1);
997         
998     // If the RHS is a constant, see if we can simplify it.
999     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
1000       return I;
1001           
1002     // Output known-0 bits are only known if clear in both the LHS & RHS.
1003     RHSKnownZero &= LHSKnownZero;
1004     // Output known-1 are known to be set if set in either the LHS | RHS.
1005     RHSKnownOne |= LHSKnownOne;
1006     break;
1007   case Instruction::Xor: {
1008     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1009                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1010         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1011                              LHSKnownZero, LHSKnownOne, Depth+1))
1012       return I;
1013     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1014     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1015     
1016     // If all of the demanded bits are known zero on one side, return the other.
1017     // These bits cannot contribute to the result of the 'xor'.
1018     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1019       return I->getOperand(0);
1020     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1021       return I->getOperand(1);
1022     
1023     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1024     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1025                          (RHSKnownOne & LHSKnownOne);
1026     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1027     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1028                         (RHSKnownOne & LHSKnownZero);
1029     
1030     // If all of the demanded bits are known to be zero on one side or the
1031     // other, turn this into an *inclusive* or.
1032     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1033     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1034       Instruction *Or =
1035         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1036                                  I->getName());
1037       return InsertNewInstBefore(Or, *I);
1038     }
1039     
1040     // If all of the demanded bits on one side are known, and all of the set
1041     // bits on that side are also known to be set on the other side, turn this
1042     // into an AND, as we know the bits will be cleared.
1043     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1044     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1045       // all known
1046       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1047         Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
1048         Instruction *And = 
1049           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1050         return InsertNewInstBefore(And, *I);
1051       }
1052     }
1053     
1054     // If the RHS is a constant, see if we can simplify it.
1055     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1056     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
1057       return I;
1058     
1059     RHSKnownZero = KnownZeroOut;
1060     RHSKnownOne  = KnownOneOut;
1061     break;
1062   }
1063   case Instruction::Select:
1064     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1065                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1066         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1067                              LHSKnownZero, LHSKnownOne, Depth+1))
1068       return I;
1069     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1070     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1071     
1072     // If the operands are constants, see if we can simplify them.
1073     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1074         ShrinkDemandedConstant(I, 2, DemandedMask, Context))
1075       return I;
1076     
1077     // Only known if known in both the LHS and RHS.
1078     RHSKnownOne &= LHSKnownOne;
1079     RHSKnownZero &= LHSKnownZero;
1080     break;
1081   case Instruction::Trunc: {
1082     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1083     DemandedMask.zext(truncBf);
1084     RHSKnownZero.zext(truncBf);
1085     RHSKnownOne.zext(truncBf);
1086     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1087                              RHSKnownZero, RHSKnownOne, Depth+1))
1088       return I;
1089     DemandedMask.trunc(BitWidth);
1090     RHSKnownZero.trunc(BitWidth);
1091     RHSKnownOne.trunc(BitWidth);
1092     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1093     break;
1094   }
1095   case Instruction::BitCast:
1096     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1097       return false;  // vector->int or fp->int?
1098
1099     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1100       if (const VectorType *SrcVTy =
1101             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1102         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1103           // Don't touch a bitcast between vectors of different element counts.
1104           return false;
1105       } else
1106         // Don't touch a scalar-to-vector bitcast.
1107         return false;
1108     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1109       // Don't touch a vector-to-scalar bitcast.
1110       return false;
1111
1112     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1113                              RHSKnownZero, RHSKnownOne, Depth+1))
1114       return I;
1115     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1116     break;
1117   case Instruction::ZExt: {
1118     // Compute the bits in the result that are not present in the input.
1119     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1120     
1121     DemandedMask.trunc(SrcBitWidth);
1122     RHSKnownZero.trunc(SrcBitWidth);
1123     RHSKnownOne.trunc(SrcBitWidth);
1124     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1125                              RHSKnownZero, RHSKnownOne, Depth+1))
1126       return I;
1127     DemandedMask.zext(BitWidth);
1128     RHSKnownZero.zext(BitWidth);
1129     RHSKnownOne.zext(BitWidth);
1130     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1131     // The top bits are known to be zero.
1132     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1133     break;
1134   }
1135   case Instruction::SExt: {
1136     // Compute the bits in the result that are not present in the input.
1137     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1138     
1139     APInt InputDemandedBits = DemandedMask & 
1140                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1141
1142     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1143     // If any of the sign extended bits are demanded, we know that the sign
1144     // bit is demanded.
1145     if ((NewBits & DemandedMask) != 0)
1146       InputDemandedBits.set(SrcBitWidth-1);
1147       
1148     InputDemandedBits.trunc(SrcBitWidth);
1149     RHSKnownZero.trunc(SrcBitWidth);
1150     RHSKnownOne.trunc(SrcBitWidth);
1151     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1152                              RHSKnownZero, RHSKnownOne, Depth+1))
1153       return I;
1154     InputDemandedBits.zext(BitWidth);
1155     RHSKnownZero.zext(BitWidth);
1156     RHSKnownOne.zext(BitWidth);
1157     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1158       
1159     // If the sign bit of the input is known set or clear, then we know the
1160     // top bits of the result.
1161
1162     // If the input sign bit is known zero, or if the NewBits are not demanded
1163     // convert this into a zero extension.
1164     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1165       // Convert to ZExt cast
1166       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1167       return InsertNewInstBefore(NewCast, *I);
1168     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1169       RHSKnownOne |= NewBits;
1170     }
1171     break;
1172   }
1173   case Instruction::Add: {
1174     // Figure out what the input bits are.  If the top bits of the and result
1175     // are not demanded, then the add doesn't demand them from its input
1176     // either.
1177     unsigned NLZ = DemandedMask.countLeadingZeros();
1178       
1179     // If there is a constant on the RHS, there are a variety of xformations
1180     // we can do.
1181     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1182       // If null, this should be simplified elsewhere.  Some of the xforms here
1183       // won't work if the RHS is zero.
1184       if (RHS->isZero())
1185         break;
1186       
1187       // If the top bit of the output is demanded, demand everything from the
1188       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1189       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1190
1191       // Find information about known zero/one bits in the input.
1192       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1193                                LHSKnownZero, LHSKnownOne, Depth+1))
1194         return I;
1195
1196       // If the RHS of the add has bits set that can't affect the input, reduce
1197       // the constant.
1198       if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
1199         return I;
1200       
1201       // Avoid excess work.
1202       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1203         break;
1204       
1205       // Turn it into OR if input bits are zero.
1206       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1207         Instruction *Or =
1208           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1209                                    I->getName());
1210         return InsertNewInstBefore(Or, *I);
1211       }
1212       
1213       // We can say something about the output known-zero and known-one bits,
1214       // depending on potential carries from the input constant and the
1215       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1216       // bits set and the RHS constant is 0x01001, then we know we have a known
1217       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1218       
1219       // To compute this, we first compute the potential carry bits.  These are
1220       // the bits which may be modified.  I'm not aware of a better way to do
1221       // this scan.
1222       const APInt &RHSVal = RHS->getValue();
1223       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1224       
1225       // Now that we know which bits have carries, compute the known-1/0 sets.
1226       
1227       // Bits are known one if they are known zero in one operand and one in the
1228       // other, and there is no input carry.
1229       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1230                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1231       
1232       // Bits are known zero if they are known zero in both operands and there
1233       // is no input carry.
1234       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1235     } else {
1236       // If the high-bits of this ADD are not demanded, then it does not demand
1237       // the high bits of its LHS or RHS.
1238       if (DemandedMask[BitWidth-1] == 0) {
1239         // Right fill the mask of bits for this ADD to demand the most
1240         // significant bit and all those below it.
1241         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1242         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1243                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1244             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1245                                  LHSKnownZero, LHSKnownOne, Depth+1))
1246           return I;
1247       }
1248     }
1249     break;
1250   }
1251   case Instruction::Sub:
1252     // If the high-bits of this SUB are not demanded, then it does not demand
1253     // the high bits of its LHS or RHS.
1254     if (DemandedMask[BitWidth-1] == 0) {
1255       // Right fill the mask of bits for this SUB to demand the most
1256       // significant bit and all those below it.
1257       uint32_t NLZ = DemandedMask.countLeadingZeros();
1258       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1259       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1260                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1261           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1262                                LHSKnownZero, LHSKnownOne, Depth+1))
1263         return I;
1264     }
1265     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1266     // the known zeros and ones.
1267     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1268     break;
1269   case Instruction::Shl:
1270     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1271       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1272       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1273       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1274                                RHSKnownZero, RHSKnownOne, Depth+1))
1275         return I;
1276       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1277       RHSKnownZero <<= ShiftAmt;
1278       RHSKnownOne  <<= ShiftAmt;
1279       // low bits known zero.
1280       if (ShiftAmt)
1281         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1282     }
1283     break;
1284   case Instruction::LShr:
1285     // For a logical shift right
1286     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1287       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1288       
1289       // Unsigned shift right.
1290       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1291       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1292                                RHSKnownZero, RHSKnownOne, Depth+1))
1293         return I;
1294       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1295       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1296       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1297       if (ShiftAmt) {
1298         // Compute the new bits that are at the top now.
1299         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1300         RHSKnownZero |= HighBits;  // high bits known zero.
1301       }
1302     }
1303     break;
1304   case Instruction::AShr:
1305     // If this is an arithmetic shift right and only the low-bit is set, we can
1306     // always convert this into a logical shr, even if the shift amount is
1307     // variable.  The low bit of the shift cannot be an input sign bit unless
1308     // the shift amount is >= the size of the datatype, which is undefined.
1309     if (DemandedMask == 1) {
1310       // Perform the logical shift right.
1311       Instruction *NewVal = BinaryOperator::CreateLShr(
1312                         I->getOperand(0), I->getOperand(1), I->getName());
1313       return InsertNewInstBefore(NewVal, *I);
1314     }    
1315
1316     // If the sign bit is the only bit demanded by this ashr, then there is no
1317     // need to do it, the shift doesn't change the high bit.
1318     if (DemandedMask.isSignBit())
1319       return I->getOperand(0);
1320     
1321     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1322       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1323       
1324       // Signed shift right.
1325       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1326       // If any of the "high bits" are demanded, we should set the sign bit as
1327       // demanded.
1328       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1329         DemandedMaskIn.set(BitWidth-1);
1330       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1331                                RHSKnownZero, RHSKnownOne, Depth+1))
1332         return I;
1333       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1334       // Compute the new bits that are at the top now.
1335       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1336       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1337       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1338         
1339       // Handle the sign bits.
1340       APInt SignBit(APInt::getSignBit(BitWidth));
1341       // Adjust to where it is now in the mask.
1342       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1343         
1344       // If the input sign bit is known to be zero, or if none of the top bits
1345       // are demanded, turn this into an unsigned shift right.
1346       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1347           (HighBits & ~DemandedMask) == HighBits) {
1348         // Perform the logical shift right.
1349         Instruction *NewVal = BinaryOperator::CreateLShr(
1350                           I->getOperand(0), SA, I->getName());
1351         return InsertNewInstBefore(NewVal, *I);
1352       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1353         RHSKnownOne |= HighBits;
1354       }
1355     }
1356     break;
1357   case Instruction::SRem:
1358     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1359       APInt RA = Rem->getValue().abs();
1360       if (RA.isPowerOf2()) {
1361         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1362           return I->getOperand(0);
1363
1364         APInt LowBits = RA - 1;
1365         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1366         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1367                                  LHSKnownZero, LHSKnownOne, Depth+1))
1368           return I;
1369
1370         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1371           LHSKnownZero |= ~LowBits;
1372
1373         KnownZero |= LHSKnownZero & DemandedMask;
1374
1375         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1376       }
1377     }
1378     break;
1379   case Instruction::URem: {
1380     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1381     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1382     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1383                              KnownZero2, KnownOne2, Depth+1) ||
1384         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1385                              KnownZero2, KnownOne2, Depth+1))
1386       return I;
1387
1388     unsigned Leaders = KnownZero2.countLeadingOnes();
1389     Leaders = std::max(Leaders,
1390                        KnownZero2.countLeadingOnes());
1391     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1392     break;
1393   }
1394   case Instruction::Call:
1395     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1396       switch (II->getIntrinsicID()) {
1397       default: break;
1398       case Intrinsic::bswap: {
1399         // If the only bits demanded come from one byte of the bswap result,
1400         // just shift the input byte into position to eliminate the bswap.
1401         unsigned NLZ = DemandedMask.countLeadingZeros();
1402         unsigned NTZ = DemandedMask.countTrailingZeros();
1403           
1404         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1405         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1406         // have 14 leading zeros, round to 8.
1407         NLZ &= ~7;
1408         NTZ &= ~7;
1409         // If we need exactly one byte, we can do this transformation.
1410         if (BitWidth-NLZ-NTZ == 8) {
1411           unsigned ResultBit = NTZ;
1412           unsigned InputBit = BitWidth-NTZ-8;
1413           
1414           // Replace this with either a left or right shift to get the byte into
1415           // the right place.
1416           Instruction *NewVal;
1417           if (InputBit > ResultBit)
1418             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1419                     Context->getConstantInt(I->getType(), InputBit-ResultBit));
1420           else
1421             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1422                     Context->getConstantInt(I->getType(), ResultBit-InputBit));
1423           NewVal->takeName(I);
1424           return InsertNewInstBefore(NewVal, *I);
1425         }
1426           
1427         // TODO: Could compute known zero/one bits based on the input.
1428         break;
1429       }
1430       }
1431     }
1432     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1433     break;
1434   }
1435   
1436   // If the client is only demanding bits that we know, return the known
1437   // constant.
1438   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1439     Constant *C = Context->getConstantInt(RHSKnownOne);
1440     if (isa<PointerType>(V->getType()))
1441       C = Context->getConstantExprIntToPtr(C, V->getType());
1442     return C;
1443   }
1444   return false;
1445 }
1446
1447
1448 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1449 /// any number of elements. DemandedElts contains the set of elements that are
1450 /// actually used by the caller.  This method analyzes which elements of the
1451 /// operand are undef and returns that information in UndefElts.
1452 ///
1453 /// If the information about demanded elements can be used to simplify the
1454 /// operation, the operation is simplified, then the resultant value is
1455 /// returned.  This returns null if no change was made.
1456 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1457                                                 APInt& UndefElts,
1458                                                 unsigned Depth) {
1459   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1460   APInt EltMask(APInt::getAllOnesValue(VWidth));
1461   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1462
1463   if (isa<UndefValue>(V)) {
1464     // If the entire vector is undefined, just return this info.
1465     UndefElts = EltMask;
1466     return 0;
1467   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1468     UndefElts = EltMask;
1469     return Context->getUndef(V->getType());
1470   }
1471
1472   UndefElts = 0;
1473   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1474     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1475     Constant *Undef = Context->getUndef(EltTy);
1476
1477     std::vector<Constant*> Elts;
1478     for (unsigned i = 0; i != VWidth; ++i)
1479       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1480         Elts.push_back(Undef);
1481         UndefElts.set(i);
1482       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1483         Elts.push_back(Undef);
1484         UndefElts.set(i);
1485       } else {                               // Otherwise, defined.
1486         Elts.push_back(CP->getOperand(i));
1487       }
1488
1489     // If we changed the constant, return it.
1490     Constant *NewCP = Context->getConstantVector(Elts);
1491     return NewCP != CP ? NewCP : 0;
1492   } else if (isa<ConstantAggregateZero>(V)) {
1493     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1494     // set to undef.
1495     
1496     // Check if this is identity. If so, return 0 since we are not simplifying
1497     // anything.
1498     if (DemandedElts == ((1ULL << VWidth) -1))
1499       return 0;
1500     
1501     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1502     Constant *Zero = Context->getNullValue(EltTy);
1503     Constant *Undef = Context->getUndef(EltTy);
1504     std::vector<Constant*> Elts;
1505     for (unsigned i = 0; i != VWidth; ++i) {
1506       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1507       Elts.push_back(Elt);
1508     }
1509     UndefElts = DemandedElts ^ EltMask;
1510     return Context->getConstantVector(Elts);
1511   }
1512   
1513   // Limit search depth.
1514   if (Depth == 10)
1515     return 0;
1516
1517   // If multiple users are using the root value, procede with
1518   // simplification conservatively assuming that all elements
1519   // are needed.
1520   if (!V->hasOneUse()) {
1521     // Quit if we find multiple users of a non-root value though.
1522     // They'll be handled when it's their turn to be visited by
1523     // the main instcombine process.
1524     if (Depth != 0)
1525       // TODO: Just compute the UndefElts information recursively.
1526       return 0;
1527
1528     // Conservatively assume that all elements are needed.
1529     DemandedElts = EltMask;
1530   }
1531   
1532   Instruction *I = dyn_cast<Instruction>(V);
1533   if (!I) return 0;        // Only analyze instructions.
1534   
1535   bool MadeChange = false;
1536   APInt UndefElts2(VWidth, 0);
1537   Value *TmpV;
1538   switch (I->getOpcode()) {
1539   default: break;
1540     
1541   case Instruction::InsertElement: {
1542     // If this is a variable index, we don't know which element it overwrites.
1543     // demand exactly the same input as we produce.
1544     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1545     if (Idx == 0) {
1546       // Note that we can't propagate undef elt info, because we don't know
1547       // which elt is getting updated.
1548       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1549                                         UndefElts2, Depth+1);
1550       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1551       break;
1552     }
1553     
1554     // If this is inserting an element that isn't demanded, remove this
1555     // insertelement.
1556     unsigned IdxNo = Idx->getZExtValue();
1557     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1558       return AddSoonDeadInstToWorklist(*I, 0);
1559     
1560     // Otherwise, the element inserted overwrites whatever was there, so the
1561     // input demanded set is simpler than the output set.
1562     APInt DemandedElts2 = DemandedElts;
1563     DemandedElts2.clear(IdxNo);
1564     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1565                                       UndefElts, Depth+1);
1566     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1567
1568     // The inserted element is defined.
1569     UndefElts.clear(IdxNo);
1570     break;
1571   }
1572   case Instruction::ShuffleVector: {
1573     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1574     uint64_t LHSVWidth =
1575       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1576     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1577     for (unsigned i = 0; i < VWidth; i++) {
1578       if (DemandedElts[i]) {
1579         unsigned MaskVal = Shuffle->getMaskValue(i);
1580         if (MaskVal != -1u) {
1581           assert(MaskVal < LHSVWidth * 2 &&
1582                  "shufflevector mask index out of range!");
1583           if (MaskVal < LHSVWidth)
1584             LeftDemanded.set(MaskVal);
1585           else
1586             RightDemanded.set(MaskVal - LHSVWidth);
1587         }
1588       }
1589     }
1590
1591     APInt UndefElts4(LHSVWidth, 0);
1592     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1593                                       UndefElts4, Depth+1);
1594     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1595
1596     APInt UndefElts3(LHSVWidth, 0);
1597     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1598                                       UndefElts3, Depth+1);
1599     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1600
1601     bool NewUndefElts = false;
1602     for (unsigned i = 0; i < VWidth; i++) {
1603       unsigned MaskVal = Shuffle->getMaskValue(i);
1604       if (MaskVal == -1u) {
1605         UndefElts.set(i);
1606       } else if (MaskVal < LHSVWidth) {
1607         if (UndefElts4[MaskVal]) {
1608           NewUndefElts = true;
1609           UndefElts.set(i);
1610         }
1611       } else {
1612         if (UndefElts3[MaskVal - LHSVWidth]) {
1613           NewUndefElts = true;
1614           UndefElts.set(i);
1615         }
1616       }
1617     }
1618
1619     if (NewUndefElts) {
1620       // Add additional discovered undefs.
1621       std::vector<Constant*> Elts;
1622       for (unsigned i = 0; i < VWidth; ++i) {
1623         if (UndefElts[i])
1624           Elts.push_back(Context->getUndef(Type::Int32Ty));
1625         else
1626           Elts.push_back(Context->getConstantInt(Type::Int32Ty,
1627                                           Shuffle->getMaskValue(i)));
1628       }
1629       I->setOperand(2, Context->getConstantVector(Elts));
1630       MadeChange = true;
1631     }
1632     break;
1633   }
1634   case Instruction::BitCast: {
1635     // Vector->vector casts only.
1636     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1637     if (!VTy) break;
1638     unsigned InVWidth = VTy->getNumElements();
1639     APInt InputDemandedElts(InVWidth, 0);
1640     unsigned Ratio;
1641
1642     if (VWidth == InVWidth) {
1643       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1644       // elements as are demanded of us.
1645       Ratio = 1;
1646       InputDemandedElts = DemandedElts;
1647     } else if (VWidth > InVWidth) {
1648       // Untested so far.
1649       break;
1650       
1651       // If there are more elements in the result than there are in the source,
1652       // then an input element is live if any of the corresponding output
1653       // elements are live.
1654       Ratio = VWidth/InVWidth;
1655       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1656         if (DemandedElts[OutIdx])
1657           InputDemandedElts.set(OutIdx/Ratio);
1658       }
1659     } else {
1660       // Untested so far.
1661       break;
1662       
1663       // If there are more elements in the source than there are in the result,
1664       // then an input element is live if the corresponding output element is
1665       // live.
1666       Ratio = InVWidth/VWidth;
1667       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1668         if (DemandedElts[InIdx/Ratio])
1669           InputDemandedElts.set(InIdx);
1670     }
1671     
1672     // div/rem demand all inputs, because they don't want divide by zero.
1673     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1674                                       UndefElts2, Depth+1);
1675     if (TmpV) {
1676       I->setOperand(0, TmpV);
1677       MadeChange = true;
1678     }
1679     
1680     UndefElts = UndefElts2;
1681     if (VWidth > InVWidth) {
1682       LLVM_UNREACHABLE("Unimp");
1683       // If there are more elements in the result than there are in the source,
1684       // then an output element is undef if the corresponding input element is
1685       // undef.
1686       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1687         if (UndefElts2[OutIdx/Ratio])
1688           UndefElts.set(OutIdx);
1689     } else if (VWidth < InVWidth) {
1690       LLVM_UNREACHABLE("Unimp");
1691       // If there are more elements in the source than there are in the result,
1692       // then a result element is undef if all of the corresponding input
1693       // elements are undef.
1694       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1695       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1696         if (!UndefElts2[InIdx])            // Not undef?
1697           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1698     }
1699     break;
1700   }
1701   case Instruction::And:
1702   case Instruction::Or:
1703   case Instruction::Xor:
1704   case Instruction::Add:
1705   case Instruction::Sub:
1706   case Instruction::Mul:
1707     // div/rem demand all inputs, because they don't want divide by zero.
1708     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1709                                       UndefElts, Depth+1);
1710     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1711     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1712                                       UndefElts2, Depth+1);
1713     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1714       
1715     // Output elements are undefined if both are undefined.  Consider things
1716     // like undef&0.  The result is known zero, not undef.
1717     UndefElts &= UndefElts2;
1718     break;
1719     
1720   case Instruction::Call: {
1721     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1722     if (!II) break;
1723     switch (II->getIntrinsicID()) {
1724     default: break;
1725       
1726     // Binary vector operations that work column-wise.  A dest element is a
1727     // function of the corresponding input elements from the two inputs.
1728     case Intrinsic::x86_sse_sub_ss:
1729     case Intrinsic::x86_sse_mul_ss:
1730     case Intrinsic::x86_sse_min_ss:
1731     case Intrinsic::x86_sse_max_ss:
1732     case Intrinsic::x86_sse2_sub_sd:
1733     case Intrinsic::x86_sse2_mul_sd:
1734     case Intrinsic::x86_sse2_min_sd:
1735     case Intrinsic::x86_sse2_max_sd:
1736       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1737                                         UndefElts, Depth+1);
1738       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1739       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1740                                         UndefElts2, Depth+1);
1741       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1742
1743       // If only the low elt is demanded and this is a scalarizable intrinsic,
1744       // scalarize it now.
1745       if (DemandedElts == 1) {
1746         switch (II->getIntrinsicID()) {
1747         default: break;
1748         case Intrinsic::x86_sse_sub_ss:
1749         case Intrinsic::x86_sse_mul_ss:
1750         case Intrinsic::x86_sse2_sub_sd:
1751         case Intrinsic::x86_sse2_mul_sd:
1752           // TODO: Lower MIN/MAX/ABS/etc
1753           Value *LHS = II->getOperand(1);
1754           Value *RHS = II->getOperand(2);
1755           // Extract the element as scalars.
1756           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1757           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1758           
1759           switch (II->getIntrinsicID()) {
1760           default: LLVM_UNREACHABLE("Case stmts out of sync!");
1761           case Intrinsic::x86_sse_sub_ss:
1762           case Intrinsic::x86_sse2_sub_sd:
1763             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1764                                                         II->getName()), *II);
1765             break;
1766           case Intrinsic::x86_sse_mul_ss:
1767           case Intrinsic::x86_sse2_mul_sd:
1768             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1769                                                          II->getName()), *II);
1770             break;
1771           }
1772           
1773           Instruction *New =
1774             InsertElementInst::Create(
1775               Context->getUndef(II->getType()), TmpV, 0U, II->getName());
1776           InsertNewInstBefore(New, *II);
1777           AddSoonDeadInstToWorklist(*II, 0);
1778           return New;
1779         }            
1780       }
1781         
1782       // Output elements are undefined if both are undefined.  Consider things
1783       // like undef&0.  The result is known zero, not undef.
1784       UndefElts &= UndefElts2;
1785       break;
1786     }
1787     break;
1788   }
1789   }
1790   return MadeChange ? I : 0;
1791 }
1792
1793
1794 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1795 /// function is designed to check a chain of associative operators for a
1796 /// potential to apply a certain optimization.  Since the optimization may be
1797 /// applicable if the expression was reassociated, this checks the chain, then
1798 /// reassociates the expression as necessary to expose the optimization
1799 /// opportunity.  This makes use of a special Functor, which must define
1800 /// 'shouldApply' and 'apply' methods.
1801 ///
1802 template<typename Functor>
1803 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
1804                                    LLVMContext *Context) {
1805   unsigned Opcode = Root.getOpcode();
1806   Value *LHS = Root.getOperand(0);
1807
1808   // Quick check, see if the immediate LHS matches...
1809   if (F.shouldApply(LHS))
1810     return F.apply(Root);
1811
1812   // Otherwise, if the LHS is not of the same opcode as the root, return.
1813   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1814   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1815     // Should we apply this transform to the RHS?
1816     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1817
1818     // If not to the RHS, check to see if we should apply to the LHS...
1819     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1820       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1821       ShouldApply = true;
1822     }
1823
1824     // If the functor wants to apply the optimization to the RHS of LHSI,
1825     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1826     if (ShouldApply) {
1827       // Now all of the instructions are in the current basic block, go ahead
1828       // and perform the reassociation.
1829       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1830
1831       // First move the selected RHS to the LHS of the root...
1832       Root.setOperand(0, LHSI->getOperand(1));
1833
1834       // Make what used to be the LHS of the root be the user of the root...
1835       Value *ExtraOperand = TmpLHSI->getOperand(1);
1836       if (&Root == TmpLHSI) {
1837         Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
1838         return 0;
1839       }
1840       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1841       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1842       BasicBlock::iterator ARI = &Root; ++ARI;
1843       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1844       ARI = Root;
1845
1846       // Now propagate the ExtraOperand down the chain of instructions until we
1847       // get to LHSI.
1848       while (TmpLHSI != LHSI) {
1849         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1850         // Move the instruction to immediately before the chain we are
1851         // constructing to avoid breaking dominance properties.
1852         NextLHSI->moveBefore(ARI);
1853         ARI = NextLHSI;
1854
1855         Value *NextOp = NextLHSI->getOperand(1);
1856         NextLHSI->setOperand(1, ExtraOperand);
1857         TmpLHSI = NextLHSI;
1858         ExtraOperand = NextOp;
1859       }
1860
1861       // Now that the instructions are reassociated, have the functor perform
1862       // the transformation...
1863       return F.apply(Root);
1864     }
1865
1866     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1867   }
1868   return 0;
1869 }
1870
1871 namespace {
1872
1873 // AddRHS - Implements: X + X --> X << 1
1874 struct AddRHS {
1875   Value *RHS;
1876   LLVMContext *Context;
1877   AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
1878   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1879   Instruction *apply(BinaryOperator &Add) const {
1880     return BinaryOperator::CreateShl(Add.getOperand(0),
1881                                      Context->getConstantInt(Add.getType(), 1));
1882   }
1883 };
1884
1885 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1886 //                 iff C1&C2 == 0
1887 struct AddMaskingAnd {
1888   Constant *C2;
1889   LLVMContext *Context;
1890   AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
1891   bool shouldApply(Value *LHS) const {
1892     ConstantInt *C1;
1893     return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
1894            Context->getConstantExprAnd(C1, C2)->isNullValue();
1895   }
1896   Instruction *apply(BinaryOperator &Add) const {
1897     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1898   }
1899 };
1900
1901 }
1902
1903 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1904                                              InstCombiner *IC) {
1905   LLVMContext *Context = IC->getContext();
1906   
1907   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1908     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1909   }
1910
1911   // Figure out if the constant is the left or the right argument.
1912   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1913   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1914
1915   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1916     if (ConstIsRHS)
1917       return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1918     return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
1919   }
1920
1921   Value *Op0 = SO, *Op1 = ConstOperand;
1922   if (!ConstIsRHS)
1923     std::swap(Op0, Op1);
1924   Instruction *New;
1925   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1926     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1927   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1928     New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1929                           Op0, Op1, SO->getName()+".cmp");
1930   else {
1931     LLVM_UNREACHABLE("Unknown binary instruction type!");
1932   }
1933   return IC->InsertNewInstBefore(New, I);
1934 }
1935
1936 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1937 // constant as the other operand, try to fold the binary operator into the
1938 // select arguments.  This also works for Cast instructions, which obviously do
1939 // not have a second operand.
1940 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1941                                      InstCombiner *IC) {
1942   // Don't modify shared select instructions
1943   if (!SI->hasOneUse()) return 0;
1944   Value *TV = SI->getOperand(1);
1945   Value *FV = SI->getOperand(2);
1946
1947   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1948     // Bool selects with constant operands can be folded to logical ops.
1949     if (SI->getType() == Type::Int1Ty) return 0;
1950
1951     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1952     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1953
1954     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1955                               SelectFalseVal);
1956   }
1957   return 0;
1958 }
1959
1960
1961 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1962 /// node as operand #0, see if we can fold the instruction into the PHI (which
1963 /// is only possible if all operands to the PHI are constants).
1964 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1965   PHINode *PN = cast<PHINode>(I.getOperand(0));
1966   unsigned NumPHIValues = PN->getNumIncomingValues();
1967   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1968
1969   // Check to see if all of the operands of the PHI are constants.  If there is
1970   // one non-constant value, remember the BB it is.  If there is more than one
1971   // or if *it* is a PHI, bail out.
1972   BasicBlock *NonConstBB = 0;
1973   for (unsigned i = 0; i != NumPHIValues; ++i)
1974     if (!isa<Constant>(PN->getIncomingValue(i))) {
1975       if (NonConstBB) return 0;  // More than one non-const value.
1976       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1977       NonConstBB = PN->getIncomingBlock(i);
1978       
1979       // If the incoming non-constant value is in I's block, we have an infinite
1980       // loop.
1981       if (NonConstBB == I.getParent())
1982         return 0;
1983     }
1984   
1985   // If there is exactly one non-constant value, we can insert a copy of the
1986   // operation in that block.  However, if this is a critical edge, we would be
1987   // inserting the computation one some other paths (e.g. inside a loop).  Only
1988   // do this if the pred block is unconditionally branching into the phi block.
1989   if (NonConstBB) {
1990     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1991     if (!BI || !BI->isUnconditional()) return 0;
1992   }
1993
1994   // Okay, we can do the transformation: create the new PHI node.
1995   PHINode *NewPN = PHINode::Create(I.getType(), "");
1996   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1997   InsertNewInstBefore(NewPN, *PN);
1998   NewPN->takeName(PN);
1999
2000   // Next, add all of the operands to the PHI.
2001   if (I.getNumOperands() == 2) {
2002     Constant *C = cast<Constant>(I.getOperand(1));
2003     for (unsigned i = 0; i != NumPHIValues; ++i) {
2004       Value *InV = 0;
2005       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2006         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2007           InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
2008         else
2009           InV = Context->getConstantExpr(I.getOpcode(), InC, C);
2010       } else {
2011         assert(PN->getIncomingBlock(i) == NonConstBB);
2012         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2013           InV = BinaryOperator::Create(BO->getOpcode(),
2014                                        PN->getIncomingValue(i), C, "phitmp",
2015                                        NonConstBB->getTerminator());
2016         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2017           InV = CmpInst::Create(*Context, CI->getOpcode(), 
2018                                 CI->getPredicate(),
2019                                 PN->getIncomingValue(i), C, "phitmp",
2020                                 NonConstBB->getTerminator());
2021         else
2022           LLVM_UNREACHABLE("Unknown binop!");
2023         
2024         AddToWorkList(cast<Instruction>(InV));
2025       }
2026       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2027     }
2028   } else { 
2029     CastInst *CI = cast<CastInst>(&I);
2030     const Type *RetTy = CI->getType();
2031     for (unsigned i = 0; i != NumPHIValues; ++i) {
2032       Value *InV;
2033       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2034         InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
2035       } else {
2036         assert(PN->getIncomingBlock(i) == NonConstBB);
2037         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2038                                I.getType(), "phitmp", 
2039                                NonConstBB->getTerminator());
2040         AddToWorkList(cast<Instruction>(InV));
2041       }
2042       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2043     }
2044   }
2045   return ReplaceInstUsesWith(I, NewPN);
2046 }
2047
2048
2049 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2050 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2051 /// This basically requires proving that the add in the original type would not
2052 /// overflow to change the sign bit or have a carry out.
2053 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2054   // There are different heuristics we can use for this.  Here are some simple
2055   // ones.
2056   
2057   // Add has the property that adding any two 2's complement numbers can only 
2058   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2059   // have at least two sign bits, we know that the addition of the two values will
2060   // sign extend fine.
2061   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2062     return true;
2063   
2064   
2065   // If one of the operands only has one non-zero bit, and if the other operand
2066   // has a known-zero bit in a more significant place than it (not including the
2067   // sign bit) the ripple may go up to and fill the zero, but won't change the
2068   // sign.  For example, (X & ~4) + 1.
2069   
2070   // TODO: Implement.
2071   
2072   return false;
2073 }
2074
2075
2076 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2077   bool Changed = SimplifyCommutative(I);
2078   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2079
2080   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2081     // X + undef -> undef
2082     if (isa<UndefValue>(RHS))
2083       return ReplaceInstUsesWith(I, RHS);
2084
2085     // X + 0 --> X
2086     if (RHSC->isNullValue())
2087       return ReplaceInstUsesWith(I, LHS);
2088
2089     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2090       // X + (signbit) --> X ^ signbit
2091       const APInt& Val = CI->getValue();
2092       uint32_t BitWidth = Val.getBitWidth();
2093       if (Val == APInt::getSignBit(BitWidth))
2094         return BinaryOperator::CreateXor(LHS, RHS);
2095       
2096       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2097       // (X & 254)+1 -> (X&254)|1
2098       if (SimplifyDemandedInstructionBits(I))
2099         return &I;
2100
2101       // zext(i1) - 1  ->  select i1, 0, -1
2102       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2103         if (CI->isAllOnesValue() &&
2104             ZI->getOperand(0)->getType() == Type::Int1Ty)
2105           return SelectInst::Create(ZI->getOperand(0),
2106                                     Context->getNullValue(I.getType()),
2107                               Context->getConstantIntAllOnesValue(I.getType()));
2108     }
2109
2110     if (isa<PHINode>(LHS))
2111       if (Instruction *NV = FoldOpIntoPhi(I))
2112         return NV;
2113     
2114     ConstantInt *XorRHS = 0;
2115     Value *XorLHS = 0;
2116     if (isa<ConstantInt>(RHSC) &&
2117         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
2118       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2119       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2120       
2121       uint32_t Size = TySizeBits / 2;
2122       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2123       APInt CFF80Val(-C0080Val);
2124       do {
2125         if (TySizeBits > Size) {
2126           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2127           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2128           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2129               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2130             // This is a sign extend if the top bits are known zero.
2131             if (!MaskedValueIsZero(XorLHS, 
2132                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2133               Size = 0;  // Not a sign ext, but can't be any others either.
2134             break;
2135           }
2136         }
2137         Size >>= 1;
2138         C0080Val = APIntOps::lshr(C0080Val, Size);
2139         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2140       } while (Size >= 1);
2141       
2142       // FIXME: This shouldn't be necessary. When the backends can handle types
2143       // with funny bit widths then this switch statement should be removed. It
2144       // is just here to get the size of the "middle" type back up to something
2145       // that the back ends can handle.
2146       const Type *MiddleType = 0;
2147       switch (Size) {
2148         default: break;
2149         case 32: MiddleType = Type::Int32Ty; break;
2150         case 16: MiddleType = Type::Int16Ty; break;
2151         case  8: MiddleType = Type::Int8Ty; break;
2152       }
2153       if (MiddleType) {
2154         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2155         InsertNewInstBefore(NewTrunc, I);
2156         return new SExtInst(NewTrunc, I.getType(), I.getName());
2157       }
2158     }
2159   }
2160
2161   if (I.getType() == Type::Int1Ty)
2162     return BinaryOperator::CreateXor(LHS, RHS);
2163
2164   // X + X --> X << 1
2165   if (I.getType()->isInteger()) {
2166     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2167       return Result;
2168
2169     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2170       if (RHSI->getOpcode() == Instruction::Sub)
2171         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2172           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2173     }
2174     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2175       if (LHSI->getOpcode() == Instruction::Sub)
2176         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2177           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2178     }
2179   }
2180
2181   // -A + B  -->  B - A
2182   // -A + -B  -->  -(A + B)
2183   if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
2184     if (LHS->getType()->isIntOrIntVector()) {
2185       if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
2186         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2187         InsertNewInstBefore(NewAdd, I);
2188         return BinaryOperator::CreateNeg(NewAdd);
2189       }
2190     }
2191     
2192     return BinaryOperator::CreateSub(RHS, LHSV);
2193   }
2194
2195   // A + -B  -->  A - B
2196   if (!isa<Constant>(RHS))
2197     if (Value *V = dyn_castNegVal(RHS, Context))
2198       return BinaryOperator::CreateSub(LHS, V);
2199
2200
2201   ConstantInt *C2;
2202   if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
2203     if (X == RHS)   // X*C + X --> X * (C+1)
2204       return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
2205
2206     // X*C1 + X*C2 --> X * (C1+C2)
2207     ConstantInt *C1;
2208     if (X == dyn_castFoldableMul(RHS, C1, Context))
2209       return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
2210   }
2211
2212   // X + X*C --> X * (C+1)
2213   if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2214     return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
2215
2216   // X + ~X --> -1   since   ~X = -X-1
2217   if (dyn_castNotVal(LHS, Context) == RHS ||
2218       dyn_castNotVal(RHS, Context) == LHS)
2219     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
2220   
2221
2222   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2223   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
2224     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
2225       return R;
2226   
2227   // A+B --> A|B iff A and B have no bits set in common.
2228   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2229     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2230     APInt LHSKnownOne(IT->getBitWidth(), 0);
2231     APInt LHSKnownZero(IT->getBitWidth(), 0);
2232     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2233     if (LHSKnownZero != 0) {
2234       APInt RHSKnownOne(IT->getBitWidth(), 0);
2235       APInt RHSKnownZero(IT->getBitWidth(), 0);
2236       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2237       
2238       // No bits in common -> bitwise or.
2239       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2240         return BinaryOperator::CreateOr(LHS, RHS);
2241     }
2242   }
2243
2244   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2245   if (I.getType()->isIntOrIntVector()) {
2246     Value *W, *X, *Y, *Z;
2247     if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2248         match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
2249       if (W != Y) {
2250         if (W == Z) {
2251           std::swap(Y, Z);
2252         } else if (Y == X) {
2253           std::swap(W, X);
2254         } else if (X == Z) {
2255           std::swap(Y, Z);
2256           std::swap(W, X);
2257         }
2258       }
2259
2260       if (W == Y) {
2261         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2262                                                             LHS->getName()), I);
2263         return BinaryOperator::CreateMul(W, NewAdd);
2264       }
2265     }
2266   }
2267
2268   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2269     Value *X = 0;
2270     if (match(LHS, m_Not(m_Value(X)), *Context))    // ~X + C --> (C-1) - X
2271       return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
2272
2273     // (X & FF00) + xx00  -> (X+xx00) & FF00
2274     if (LHS->hasOneUse() &&
2275         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
2276       Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
2277       if (Anded == CRHS) {
2278         // See if all bits from the first bit set in the Add RHS up are included
2279         // in the mask.  First, get the rightmost bit.
2280         const APInt& AddRHSV = CRHS->getValue();
2281
2282         // Form a mask of all bits from the lowest bit added through the top.
2283         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2284
2285         // See if the and mask includes all of these bits.
2286         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2287
2288         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2289           // Okay, the xform is safe.  Insert the new add pronto.
2290           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2291                                                             LHS->getName()), I);
2292           return BinaryOperator::CreateAnd(NewAdd, C2);
2293         }
2294       }
2295     }
2296
2297     // Try to fold constant add into select arguments.
2298     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2299       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2300         return R;
2301   }
2302
2303   // add (cast *A to intptrtype) B -> 
2304   //   cast (GEP (cast *A to i8*) B)  -->  intptrtype
2305   {
2306     CastInst *CI = dyn_cast<CastInst>(LHS);
2307     Value *Other = RHS;
2308     if (!CI) {
2309       CI = dyn_cast<CastInst>(RHS);
2310       Other = LHS;
2311     }
2312     if (CI && CI->getType()->isSized() && 
2313         (CI->getType()->getScalarSizeInBits() ==
2314          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2315         && isa<PointerType>(CI->getOperand(0)->getType())) {
2316       unsigned AS =
2317         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2318       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2319                                   Context->getPointerType(Type::Int8Ty, AS), I);
2320       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2321       return new PtrToIntInst(I2, CI->getType());
2322     }
2323   }
2324   
2325   // add (select X 0 (sub n A)) A  -->  select X A n
2326   {
2327     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2328     Value *A = RHS;
2329     if (!SI) {
2330       SI = dyn_cast<SelectInst>(RHS);
2331       A = LHS;
2332     }
2333     if (SI && SI->hasOneUse()) {
2334       Value *TV = SI->getTrueValue();
2335       Value *FV = SI->getFalseValue();
2336       Value *N;
2337
2338       // Can we fold the add into the argument of the select?
2339       // We check both true and false select arguments for a matching subtract.
2340       if (match(FV, m_Zero(), *Context) &&
2341           match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2342         // Fold the add into the true select value.
2343         return SelectInst::Create(SI->getCondition(), N, A);
2344       if (match(TV, m_Zero(), *Context) &&
2345           match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2346         // Fold the add into the false select value.
2347         return SelectInst::Create(SI->getCondition(), A, N);
2348     }
2349   }
2350
2351   // Check for (add (sext x), y), see if we can merge this into an
2352   // integer add followed by a sext.
2353   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2354     // (add (sext x), cst) --> (sext (add x, cst'))
2355     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2356       Constant *CI = 
2357         Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
2358       if (LHSConv->hasOneUse() &&
2359           Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
2360           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2361         // Insert the new, smaller add.
2362         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2363                                                         CI, "addconv");
2364         InsertNewInstBefore(NewAdd, I);
2365         return new SExtInst(NewAdd, I.getType());
2366       }
2367     }
2368     
2369     // (add (sext x), (sext y)) --> (sext (add int x, y))
2370     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2371       // Only do this if x/y have the same type, if at last one of them has a
2372       // single use (so we don't increase the number of sexts), and if the
2373       // integer add will not overflow.
2374       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2375           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2376           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2377                                    RHSConv->getOperand(0))) {
2378         // Insert the new integer add.
2379         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2380                                                         RHSConv->getOperand(0),
2381                                                         "addconv");
2382         InsertNewInstBefore(NewAdd, I);
2383         return new SExtInst(NewAdd, I.getType());
2384       }
2385     }
2386   }
2387
2388   return Changed ? &I : 0;
2389 }
2390
2391 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2392   bool Changed = SimplifyCommutative(I);
2393   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2394
2395   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2396     // X + 0 --> X
2397     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2398       if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
2399                               (I.getType())->getValueAPF()))
2400         return ReplaceInstUsesWith(I, LHS);
2401     }
2402
2403     if (isa<PHINode>(LHS))
2404       if (Instruction *NV = FoldOpIntoPhi(I))
2405         return NV;
2406   }
2407
2408   // -A + B  -->  B - A
2409   // -A + -B  -->  -(A + B)
2410   if (Value *LHSV = dyn_castFNegVal(LHS, Context))
2411     return BinaryOperator::CreateFSub(RHS, LHSV);
2412
2413   // A + -B  -->  A - B
2414   if (!isa<Constant>(RHS))
2415     if (Value *V = dyn_castFNegVal(RHS, Context))
2416       return BinaryOperator::CreateFSub(LHS, V);
2417
2418   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2419   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2420     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2421       return ReplaceInstUsesWith(I, LHS);
2422
2423   // Check for (add double (sitofp x), y), see if we can merge this into an
2424   // integer add followed by a promotion.
2425   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2426     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2427     // ... if the constant fits in the integer value.  This is useful for things
2428     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2429     // requires a constant pool load, and generally allows the add to be better
2430     // instcombined.
2431     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2432       Constant *CI = 
2433       Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
2434       if (LHSConv->hasOneUse() &&
2435           Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
2436           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2437         // Insert the new integer add.
2438         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2439                                                         CI, "addconv");
2440         InsertNewInstBefore(NewAdd, I);
2441         return new SIToFPInst(NewAdd, I.getType());
2442       }
2443     }
2444     
2445     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2446     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2447       // Only do this if x/y have the same type, if at last one of them has a
2448       // single use (so we don't increase the number of int->fp conversions),
2449       // and if the integer add will not overflow.
2450       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2451           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2452           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2453                                    RHSConv->getOperand(0))) {
2454         // Insert the new integer add.
2455         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2456                                                         RHSConv->getOperand(0),
2457                                                         "addconv");
2458         InsertNewInstBefore(NewAdd, I);
2459         return new SIToFPInst(NewAdd, I.getType());
2460       }
2461     }
2462   }
2463   
2464   return Changed ? &I : 0;
2465 }
2466
2467 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2468   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2469
2470   if (Op0 == Op1)                        // sub X, X  -> 0
2471     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2472
2473   // If this is a 'B = x-(-A)', change to B = x+A...
2474   if (Value *V = dyn_castNegVal(Op1, Context))
2475     return BinaryOperator::CreateAdd(Op0, V);
2476
2477   if (isa<UndefValue>(Op0))
2478     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2479   if (isa<UndefValue>(Op1))
2480     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2481
2482   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2483     // Replace (-1 - A) with (~A)...
2484     if (C->isAllOnesValue())
2485       return BinaryOperator::CreateNot(Op1);
2486
2487     // C - ~X == X + (1+C)
2488     Value *X = 0;
2489     if (match(Op1, m_Not(m_Value(X)), *Context))
2490       return BinaryOperator::CreateAdd(X, AddOne(C, Context));
2491
2492     // -(X >>u 31) -> (X >>s 31)
2493     // -(X >>s 31) -> (X >>u 31)
2494     if (C->isZero()) {
2495       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2496         if (SI->getOpcode() == Instruction::LShr) {
2497           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2498             // Check to see if we are shifting out everything but the sign bit.
2499             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2500                 SI->getType()->getPrimitiveSizeInBits()-1) {
2501               // Ok, the transformation is safe.  Insert AShr.
2502               return BinaryOperator::Create(Instruction::AShr, 
2503                                           SI->getOperand(0), CU, SI->getName());
2504             }
2505           }
2506         }
2507         else if (SI->getOpcode() == Instruction::AShr) {
2508           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2509             // Check to see if we are shifting out everything but the sign bit.
2510             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2511                 SI->getType()->getPrimitiveSizeInBits()-1) {
2512               // Ok, the transformation is safe.  Insert LShr. 
2513               return BinaryOperator::CreateLShr(
2514                                           SI->getOperand(0), CU, SI->getName());
2515             }
2516           }
2517         }
2518       }
2519     }
2520
2521     // Try to fold constant sub into select arguments.
2522     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2523       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2524         return R;
2525   }
2526
2527   if (I.getType() == Type::Int1Ty)
2528     return BinaryOperator::CreateXor(Op0, Op1);
2529
2530   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2531     if (Op1I->getOpcode() == Instruction::Add) {
2532       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2533         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2534       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2535         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2536       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2537         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2538           // C1-(X+C2) --> (C1-C2)-X
2539           return BinaryOperator::CreateSub(
2540             Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
2541       }
2542     }
2543
2544     if (Op1I->hasOneUse()) {
2545       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2546       // is not used by anyone else...
2547       //
2548       if (Op1I->getOpcode() == Instruction::Sub) {
2549         // Swap the two operands of the subexpr...
2550         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2551         Op1I->setOperand(0, IIOp1);
2552         Op1I->setOperand(1, IIOp0);
2553
2554         // Create the new top level add instruction...
2555         return BinaryOperator::CreateAdd(Op0, Op1);
2556       }
2557
2558       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2559       //
2560       if (Op1I->getOpcode() == Instruction::And &&
2561           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2562         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2563
2564         Value *NewNot =
2565           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2566         return BinaryOperator::CreateAnd(Op0, NewNot);
2567       }
2568
2569       // 0 - (X sdiv C)  -> (X sdiv -C)
2570       if (Op1I->getOpcode() == Instruction::SDiv)
2571         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2572           if (CSI->isZero())
2573             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2574               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2575                                           Context->getConstantExprNeg(DivRHS));
2576
2577       // X - X*C --> X * (1-C)
2578       ConstantInt *C2 = 0;
2579       if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2580         Constant *CP1 = 
2581           Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
2582                                              C2);
2583         return BinaryOperator::CreateMul(Op0, CP1);
2584       }
2585     }
2586   }
2587
2588   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2589     if (Op0I->getOpcode() == Instruction::Add) {
2590       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2591         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2592       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2593         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2594     } else if (Op0I->getOpcode() == Instruction::Sub) {
2595       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2596         return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2597     }
2598   }
2599
2600   ConstantInt *C1;
2601   if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
2602     if (X == Op1)  // X*C - X --> X * (C-1)
2603       return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
2604
2605     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2606     if (X == dyn_castFoldableMul(Op1, C2, Context))
2607       return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
2608   }
2609   return 0;
2610 }
2611
2612 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2613   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2614
2615   // If this is a 'B = x-(-A)', change to B = x+A...
2616   if (Value *V = dyn_castFNegVal(Op1, Context))
2617     return BinaryOperator::CreateFAdd(Op0, V);
2618
2619   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2620     if (Op1I->getOpcode() == Instruction::FAdd) {
2621       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2622         return BinaryOperator::CreateFNeg(Op1I->getOperand(1), I.getName());
2623       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2624         return BinaryOperator::CreateFNeg(Op1I->getOperand(0), I.getName());
2625     }
2626   }
2627
2628   return 0;
2629 }
2630
2631 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2632 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2633 /// TrueIfSigned if the result of the comparison is true when the input value is
2634 /// signed.
2635 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2636                            bool &TrueIfSigned) {
2637   switch (pred) {
2638   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2639     TrueIfSigned = true;
2640     return RHS->isZero();
2641   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2642     TrueIfSigned = true;
2643     return RHS->isAllOnesValue();
2644   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2645     TrueIfSigned = false;
2646     return RHS->isAllOnesValue();
2647   case ICmpInst::ICMP_UGT:
2648     // True if LHS u> RHS and RHS == high-bit-mask - 1
2649     TrueIfSigned = true;
2650     return RHS->getValue() ==
2651       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2652   case ICmpInst::ICMP_UGE: 
2653     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2654     TrueIfSigned = true;
2655     return RHS->getValue().isSignBit();
2656   default:
2657     return false;
2658   }
2659 }
2660
2661 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2662   bool Changed = SimplifyCommutative(I);
2663   Value *Op0 = I.getOperand(0);
2664
2665   // TODO: If Op1 is undef and Op0 is finite, return zero.
2666   if (!I.getType()->isFPOrFPVector() &&
2667       isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2668     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2669
2670   // Simplify mul instructions with a constant RHS...
2671   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2672     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2673
2674       // ((X << C1)*C2) == (X * (C2 << C1))
2675       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2676         if (SI->getOpcode() == Instruction::Shl)
2677           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2678             return BinaryOperator::CreateMul(SI->getOperand(0),
2679                                         Context->getConstantExprShl(CI, ShOp));
2680
2681       if (CI->isZero())
2682         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2683       if (CI->equalsInt(1))                  // X * 1  == X
2684         return ReplaceInstUsesWith(I, Op0);
2685       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2686         return BinaryOperator::CreateNeg(Op0, I.getName());
2687
2688       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2689       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2690         return BinaryOperator::CreateShl(Op0,
2691                  Context->getConstantInt(Op0->getType(), Val.logBase2()));
2692       }
2693     } else if (isa<VectorType>(Op1->getType())) {
2694       // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
2695
2696       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2697         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2698           return BinaryOperator::CreateNeg(Op0, I.getName());
2699
2700         // As above, vector X*splat(1.0) -> X in all defined cases.
2701         if (Constant *Splat = Op1V->getSplatValue()) {
2702           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2703             if (CI->equalsInt(1))
2704               return ReplaceInstUsesWith(I, Op0);
2705         }
2706       }
2707     }
2708     
2709     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2710       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2711           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2712         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2713         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2714                                                      Op1, "tmp");
2715         InsertNewInstBefore(Add, I);
2716         Value *C1C2 = Context->getConstantExprMul(Op1, 
2717                                            cast<Constant>(Op0I->getOperand(1)));
2718         return BinaryOperator::CreateAdd(Add, C1C2);
2719         
2720       }
2721
2722     // Try to fold constant mul into select arguments.
2723     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2724       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2725         return R;
2726
2727     if (isa<PHINode>(Op0))
2728       if (Instruction *NV = FoldOpIntoPhi(I))
2729         return NV;
2730   }
2731
2732   if (Value *Op0v = dyn_castNegVal(Op0, Context))     // -X * -Y = X*Y
2733     if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
2734       return BinaryOperator::CreateMul(Op0v, Op1v);
2735
2736   // (X / Y) *  Y = X - (X % Y)
2737   // (X / Y) * -Y = (X % Y) - X
2738   {
2739     Value *Op1 = I.getOperand(1);
2740     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2741     if (!BO ||
2742         (BO->getOpcode() != Instruction::UDiv && 
2743          BO->getOpcode() != Instruction::SDiv)) {
2744       Op1 = Op0;
2745       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2746     }
2747     Value *Neg = dyn_castNegVal(Op1, Context);
2748     if (BO && BO->hasOneUse() &&
2749         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2750         (BO->getOpcode() == Instruction::UDiv ||
2751          BO->getOpcode() == Instruction::SDiv)) {
2752       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2753
2754       Instruction *Rem;
2755       if (BO->getOpcode() == Instruction::UDiv)
2756         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2757       else
2758         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2759
2760       InsertNewInstBefore(Rem, I);
2761       Rem->takeName(BO);
2762
2763       if (Op1BO == Op1)
2764         return BinaryOperator::CreateSub(Op0BO, Rem);
2765       else
2766         return BinaryOperator::CreateSub(Rem, Op0BO);
2767     }
2768   }
2769
2770   if (I.getType() == Type::Int1Ty)
2771     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2772
2773   // If one of the operands of the multiply is a cast from a boolean value, then
2774   // we know the bool is either zero or one, so this is a 'masking' multiply.
2775   // See if we can simplify things based on how the boolean was originally
2776   // formed.
2777   CastInst *BoolCast = 0;
2778   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2779     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2780       BoolCast = CI;
2781   if (!BoolCast)
2782     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2783       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2784         BoolCast = CI;
2785   if (BoolCast) {
2786     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2787       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2788       const Type *SCOpTy = SCIOp0->getType();
2789       bool TIS = false;
2790       
2791       // If the icmp is true iff the sign bit of X is set, then convert this
2792       // multiply into a shift/and combination.
2793       if (isa<ConstantInt>(SCIOp1) &&
2794           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2795           TIS) {
2796         // Shift the X value right to turn it into "all signbits".
2797         Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
2798                                           SCOpTy->getPrimitiveSizeInBits()-1);
2799         Value *V =
2800           InsertNewInstBefore(
2801             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2802                                             BoolCast->getOperand(0)->getName()+
2803                                             ".mask"), I);
2804
2805         // If the multiply type is not the same as the source type, sign extend
2806         // or truncate to the multiply type.
2807         if (I.getType() != V->getType()) {
2808           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2809           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2810           Instruction::CastOps opcode = 
2811             (SrcBits == DstBits ? Instruction::BitCast : 
2812              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2813           V = InsertCastBefore(opcode, V, I.getType(), I);
2814         }
2815
2816         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2817         return BinaryOperator::CreateAnd(V, OtherOp);
2818       }
2819     }
2820   }
2821
2822   return Changed ? &I : 0;
2823 }
2824
2825 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2826   bool Changed = SimplifyCommutative(I);
2827   Value *Op0 = I.getOperand(0);
2828
2829   // Simplify mul instructions with a constant RHS...
2830   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2831     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2832       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2833       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2834       if (Op1F->isExactlyValue(1.0))
2835         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2836     } else if (isa<VectorType>(Op1->getType())) {
2837       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2838         // As above, vector X*splat(1.0) -> X in all defined cases.
2839         if (Constant *Splat = Op1V->getSplatValue()) {
2840           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2841             if (F->isExactlyValue(1.0))
2842               return ReplaceInstUsesWith(I, Op0);
2843         }
2844       }
2845     }
2846
2847     // Try to fold constant mul into select arguments.
2848     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2849       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2850         return R;
2851
2852     if (isa<PHINode>(Op0))
2853       if (Instruction *NV = FoldOpIntoPhi(I))
2854         return NV;
2855   }
2856
2857   if (Value *Op0v = dyn_castFNegVal(Op0, Context))     // -X * -Y = X*Y
2858     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
2859       return BinaryOperator::CreateFMul(Op0v, Op1v);
2860
2861   return Changed ? &I : 0;
2862 }
2863
2864 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2865 /// instruction.
2866 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2867   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2868   
2869   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2870   int NonNullOperand = -1;
2871   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2872     if (ST->isNullValue())
2873       NonNullOperand = 2;
2874   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2875   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2876     if (ST->isNullValue())
2877       NonNullOperand = 1;
2878   
2879   if (NonNullOperand == -1)
2880     return false;
2881   
2882   Value *SelectCond = SI->getOperand(0);
2883   
2884   // Change the div/rem to use 'Y' instead of the select.
2885   I.setOperand(1, SI->getOperand(NonNullOperand));
2886   
2887   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2888   // problem.  However, the select, or the condition of the select may have
2889   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2890   // propagate the known value for the select into other uses of it, and
2891   // propagate a known value of the condition into its other users.
2892   
2893   // If the select and condition only have a single use, don't bother with this,
2894   // early exit.
2895   if (SI->use_empty() && SelectCond->hasOneUse())
2896     return true;
2897   
2898   // Scan the current block backward, looking for other uses of SI.
2899   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2900   
2901   while (BBI != BBFront) {
2902     --BBI;
2903     // If we found a call to a function, we can't assume it will return, so
2904     // information from below it cannot be propagated above it.
2905     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2906       break;
2907     
2908     // Replace uses of the select or its condition with the known values.
2909     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2910          I != E; ++I) {
2911       if (*I == SI) {
2912         *I = SI->getOperand(NonNullOperand);
2913         AddToWorkList(BBI);
2914       } else if (*I == SelectCond) {
2915         *I = NonNullOperand == 1 ? Context->getConstantIntTrue() :
2916                                    Context->getConstantIntFalse();
2917         AddToWorkList(BBI);
2918       }
2919     }
2920     
2921     // If we past the instruction, quit looking for it.
2922     if (&*BBI == SI)
2923       SI = 0;
2924     if (&*BBI == SelectCond)
2925       SelectCond = 0;
2926     
2927     // If we ran out of things to eliminate, break out of the loop.
2928     if (SelectCond == 0 && SI == 0)
2929       break;
2930     
2931   }
2932   return true;
2933 }
2934
2935
2936 /// This function implements the transforms on div instructions that work
2937 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2938 /// used by the visitors to those instructions.
2939 /// @brief Transforms common to all three div instructions
2940 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2941   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2942
2943   // undef / X -> 0        for integer.
2944   // undef / X -> undef    for FP (the undef could be a snan).
2945   if (isa<UndefValue>(Op0)) {
2946     if (Op0->getType()->isFPOrFPVector())
2947       return ReplaceInstUsesWith(I, Op0);
2948     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2949   }
2950
2951   // X / undef -> undef
2952   if (isa<UndefValue>(Op1))
2953     return ReplaceInstUsesWith(I, Op1);
2954
2955   return 0;
2956 }
2957
2958 /// This function implements the transforms common to both integer division
2959 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2960 /// division instructions.
2961 /// @brief Common integer divide transforms
2962 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2963   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2964
2965   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2966   if (Op0 == Op1) {
2967     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2968       Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
2969       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2970       return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
2971     }
2972
2973     Constant *CI = Context->getConstantInt(I.getType(), 1);
2974     return ReplaceInstUsesWith(I, CI);
2975   }
2976   
2977   if (Instruction *Common = commonDivTransforms(I))
2978     return Common;
2979   
2980   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2981   // This does not apply for fdiv.
2982   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2983     return &I;
2984
2985   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2986     // div X, 1 == X
2987     if (RHS->equalsInt(1))
2988       return ReplaceInstUsesWith(I, Op0);
2989
2990     // (X / C1) / C2  -> X / (C1*C2)
2991     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2992       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2993         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2994           if (MultiplyOverflows(RHS, LHSRHS,
2995                                 I.getOpcode()==Instruction::SDiv, Context))
2996             return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2997           else 
2998             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2999                                       Context->getConstantExprMul(RHS, LHSRHS));
3000         }
3001
3002     if (!RHS->isZero()) { // avoid X udiv 0
3003       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3004         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3005           return R;
3006       if (isa<PHINode>(Op0))
3007         if (Instruction *NV = FoldOpIntoPhi(I))
3008           return NV;
3009     }
3010   }
3011
3012   // 0 / X == 0, we don't need to preserve faults!
3013   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3014     if (LHS->equalsInt(0))
3015       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3016
3017   // It can't be division by zero, hence it must be division by one.
3018   if (I.getType() == Type::Int1Ty)
3019     return ReplaceInstUsesWith(I, Op0);
3020
3021   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3022     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3023       // div X, 1 == X
3024       if (X->isOne())
3025         return ReplaceInstUsesWith(I, Op0);
3026   }
3027
3028   return 0;
3029 }
3030
3031 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3032   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3033
3034   // Handle the integer div common cases
3035   if (Instruction *Common = commonIDivTransforms(I))
3036     return Common;
3037
3038   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3039     // X udiv C^2 -> X >> C
3040     // Check to see if this is an unsigned division with an exact power of 2,
3041     // if so, convert to a right shift.
3042     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3043       return BinaryOperator::CreateLShr(Op0, 
3044             Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
3045
3046     // X udiv C, where C >= signbit
3047     if (C->getValue().isNegative()) {
3048       Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3049                                                     ICmpInst::ICMP_ULT, Op0, C),
3050                                       I);
3051       return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3052                                 Context->getConstantInt(I.getType(), 1));
3053     }
3054   }
3055
3056   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3057   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3058     if (RHSI->getOpcode() == Instruction::Shl &&
3059         isa<ConstantInt>(RHSI->getOperand(0))) {
3060       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3061       if (C1.isPowerOf2()) {
3062         Value *N = RHSI->getOperand(1);
3063         const Type *NTy = N->getType();
3064         if (uint32_t C2 = C1.logBase2()) {
3065           Constant *C2V = Context->getConstantInt(NTy, C2);
3066           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3067         }
3068         return BinaryOperator::CreateLShr(Op0, N);
3069       }
3070     }
3071   }
3072   
3073   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3074   // where C1&C2 are powers of two.
3075   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3076     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3077       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3078         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3079         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3080           // Compute the shift amounts
3081           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3082           // Construct the "on true" case of the select
3083           Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
3084           Instruction *TSI = BinaryOperator::CreateLShr(
3085                                                  Op0, TC, SI->getName()+".t");
3086           TSI = InsertNewInstBefore(TSI, I);
3087   
3088           // Construct the "on false" case of the select
3089           Constant *FC = Context->getConstantInt(Op0->getType(), FSA); 
3090           Instruction *FSI = BinaryOperator::CreateLShr(
3091                                                  Op0, FC, SI->getName()+".f");
3092           FSI = InsertNewInstBefore(FSI, I);
3093
3094           // construct the select instruction and return it.
3095           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3096         }
3097       }
3098   return 0;
3099 }
3100
3101 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3102   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3103
3104   // Handle the integer div common cases
3105   if (Instruction *Common = commonIDivTransforms(I))
3106     return Common;
3107
3108   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3109     // sdiv X, -1 == -X
3110     if (RHS->isAllOnesValue())
3111       return BinaryOperator::CreateNeg(Op0);
3112   }
3113
3114   // If the sign bits of both operands are zero (i.e. we can prove they are
3115   // unsigned inputs), turn this into a udiv.
3116   if (I.getType()->isInteger()) {
3117     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3118     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3119       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3120       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3121     }
3122   }      
3123   
3124   return 0;
3125 }
3126
3127 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3128   return commonDivTransforms(I);
3129 }
3130
3131 /// This function implements the transforms on rem instructions that work
3132 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3133 /// is used by the visitors to those instructions.
3134 /// @brief Transforms common to all three rem instructions
3135 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3136   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3137
3138   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3139     if (I.getType()->isFPOrFPVector())
3140       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3141     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3142   }
3143   if (isa<UndefValue>(Op1))
3144     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3145
3146   // Handle cases involving: rem X, (select Cond, Y, Z)
3147   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3148     return &I;
3149
3150   return 0;
3151 }
3152
3153 /// This function implements the transforms common to both integer remainder
3154 /// instructions (urem and srem). It is called by the visitors to those integer
3155 /// remainder instructions.
3156 /// @brief Common integer remainder transforms
3157 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3158   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3159
3160   if (Instruction *common = commonRemTransforms(I))
3161     return common;
3162
3163   // 0 % X == 0 for integer, we don't need to preserve faults!
3164   if (Constant *LHS = dyn_cast<Constant>(Op0))
3165     if (LHS->isNullValue())
3166       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3167
3168   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3169     // X % 0 == undef, we don't need to preserve faults!
3170     if (RHS->equalsInt(0))
3171       return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
3172     
3173     if (RHS->equalsInt(1))  // X % 1 == 0
3174       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3175
3176     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3177       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3178         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3179           return R;
3180       } else if (isa<PHINode>(Op0I)) {
3181         if (Instruction *NV = FoldOpIntoPhi(I))
3182           return NV;
3183       }
3184
3185       // See if we can fold away this rem instruction.
3186       if (SimplifyDemandedInstructionBits(I))
3187         return &I;
3188     }
3189   }
3190
3191   return 0;
3192 }
3193
3194 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3195   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3196
3197   if (Instruction *common = commonIRemTransforms(I))
3198     return common;
3199   
3200   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3201     // X urem C^2 -> X and C
3202     // Check to see if this is an unsigned remainder with an exact power of 2,
3203     // if so, convert to a bitwise and.
3204     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3205       if (C->getValue().isPowerOf2())
3206         return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
3207   }
3208
3209   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3210     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3211     if (RHSI->getOpcode() == Instruction::Shl &&
3212         isa<ConstantInt>(RHSI->getOperand(0))) {
3213       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3214         Constant *N1 = Context->getConstantIntAllOnesValue(I.getType());
3215         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3216                                                                    "tmp"), I);
3217         return BinaryOperator::CreateAnd(Op0, Add);
3218       }
3219     }
3220   }
3221
3222   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3223   // where C1&C2 are powers of two.
3224   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3225     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3226       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3227         // STO == 0 and SFO == 0 handled above.
3228         if ((STO->getValue().isPowerOf2()) && 
3229             (SFO->getValue().isPowerOf2())) {
3230           Value *TrueAnd = InsertNewInstBefore(
3231             BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3232                                       SI->getName()+".t"), I);
3233           Value *FalseAnd = InsertNewInstBefore(
3234             BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3235                                       SI->getName()+".f"), I);
3236           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3237         }
3238       }
3239   }
3240   
3241   return 0;
3242 }
3243
3244 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3245   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3246
3247   // Handle the integer rem common cases
3248   if (Instruction *common = commonIRemTransforms(I))
3249     return common;
3250   
3251   if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
3252     if (!isa<Constant>(RHSNeg) ||
3253         (isa<ConstantInt>(RHSNeg) &&
3254          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3255       // X % -Y -> X % Y
3256       AddUsesToWorkList(I);
3257       I.setOperand(1, RHSNeg);
3258       return &I;
3259     }
3260
3261   // If the sign bits of both operands are zero (i.e. we can prove they are
3262   // unsigned inputs), turn this into a urem.
3263   if (I.getType()->isInteger()) {
3264     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3265     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3266       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3267       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3268     }
3269   }
3270
3271   // If it's a constant vector, flip any negative values positive.
3272   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3273     unsigned VWidth = RHSV->getNumOperands();
3274
3275     bool hasNegative = false;
3276     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3277       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3278         if (RHS->getValue().isNegative())
3279           hasNegative = true;
3280
3281     if (hasNegative) {
3282       std::vector<Constant *> Elts(VWidth);
3283       for (unsigned i = 0; i != VWidth; ++i) {
3284         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3285           if (RHS->getValue().isNegative())
3286             Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
3287           else
3288             Elts[i] = RHS;
3289         }
3290       }
3291
3292       Constant *NewRHSV = Context->getConstantVector(Elts);
3293       if (NewRHSV != RHSV) {
3294         AddUsesToWorkList(I);
3295         I.setOperand(1, NewRHSV);
3296         return &I;
3297       }
3298     }
3299   }
3300
3301   return 0;
3302 }
3303
3304 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3305   return commonRemTransforms(I);
3306 }
3307
3308 // isOneBitSet - Return true if there is exactly one bit set in the specified
3309 // constant.
3310 static bool isOneBitSet(const ConstantInt *CI) {
3311   return CI->getValue().isPowerOf2();
3312 }
3313
3314 // isHighOnes - Return true if the constant is of the form 1+0+.
3315 // This is the same as lowones(~X).
3316 static bool isHighOnes(const ConstantInt *CI) {
3317   return (~CI->getValue() + 1).isPowerOf2();
3318 }
3319
3320 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3321 /// are carefully arranged to allow folding of expressions such as:
3322 ///
3323 ///      (A < B) | (A > B) --> (A != B)
3324 ///
3325 /// Note that this is only valid if the first and second predicates have the
3326 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3327 ///
3328 /// Three bits are used to represent the condition, as follows:
3329 ///   0  A > B
3330 ///   1  A == B
3331 ///   2  A < B
3332 ///
3333 /// <=>  Value  Definition
3334 /// 000     0   Always false
3335 /// 001     1   A >  B
3336 /// 010     2   A == B
3337 /// 011     3   A >= B
3338 /// 100     4   A <  B
3339 /// 101     5   A != B
3340 /// 110     6   A <= B
3341 /// 111     7   Always true
3342 ///  
3343 static unsigned getICmpCode(const ICmpInst *ICI) {
3344   switch (ICI->getPredicate()) {
3345     // False -> 0
3346   case ICmpInst::ICMP_UGT: return 1;  // 001
3347   case ICmpInst::ICMP_SGT: return 1;  // 001
3348   case ICmpInst::ICMP_EQ:  return 2;  // 010
3349   case ICmpInst::ICMP_UGE: return 3;  // 011
3350   case ICmpInst::ICMP_SGE: return 3;  // 011
3351   case ICmpInst::ICMP_ULT: return 4;  // 100
3352   case ICmpInst::ICMP_SLT: return 4;  // 100
3353   case ICmpInst::ICMP_NE:  return 5;  // 101
3354   case ICmpInst::ICMP_ULE: return 6;  // 110
3355   case ICmpInst::ICMP_SLE: return 6;  // 110
3356     // True -> 7
3357   default:
3358     LLVM_UNREACHABLE("Invalid ICmp predicate!");
3359     return 0;
3360   }
3361 }
3362
3363 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3364 /// predicate into a three bit mask. It also returns whether it is an ordered
3365 /// predicate by reference.
3366 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3367   isOrdered = false;
3368   switch (CC) {
3369   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3370   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3371   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3372   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3373   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3374   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3375   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3376   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3377   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3378   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3379   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3380   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3381   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3382   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3383     // True -> 7
3384   default:
3385     // Not expecting FCMP_FALSE and FCMP_TRUE;
3386     LLVM_UNREACHABLE("Unexpected FCmp predicate!");
3387     return 0;
3388   }
3389 }
3390
3391 /// getICmpValue - This is the complement of getICmpCode, which turns an
3392 /// opcode and two operands into either a constant true or false, or a brand 
3393 /// new ICmp instruction. The sign is passed in to determine which kind
3394 /// of predicate to use in the new icmp instruction.
3395 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3396                            LLVMContext *Context) {
3397   switch (code) {
3398   default: LLVM_UNREACHABLE("Illegal ICmp code!");
3399   case  0: return Context->getConstantIntFalse();
3400   case  1: 
3401     if (sign)
3402       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
3403     else
3404       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3405   case  2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ,  LHS, RHS);
3406   case  3: 
3407     if (sign)
3408       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
3409     else
3410       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
3411   case  4: 
3412     if (sign)
3413       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
3414     else
3415       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3416   case  5: return new ICmpInst(*Context, ICmpInst::ICMP_NE,  LHS, RHS);
3417   case  6: 
3418     if (sign)
3419       return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
3420     else
3421       return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
3422   case  7: return Context->getConstantIntTrue();
3423   }
3424 }
3425
3426 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3427 /// opcode and two operands into either a FCmp instruction. isordered is passed
3428 /// in to determine which kind of predicate to use in the new fcmp instruction.
3429 static Value *getFCmpValue(bool isordered, unsigned code,
3430                            Value *LHS, Value *RHS, LLVMContext *Context) {
3431   switch (code) {
3432   default: LLVM_UNREACHABLE("Illegal FCmp code!");
3433   case  0:
3434     if (isordered)
3435       return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
3436     else
3437       return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
3438   case  1: 
3439     if (isordered)
3440       return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
3441     else
3442       return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
3443   case  2: 
3444     if (isordered)
3445       return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
3446     else
3447       return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
3448   case  3: 
3449     if (isordered)
3450       return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
3451     else
3452       return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
3453   case  4: 
3454     if (isordered)
3455       return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
3456     else
3457       return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
3458   case  5: 
3459     if (isordered)
3460       return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
3461     else
3462       return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
3463   case  6: 
3464     if (isordered)
3465       return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
3466     else
3467       return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
3468   case  7: return Context->getConstantIntTrue();
3469   }
3470 }
3471
3472 /// PredicatesFoldable - Return true if both predicates match sign or if at
3473 /// least one of them is an equality comparison (which is signless).
3474 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3475   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3476          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3477          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3478 }
3479
3480 namespace { 
3481 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3482 struct FoldICmpLogical {
3483   InstCombiner &IC;
3484   Value *LHS, *RHS;
3485   ICmpInst::Predicate pred;
3486   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3487     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3488       pred(ICI->getPredicate()) {}
3489   bool shouldApply(Value *V) const {
3490     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3491       if (PredicatesFoldable(pred, ICI->getPredicate()))
3492         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3493                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3494     return false;
3495   }
3496   Instruction *apply(Instruction &Log) const {
3497     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3498     if (ICI->getOperand(0) != LHS) {
3499       assert(ICI->getOperand(1) == LHS);
3500       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3501     }
3502
3503     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3504     unsigned LHSCode = getICmpCode(ICI);
3505     unsigned RHSCode = getICmpCode(RHSICI);
3506     unsigned Code;
3507     switch (Log.getOpcode()) {
3508     case Instruction::And: Code = LHSCode & RHSCode; break;
3509     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3510     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3511     default: LLVM_UNREACHABLE("Illegal logical opcode!"); return 0;
3512     }
3513
3514     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3515                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3516       
3517     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3518     if (Instruction *I = dyn_cast<Instruction>(RV))
3519       return I;
3520     // Otherwise, it's a constant boolean value...
3521     return IC.ReplaceInstUsesWith(Log, RV);
3522   }
3523 };
3524 } // end anonymous namespace
3525
3526 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3527 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3528 // guaranteed to be a binary operator.
3529 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3530                                     ConstantInt *OpRHS,
3531                                     ConstantInt *AndRHS,
3532                                     BinaryOperator &TheAnd) {
3533   Value *X = Op->getOperand(0);
3534   Constant *Together = 0;
3535   if (!Op->isShift())
3536     Together = Context->getConstantExprAnd(AndRHS, OpRHS);
3537
3538   switch (Op->getOpcode()) {
3539   case Instruction::Xor:
3540     if (Op->hasOneUse()) {
3541       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3542       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3543       InsertNewInstBefore(And, TheAnd);
3544       And->takeName(Op);
3545       return BinaryOperator::CreateXor(And, Together);
3546     }
3547     break;
3548   case Instruction::Or:
3549     if (Together == AndRHS) // (X | C) & C --> C
3550       return ReplaceInstUsesWith(TheAnd, AndRHS);
3551
3552     if (Op->hasOneUse() && Together != OpRHS) {
3553       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3554       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3555       InsertNewInstBefore(Or, TheAnd);
3556       Or->takeName(Op);
3557       return BinaryOperator::CreateAnd(Or, AndRHS);
3558     }
3559     break;
3560   case Instruction::Add:
3561     if (Op->hasOneUse()) {
3562       // Adding a one to a single bit bit-field should be turned into an XOR
3563       // of the bit.  First thing to check is to see if this AND is with a
3564       // single bit constant.
3565       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3566
3567       // If there is only one bit set...
3568       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3569         // Ok, at this point, we know that we are masking the result of the
3570         // ADD down to exactly one bit.  If the constant we are adding has
3571         // no bits set below this bit, then we can eliminate the ADD.
3572         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3573
3574         // Check to see if any bits below the one bit set in AndRHSV are set.
3575         if ((AddRHS & (AndRHSV-1)) == 0) {
3576           // If not, the only thing that can effect the output of the AND is
3577           // the bit specified by AndRHSV.  If that bit is set, the effect of
3578           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3579           // no effect.
3580           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3581             TheAnd.setOperand(0, X);
3582             return &TheAnd;
3583           } else {
3584             // Pull the XOR out of the AND.
3585             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3586             InsertNewInstBefore(NewAnd, TheAnd);
3587             NewAnd->takeName(Op);
3588             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3589           }
3590         }
3591       }
3592     }
3593     break;
3594
3595   case Instruction::Shl: {
3596     // We know that the AND will not produce any of the bits shifted in, so if
3597     // the anded constant includes them, clear them now!
3598     //
3599     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3600     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3601     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3602     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
3603
3604     if (CI->getValue() == ShlMask) { 
3605     // Masking out bits that the shift already masks
3606       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3607     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3608       TheAnd.setOperand(1, CI);
3609       return &TheAnd;
3610     }
3611     break;
3612   }
3613   case Instruction::LShr:
3614   {
3615     // We know that the AND will not produce any of the bits shifted in, so if
3616     // the anded constant includes them, clear them now!  This only applies to
3617     // unsigned shifts, because a signed shr may bring in set bits!
3618     //
3619     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3620     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3621     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3622     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3623
3624     if (CI->getValue() == ShrMask) {   
3625     // Masking out bits that the shift already masks.
3626       return ReplaceInstUsesWith(TheAnd, Op);
3627     } else if (CI != AndRHS) {
3628       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3629       return &TheAnd;
3630     }
3631     break;
3632   }
3633   case Instruction::AShr:
3634     // Signed shr.
3635     // See if this is shifting in some sign extension, then masking it out
3636     // with an and.
3637     if (Op->hasOneUse()) {
3638       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3639       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3640       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3641       Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3642       if (C == AndRHS) {          // Masking out bits shifted in.
3643         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3644         // Make the argument unsigned.
3645         Value *ShVal = Op->getOperand(0);
3646         ShVal = InsertNewInstBefore(
3647             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3648                                    Op->getName()), TheAnd);
3649         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3650       }
3651     }
3652     break;
3653   }
3654   return 0;
3655 }
3656
3657
3658 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3659 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3660 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3661 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3662 /// insert new instructions.
3663 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3664                                            bool isSigned, bool Inside, 
3665                                            Instruction &IB) {
3666   assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ? 
3667             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3668          "Lo is not <= Hi in range emission code!");
3669     
3670   if (Inside) {
3671     if (Lo == Hi)  // Trivially false.
3672       return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
3673
3674     // V >= Min && V < Hi --> V < Hi
3675     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3676       ICmpInst::Predicate pred = (isSigned ? 
3677         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3678       return new ICmpInst(*Context, pred, V, Hi);
3679     }
3680
3681     // Emit V-Lo <u Hi-Lo
3682     Constant *NegLo = Context->getConstantExprNeg(Lo);
3683     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3684     InsertNewInstBefore(Add, IB);
3685     Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
3686     return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
3687   }
3688
3689   if (Lo == Hi)  // Trivially true.
3690     return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
3691
3692   // V < Min || V >= Hi -> V > Hi-1
3693   Hi = SubOne(cast<ConstantInt>(Hi), Context);
3694   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3695     ICmpInst::Predicate pred = (isSigned ? 
3696         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3697     return new ICmpInst(*Context, pred, V, Hi);
3698   }
3699
3700   // Emit V-Lo >u Hi-1-Lo
3701   // Note that Hi has already had one subtracted from it, above.
3702   ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
3703   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3704   InsertNewInstBefore(Add, IB);
3705   Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
3706   return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
3707 }
3708
3709 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3710 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3711 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3712 // not, since all 1s are not contiguous.
3713 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3714   const APInt& V = Val->getValue();
3715   uint32_t BitWidth = Val->getType()->getBitWidth();
3716   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3717
3718   // look for the first zero bit after the run of ones
3719   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3720   // look for the first non-zero bit
3721   ME = V.getActiveBits(); 
3722   return true;
3723 }
3724
3725 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3726 /// where isSub determines whether the operator is a sub.  If we can fold one of
3727 /// the following xforms:
3728 /// 
3729 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3730 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3731 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3732 ///
3733 /// return (A +/- B).
3734 ///
3735 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3736                                         ConstantInt *Mask, bool isSub,
3737                                         Instruction &I) {
3738   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3739   if (!LHSI || LHSI->getNumOperands() != 2 ||
3740       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3741
3742   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3743
3744   switch (LHSI->getOpcode()) {
3745   default: return 0;
3746   case Instruction::And:
3747     if (Context->getConstantExprAnd(N, Mask) == Mask) {
3748       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3749       if ((Mask->getValue().countLeadingZeros() + 
3750            Mask->getValue().countPopulation()) == 
3751           Mask->getValue().getBitWidth())
3752         break;
3753
3754       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3755       // part, we don't need any explicit masks to take them out of A.  If that
3756       // is all N is, ignore it.
3757       uint32_t MB = 0, ME = 0;
3758       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3759         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3760         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3761         if (MaskedValueIsZero(RHS, Mask))
3762           break;
3763       }
3764     }
3765     return 0;
3766   case Instruction::Or:
3767   case Instruction::Xor:
3768     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3769     if ((Mask->getValue().countLeadingZeros() + 
3770          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3771         && Context->getConstantExprAnd(N, Mask)->isNullValue())
3772       break;
3773     return 0;
3774   }
3775   
3776   Instruction *New;
3777   if (isSub)
3778     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3779   else
3780     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3781   return InsertNewInstBefore(New, I);
3782 }
3783
3784 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3785 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3786                                           ICmpInst *LHS, ICmpInst *RHS) {
3787   Value *Val, *Val2;
3788   ConstantInt *LHSCst, *RHSCst;
3789   ICmpInst::Predicate LHSCC, RHSCC;
3790   
3791   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3792   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3793                          m_ConstantInt(LHSCst)), *Context) ||
3794       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3795                          m_ConstantInt(RHSCst)), *Context))
3796     return 0;
3797   
3798   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3799   // where C is a power of 2
3800   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3801       LHSCst->getValue().isPowerOf2()) {
3802     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3803     InsertNewInstBefore(NewOr, I);
3804     return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
3805   }
3806   
3807   // From here on, we only handle:
3808   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3809   if (Val != Val2) return 0;
3810   
3811   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3812   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3813       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3814       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3815       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3816     return 0;
3817   
3818   // We can't fold (ugt x, C) & (sgt x, C2).
3819   if (!PredicatesFoldable(LHSCC, RHSCC))
3820     return 0;
3821     
3822   // Ensure that the larger constant is on the RHS.
3823   bool ShouldSwap;
3824   if (ICmpInst::isSignedPredicate(LHSCC) ||
3825       (ICmpInst::isEquality(LHSCC) && 
3826        ICmpInst::isSignedPredicate(RHSCC)))
3827     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3828   else
3829     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3830     
3831   if (ShouldSwap) {
3832     std::swap(LHS, RHS);
3833     std::swap(LHSCst, RHSCst);
3834     std::swap(LHSCC, RHSCC);
3835   }
3836
3837   // At this point, we know we have have two icmp instructions
3838   // comparing a value against two constants and and'ing the result
3839   // together.  Because of the above check, we know that we only have
3840   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3841   // (from the FoldICmpLogical check above), that the two constants 
3842   // are not equal and that the larger constant is on the RHS
3843   assert(LHSCst != RHSCst && "Compares not folded above?");
3844
3845   switch (LHSCC) {
3846   default: LLVM_UNREACHABLE("Unknown integer condition code!");
3847   case ICmpInst::ICMP_EQ:
3848     switch (RHSCC) {
3849     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3850     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3851     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3852     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3853       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3854     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3855     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3856     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3857       return ReplaceInstUsesWith(I, LHS);
3858     }
3859   case ICmpInst::ICMP_NE:
3860     switch (RHSCC) {
3861     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3862     case ICmpInst::ICMP_ULT:
3863       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
3864         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
3865       break;                        // (X != 13 & X u< 15) -> no change
3866     case ICmpInst::ICMP_SLT:
3867       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
3868         return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
3869       break;                        // (X != 13 & X s< 15) -> no change
3870     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3871     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3872     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3873       return ReplaceInstUsesWith(I, RHS);
3874     case ICmpInst::ICMP_NE:
3875       if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3876         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
3877         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3878                                                      Val->getName()+".off");
3879         InsertNewInstBefore(Add, I);
3880         return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
3881                             Context->getConstantInt(Add->getType(), 1));
3882       }
3883       break;                        // (X != 13 & X != 15) -> no change
3884     }
3885     break;
3886   case ICmpInst::ICMP_ULT:
3887     switch (RHSCC) {
3888     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3889     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3890     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3891       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3892     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3893       break;
3894     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3895     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3896       return ReplaceInstUsesWith(I, LHS);
3897     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3898       break;
3899     }
3900     break;
3901   case ICmpInst::ICMP_SLT:
3902     switch (RHSCC) {
3903     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3904     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3905     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3906       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3907     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3908       break;
3909     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3910     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3911       return ReplaceInstUsesWith(I, LHS);
3912     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3913       break;
3914     }
3915     break;
3916   case ICmpInst::ICMP_UGT:
3917     switch (RHSCC) {
3918     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3919     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3920     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3921       return ReplaceInstUsesWith(I, RHS);
3922     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3923       break;
3924     case ICmpInst::ICMP_NE:
3925       if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
3926         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3927       break;                        // (X u> 13 & X != 15) -> no change
3928     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3929       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3930                              RHSCst, false, true, I);
3931     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3932       break;
3933     }
3934     break;
3935   case ICmpInst::ICMP_SGT:
3936     switch (RHSCC) {
3937     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3938     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3939     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3940       return ReplaceInstUsesWith(I, RHS);
3941     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3942       break;
3943     case ICmpInst::ICMP_NE:
3944       if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
3945         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3946       break;                        // (X s> 13 & X != 15) -> no change
3947     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3948       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3949                              RHSCst, true, true, I);
3950     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3951       break;
3952     }
3953     break;
3954   }
3955  
3956   return 0;
3957 }
3958
3959
3960 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3961   bool Changed = SimplifyCommutative(I);
3962   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3963
3964   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3965     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3966
3967   // and X, X = X
3968   if (Op0 == Op1)
3969     return ReplaceInstUsesWith(I, Op1);
3970
3971   // See if we can simplify any instructions used by the instruction whose sole 
3972   // purpose is to compute bits we don't care about.
3973   if (SimplifyDemandedInstructionBits(I))
3974     return &I;
3975   if (isa<VectorType>(I.getType())) {
3976     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3977       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3978         return ReplaceInstUsesWith(I, I.getOperand(0));
3979     } else if (isa<ConstantAggregateZero>(Op1)) {
3980       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3981     }
3982   }
3983
3984   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3985     const APInt& AndRHSMask = AndRHS->getValue();
3986     APInt NotAndRHS(~AndRHSMask);
3987
3988     // Optimize a variety of ((val OP C1) & C2) combinations...
3989     if (isa<BinaryOperator>(Op0)) {
3990       Instruction *Op0I = cast<Instruction>(Op0);
3991       Value *Op0LHS = Op0I->getOperand(0);
3992       Value *Op0RHS = Op0I->getOperand(1);
3993       switch (Op0I->getOpcode()) {
3994       case Instruction::Xor:
3995       case Instruction::Or:
3996         // If the mask is only needed on one incoming arm, push it up.
3997         if (Op0I->hasOneUse()) {
3998           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3999             // Not masking anything out for the LHS, move to RHS.
4000             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4001                                                    Op0RHS->getName()+".masked");
4002             InsertNewInstBefore(NewRHS, I);
4003             return BinaryOperator::Create(
4004                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4005           }
4006           if (!isa<Constant>(Op0RHS) &&
4007               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4008             // Not masking anything out for the RHS, move to LHS.
4009             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4010                                                    Op0LHS->getName()+".masked");
4011             InsertNewInstBefore(NewLHS, I);
4012             return BinaryOperator::Create(
4013                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4014           }
4015         }
4016
4017         break;
4018       case Instruction::Add:
4019         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4020         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4021         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4022         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4023           return BinaryOperator::CreateAnd(V, AndRHS);
4024         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4025           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4026         break;
4027
4028       case Instruction::Sub:
4029         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4030         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4031         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4032         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4033           return BinaryOperator::CreateAnd(V, AndRHS);
4034
4035         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4036         // has 1's for all bits that the subtraction with A might affect.
4037         if (Op0I->hasOneUse()) {
4038           uint32_t BitWidth = AndRHSMask.getBitWidth();
4039           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4040           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4041
4042           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4043           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4044               MaskedValueIsZero(Op0LHS, Mask)) {
4045             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4046             InsertNewInstBefore(NewNeg, I);
4047             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4048           }
4049         }
4050         break;
4051
4052       case Instruction::Shl:
4053       case Instruction::LShr:
4054         // (1 << x) & 1 --> zext(x == 0)
4055         // (1 >> x) & 1 --> zext(x == 0)
4056         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4057           Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4058                                     Op0RHS, Context->getNullValue(I.getType()));
4059           InsertNewInstBefore(NewICmp, I);
4060           return new ZExtInst(NewICmp, I.getType());
4061         }
4062         break;
4063       }
4064
4065       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4066         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4067           return Res;
4068     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4069       // If this is an integer truncation or change from signed-to-unsigned, and
4070       // if the source is an and/or with immediate, transform it.  This
4071       // frequently occurs for bitfield accesses.
4072       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4073         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4074             CastOp->getNumOperands() == 2)
4075           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4076             if (CastOp->getOpcode() == Instruction::And) {
4077               // Change: and (cast (and X, C1) to T), C2
4078               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4079               // This will fold the two constants together, which may allow 
4080               // other simplifications.
4081               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4082                 CastOp->getOperand(0), I.getType(), 
4083                 CastOp->getName()+".shrunk");
4084               NewCast = InsertNewInstBefore(NewCast, I);
4085               // trunc_or_bitcast(C1)&C2
4086               Constant *C3 =
4087                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4088               C3 = Context->getConstantExprAnd(C3, AndRHS);
4089               return BinaryOperator::CreateAnd(NewCast, C3);
4090             } else if (CastOp->getOpcode() == Instruction::Or) {
4091               // Change: and (cast (or X, C1) to T), C2
4092               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4093               Constant *C3 =
4094                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4095               if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4096                 // trunc(C1)&C2
4097                 return ReplaceInstUsesWith(I, AndRHS);
4098             }
4099           }
4100       }
4101     }
4102
4103     // Try to fold constant and into select arguments.
4104     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4105       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4106         return R;
4107     if (isa<PHINode>(Op0))
4108       if (Instruction *NV = FoldOpIntoPhi(I))
4109         return NV;
4110   }
4111
4112   Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4113   Value *Op1NotVal = dyn_castNotVal(Op1, Context);
4114
4115   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4116     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4117
4118   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4119   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4120     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4121                                                I.getName()+".demorgan");
4122     InsertNewInstBefore(Or, I);
4123     return BinaryOperator::CreateNot(Or);
4124   }
4125   
4126   {
4127     Value *A = 0, *B = 0, *C = 0, *D = 0;
4128     if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
4129       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4130         return ReplaceInstUsesWith(I, Op1);
4131     
4132       // (A|B) & ~(A&B) -> A^B
4133       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4134         if ((A == C && B == D) || (A == D && B == C))
4135           return BinaryOperator::CreateXor(A, B);
4136       }
4137     }
4138     
4139     if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
4140       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4141         return ReplaceInstUsesWith(I, Op0);
4142
4143       // ~(A&B) & (A|B) -> A^B
4144       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4145         if ((A == C && B == D) || (A == D && B == C))
4146           return BinaryOperator::CreateXor(A, B);
4147       }
4148     }
4149     
4150     if (Op0->hasOneUse() &&
4151         match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4152       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4153         I.swapOperands();     // Simplify below
4154         std::swap(Op0, Op1);
4155       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4156         cast<BinaryOperator>(Op0)->swapOperands();
4157         I.swapOperands();     // Simplify below
4158         std::swap(Op0, Op1);
4159       }
4160     }
4161
4162     if (Op1->hasOneUse() &&
4163         match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4164       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4165         cast<BinaryOperator>(Op1)->swapOperands();
4166         std::swap(A, B);
4167       }
4168       if (A == Op0) {                                // A&(A^B) -> A & ~B
4169         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4170         InsertNewInstBefore(NotB, I);
4171         return BinaryOperator::CreateAnd(A, NotB);
4172       }
4173     }
4174
4175     // (A&((~A)|B)) -> A&B
4176     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4177         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
4178       return BinaryOperator::CreateAnd(A, Op1);
4179     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4180         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
4181       return BinaryOperator::CreateAnd(A, Op0);
4182   }
4183   
4184   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4185     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4186     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4187       return R;
4188
4189     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4190       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4191         return Res;
4192   }
4193
4194   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4195   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4196     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4197       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4198         const Type *SrcTy = Op0C->getOperand(0)->getType();
4199         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4200             // Only do this if the casts both really cause code to be generated.
4201             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4202                               I.getType(), TD) &&
4203             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4204                               I.getType(), TD)) {
4205           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4206                                                          Op1C->getOperand(0),
4207                                                          I.getName());
4208           InsertNewInstBefore(NewOp, I);
4209           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4210         }
4211       }
4212     
4213   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4214   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4215     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4216       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4217           SI0->getOperand(1) == SI1->getOperand(1) &&
4218           (SI0->hasOneUse() || SI1->hasOneUse())) {
4219         Instruction *NewOp =
4220           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4221                                                         SI1->getOperand(0),
4222                                                         SI0->getName()), I);
4223         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4224                                       SI1->getOperand(1));
4225       }
4226   }
4227
4228   // If and'ing two fcmp, try combine them into one.
4229   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4230     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4231       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4232           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4233         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4234         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4235           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4236             // If either of the constants are nans, then the whole thing returns
4237             // false.
4238             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4239               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4240             return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 
4241                                 LHS->getOperand(0), RHS->getOperand(0));
4242           }
4243       } else {
4244         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4245         FCmpInst::Predicate Op0CC, Op1CC;
4246         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4247                   m_Value(Op0RHS)), *Context) &&
4248             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4249                   m_Value(Op1RHS)), *Context)) {
4250           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4251             // Swap RHS operands to match LHS.
4252             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4253             std::swap(Op1LHS, Op1RHS);
4254           }
4255           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4256             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4257             if (Op0CC == Op1CC)
4258               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4259                                   Op0LHS, Op0RHS);
4260             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4261                      Op1CC == FCmpInst::FCMP_FALSE)
4262               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4263             else if (Op0CC == FCmpInst::FCMP_TRUE)
4264               return ReplaceInstUsesWith(I, Op1);
4265             else if (Op1CC == FCmpInst::FCMP_TRUE)
4266               return ReplaceInstUsesWith(I, Op0);
4267             bool Op0Ordered;
4268             bool Op1Ordered;
4269             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4270             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4271             if (Op1Pred == 0) {
4272               std::swap(Op0, Op1);
4273               std::swap(Op0Pred, Op1Pred);
4274               std::swap(Op0Ordered, Op1Ordered);
4275             }
4276             if (Op0Pred == 0) {
4277               // uno && ueq -> uno && (uno || eq) -> ueq
4278               // ord && olt -> ord && (ord && lt) -> olt
4279               if (Op0Ordered == Op1Ordered)
4280                 return ReplaceInstUsesWith(I, Op1);
4281               // uno && oeq -> uno && (ord && eq) -> false
4282               // uno && ord -> false
4283               if (!Op0Ordered)
4284                 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4285               // ord && ueq -> ord && (uno || eq) -> oeq
4286               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4287                                                     Op0LHS, Op0RHS, Context));
4288             }
4289           }
4290         }
4291       }
4292     }
4293   }
4294
4295   return Changed ? &I : 0;
4296 }
4297
4298 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4299 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4300 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4301 /// the expression came from the corresponding "byte swapped" byte in some other
4302 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4303 /// we know that the expression deposits the low byte of %X into the high byte
4304 /// of the bswap result and that all other bytes are zero.  This expression is
4305 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4306 /// match.
4307 ///
4308 /// This function returns true if the match was unsuccessful and false if so.
4309 /// On entry to the function the "OverallLeftShift" is a signed integer value
4310 /// indicating the number of bytes that the subexpression is later shifted.  For
4311 /// example, if the expression is later right shifted by 16 bits, the
4312 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4313 /// byte of ByteValues is actually being set.
4314 ///
4315 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4316 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4317 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4318 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4319 /// always in the local (OverallLeftShift) coordinate space.
4320 ///
4321 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4322                               SmallVector<Value*, 8> &ByteValues) {
4323   if (Instruction *I = dyn_cast<Instruction>(V)) {
4324     // If this is an or instruction, it may be an inner node of the bswap.
4325     if (I->getOpcode() == Instruction::Or) {
4326       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4327                                ByteValues) ||
4328              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4329                                ByteValues);
4330     }
4331   
4332     // If this is a logical shift by a constant multiple of 8, recurse with
4333     // OverallLeftShift and ByteMask adjusted.
4334     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4335       unsigned ShAmt = 
4336         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4337       // Ensure the shift amount is defined and of a byte value.
4338       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4339         return true;
4340
4341       unsigned ByteShift = ShAmt >> 3;
4342       if (I->getOpcode() == Instruction::Shl) {
4343         // X << 2 -> collect(X, +2)
4344         OverallLeftShift += ByteShift;
4345         ByteMask >>= ByteShift;
4346       } else {
4347         // X >>u 2 -> collect(X, -2)
4348         OverallLeftShift -= ByteShift;
4349         ByteMask <<= ByteShift;
4350         ByteMask &= (~0U >> (32-ByteValues.size()));
4351       }
4352
4353       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4354       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4355
4356       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4357                                ByteValues);
4358     }
4359
4360     // If this is a logical 'and' with a mask that clears bytes, clear the
4361     // corresponding bytes in ByteMask.
4362     if (I->getOpcode() == Instruction::And &&
4363         isa<ConstantInt>(I->getOperand(1))) {
4364       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4365       unsigned NumBytes = ByteValues.size();
4366       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4367       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4368       
4369       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4370         // If this byte is masked out by a later operation, we don't care what
4371         // the and mask is.
4372         if ((ByteMask & (1 << i)) == 0)
4373           continue;
4374         
4375         // If the AndMask is all zeros for this byte, clear the bit.
4376         APInt MaskB = AndMask & Byte;
4377         if (MaskB == 0) {
4378           ByteMask &= ~(1U << i);
4379           continue;
4380         }
4381         
4382         // If the AndMask is not all ones for this byte, it's not a bytezap.
4383         if (MaskB != Byte)
4384           return true;
4385
4386         // Otherwise, this byte is kept.
4387       }
4388
4389       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4390                                ByteValues);
4391     }
4392   }
4393   
4394   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4395   // the input value to the bswap.  Some observations: 1) if more than one byte
4396   // is demanded from this input, then it could not be successfully assembled
4397   // into a byteswap.  At least one of the two bytes would not be aligned with
4398   // their ultimate destination.
4399   if (!isPowerOf2_32(ByteMask)) return true;
4400   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4401   
4402   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4403   // is demanded, it needs to go into byte 0 of the result.  This means that the
4404   // byte needs to be shifted until it lands in the right byte bucket.  The
4405   // shift amount depends on the position: if the byte is coming from the high
4406   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4407   // low part, it must be shifted left.
4408   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4409   if (InputByteNo < ByteValues.size()/2) {
4410     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4411       return true;
4412   } else {
4413     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4414       return true;
4415   }
4416   
4417   // If the destination byte value is already defined, the values are or'd
4418   // together, which isn't a bswap (unless it's an or of the same bits).
4419   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4420     return true;
4421   ByteValues[DestByteNo] = V;
4422   return false;
4423 }
4424
4425 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4426 /// If so, insert the new bswap intrinsic and return it.
4427 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4428   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4429   if (!ITy || ITy->getBitWidth() % 16 || 
4430       // ByteMask only allows up to 32-byte values.
4431       ITy->getBitWidth() > 32*8) 
4432     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4433   
4434   /// ByteValues - For each byte of the result, we keep track of which value
4435   /// defines each byte.
4436   SmallVector<Value*, 8> ByteValues;
4437   ByteValues.resize(ITy->getBitWidth()/8);
4438     
4439   // Try to find all the pieces corresponding to the bswap.
4440   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4441   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4442     return 0;
4443   
4444   // Check to see if all of the bytes come from the same value.
4445   Value *V = ByteValues[0];
4446   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4447   
4448   // Check to make sure that all of the bytes come from the same value.
4449   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4450     if (ByteValues[i] != V)
4451       return 0;
4452   const Type *Tys[] = { ITy };
4453   Module *M = I.getParent()->getParent()->getParent();
4454   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4455   return CallInst::Create(F, V);
4456 }
4457
4458 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4459 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4460 /// we can simplify this expression to "cond ? C : D or B".
4461 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4462                                          Value *C, Value *D,
4463                                          LLVMContext *Context) {
4464   // If A is not a select of -1/0, this cannot match.
4465   Value *Cond = 0;
4466   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
4467     return 0;
4468
4469   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4470   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4471     return SelectInst::Create(Cond, C, B);
4472   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4473     return SelectInst::Create(Cond, C, B);
4474   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4475   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4476     return SelectInst::Create(Cond, C, D);
4477   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4478     return SelectInst::Create(Cond, C, D);
4479   return 0;
4480 }
4481
4482 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4483 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4484                                          ICmpInst *LHS, ICmpInst *RHS) {
4485   Value *Val, *Val2;
4486   ConstantInt *LHSCst, *RHSCst;
4487   ICmpInst::Predicate LHSCC, RHSCC;
4488   
4489   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4490   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4491              m_ConstantInt(LHSCst)), *Context) ||
4492       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4493              m_ConstantInt(RHSCst)), *Context))
4494     return 0;
4495   
4496   // From here on, we only handle:
4497   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4498   if (Val != Val2) return 0;
4499   
4500   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4501   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4502       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4503       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4504       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4505     return 0;
4506   
4507   // We can't fold (ugt x, C) | (sgt x, C2).
4508   if (!PredicatesFoldable(LHSCC, RHSCC))
4509     return 0;
4510   
4511   // Ensure that the larger constant is on the RHS.
4512   bool ShouldSwap;
4513   if (ICmpInst::isSignedPredicate(LHSCC) ||
4514       (ICmpInst::isEquality(LHSCC) && 
4515        ICmpInst::isSignedPredicate(RHSCC)))
4516     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4517   else
4518     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4519   
4520   if (ShouldSwap) {
4521     std::swap(LHS, RHS);
4522     std::swap(LHSCst, RHSCst);
4523     std::swap(LHSCC, RHSCC);
4524   }
4525   
4526   // At this point, we know we have have two icmp instructions
4527   // comparing a value against two constants and or'ing the result
4528   // together.  Because of the above check, we know that we only have
4529   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4530   // FoldICmpLogical check above), that the two constants are not
4531   // equal.
4532   assert(LHSCst != RHSCst && "Compares not folded above?");
4533
4534   switch (LHSCC) {
4535   default: LLVM_UNREACHABLE("Unknown integer condition code!");
4536   case ICmpInst::ICMP_EQ:
4537     switch (RHSCC) {
4538     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4539     case ICmpInst::ICMP_EQ:
4540       if (LHSCst == SubOne(RHSCst, Context)) {
4541         // (X == 13 | X == 14) -> X-13 <u 2
4542         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
4543         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4544                                                      Val->getName()+".off");
4545         InsertNewInstBefore(Add, I);
4546         AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
4547         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
4548       }
4549       break;                         // (X == 13 | X == 15) -> no change
4550     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4551     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4552       break;
4553     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4554     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4555     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4556       return ReplaceInstUsesWith(I, RHS);
4557     }
4558     break;
4559   case ICmpInst::ICMP_NE:
4560     switch (RHSCC) {
4561     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4562     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4563     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4564     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4565       return ReplaceInstUsesWith(I, LHS);
4566     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4567     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4568     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4569       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4570     }
4571     break;
4572   case ICmpInst::ICMP_ULT:
4573     switch (RHSCC) {
4574     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4575     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4576       break;
4577     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4578       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4579       // this can cause overflow.
4580       if (RHSCst->isMaxValue(false))
4581         return ReplaceInstUsesWith(I, LHS);
4582       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4583                              false, false, I);
4584     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4585       break;
4586     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4587     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4588       return ReplaceInstUsesWith(I, RHS);
4589     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4590       break;
4591     }
4592     break;
4593   case ICmpInst::ICMP_SLT:
4594     switch (RHSCC) {
4595     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4596     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4597       break;
4598     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4599       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4600       // this can cause overflow.
4601       if (RHSCst->isMaxValue(true))
4602         return ReplaceInstUsesWith(I, LHS);
4603       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4604                              true, false, I);
4605     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4606       break;
4607     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4608     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4609       return ReplaceInstUsesWith(I, RHS);
4610     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4611       break;
4612     }
4613     break;
4614   case ICmpInst::ICMP_UGT:
4615     switch (RHSCC) {
4616     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4617     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4618     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4619       return ReplaceInstUsesWith(I, LHS);
4620     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4621       break;
4622     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4623     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4624       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4625     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4626       break;
4627     }
4628     break;
4629   case ICmpInst::ICMP_SGT:
4630     switch (RHSCC) {
4631     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4632     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4633     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4634       return ReplaceInstUsesWith(I, LHS);
4635     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4636       break;
4637     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4638     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4639       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4640     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4641       break;
4642     }
4643     break;
4644   }
4645   return 0;
4646 }
4647
4648 /// FoldOrWithConstants - This helper function folds:
4649 ///
4650 ///     ((A | B) & C1) | (B & C2)
4651 ///
4652 /// into:
4653 /// 
4654 ///     (A & C1) | B
4655 ///
4656 /// when the XOR of the two constants is "all ones" (-1).
4657 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4658                                                Value *A, Value *B, Value *C) {
4659   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4660   if (!CI1) return 0;
4661
4662   Value *V1 = 0;
4663   ConstantInt *CI2 = 0;
4664   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
4665
4666   APInt Xor = CI1->getValue() ^ CI2->getValue();
4667   if (!Xor.isAllOnesValue()) return 0;
4668
4669   if (V1 == A || V1 == B) {
4670     Instruction *NewOp =
4671       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4672     return BinaryOperator::CreateOr(NewOp, V1);
4673   }
4674
4675   return 0;
4676 }
4677
4678 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4679   bool Changed = SimplifyCommutative(I);
4680   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4681
4682   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4683     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4684
4685   // or X, X = X
4686   if (Op0 == Op1)
4687     return ReplaceInstUsesWith(I, Op0);
4688
4689   // See if we can simplify any instructions used by the instruction whose sole 
4690   // purpose is to compute bits we don't care about.
4691   if (SimplifyDemandedInstructionBits(I))
4692     return &I;
4693   if (isa<VectorType>(I.getType())) {
4694     if (isa<ConstantAggregateZero>(Op1)) {
4695       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4696     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4697       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4698         return ReplaceInstUsesWith(I, I.getOperand(1));
4699     }
4700   }
4701
4702   // or X, -1 == -1
4703   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4704     ConstantInt *C1 = 0; Value *X = 0;
4705     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4706     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) && 
4707         isOnlyUse(Op0)) {
4708       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4709       InsertNewInstBefore(Or, I);
4710       Or->takeName(Op0);
4711       return BinaryOperator::CreateAnd(Or, 
4712                Context->getConstantInt(RHS->getValue() | C1->getValue()));
4713     }
4714
4715     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4716     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) && 
4717         isOnlyUse(Op0)) {
4718       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4719       InsertNewInstBefore(Or, I);
4720       Or->takeName(Op0);
4721       return BinaryOperator::CreateXor(Or,
4722                  Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
4723     }
4724
4725     // Try to fold constant and into select arguments.
4726     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4727       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4728         return R;
4729     if (isa<PHINode>(Op0))
4730       if (Instruction *NV = FoldOpIntoPhi(I))
4731         return NV;
4732   }
4733
4734   Value *A = 0, *B = 0;
4735   ConstantInt *C1 = 0, *C2 = 0;
4736
4737   if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
4738     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4739       return ReplaceInstUsesWith(I, Op1);
4740   if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
4741     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4742       return ReplaceInstUsesWith(I, Op0);
4743
4744   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4745   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4746   if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4747       match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4748       (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4749        match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
4750     if (Instruction *BSwap = MatchBSwap(I))
4751       return BSwap;
4752   }
4753   
4754   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4755   if (Op0->hasOneUse() &&
4756       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4757       MaskedValueIsZero(Op1, C1->getValue())) {
4758     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4759     InsertNewInstBefore(NOr, I);
4760     NOr->takeName(Op0);
4761     return BinaryOperator::CreateXor(NOr, C1);
4762   }
4763
4764   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4765   if (Op1->hasOneUse() &&
4766       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4767       MaskedValueIsZero(Op0, C1->getValue())) {
4768     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4769     InsertNewInstBefore(NOr, I);
4770     NOr->takeName(Op0);
4771     return BinaryOperator::CreateXor(NOr, C1);
4772   }
4773
4774   // (A & C)|(B & D)
4775   Value *C = 0, *D = 0;
4776   if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4777       match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
4778     Value *V1 = 0, *V2 = 0, *V3 = 0;
4779     C1 = dyn_cast<ConstantInt>(C);
4780     C2 = dyn_cast<ConstantInt>(D);
4781     if (C1 && C2) {  // (A & C1)|(B & C2)
4782       // If we have: ((V + N) & C1) | (V & C2)
4783       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4784       // replace with V+N.
4785       if (C1->getValue() == ~C2->getValue()) {
4786         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4787             match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4788           // Add commutes, try both ways.
4789           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4790             return ReplaceInstUsesWith(I, A);
4791           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4792             return ReplaceInstUsesWith(I, A);
4793         }
4794         // Or commutes, try both ways.
4795         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4796             match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4797           // Add commutes, try both ways.
4798           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4799             return ReplaceInstUsesWith(I, B);
4800           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4801             return ReplaceInstUsesWith(I, B);
4802         }
4803       }
4804       V1 = 0; V2 = 0; V3 = 0;
4805     }
4806     
4807     // Check to see if we have any common things being and'ed.  If so, find the
4808     // terms for V1 & (V2|V3).
4809     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4810       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4811         V1 = A, V2 = C, V3 = D;
4812       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4813         V1 = A, V2 = B, V3 = C;
4814       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4815         V1 = C, V2 = A, V3 = D;
4816       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4817         V1 = C, V2 = A, V3 = B;
4818       
4819       if (V1) {
4820         Value *Or =
4821           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4822         return BinaryOperator::CreateAnd(V1, Or);
4823       }
4824     }
4825
4826     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4827     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4828       return Match;
4829     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4830       return Match;
4831     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4832       return Match;
4833     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4834       return Match;
4835
4836     // ((A&~B)|(~A&B)) -> A^B
4837     if ((match(C, m_Not(m_Specific(D)), *Context) &&
4838          match(B, m_Not(m_Specific(A)), *Context)))
4839       return BinaryOperator::CreateXor(A, D);
4840     // ((~B&A)|(~A&B)) -> A^B
4841     if ((match(A, m_Not(m_Specific(D)), *Context) &&
4842          match(B, m_Not(m_Specific(C)), *Context)))
4843       return BinaryOperator::CreateXor(C, D);
4844     // ((A&~B)|(B&~A)) -> A^B
4845     if ((match(C, m_Not(m_Specific(B)), *Context) &&
4846          match(D, m_Not(m_Specific(A)), *Context)))
4847       return BinaryOperator::CreateXor(A, B);
4848     // ((~B&A)|(B&~A)) -> A^B
4849     if ((match(A, m_Not(m_Specific(B)), *Context) &&
4850          match(D, m_Not(m_Specific(C)), *Context)))
4851       return BinaryOperator::CreateXor(C, B);
4852   }
4853   
4854   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4855   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4856     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4857       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4858           SI0->getOperand(1) == SI1->getOperand(1) &&
4859           (SI0->hasOneUse() || SI1->hasOneUse())) {
4860         Instruction *NewOp =
4861         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4862                                                      SI1->getOperand(0),
4863                                                      SI0->getName()), I);
4864         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4865                                       SI1->getOperand(1));
4866       }
4867   }
4868
4869   // ((A|B)&1)|(B&-2) -> (A&1) | B
4870   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4871       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4872     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4873     if (Ret) return Ret;
4874   }
4875   // (B&-2)|((A|B)&1) -> (A&1) | B
4876   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4877       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4878     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4879     if (Ret) return Ret;
4880   }
4881
4882   if (match(Op0, m_Not(m_Value(A)), *Context)) {   // ~A | Op1
4883     if (A == Op1)   // ~A | A == -1
4884       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4885   } else {
4886     A = 0;
4887   }
4888   // Note, A is still live here!
4889   if (match(Op1, m_Not(m_Value(B)), *Context)) {   // Op0 | ~B
4890     if (Op0 == B)
4891       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4892
4893     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4894     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4895       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4896                                               I.getName()+".demorgan"), I);
4897       return BinaryOperator::CreateNot(And);
4898     }
4899   }
4900
4901   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4902   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4903     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4904       return R;
4905
4906     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4907       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4908         return Res;
4909   }
4910     
4911   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4912   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4913     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4914       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4915         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4916             !isa<ICmpInst>(Op1C->getOperand(0))) {
4917           const Type *SrcTy = Op0C->getOperand(0)->getType();
4918           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4919               // Only do this if the casts both really cause code to be
4920               // generated.
4921               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4922                                 I.getType(), TD) &&
4923               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4924                                 I.getType(), TD)) {
4925             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4926                                                           Op1C->getOperand(0),
4927                                                           I.getName());
4928             InsertNewInstBefore(NewOp, I);
4929             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4930           }
4931         }
4932       }
4933   }
4934   
4935     
4936   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4937   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4938     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4939       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4940           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4941           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4942         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4943           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4944             // If either of the constants are nans, then the whole thing returns
4945             // true.
4946             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4947               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4948             
4949             // Otherwise, no need to compare the two constants, compare the
4950             // rest.
4951             return new FCmpInst(*Context, FCmpInst::FCMP_UNO, 
4952                                 LHS->getOperand(0), RHS->getOperand(0));
4953           }
4954       } else {
4955         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4956         FCmpInst::Predicate Op0CC, Op1CC;
4957         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4958                   m_Value(Op0RHS)), *Context) &&
4959             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4960                   m_Value(Op1RHS)), *Context)) {
4961           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4962             // Swap RHS operands to match LHS.
4963             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4964             std::swap(Op1LHS, Op1RHS);
4965           }
4966           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4967             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4968             if (Op0CC == Op1CC)
4969               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4970                                   Op0LHS, Op0RHS);
4971             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4972                      Op1CC == FCmpInst::FCMP_TRUE)
4973               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4974             else if (Op0CC == FCmpInst::FCMP_FALSE)
4975               return ReplaceInstUsesWith(I, Op1);
4976             else if (Op1CC == FCmpInst::FCMP_FALSE)
4977               return ReplaceInstUsesWith(I, Op0);
4978             bool Op0Ordered;
4979             bool Op1Ordered;
4980             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4981             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4982             if (Op0Ordered == Op1Ordered) {
4983               // If both are ordered or unordered, return a new fcmp with
4984               // or'ed predicates.
4985               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4986                                        Op0LHS, Op0RHS, Context);
4987               if (Instruction *I = dyn_cast<Instruction>(RV))
4988                 return I;
4989               // Otherwise, it's a constant boolean value...
4990               return ReplaceInstUsesWith(I, RV);
4991             }
4992           }
4993         }
4994       }
4995     }
4996   }
4997
4998   return Changed ? &I : 0;
4999 }
5000
5001 namespace {
5002
5003 // XorSelf - Implements: X ^ X --> 0
5004 struct XorSelf {
5005   Value *RHS;
5006   XorSelf(Value *rhs) : RHS(rhs) {}
5007   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5008   Instruction *apply(BinaryOperator &Xor) const {
5009     return &Xor;
5010   }
5011 };
5012
5013 }
5014
5015 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5016   bool Changed = SimplifyCommutative(I);
5017   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5018
5019   if (isa<UndefValue>(Op1)) {
5020     if (isa<UndefValue>(Op0))
5021       // Handle undef ^ undef -> 0 special case. This is a common
5022       // idiom (misuse).
5023       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5024     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5025   }
5026
5027   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5028   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
5029     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5030     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5031   }
5032   
5033   // See if we can simplify any instructions used by the instruction whose sole 
5034   // purpose is to compute bits we don't care about.
5035   if (SimplifyDemandedInstructionBits(I))
5036     return &I;
5037   if (isa<VectorType>(I.getType()))
5038     if (isa<ConstantAggregateZero>(Op1))
5039       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5040
5041   // Is this a ~ operation?
5042   if (Value *NotOp = dyn_castNotVal(&I, Context)) {
5043     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5044     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5045     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5046       if (Op0I->getOpcode() == Instruction::And || 
5047           Op0I->getOpcode() == Instruction::Or) {
5048         if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5049         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
5050           Instruction *NotY =
5051             BinaryOperator::CreateNot(Op0I->getOperand(1),
5052                                       Op0I->getOperand(1)->getName()+".not");
5053           InsertNewInstBefore(NotY, I);
5054           if (Op0I->getOpcode() == Instruction::And)
5055             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5056           else
5057             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5058         }
5059       }
5060     }
5061   }
5062   
5063   
5064   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5065     if (RHS == Context->getConstantIntTrue() && Op0->hasOneUse()) {
5066       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5067       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5068         return new ICmpInst(*Context, ICI->getInversePredicate(),
5069                             ICI->getOperand(0), ICI->getOperand(1));
5070
5071       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5072         return new FCmpInst(*Context, FCI->getInversePredicate(),
5073                             FCI->getOperand(0), FCI->getOperand(1));
5074     }
5075
5076     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5077     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5078       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5079         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5080           Instruction::CastOps Opcode = Op0C->getOpcode();
5081           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5082             if (RHS == Context->getConstantExprCast(Opcode, 
5083                                              Context->getConstantIntTrue(),
5084                                              Op0C->getDestTy())) {
5085               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5086                                      *Context,
5087                                      CI->getOpcode(), CI->getInversePredicate(),
5088                                      CI->getOperand(0), CI->getOperand(1)), I);
5089               NewCI->takeName(CI);
5090               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5091             }
5092           }
5093         }
5094       }
5095     }
5096
5097     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5098       // ~(c-X) == X-c-1 == X+(-c-1)
5099       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5100         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5101           Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5102           Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5103                                       Context->getConstantInt(I.getType(), 1));
5104           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5105         }
5106           
5107       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5108         if (Op0I->getOpcode() == Instruction::Add) {
5109           // ~(X-c) --> (-c-1)-X
5110           if (RHS->isAllOnesValue()) {
5111             Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
5112             return BinaryOperator::CreateSub(
5113                            Context->getConstantExprSub(NegOp0CI,
5114                                       Context->getConstantInt(I.getType(), 1)),
5115                                       Op0I->getOperand(0));
5116           } else if (RHS->getValue().isSignBit()) {
5117             // (X + C) ^ signbit -> (X + C + signbit)
5118             Constant *C =
5119                    Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
5120             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5121
5122           }
5123         } else if (Op0I->getOpcode() == Instruction::Or) {
5124           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5125           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5126             Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
5127             // Anything in both C1 and C2 is known to be zero, remove it from
5128             // NewRHS.
5129             Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5130             NewRHS = Context->getConstantExprAnd(NewRHS, 
5131                                        Context->getConstantExprNot(CommonBits));
5132             AddToWorkList(Op0I);
5133             I.setOperand(0, Op0I->getOperand(0));
5134             I.setOperand(1, NewRHS);
5135             return &I;
5136           }
5137         }
5138       }
5139     }
5140
5141     // Try to fold constant and into select arguments.
5142     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5143       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5144         return R;
5145     if (isa<PHINode>(Op0))
5146       if (Instruction *NV = FoldOpIntoPhi(I))
5147         return NV;
5148   }
5149
5150   if (Value *X = dyn_castNotVal(Op0, Context))   // ~A ^ A == -1
5151     if (X == Op1)
5152       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5153
5154   if (Value *X = dyn_castNotVal(Op1, Context))   // A ^ ~A == -1
5155     if (X == Op0)
5156       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5157
5158   
5159   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5160   if (Op1I) {
5161     Value *A, *B;
5162     if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
5163       if (A == Op0) {              // B^(B|A) == (A|B)^B
5164         Op1I->swapOperands();
5165         I.swapOperands();
5166         std::swap(Op0, Op1);
5167       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5168         I.swapOperands();     // Simplified below.
5169         std::swap(Op0, Op1);
5170       }
5171     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
5172       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5173     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
5174       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5175     } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) && 
5176                Op1I->hasOneUse()){
5177       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5178         Op1I->swapOperands();
5179         std::swap(A, B);
5180       }
5181       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5182         I.swapOperands();     // Simplified below.
5183         std::swap(Op0, Op1);
5184       }
5185     }
5186   }
5187   
5188   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5189   if (Op0I) {
5190     Value *A, *B;
5191     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5192         Op0I->hasOneUse()) {
5193       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5194         std::swap(A, B);
5195       if (B == Op1) {                                // (A|B)^B == A & ~B
5196         Instruction *NotB =
5197           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5198         return BinaryOperator::CreateAnd(A, NotB);
5199       }
5200     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
5201       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5202     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
5203       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5204     } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) && 
5205                Op0I->hasOneUse()){
5206       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5207         std::swap(A, B);
5208       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5209           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5210         Instruction *N =
5211           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5212         return BinaryOperator::CreateAnd(N, Op1);
5213       }
5214     }
5215   }
5216   
5217   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5218   if (Op0I && Op1I && Op0I->isShift() && 
5219       Op0I->getOpcode() == Op1I->getOpcode() && 
5220       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5221       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5222     Instruction *NewOp =
5223       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5224                                                     Op1I->getOperand(0),
5225                                                     Op0I->getName()), I);
5226     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5227                                   Op1I->getOperand(1));
5228   }
5229     
5230   if (Op0I && Op1I) {
5231     Value *A, *B, *C, *D;
5232     // (A & B)^(A | B) -> A ^ B
5233     if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5234         match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
5235       if ((A == C && B == D) || (A == D && B == C)) 
5236         return BinaryOperator::CreateXor(A, B);
5237     }
5238     // (A | B)^(A & B) -> A ^ B
5239     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5240         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5241       if ((A == C && B == D) || (A == D && B == C)) 
5242         return BinaryOperator::CreateXor(A, B);
5243     }
5244     
5245     // (A & B)^(C & D)
5246     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5247         match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5248         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5249       // (X & Y)^(X & Y) -> (Y^Z) & X
5250       Value *X = 0, *Y = 0, *Z = 0;
5251       if (A == C)
5252         X = A, Y = B, Z = D;
5253       else if (A == D)
5254         X = A, Y = B, Z = C;
5255       else if (B == C)
5256         X = B, Y = A, Z = D;
5257       else if (B == D)
5258         X = B, Y = A, Z = C;
5259       
5260       if (X) {
5261         Instruction *NewOp =
5262         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5263         return BinaryOperator::CreateAnd(NewOp, X);
5264       }
5265     }
5266   }
5267     
5268   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5269   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5270     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
5271       return R;
5272
5273   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5274   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5275     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5276       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5277         const Type *SrcTy = Op0C->getOperand(0)->getType();
5278         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5279             // Only do this if the casts both really cause code to be generated.
5280             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5281                               I.getType(), TD) &&
5282             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5283                               I.getType(), TD)) {
5284           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5285                                                          Op1C->getOperand(0),
5286                                                          I.getName());
5287           InsertNewInstBefore(NewOp, I);
5288           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5289         }
5290       }
5291   }
5292
5293   return Changed ? &I : 0;
5294 }
5295
5296 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5297                                    LLVMContext *Context) {
5298   return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
5299 }
5300
5301 static bool HasAddOverflow(ConstantInt *Result,
5302                            ConstantInt *In1, ConstantInt *In2,
5303                            bool IsSigned) {
5304   if (IsSigned)
5305     if (In2->getValue().isNegative())
5306       return Result->getValue().sgt(In1->getValue());
5307     else
5308       return Result->getValue().slt(In1->getValue());
5309   else
5310     return Result->getValue().ult(In1->getValue());
5311 }
5312
5313 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5314 /// overflowed for this type.
5315 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5316                             Constant *In2, LLVMContext *Context,
5317                             bool IsSigned = false) {
5318   Result = Context->getConstantExprAdd(In1, In2);
5319
5320   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5321     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5322       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5323       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5324                          ExtractElement(In1, Idx, Context),
5325                          ExtractElement(In2, Idx, Context),
5326                          IsSigned))
5327         return true;
5328     }
5329     return false;
5330   }
5331
5332   return HasAddOverflow(cast<ConstantInt>(Result),
5333                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5334                         IsSigned);
5335 }
5336
5337 static bool HasSubOverflow(ConstantInt *Result,
5338                            ConstantInt *In1, ConstantInt *In2,
5339                            bool IsSigned) {
5340   if (IsSigned)
5341     if (In2->getValue().isNegative())
5342       return Result->getValue().slt(In1->getValue());
5343     else
5344       return Result->getValue().sgt(In1->getValue());
5345   else
5346     return Result->getValue().ugt(In1->getValue());
5347 }
5348
5349 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5350 /// overflowed for this type.
5351 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5352                             Constant *In2, LLVMContext *Context,
5353                             bool IsSigned = false) {
5354   Result = Context->getConstantExprSub(In1, In2);
5355
5356   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5357     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5358       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5359       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5360                          ExtractElement(In1, Idx, Context),
5361                          ExtractElement(In2, Idx, Context),
5362                          IsSigned))
5363         return true;
5364     }
5365     return false;
5366   }
5367
5368   return HasSubOverflow(cast<ConstantInt>(Result),
5369                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5370                         IsSigned);
5371 }
5372
5373 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5374 /// code necessary to compute the offset from the base pointer (without adding
5375 /// in the base pointer).  Return the result as a signed integer of intptr size.
5376 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5377   TargetData &TD = IC.getTargetData();
5378   gep_type_iterator GTI = gep_type_begin(GEP);
5379   const Type *IntPtrTy = TD.getIntPtrType();
5380   LLVMContext *Context = IC.getContext();
5381   Value *Result = Context->getNullValue(IntPtrTy);
5382
5383   // Build a mask for high order bits.
5384   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5385   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5386
5387   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5388        ++i, ++GTI) {
5389     Value *Op = *i;
5390     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5391     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5392       if (OpC->isZero()) continue;
5393       
5394       // Handle a struct index, which adds its field offset to the pointer.
5395       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5396         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5397         
5398         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5399           Result = 
5400              Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
5401         else
5402           Result = IC.InsertNewInstBefore(
5403                    BinaryOperator::CreateAdd(Result,
5404                                         Context->getConstantInt(IntPtrTy, Size),
5405                                              GEP->getName()+".offs"), I);
5406         continue;
5407       }
5408       
5409       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5410       Constant *OC =
5411               Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5412       Scale = Context->getConstantExprMul(OC, Scale);
5413       if (Constant *RC = dyn_cast<Constant>(Result))
5414         Result = Context->getConstantExprAdd(RC, Scale);
5415       else {
5416         // Emit an add instruction.
5417         Result = IC.InsertNewInstBefore(
5418            BinaryOperator::CreateAdd(Result, Scale,
5419                                      GEP->getName()+".offs"), I);
5420       }
5421       continue;
5422     }
5423     // Convert to correct type.
5424     if (Op->getType() != IntPtrTy) {
5425       if (Constant *OpC = dyn_cast<Constant>(Op))
5426         Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
5427       else
5428         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5429                                                                 true,
5430                                                       Op->getName()+".c"), I);
5431     }
5432     if (Size != 1) {
5433       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5434       if (Constant *OpC = dyn_cast<Constant>(Op))
5435         Op = Context->getConstantExprMul(OpC, Scale);
5436       else    // We'll let instcombine(mul) convert this to a shl if possible.
5437         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5438                                                   GEP->getName()+".idx"), I);
5439     }
5440
5441     // Emit an add instruction.
5442     if (isa<Constant>(Op) && isa<Constant>(Result))
5443       Result = Context->getConstantExprAdd(cast<Constant>(Op),
5444                                     cast<Constant>(Result));
5445     else
5446       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5447                                                   GEP->getName()+".offs"), I);
5448   }
5449   return Result;
5450 }
5451
5452
5453 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5454 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5455 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5456 /// complex, and scales are involved.  The above expression would also be legal
5457 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5458 /// later form is less amenable to optimization though, and we are allowed to
5459 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5460 ///
5461 /// If we can't emit an optimized form for this expression, this returns null.
5462 /// 
5463 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5464                                           InstCombiner &IC) {
5465   TargetData &TD = IC.getTargetData();
5466   gep_type_iterator GTI = gep_type_begin(GEP);
5467
5468   // Check to see if this gep only has a single variable index.  If so, and if
5469   // any constant indices are a multiple of its scale, then we can compute this
5470   // in terms of the scale of the variable index.  For example, if the GEP
5471   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5472   // because the expression will cross zero at the same point.
5473   unsigned i, e = GEP->getNumOperands();
5474   int64_t Offset = 0;
5475   for (i = 1; i != e; ++i, ++GTI) {
5476     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5477       // Compute the aggregate offset of constant indices.
5478       if (CI->isZero()) continue;
5479
5480       // Handle a struct index, which adds its field offset to the pointer.
5481       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5482         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5483       } else {
5484         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5485         Offset += Size*CI->getSExtValue();
5486       }
5487     } else {
5488       // Found our variable index.
5489       break;
5490     }
5491   }
5492   
5493   // If there are no variable indices, we must have a constant offset, just
5494   // evaluate it the general way.
5495   if (i == e) return 0;
5496   
5497   Value *VariableIdx = GEP->getOperand(i);
5498   // Determine the scale factor of the variable element.  For example, this is
5499   // 4 if the variable index is into an array of i32.
5500   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5501   
5502   // Verify that there are no other variable indices.  If so, emit the hard way.
5503   for (++i, ++GTI; i != e; ++i, ++GTI) {
5504     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5505     if (!CI) return 0;
5506    
5507     // Compute the aggregate offset of constant indices.
5508     if (CI->isZero()) continue;
5509     
5510     // Handle a struct index, which adds its field offset to the pointer.
5511     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5512       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5513     } else {
5514       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5515       Offset += Size*CI->getSExtValue();
5516     }
5517   }
5518   
5519   // Okay, we know we have a single variable index, which must be a
5520   // pointer/array/vector index.  If there is no offset, life is simple, return
5521   // the index.
5522   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5523   if (Offset == 0) {
5524     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5525     // we don't need to bother extending: the extension won't affect where the
5526     // computation crosses zero.
5527     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5528       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5529                                   VariableIdx->getNameStart(), &I);
5530     return VariableIdx;
5531   }
5532   
5533   // Otherwise, there is an index.  The computation we will do will be modulo
5534   // the pointer size, so get it.
5535   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5536   
5537   Offset &= PtrSizeMask;
5538   VariableScale &= PtrSizeMask;
5539
5540   // To do this transformation, any constant index must be a multiple of the
5541   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5542   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5543   // multiple of the variable scale.
5544   int64_t NewOffs = Offset / (int64_t)VariableScale;
5545   if (Offset != NewOffs*(int64_t)VariableScale)
5546     return 0;
5547
5548   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5549   const Type *IntPtrTy = TD.getIntPtrType();
5550   if (VariableIdx->getType() != IntPtrTy)
5551     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5552                                               true /*SExt*/, 
5553                                               VariableIdx->getNameStart(), &I);
5554   Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
5555   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5556 }
5557
5558
5559 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5560 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5561 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5562                                        ICmpInst::Predicate Cond,
5563                                        Instruction &I) {
5564   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5565
5566   // Look through bitcasts.
5567   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5568     RHS = BCI->getOperand(0);
5569
5570   Value *PtrBase = GEPLHS->getOperand(0);
5571   if (PtrBase == RHS) {
5572     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5573     // This transformation (ignoring the base and scales) is valid because we
5574     // know pointers can't overflow.  See if we can output an optimized form.
5575     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5576     
5577     // If not, synthesize the offset the hard way.
5578     if (Offset == 0)
5579       Offset = EmitGEPOffset(GEPLHS, I, *this);
5580     return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
5581                         Context->getNullValue(Offset->getType()));
5582   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5583     // If the base pointers are different, but the indices are the same, just
5584     // compare the base pointer.
5585     if (PtrBase != GEPRHS->getOperand(0)) {
5586       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5587       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5588                         GEPRHS->getOperand(0)->getType();
5589       if (IndicesTheSame)
5590         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5591           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5592             IndicesTheSame = false;
5593             break;
5594           }
5595
5596       // If all indices are the same, just compare the base pointers.
5597       if (IndicesTheSame)
5598         return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), 
5599                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5600
5601       // Otherwise, the base pointers are different and the indices are
5602       // different, bail out.
5603       return 0;
5604     }
5605
5606     // If one of the GEPs has all zero indices, recurse.
5607     bool AllZeros = true;
5608     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5609       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5610           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5611         AllZeros = false;
5612         break;
5613       }
5614     if (AllZeros)
5615       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5616                           ICmpInst::getSwappedPredicate(Cond), I);
5617
5618     // If the other GEP has all zero indices, recurse.
5619     AllZeros = true;
5620     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5621       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5622           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5623         AllZeros = false;
5624         break;
5625       }
5626     if (AllZeros)
5627       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5628
5629     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5630       // If the GEPs only differ by one index, compare it.
5631       unsigned NumDifferences = 0;  // Keep track of # differences.
5632       unsigned DiffOperand = 0;     // The operand that differs.
5633       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5634         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5635           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5636                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5637             // Irreconcilable differences.
5638             NumDifferences = 2;
5639             break;
5640           } else {
5641             if (NumDifferences++) break;
5642             DiffOperand = i;
5643           }
5644         }
5645
5646       if (NumDifferences == 0)   // SAME GEP?
5647         return ReplaceInstUsesWith(I, // No comparison is needed here.
5648                                    Context->getConstantInt(Type::Int1Ty,
5649                                              ICmpInst::isTrueWhenEqual(Cond)));
5650
5651       else if (NumDifferences == 1) {
5652         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5653         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5654         // Make sure we do a signed comparison here.
5655         return new ICmpInst(*Context,
5656                             ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5657       }
5658     }
5659
5660     // Only lower this if the icmp is the only user of the GEP or if we expect
5661     // the result to fold to a constant!
5662     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5663         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5664       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5665       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5666       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5667       return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
5668     }
5669   }
5670   return 0;
5671 }
5672
5673 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5674 ///
5675 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5676                                                 Instruction *LHSI,
5677                                                 Constant *RHSC) {
5678   if (!isa<ConstantFP>(RHSC)) return 0;
5679   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5680   
5681   // Get the width of the mantissa.  We don't want to hack on conversions that
5682   // might lose information from the integer, e.g. "i64 -> float"
5683   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5684   if (MantissaWidth == -1) return 0;  // Unknown.
5685   
5686   // Check to see that the input is converted from an integer type that is small
5687   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5688   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5689   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5690   
5691   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5692   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5693   if (LHSUnsigned)
5694     ++InputSize;
5695   
5696   // If the conversion would lose info, don't hack on this.
5697   if ((int)InputSize > MantissaWidth)
5698     return 0;
5699   
5700   // Otherwise, we can potentially simplify the comparison.  We know that it
5701   // will always come through as an integer value and we know the constant is
5702   // not a NAN (it would have been previously simplified).
5703   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5704   
5705   ICmpInst::Predicate Pred;
5706   switch (I.getPredicate()) {
5707   default: LLVM_UNREACHABLE("Unexpected predicate!");
5708   case FCmpInst::FCMP_UEQ:
5709   case FCmpInst::FCMP_OEQ:
5710     Pred = ICmpInst::ICMP_EQ;
5711     break;
5712   case FCmpInst::FCMP_UGT:
5713   case FCmpInst::FCMP_OGT:
5714     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5715     break;
5716   case FCmpInst::FCMP_UGE:
5717   case FCmpInst::FCMP_OGE:
5718     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5719     break;
5720   case FCmpInst::FCMP_ULT:
5721   case FCmpInst::FCMP_OLT:
5722     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5723     break;
5724   case FCmpInst::FCMP_ULE:
5725   case FCmpInst::FCMP_OLE:
5726     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5727     break;
5728   case FCmpInst::FCMP_UNE:
5729   case FCmpInst::FCMP_ONE:
5730     Pred = ICmpInst::ICMP_NE;
5731     break;
5732   case FCmpInst::FCMP_ORD:
5733     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5734   case FCmpInst::FCMP_UNO:
5735     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5736   }
5737   
5738   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5739   
5740   // Now we know that the APFloat is a normal number, zero or inf.
5741   
5742   // See if the FP constant is too large for the integer.  For example,
5743   // comparing an i8 to 300.0.
5744   unsigned IntWidth = IntTy->getScalarSizeInBits();
5745   
5746   if (!LHSUnsigned) {
5747     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5748     // and large values.
5749     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5750     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5751                           APFloat::rmNearestTiesToEven);
5752     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5753       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5754           Pred == ICmpInst::ICMP_SLE)
5755         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5756       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5757     }
5758   } else {
5759     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5760     // +INF and large values.
5761     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5762     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5763                           APFloat::rmNearestTiesToEven);
5764     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5765       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5766           Pred == ICmpInst::ICMP_ULE)
5767         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5768       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5769     }
5770   }
5771   
5772   if (!LHSUnsigned) {
5773     // See if the RHS value is < SignedMin.
5774     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5775     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5776                           APFloat::rmNearestTiesToEven);
5777     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5778       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5779           Pred == ICmpInst::ICMP_SGE)
5780         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5781       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5782     }
5783   }
5784
5785   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5786   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5787   // casting the FP value to the integer value and back, checking for equality.
5788   // Don't do this for zero, because -0.0 is not fractional.
5789   Constant *RHSInt = LHSUnsigned
5790     ? Context->getConstantExprFPToUI(RHSC, IntTy)
5791     : Context->getConstantExprFPToSI(RHSC, IntTy);
5792   if (!RHS.isZero()) {
5793     bool Equal = LHSUnsigned
5794       ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5795       : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
5796     if (!Equal) {
5797       // If we had a comparison against a fractional value, we have to adjust
5798       // the compare predicate and sometimes the value.  RHSC is rounded towards
5799       // zero at this point.
5800       switch (Pred) {
5801       default: LLVM_UNREACHABLE("Unexpected integer comparison!");
5802       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5803         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5804       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5805         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5806       case ICmpInst::ICMP_ULE:
5807         // (float)int <= 4.4   --> int <= 4
5808         // (float)int <= -4.4  --> false
5809         if (RHS.isNegative())
5810           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5811         break;
5812       case ICmpInst::ICMP_SLE:
5813         // (float)int <= 4.4   --> int <= 4
5814         // (float)int <= -4.4  --> int < -4
5815         if (RHS.isNegative())
5816           Pred = ICmpInst::ICMP_SLT;
5817         break;
5818       case ICmpInst::ICMP_ULT:
5819         // (float)int < -4.4   --> false
5820         // (float)int < 4.4    --> int <= 4
5821         if (RHS.isNegative())
5822           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5823         Pred = ICmpInst::ICMP_ULE;
5824         break;
5825       case ICmpInst::ICMP_SLT:
5826         // (float)int < -4.4   --> int < -4
5827         // (float)int < 4.4    --> int <= 4
5828         if (!RHS.isNegative())
5829           Pred = ICmpInst::ICMP_SLE;
5830         break;
5831       case ICmpInst::ICMP_UGT:
5832         // (float)int > 4.4    --> int > 4
5833         // (float)int > -4.4   --> true
5834         if (RHS.isNegative())
5835           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5836         break;
5837       case ICmpInst::ICMP_SGT:
5838         // (float)int > 4.4    --> int > 4
5839         // (float)int > -4.4   --> int >= -4
5840         if (RHS.isNegative())
5841           Pred = ICmpInst::ICMP_SGE;
5842         break;
5843       case ICmpInst::ICMP_UGE:
5844         // (float)int >= -4.4   --> true
5845         // (float)int >= 4.4    --> int > 4
5846         if (!RHS.isNegative())
5847           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5848         Pred = ICmpInst::ICMP_UGT;
5849         break;
5850       case ICmpInst::ICMP_SGE:
5851         // (float)int >= -4.4   --> int >= -4
5852         // (float)int >= 4.4    --> int > 4
5853         if (!RHS.isNegative())
5854           Pred = ICmpInst::ICMP_SGT;
5855         break;
5856       }
5857     }
5858   }
5859
5860   // Lower this FP comparison into an appropriate integer version of the
5861   // comparison.
5862   return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
5863 }
5864
5865 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5866   bool Changed = SimplifyCompare(I);
5867   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5868
5869   // Fold trivial predicates.
5870   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5871     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5872   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5873     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5874   
5875   // Simplify 'fcmp pred X, X'
5876   if (Op0 == Op1) {
5877     switch (I.getPredicate()) {
5878     default: LLVM_UNREACHABLE("Unknown predicate!");
5879     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5880     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5881     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5882       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5883     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5884     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5885     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5886       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5887       
5888     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5889     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5890     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5891     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5892       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5893       I.setPredicate(FCmpInst::FCMP_UNO);
5894       I.setOperand(1, Context->getNullValue(Op0->getType()));
5895       return &I;
5896       
5897     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5898     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5899     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5900     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5901       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5902       I.setPredicate(FCmpInst::FCMP_ORD);
5903       I.setOperand(1, Context->getNullValue(Op0->getType()));
5904       return &I;
5905     }
5906   }
5907     
5908   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5909     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5910
5911   // Handle fcmp with constant RHS
5912   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5913     // If the constant is a nan, see if we can fold the comparison based on it.
5914     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5915       if (CFP->getValueAPF().isNaN()) {
5916         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5917           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5918         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5919                "Comparison must be either ordered or unordered!");
5920         // True if unordered.
5921         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5922       }
5923     }
5924     
5925     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5926       switch (LHSI->getOpcode()) {
5927       case Instruction::PHI:
5928         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5929         // block.  If in the same block, we're encouraging jump threading.  If
5930         // not, we are just pessimizing the code by making an i1 phi.
5931         if (LHSI->getParent() == I.getParent())
5932           if (Instruction *NV = FoldOpIntoPhi(I))
5933             return NV;
5934         break;
5935       case Instruction::SIToFP:
5936       case Instruction::UIToFP:
5937         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5938           return NV;
5939         break;
5940       case Instruction::Select:
5941         // If either operand of the select is a constant, we can fold the
5942         // comparison into the select arms, which will cause one to be
5943         // constant folded and the select turned into a bitwise or.
5944         Value *Op1 = 0, *Op2 = 0;
5945         if (LHSI->hasOneUse()) {
5946           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5947             // Fold the known value into the constant operand.
5948             Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5949             // Insert a new FCmp of the other select operand.
5950             Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5951                                                       LHSI->getOperand(2), RHSC,
5952                                                       I.getName()), I);
5953           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5954             // Fold the known value into the constant operand.
5955             Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5956             // Insert a new FCmp of the other select operand.
5957             Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5958                                                       LHSI->getOperand(1), RHSC,
5959                                                       I.getName()), I);
5960           }
5961         }
5962
5963         if (Op1)
5964           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5965         break;
5966       }
5967   }
5968
5969   return Changed ? &I : 0;
5970 }
5971
5972 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5973   bool Changed = SimplifyCompare(I);
5974   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5975   const Type *Ty = Op0->getType();
5976
5977   // icmp X, X
5978   if (Op0 == Op1)
5979     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
5980                                                    I.isTrueWhenEqual()));
5981
5982   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5983     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5984   
5985   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5986   // addresses never equal each other!  We already know that Op0 != Op1.
5987   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5988        isa<ConstantPointerNull>(Op0)) &&
5989       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5990        isa<ConstantPointerNull>(Op1)))
5991     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
5992                                                    !I.isTrueWhenEqual()));
5993
5994   // icmp's with boolean values can always be turned into bitwise operations
5995   if (Ty == Type::Int1Ty) {
5996     switch (I.getPredicate()) {
5997     default: LLVM_UNREACHABLE("Invalid icmp instruction!");
5998     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5999       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
6000       InsertNewInstBefore(Xor, I);
6001       return BinaryOperator::CreateNot(Xor);
6002     }
6003     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6004       return BinaryOperator::CreateXor(Op0, Op1);
6005
6006     case ICmpInst::ICMP_UGT:
6007       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6008       // FALL THROUGH
6009     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6010       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
6011       InsertNewInstBefore(Not, I);
6012       return BinaryOperator::CreateAnd(Not, Op1);
6013     }
6014     case ICmpInst::ICMP_SGT:
6015       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6016       // FALL THROUGH
6017     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6018       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6019       InsertNewInstBefore(Not, I);
6020       return BinaryOperator::CreateAnd(Not, Op0);
6021     }
6022     case ICmpInst::ICMP_UGE:
6023       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6024       // FALL THROUGH
6025     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6026       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
6027       InsertNewInstBefore(Not, I);
6028       return BinaryOperator::CreateOr(Not, Op1);
6029     }
6030     case ICmpInst::ICMP_SGE:
6031       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6032       // FALL THROUGH
6033     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6034       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6035       InsertNewInstBefore(Not, I);
6036       return BinaryOperator::CreateOr(Not, Op0);
6037     }
6038     }
6039   }
6040
6041   unsigned BitWidth = 0;
6042   if (TD)
6043     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6044   else if (Ty->isIntOrIntVector())
6045     BitWidth = Ty->getScalarSizeInBits();
6046
6047   bool isSignBit = false;
6048
6049   // See if we are doing a comparison with a constant.
6050   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6051     Value *A = 0, *B = 0;
6052     
6053     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6054     if (I.isEquality() && CI->isNullValue() &&
6055         match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
6056       // (icmp cond A B) if cond is equality
6057       return new ICmpInst(*Context, I.getPredicate(), A, B);
6058     }
6059     
6060     // If we have an icmp le or icmp ge instruction, turn it into the
6061     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6062     // them being folded in the code below.
6063     switch (I.getPredicate()) {
6064     default: break;
6065     case ICmpInst::ICMP_ULE:
6066       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6067         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6068       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6069                           AddOne(CI, Context));
6070     case ICmpInst::ICMP_SLE:
6071       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6072         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6073       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6074                           AddOne(CI, Context));
6075     case ICmpInst::ICMP_UGE:
6076       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6077         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6078       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6079                           SubOne(CI, Context));
6080     case ICmpInst::ICMP_SGE:
6081       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6082         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6083       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6084                           SubOne(CI, Context));
6085     }
6086     
6087     // If this comparison is a normal comparison, it demands all
6088     // bits, if it is a sign bit comparison, it only demands the sign bit.
6089     bool UnusedBit;
6090     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6091   }
6092
6093   // See if we can fold the comparison based on range information we can get
6094   // by checking whether bits are known to be zero or one in the input.
6095   if (BitWidth != 0) {
6096     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6097     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6098
6099     if (SimplifyDemandedBits(I.getOperandUse(0),
6100                              isSignBit ? APInt::getSignBit(BitWidth)
6101                                        : APInt::getAllOnesValue(BitWidth),
6102                              Op0KnownZero, Op0KnownOne, 0))
6103       return &I;
6104     if (SimplifyDemandedBits(I.getOperandUse(1),
6105                              APInt::getAllOnesValue(BitWidth),
6106                              Op1KnownZero, Op1KnownOne, 0))
6107       return &I;
6108
6109     // Given the known and unknown bits, compute a range that the LHS could be
6110     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6111     // EQ and NE we use unsigned values.
6112     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6113     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6114     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6115       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6116                                              Op0Min, Op0Max);
6117       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6118                                              Op1Min, Op1Max);
6119     } else {
6120       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6121                                                Op0Min, Op0Max);
6122       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6123                                                Op1Min, Op1Max);
6124     }
6125
6126     // If Min and Max are known to be the same, then SimplifyDemandedBits
6127     // figured out that the LHS is a constant.  Just constant fold this now so
6128     // that code below can assume that Min != Max.
6129     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6130       return new ICmpInst(*Context, I.getPredicate(),
6131                           Context->getConstantInt(Op0Min), Op1);
6132     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6133       return new ICmpInst(*Context, I.getPredicate(), Op0, 
6134                           Context->getConstantInt(Op1Min));
6135
6136     // Based on the range information we know about the LHS, see if we can
6137     // simplify this comparison.  For example, (x&4) < 8  is always true.
6138     switch (I.getPredicate()) {
6139     default: LLVM_UNREACHABLE("Unknown icmp opcode!");
6140     case ICmpInst::ICMP_EQ:
6141       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6142         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6143       break;
6144     case ICmpInst::ICMP_NE:
6145       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6146         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6147       break;
6148     case ICmpInst::ICMP_ULT:
6149       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6150         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6151       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6152         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6153       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6154         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6155       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6156         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6157           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6158                               SubOne(CI, Context));
6159
6160         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6161         if (CI->isMinValue(true))
6162           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6163                            Context->getConstantIntAllOnesValue(Op0->getType()));
6164       }
6165       break;
6166     case ICmpInst::ICMP_UGT:
6167       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6168         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6169       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6170         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6171
6172       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6173         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6174       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6175         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6176           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6177                               AddOne(CI, Context));
6178
6179         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6180         if (CI->isMaxValue(true))
6181           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6182                               Context->getNullValue(Op0->getType()));
6183       }
6184       break;
6185     case ICmpInst::ICMP_SLT:
6186       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6187         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6188       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6189         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6190       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6191         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6192       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6193         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6194           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6195                               SubOne(CI, Context));
6196       }
6197       break;
6198     case ICmpInst::ICMP_SGT:
6199       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6200         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6201       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6202         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6203
6204       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6205         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6206       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6207         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6208           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6209                               AddOne(CI, Context));
6210       }
6211       break;
6212     case ICmpInst::ICMP_SGE:
6213       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6214       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6215         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6216       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6217         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6218       break;
6219     case ICmpInst::ICMP_SLE:
6220       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6221       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6222         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6223       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6224         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6225       break;
6226     case ICmpInst::ICMP_UGE:
6227       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6228       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6229         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6230       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6231         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6232       break;
6233     case ICmpInst::ICMP_ULE:
6234       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6235       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6236         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6237       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6238         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6239       break;
6240     }
6241
6242     // Turn a signed comparison into an unsigned one if both operands
6243     // are known to have the same sign.
6244     if (I.isSignedPredicate() &&
6245         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6246          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6247       return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
6248   }
6249
6250   // Test if the ICmpInst instruction is used exclusively by a select as
6251   // part of a minimum or maximum operation. If so, refrain from doing
6252   // any other folding. This helps out other analyses which understand
6253   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6254   // and CodeGen. And in this case, at least one of the comparison
6255   // operands has at least one user besides the compare (the select),
6256   // which would often largely negate the benefit of folding anyway.
6257   if (I.hasOneUse())
6258     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6259       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6260           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6261         return 0;
6262
6263   // See if we are doing a comparison between a constant and an instruction that
6264   // can be folded into the comparison.
6265   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6266     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6267     // instruction, see if that instruction also has constants so that the 
6268     // instruction can be folded into the icmp 
6269     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6270       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6271         return Res;
6272   }
6273
6274   // Handle icmp with constant (but not simple integer constant) RHS
6275   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6276     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6277       switch (LHSI->getOpcode()) {
6278       case Instruction::GetElementPtr:
6279         if (RHSC->isNullValue()) {
6280           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6281           bool isAllZeros = true;
6282           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6283             if (!isa<Constant>(LHSI->getOperand(i)) ||
6284                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6285               isAllZeros = false;
6286               break;
6287             }
6288           if (isAllZeros)
6289             return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
6290                     Context->getNullValue(LHSI->getOperand(0)->getType()));
6291         }
6292         break;
6293
6294       case Instruction::PHI:
6295         // Only fold icmp into the PHI if the phi and fcmp are in the same
6296         // block.  If in the same block, we're encouraging jump threading.  If
6297         // not, we are just pessimizing the code by making an i1 phi.
6298         if (LHSI->getParent() == I.getParent())
6299           if (Instruction *NV = FoldOpIntoPhi(I))
6300             return NV;
6301         break;
6302       case Instruction::Select: {
6303         // If either operand of the select is a constant, we can fold the
6304         // comparison into the select arms, which will cause one to be
6305         // constant folded and the select turned into a bitwise or.
6306         Value *Op1 = 0, *Op2 = 0;
6307         if (LHSI->hasOneUse()) {
6308           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6309             // Fold the known value into the constant operand.
6310             Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6311             // Insert a new ICmp of the other select operand.
6312             Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6313                                                    LHSI->getOperand(2), RHSC,
6314                                                    I.getName()), I);
6315           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6316             // Fold the known value into the constant operand.
6317             Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6318             // Insert a new ICmp of the other select operand.
6319             Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6320                                                    LHSI->getOperand(1), RHSC,
6321                                                    I.getName()), I);
6322           }
6323         }
6324
6325         if (Op1)
6326           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6327         break;
6328       }
6329       case Instruction::Malloc:
6330         // If we have (malloc != null), and if the malloc has a single use, we
6331         // can assume it is successful and remove the malloc.
6332         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6333           AddToWorkList(LHSI);
6334           return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
6335                                                          !I.isTrueWhenEqual()));
6336         }
6337         break;
6338       }
6339   }
6340
6341   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6342   if (User *GEP = dyn_castGetElementPtr(Op0))
6343     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6344       return NI;
6345   if (User *GEP = dyn_castGetElementPtr(Op1))
6346     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6347                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6348       return NI;
6349
6350   // Test to see if the operands of the icmp are casted versions of other
6351   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6352   // now.
6353   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6354     if (isa<PointerType>(Op0->getType()) && 
6355         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6356       // We keep moving the cast from the left operand over to the right
6357       // operand, where it can often be eliminated completely.
6358       Op0 = CI->getOperand(0);
6359
6360       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6361       // so eliminate it as well.
6362       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6363         Op1 = CI2->getOperand(0);
6364
6365       // If Op1 is a constant, we can fold the cast into the constant.
6366       if (Op0->getType() != Op1->getType()) {
6367         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6368           Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
6369         } else {
6370           // Otherwise, cast the RHS right before the icmp
6371           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6372         }
6373       }
6374       return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
6375     }
6376   }
6377   
6378   if (isa<CastInst>(Op0)) {
6379     // Handle the special case of: icmp (cast bool to X), <cst>
6380     // This comes up when you have code like
6381     //   int X = A < B;
6382     //   if (X) ...
6383     // For generality, we handle any zero-extension of any operand comparison
6384     // with a constant or another cast from the same type.
6385     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6386       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6387         return R;
6388   }
6389   
6390   // See if it's the same type of instruction on the left and right.
6391   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6392     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6393       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6394           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6395         switch (Op0I->getOpcode()) {
6396         default: break;
6397         case Instruction::Add:
6398         case Instruction::Sub:
6399         case Instruction::Xor:
6400           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6401             return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
6402                                 Op1I->getOperand(0));
6403           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6404           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6405             if (CI->getValue().isSignBit()) {
6406               ICmpInst::Predicate Pred = I.isSignedPredicate()
6407                                              ? I.getUnsignedPredicate()
6408                                              : I.getSignedPredicate();
6409               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6410                                   Op1I->getOperand(0));
6411             }
6412             
6413             if (CI->getValue().isMaxSignedValue()) {
6414               ICmpInst::Predicate Pred = I.isSignedPredicate()
6415                                              ? I.getUnsignedPredicate()
6416                                              : I.getSignedPredicate();
6417               Pred = I.getSwappedPredicate(Pred);
6418               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6419                                   Op1I->getOperand(0));
6420             }
6421           }
6422           break;
6423         case Instruction::Mul:
6424           if (!I.isEquality())
6425             break;
6426
6427           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6428             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6429             // Mask = -1 >> count-trailing-zeros(Cst).
6430             if (!CI->isZero() && !CI->isOne()) {
6431               const APInt &AP = CI->getValue();
6432               ConstantInt *Mask = Context->getConstantInt(
6433                                       APInt::getLowBitsSet(AP.getBitWidth(),
6434                                                            AP.getBitWidth() -
6435                                                       AP.countTrailingZeros()));
6436               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6437                                                             Mask);
6438               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6439                                                             Mask);
6440               InsertNewInstBefore(And1, I);
6441               InsertNewInstBefore(And2, I);
6442               return new ICmpInst(*Context, I.getPredicate(), And1, And2);
6443             }
6444           }
6445           break;
6446         }
6447       }
6448     }
6449   }
6450   
6451   // ~x < ~y --> y < x
6452   { Value *A, *B;
6453     if (match(Op0, m_Not(m_Value(A)), *Context) &&
6454         match(Op1, m_Not(m_Value(B)), *Context))
6455       return new ICmpInst(*Context, I.getPredicate(), B, A);
6456   }
6457   
6458   if (I.isEquality()) {
6459     Value *A, *B, *C, *D;
6460     
6461     // -x == -y --> x == y
6462     if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6463         match(Op1, m_Neg(m_Value(B)), *Context))
6464       return new ICmpInst(*Context, I.getPredicate(), A, B);
6465     
6466     if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
6467       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6468         Value *OtherVal = A == Op1 ? B : A;
6469         return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6470                             Context->getNullValue(A->getType()));
6471       }
6472
6473       if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
6474         // A^c1 == C^c2 --> A == C^(c1^c2)
6475         ConstantInt *C1, *C2;
6476         if (match(B, m_ConstantInt(C1), *Context) &&
6477             match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
6478           Constant *NC = 
6479                        Context->getConstantInt(C1->getValue() ^ C2->getValue());
6480           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6481           return new ICmpInst(*Context, I.getPredicate(), A,
6482                               InsertNewInstBefore(Xor, I));
6483         }
6484         
6485         // A^B == A^D -> B == D
6486         if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6487         if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6488         if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6489         if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
6490       }
6491     }
6492     
6493     if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
6494         (A == Op0 || B == Op0)) {
6495       // A == (A^B)  ->  B == 0
6496       Value *OtherVal = A == Op0 ? B : A;
6497       return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6498                           Context->getNullValue(A->getType()));
6499     }
6500
6501     // (A-B) == A  ->  B == 0
6502     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
6503       return new ICmpInst(*Context, I.getPredicate(), B, 
6504                           Context->getNullValue(B->getType()));
6505
6506     // A == (A-B)  ->  B == 0
6507     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
6508       return new ICmpInst(*Context, I.getPredicate(), B,
6509                           Context->getNullValue(B->getType()));
6510     
6511     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6512     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6513         match(Op0, m_And(m_Value(A), m_Value(B)), *Context) && 
6514         match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
6515       Value *X = 0, *Y = 0, *Z = 0;
6516       
6517       if (A == C) {
6518         X = B; Y = D; Z = A;
6519       } else if (A == D) {
6520         X = B; Y = C; Z = A;
6521       } else if (B == C) {
6522         X = A; Y = D; Z = B;
6523       } else if (B == D) {
6524         X = A; Y = C; Z = B;
6525       }
6526       
6527       if (X) {   // Build (X^Y) & Z
6528         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6529         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6530         I.setOperand(0, Op1);
6531         I.setOperand(1, Context->getNullValue(Op1->getType()));
6532         return &I;
6533       }
6534     }
6535   }
6536   return Changed ? &I : 0;
6537 }
6538
6539
6540 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6541 /// and CmpRHS are both known to be integer constants.
6542 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6543                                           ConstantInt *DivRHS) {
6544   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6545   const APInt &CmpRHSV = CmpRHS->getValue();
6546   
6547   // FIXME: If the operand types don't match the type of the divide 
6548   // then don't attempt this transform. The code below doesn't have the
6549   // logic to deal with a signed divide and an unsigned compare (and
6550   // vice versa). This is because (x /s C1) <s C2  produces different 
6551   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6552   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6553   // work. :(  The if statement below tests that condition and bails 
6554   // if it finds it. 
6555   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6556   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6557     return 0;
6558   if (DivRHS->isZero())
6559     return 0; // The ProdOV computation fails on divide by zero.
6560   if (DivIsSigned && DivRHS->isAllOnesValue())
6561     return 0; // The overflow computation also screws up here
6562   if (DivRHS->isOne())
6563     return 0; // Not worth bothering, and eliminates some funny cases
6564               // with INT_MIN.
6565
6566   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6567   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6568   // C2 (CI). By solving for X we can turn this into a range check 
6569   // instead of computing a divide. 
6570   Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
6571
6572   // Determine if the product overflows by seeing if the product is
6573   // not equal to the divide. Make sure we do the same kind of divide
6574   // as in the LHS instruction that we're folding. 
6575   bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6576                  Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
6577
6578   // Get the ICmp opcode
6579   ICmpInst::Predicate Pred = ICI.getPredicate();
6580
6581   // Figure out the interval that is being checked.  For example, a comparison
6582   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6583   // Compute this interval based on the constants involved and the signedness of
6584   // the compare/divide.  This computes a half-open interval, keeping track of
6585   // whether either value in the interval overflows.  After analysis each
6586   // overflow variable is set to 0 if it's corresponding bound variable is valid
6587   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6588   int LoOverflow = 0, HiOverflow = 0;
6589   Constant *LoBound = 0, *HiBound = 0;
6590   
6591   if (!DivIsSigned) {  // udiv
6592     // e.g. X/5 op 3  --> [15, 20)
6593     LoBound = Prod;
6594     HiOverflow = LoOverflow = ProdOV;
6595     if (!HiOverflow)
6596       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6597   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6598     if (CmpRHSV == 0) {       // (X / pos) op 0
6599       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6600       LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS, 
6601                                                                     Context)));
6602       HiBound = DivRHS;
6603     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6604       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6605       HiOverflow = LoOverflow = ProdOV;
6606       if (!HiOverflow)
6607         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6608     } else {                       // (X / pos) op neg
6609       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6610       HiBound = AddOne(Prod, Context);
6611       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6612       if (!LoOverflow) {
6613         ConstantInt* DivNeg =
6614                          cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6615         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6616                                      true) ? -1 : 0;
6617        }
6618     }
6619   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6620     if (CmpRHSV == 0) {       // (X / neg) op 0
6621       // e.g. X/-5 op 0  --> [-4, 5)
6622       LoBound = AddOne(DivRHS, Context);
6623       HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6624       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6625         HiOverflow = 1;            // [INTMIN+1, overflow)
6626         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6627       }
6628     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6629       // e.g. X/-5 op 3  --> [-19, -14)
6630       HiBound = AddOne(Prod, Context);
6631       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6632       if (!LoOverflow)
6633         LoOverflow = AddWithOverflow(LoBound, HiBound,
6634                                      DivRHS, Context, true) ? -1 : 0;
6635     } else {                       // (X / neg) op neg
6636       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6637       LoOverflow = HiOverflow = ProdOV;
6638       if (!HiOverflow)
6639         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6640     }
6641     
6642     // Dividing by a negative swaps the condition.  LT <-> GT
6643     Pred = ICmpInst::getSwappedPredicate(Pred);
6644   }
6645
6646   Value *X = DivI->getOperand(0);
6647   switch (Pred) {
6648   default: LLVM_UNREACHABLE("Unhandled icmp opcode!");
6649   case ICmpInst::ICMP_EQ:
6650     if (LoOverflow && HiOverflow)
6651       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6652     else if (HiOverflow)
6653       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6654                           ICmpInst::ICMP_UGE, X, LoBound);
6655     else if (LoOverflow)
6656       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6657                           ICmpInst::ICMP_ULT, X, HiBound);
6658     else
6659       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6660   case ICmpInst::ICMP_NE:
6661     if (LoOverflow && HiOverflow)
6662       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6663     else if (HiOverflow)
6664       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6665                           ICmpInst::ICMP_ULT, X, LoBound);
6666     else if (LoOverflow)
6667       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6668                           ICmpInst::ICMP_UGE, X, HiBound);
6669     else
6670       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6671   case ICmpInst::ICMP_ULT:
6672   case ICmpInst::ICMP_SLT:
6673     if (LoOverflow == +1)   // Low bound is greater than input range.
6674       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6675     if (LoOverflow == -1)   // Low bound is less than input range.
6676       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6677     return new ICmpInst(*Context, Pred, X, LoBound);
6678   case ICmpInst::ICMP_UGT:
6679   case ICmpInst::ICMP_SGT:
6680     if (HiOverflow == +1)       // High bound greater than input range.
6681       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6682     else if (HiOverflow == -1)  // High bound less than input range.
6683       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6684     if (Pred == ICmpInst::ICMP_UGT)
6685       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
6686     else
6687       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
6688   }
6689 }
6690
6691
6692 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6693 ///
6694 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6695                                                           Instruction *LHSI,
6696                                                           ConstantInt *RHS) {
6697   const APInt &RHSV = RHS->getValue();
6698   
6699   switch (LHSI->getOpcode()) {
6700   case Instruction::Trunc:
6701     if (ICI.isEquality() && LHSI->hasOneUse()) {
6702       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6703       // of the high bits truncated out of x are known.
6704       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6705              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6706       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6707       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6708       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6709       
6710       // If all the high bits are known, we can do this xform.
6711       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6712         // Pull in the high bits from known-ones set.
6713         APInt NewRHS(RHS->getValue());
6714         NewRHS.zext(SrcBits);
6715         NewRHS |= KnownOne;
6716         return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6717                             Context->getConstantInt(NewRHS));
6718       }
6719     }
6720     break;
6721       
6722   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6723     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6724       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6725       // fold the xor.
6726       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6727           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6728         Value *CompareVal = LHSI->getOperand(0);
6729         
6730         // If the sign bit of the XorCST is not set, there is no change to
6731         // the operation, just stop using the Xor.
6732         if (!XorCST->getValue().isNegative()) {
6733           ICI.setOperand(0, CompareVal);
6734           AddToWorkList(LHSI);
6735           return &ICI;
6736         }
6737         
6738         // Was the old condition true if the operand is positive?
6739         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6740         
6741         // If so, the new one isn't.
6742         isTrueIfPositive ^= true;
6743         
6744         if (isTrueIfPositive)
6745           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
6746                               SubOne(RHS, Context));
6747         else
6748           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
6749                               AddOne(RHS, Context));
6750       }
6751
6752       if (LHSI->hasOneUse()) {
6753         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6754         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6755           const APInt &SignBit = XorCST->getValue();
6756           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6757                                          ? ICI.getUnsignedPredicate()
6758                                          : ICI.getSignedPredicate();
6759           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6760                               Context->getConstantInt(RHSV ^ SignBit));
6761         }
6762
6763         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6764         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6765           const APInt &NotSignBit = XorCST->getValue();
6766           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6767                                          ? ICI.getUnsignedPredicate()
6768                                          : ICI.getSignedPredicate();
6769           Pred = ICI.getSwappedPredicate(Pred);
6770           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6771                               Context->getConstantInt(RHSV ^ NotSignBit));
6772         }
6773       }
6774     }
6775     break;
6776   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6777     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6778         LHSI->getOperand(0)->hasOneUse()) {
6779       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6780       
6781       // If the LHS is an AND of a truncating cast, we can widen the
6782       // and/compare to be the input width without changing the value
6783       // produced, eliminating a cast.
6784       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6785         // We can do this transformation if either the AND constant does not
6786         // have its sign bit set or if it is an equality comparison. 
6787         // Extending a relational comparison when we're checking the sign
6788         // bit would not work.
6789         if (Cast->hasOneUse() &&
6790             (ICI.isEquality() ||
6791              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6792           uint32_t BitWidth = 
6793             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6794           APInt NewCST = AndCST->getValue();
6795           NewCST.zext(BitWidth);
6796           APInt NewCI = RHSV;
6797           NewCI.zext(BitWidth);
6798           Instruction *NewAnd = 
6799             BinaryOperator::CreateAnd(Cast->getOperand(0),
6800                                Context->getConstantInt(NewCST),LHSI->getName());
6801           InsertNewInstBefore(NewAnd, ICI);
6802           return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
6803                               Context->getConstantInt(NewCI));
6804         }
6805       }
6806       
6807       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6808       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6809       // happens a LOT in code produced by the C front-end, for bitfield
6810       // access.
6811       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6812       if (Shift && !Shift->isShift())
6813         Shift = 0;
6814       
6815       ConstantInt *ShAmt;
6816       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6817       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6818       const Type *AndTy = AndCST->getType();          // Type of the and.
6819       
6820       // We can fold this as long as we can't shift unknown bits
6821       // into the mask.  This can only happen with signed shift
6822       // rights, as they sign-extend.
6823       if (ShAmt) {
6824         bool CanFold = Shift->isLogicalShift();
6825         if (!CanFold) {
6826           // To test for the bad case of the signed shr, see if any
6827           // of the bits shifted in could be tested after the mask.
6828           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6829           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6830           
6831           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6832           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6833                AndCST->getValue()) == 0)
6834             CanFold = true;
6835         }
6836         
6837         if (CanFold) {
6838           Constant *NewCst;
6839           if (Shift->getOpcode() == Instruction::Shl)
6840             NewCst = Context->getConstantExprLShr(RHS, ShAmt);
6841           else
6842             NewCst = Context->getConstantExprShl(RHS, ShAmt);
6843           
6844           // Check to see if we are shifting out any of the bits being
6845           // compared.
6846           if (Context->getConstantExpr(Shift->getOpcode(),
6847                                        NewCst, ShAmt) != RHS) {
6848             // If we shifted bits out, the fold is not going to work out.
6849             // As a special case, check to see if this means that the
6850             // result is always true or false now.
6851             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6852               return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6853             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6854               return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6855           } else {
6856             ICI.setOperand(1, NewCst);
6857             Constant *NewAndCST;
6858             if (Shift->getOpcode() == Instruction::Shl)
6859               NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
6860             else
6861               NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
6862             LHSI->setOperand(1, NewAndCST);
6863             LHSI->setOperand(0, Shift->getOperand(0));
6864             AddToWorkList(Shift); // Shift is dead.
6865             AddUsesToWorkList(ICI);
6866             return &ICI;
6867           }
6868         }
6869       }
6870       
6871       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6872       // preferable because it allows the C<<Y expression to be hoisted out
6873       // of a loop if Y is invariant and X is not.
6874       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6875           ICI.isEquality() && !Shift->isArithmeticShift() &&
6876           !isa<Constant>(Shift->getOperand(0))) {
6877         // Compute C << Y.
6878         Value *NS;
6879         if (Shift->getOpcode() == Instruction::LShr) {
6880           NS = BinaryOperator::CreateShl(AndCST, 
6881                                          Shift->getOperand(1), "tmp");
6882         } else {
6883           // Insert a logical shift.
6884           NS = BinaryOperator::CreateLShr(AndCST,
6885                                           Shift->getOperand(1), "tmp");
6886         }
6887         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6888         
6889         // Compute X & (C << Y).
6890         Instruction *NewAnd = 
6891           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6892         InsertNewInstBefore(NewAnd, ICI);
6893         
6894         ICI.setOperand(0, NewAnd);
6895         return &ICI;
6896       }
6897     }
6898     break;
6899     
6900   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6901     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6902     if (!ShAmt) break;
6903     
6904     uint32_t TypeBits = RHSV.getBitWidth();
6905     
6906     // Check that the shift amount is in range.  If not, don't perform
6907     // undefined shifts.  When the shift is visited it will be
6908     // simplified.
6909     if (ShAmt->uge(TypeBits))
6910       break;
6911     
6912     if (ICI.isEquality()) {
6913       // If we are comparing against bits always shifted out, the
6914       // comparison cannot succeed.
6915       Constant *Comp =
6916         Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6917                                                                  ShAmt);
6918       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6919         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6920         Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6921         return ReplaceInstUsesWith(ICI, Cst);
6922       }
6923       
6924       if (LHSI->hasOneUse()) {
6925         // Otherwise strength reduce the shift into an and.
6926         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6927         Constant *Mask =
6928           Context->getConstantInt(APInt::getLowBitsSet(TypeBits, 
6929                                                        TypeBits-ShAmtVal));
6930         
6931         Instruction *AndI =
6932           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6933                                     Mask, LHSI->getName()+".mask");
6934         Value *And = InsertNewInstBefore(AndI, ICI);
6935         return new ICmpInst(*Context, ICI.getPredicate(), And,
6936                             Context->getConstantInt(RHSV.lshr(ShAmtVal)));
6937       }
6938     }
6939     
6940     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6941     bool TrueIfSigned = false;
6942     if (LHSI->hasOneUse() &&
6943         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6944       // (X << 31) <s 0  --> (X&1) != 0
6945       Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
6946                                            (TypeBits-ShAmt->getZExtValue()-1));
6947       Instruction *AndI =
6948         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6949                                   Mask, LHSI->getName()+".mask");
6950       Value *And = InsertNewInstBefore(AndI, ICI);
6951       
6952       return new ICmpInst(*Context,
6953                           TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6954                           And, Context->getNullValue(And->getType()));
6955     }
6956     break;
6957   }
6958     
6959   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6960   case Instruction::AShr: {
6961     // Only handle equality comparisons of shift-by-constant.
6962     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6963     if (!ShAmt || !ICI.isEquality()) break;
6964
6965     // Check that the shift amount is in range.  If not, don't perform
6966     // undefined shifts.  When the shift is visited it will be
6967     // simplified.
6968     uint32_t TypeBits = RHSV.getBitWidth();
6969     if (ShAmt->uge(TypeBits))
6970       break;
6971     
6972     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6973       
6974     // If we are comparing against bits always shifted out, the
6975     // comparison cannot succeed.
6976     APInt Comp = RHSV << ShAmtVal;
6977     if (LHSI->getOpcode() == Instruction::LShr)
6978       Comp = Comp.lshr(ShAmtVal);
6979     else
6980       Comp = Comp.ashr(ShAmtVal);
6981     
6982     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6983       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6984       Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6985       return ReplaceInstUsesWith(ICI, Cst);
6986     }
6987     
6988     // Otherwise, check to see if the bits shifted out are known to be zero.
6989     // If so, we can compare against the unshifted value:
6990     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6991     if (LHSI->hasOneUse() &&
6992         MaskedValueIsZero(LHSI->getOperand(0), 
6993                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6994       return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6995                           Context->getConstantExprShl(RHS, ShAmt));
6996     }
6997       
6998     if (LHSI->hasOneUse()) {
6999       // Otherwise strength reduce the shift into an and.
7000       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7001       Constant *Mask = Context->getConstantInt(Val);
7002       
7003       Instruction *AndI =
7004         BinaryOperator::CreateAnd(LHSI->getOperand(0),
7005                                   Mask, LHSI->getName()+".mask");
7006       Value *And = InsertNewInstBefore(AndI, ICI);
7007       return new ICmpInst(*Context, ICI.getPredicate(), And,
7008                           Context->getConstantExprShl(RHS, ShAmt));
7009     }
7010     break;
7011   }
7012     
7013   case Instruction::SDiv:
7014   case Instruction::UDiv:
7015     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7016     // Fold this div into the comparison, producing a range check. 
7017     // Determine, based on the divide type, what the range is being 
7018     // checked.  If there is an overflow on the low or high side, remember 
7019     // it, otherwise compute the range [low, hi) bounding the new value.
7020     // See: InsertRangeTest above for the kinds of replacements possible.
7021     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7022       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7023                                           DivRHS))
7024         return R;
7025     break;
7026
7027   case Instruction::Add:
7028     // Fold: icmp pred (add, X, C1), C2
7029
7030     if (!ICI.isEquality()) {
7031       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7032       if (!LHSC) break;
7033       const APInt &LHSV = LHSC->getValue();
7034
7035       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7036                             .subtract(LHSV);
7037
7038       if (ICI.isSignedPredicate()) {
7039         if (CR.getLower().isSignBit()) {
7040           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7041                               Context->getConstantInt(CR.getUpper()));
7042         } else if (CR.getUpper().isSignBit()) {
7043           return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7044                               Context->getConstantInt(CR.getLower()));
7045         }
7046       } else {
7047         if (CR.getLower().isMinValue()) {
7048           return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7049                               Context->getConstantInt(CR.getUpper()));
7050         } else if (CR.getUpper().isMinValue()) {
7051           return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7052                               Context->getConstantInt(CR.getLower()));
7053         }
7054       }
7055     }
7056     break;
7057   }
7058   
7059   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7060   if (ICI.isEquality()) {
7061     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7062     
7063     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7064     // the second operand is a constant, simplify a bit.
7065     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7066       switch (BO->getOpcode()) {
7067       case Instruction::SRem:
7068         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7069         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7070           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7071           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7072             Instruction *NewRem =
7073               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7074                                          BO->getName());
7075             InsertNewInstBefore(NewRem, ICI);
7076             return new ICmpInst(*Context, ICI.getPredicate(), NewRem, 
7077                                 Context->getNullValue(BO->getType()));
7078           }
7079         }
7080         break;
7081       case Instruction::Add:
7082         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7083         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7084           if (BO->hasOneUse())
7085             return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7086                                 Context->getConstantExprSub(RHS, BOp1C));
7087         } else if (RHSV == 0) {
7088           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7089           // efficiently invertible, or if the add has just this one use.
7090           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7091           
7092           if (Value *NegVal = dyn_castNegVal(BOp1, Context))
7093             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
7094           else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
7095             return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
7096           else if (BO->hasOneUse()) {
7097             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
7098             InsertNewInstBefore(Neg, ICI);
7099             Neg->takeName(BO);
7100             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
7101           }
7102         }
7103         break;
7104       case Instruction::Xor:
7105         // For the xor case, we can xor two constants together, eliminating
7106         // the explicit xor.
7107         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7108           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0), 
7109                               Context->getConstantExprXor(RHS, BOC));
7110         
7111         // FALLTHROUGH
7112       case Instruction::Sub:
7113         // Replace (([sub|xor] A, B) != 0) with (A != B)
7114         if (RHSV == 0)
7115           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7116                               BO->getOperand(1));
7117         break;
7118         
7119       case Instruction::Or:
7120         // If bits are being or'd in that are not present in the constant we
7121         // are comparing against, then the comparison could never succeed!
7122         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7123           Constant *NotCI = Context->getConstantExprNot(RHS);
7124           if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7125             return ReplaceInstUsesWith(ICI,
7126                                        Context->getConstantInt(Type::Int1Ty, 
7127                                        isICMP_NE));
7128         }
7129         break;
7130         
7131       case Instruction::And:
7132         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7133           // If bits are being compared against that are and'd out, then the
7134           // comparison can never succeed!
7135           if ((RHSV & ~BOC->getValue()) != 0)
7136             return ReplaceInstUsesWith(ICI,
7137                                        Context->getConstantInt(Type::Int1Ty,
7138                                        isICMP_NE));
7139           
7140           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7141           if (RHS == BOC && RHSV.isPowerOf2())
7142             return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
7143                                 ICmpInst::ICMP_NE, LHSI,
7144                                 Context->getNullValue(RHS->getType()));
7145           
7146           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7147           if (BOC->getValue().isSignBit()) {
7148             Value *X = BO->getOperand(0);
7149             Constant *Zero = Context->getNullValue(X->getType());
7150             ICmpInst::Predicate pred = isICMP_NE ? 
7151               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7152             return new ICmpInst(*Context, pred, X, Zero);
7153           }
7154           
7155           // ((X & ~7) == 0) --> X < 8
7156           if (RHSV == 0 && isHighOnes(BOC)) {
7157             Value *X = BO->getOperand(0);
7158             Constant *NegX = Context->getConstantExprNeg(BOC);
7159             ICmpInst::Predicate pred = isICMP_NE ? 
7160               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7161             return new ICmpInst(*Context, pred, X, NegX);
7162           }
7163         }
7164       default: break;
7165       }
7166     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7167       // Handle icmp {eq|ne} <intrinsic>, intcst.
7168       if (II->getIntrinsicID() == Intrinsic::bswap) {
7169         AddToWorkList(II);
7170         ICI.setOperand(0, II->getOperand(1));
7171         ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
7172         return &ICI;
7173       }
7174     }
7175   }
7176   return 0;
7177 }
7178
7179 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7180 /// We only handle extending casts so far.
7181 ///
7182 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7183   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7184   Value *LHSCIOp        = LHSCI->getOperand(0);
7185   const Type *SrcTy     = LHSCIOp->getType();
7186   const Type *DestTy    = LHSCI->getType();
7187   Value *RHSCIOp;
7188
7189   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7190   // integer type is the same size as the pointer type.
7191   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7192       getTargetData().getPointerSizeInBits() == 
7193          cast<IntegerType>(DestTy)->getBitWidth()) {
7194     Value *RHSOp = 0;
7195     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7196       RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
7197     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7198       RHSOp = RHSC->getOperand(0);
7199       // If the pointer types don't match, insert a bitcast.
7200       if (LHSCIOp->getType() != RHSOp->getType())
7201         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7202     }
7203
7204     if (RHSOp)
7205       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
7206   }
7207   
7208   // The code below only handles extension cast instructions, so far.
7209   // Enforce this.
7210   if (LHSCI->getOpcode() != Instruction::ZExt &&
7211       LHSCI->getOpcode() != Instruction::SExt)
7212     return 0;
7213
7214   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7215   bool isSignedCmp = ICI.isSignedPredicate();
7216
7217   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7218     // Not an extension from the same type?
7219     RHSCIOp = CI->getOperand(0);
7220     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7221       return 0;
7222     
7223     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7224     // and the other is a zext), then we can't handle this.
7225     if (CI->getOpcode() != LHSCI->getOpcode())
7226       return 0;
7227
7228     // Deal with equality cases early.
7229     if (ICI.isEquality())
7230       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7231
7232     // A signed comparison of sign extended values simplifies into a
7233     // signed comparison.
7234     if (isSignedCmp && isSignedExt)
7235       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7236
7237     // The other three cases all fold into an unsigned comparison.
7238     return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7239   }
7240
7241   // If we aren't dealing with a constant on the RHS, exit early
7242   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7243   if (!CI)
7244     return 0;
7245
7246   // Compute the constant that would happen if we truncated to SrcTy then
7247   // reextended to DestTy.
7248   Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7249   Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7250                                                 Res1, DestTy);
7251
7252   // If the re-extended constant didn't change...
7253   if (Res2 == CI) {
7254     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7255     // For example, we might have:
7256     //    %A = sext i16 %X to i32
7257     //    %B = icmp ugt i32 %A, 1330
7258     // It is incorrect to transform this into 
7259     //    %B = icmp ugt i16 %X, 1330
7260     // because %A may have negative value. 
7261     //
7262     // However, we allow this when the compare is EQ/NE, because they are
7263     // signless.
7264     if (isSignedExt == isSignedCmp || ICI.isEquality())
7265       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
7266     return 0;
7267   }
7268
7269   // The re-extended constant changed so the constant cannot be represented 
7270   // in the shorter type. Consequently, we cannot emit a simple comparison.
7271
7272   // First, handle some easy cases. We know the result cannot be equal at this
7273   // point so handle the ICI.isEquality() cases
7274   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7275     return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
7276   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7277     return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
7278
7279   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7280   // should have been folded away previously and not enter in here.
7281   Value *Result;
7282   if (isSignedCmp) {
7283     // We're performing a signed comparison.
7284     if (cast<ConstantInt>(CI)->getValue().isNegative())
7285       Result = Context->getConstantIntFalse();          // X < (small) --> false
7286     else
7287       Result = Context->getConstantIntTrue();           // X < (large) --> true
7288   } else {
7289     // We're performing an unsigned comparison.
7290     if (isSignedExt) {
7291       // We're performing an unsigned comp with a sign extended value.
7292       // This is true if the input is >= 0. [aka >s -1]
7293       Constant *NegOne = Context->getConstantIntAllOnesValue(SrcTy);
7294       Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT, 
7295                                    LHSCIOp, NegOne, ICI.getName()), ICI);
7296     } else {
7297       // Unsigned extend & unsigned compare -> always true.
7298       Result = Context->getConstantIntTrue();
7299     }
7300   }
7301
7302   // Finally, return the value computed.
7303   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7304       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7305     return ReplaceInstUsesWith(ICI, Result);
7306
7307   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7308           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7309          "ICmp should be folded!");
7310   if (Constant *CI = dyn_cast<Constant>(Result))
7311     return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
7312   return BinaryOperator::CreateNot(Result);
7313 }
7314
7315 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7316   return commonShiftTransforms(I);
7317 }
7318
7319 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7320   return commonShiftTransforms(I);
7321 }
7322
7323 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7324   if (Instruction *R = commonShiftTransforms(I))
7325     return R;
7326   
7327   Value *Op0 = I.getOperand(0);
7328   
7329   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7330   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7331     if (CSI->isAllOnesValue())
7332       return ReplaceInstUsesWith(I, CSI);
7333
7334   // See if we can turn a signed shr into an unsigned shr.
7335   if (MaskedValueIsZero(Op0,
7336                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7337     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7338
7339   // Arithmetic shifting an all-sign-bit value is a no-op.
7340   unsigned NumSignBits = ComputeNumSignBits(Op0);
7341   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7342     return ReplaceInstUsesWith(I, Op0);
7343
7344   return 0;
7345 }
7346
7347 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7348   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7349   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7350
7351   // shl X, 0 == X and shr X, 0 == X
7352   // shl 0, X == 0 and shr 0, X == 0
7353   if (Op1 == Context->getNullValue(Op1->getType()) ||
7354       Op0 == Context->getNullValue(Op0->getType()))
7355     return ReplaceInstUsesWith(I, Op0);
7356   
7357   if (isa<UndefValue>(Op0)) {            
7358     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7359       return ReplaceInstUsesWith(I, Op0);
7360     else                                    // undef << X -> 0, undef >>u X -> 0
7361       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7362   }
7363   if (isa<UndefValue>(Op1)) {
7364     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7365       return ReplaceInstUsesWith(I, Op0);          
7366     else                                     // X << undef, X >>u undef -> 0
7367       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7368   }
7369
7370   // See if we can fold away this shift.
7371   if (SimplifyDemandedInstructionBits(I))
7372     return &I;
7373
7374   // Try to fold constant and into select arguments.
7375   if (isa<Constant>(Op0))
7376     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7377       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7378         return R;
7379
7380   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7381     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7382       return Res;
7383   return 0;
7384 }
7385
7386 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7387                                                BinaryOperator &I) {
7388   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7389
7390   // See if we can simplify any instructions used by the instruction whose sole 
7391   // purpose is to compute bits we don't care about.
7392   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7393   
7394   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7395   // a signed shift.
7396   //
7397   if (Op1->uge(TypeBits)) {
7398     if (I.getOpcode() != Instruction::AShr)
7399       return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
7400     else {
7401       I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
7402       return &I;
7403     }
7404   }
7405   
7406   // ((X*C1) << C2) == (X * (C1 << C2))
7407   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7408     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7409       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7410         return BinaryOperator::CreateMul(BO->getOperand(0),
7411                                         Context->getConstantExprShl(BOOp, Op1));
7412   
7413   // Try to fold constant and into select arguments.
7414   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7415     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7416       return R;
7417   if (isa<PHINode>(Op0))
7418     if (Instruction *NV = FoldOpIntoPhi(I))
7419       return NV;
7420   
7421   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7422   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7423     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7424     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7425     // place.  Don't try to do this transformation in this case.  Also, we
7426     // require that the input operand is a shift-by-constant so that we have
7427     // confidence that the shifts will get folded together.  We could do this
7428     // xform in more cases, but it is unlikely to be profitable.
7429     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7430         isa<ConstantInt>(TrOp->getOperand(1))) {
7431       // Okay, we'll do this xform.  Make the shift of shift.
7432       Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
7433       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7434                                                 I.getName());
7435       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7436
7437       // For logical shifts, the truncation has the effect of making the high
7438       // part of the register be zeros.  Emulate this by inserting an AND to
7439       // clear the top bits as needed.  This 'and' will usually be zapped by
7440       // other xforms later if dead.
7441       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7442       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7443       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7444       
7445       // The mask we constructed says what the trunc would do if occurring
7446       // between the shifts.  We want to know the effect *after* the second
7447       // shift.  We know that it is a logical shift by a constant, so adjust the
7448       // mask as appropriate.
7449       if (I.getOpcode() == Instruction::Shl)
7450         MaskV <<= Op1->getZExtValue();
7451       else {
7452         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7453         MaskV = MaskV.lshr(Op1->getZExtValue());
7454       }
7455
7456       Instruction *And =
7457         BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV), 
7458                                   TI->getName());
7459       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7460
7461       // Return the value truncated to the interesting size.
7462       return new TruncInst(And, I.getType());
7463     }
7464   }
7465   
7466   if (Op0->hasOneUse()) {
7467     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7468       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7469       Value *V1, *V2;
7470       ConstantInt *CC;
7471       switch (Op0BO->getOpcode()) {
7472         default: break;
7473         case Instruction::Add:
7474         case Instruction::And:
7475         case Instruction::Or:
7476         case Instruction::Xor: {
7477           // These operators commute.
7478           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7479           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7480               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7481                     m_Specific(Op1)), *Context)){
7482             Instruction *YS = BinaryOperator::CreateShl(
7483                                             Op0BO->getOperand(0), Op1,
7484                                             Op0BO->getName());
7485             InsertNewInstBefore(YS, I); // (Y << C)
7486             Instruction *X = 
7487               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7488                                      Op0BO->getOperand(1)->getName());
7489             InsertNewInstBefore(X, I);  // (X + (Y << C))
7490             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7491             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7492                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7493           }
7494           
7495           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7496           Value *Op0BOOp1 = Op0BO->getOperand(1);
7497           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7498               match(Op0BOOp1, 
7499                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7500                           m_ConstantInt(CC)), *Context) &&
7501               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7502             Instruction *YS = BinaryOperator::CreateShl(
7503                                                      Op0BO->getOperand(0), Op1,
7504                                                      Op0BO->getName());
7505             InsertNewInstBefore(YS, I); // (Y << C)
7506             Instruction *XM =
7507               BinaryOperator::CreateAnd(V1,
7508                                         Context->getConstantExprShl(CC, Op1),
7509                                         V1->getName()+".mask");
7510             InsertNewInstBefore(XM, I); // X & (CC << C)
7511             
7512             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7513           }
7514         }
7515           
7516         // FALL THROUGH.
7517         case Instruction::Sub: {
7518           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7519           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7520               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7521                     m_Specific(Op1)), *Context)){
7522             Instruction *YS = BinaryOperator::CreateShl(
7523                                                      Op0BO->getOperand(1), Op1,
7524                                                      Op0BO->getName());
7525             InsertNewInstBefore(YS, I); // (Y << C)
7526             Instruction *X =
7527               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7528                                      Op0BO->getOperand(0)->getName());
7529             InsertNewInstBefore(X, I);  // (X + (Y << C))
7530             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7531             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7532                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7533           }
7534           
7535           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7536           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7537               match(Op0BO->getOperand(0),
7538                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7539                           m_ConstantInt(CC)), *Context) && V2 == Op1 &&
7540               cast<BinaryOperator>(Op0BO->getOperand(0))
7541                   ->getOperand(0)->hasOneUse()) {
7542             Instruction *YS = BinaryOperator::CreateShl(
7543                                                      Op0BO->getOperand(1), Op1,
7544                                                      Op0BO->getName());
7545             InsertNewInstBefore(YS, I); // (Y << C)
7546             Instruction *XM =
7547               BinaryOperator::CreateAnd(V1, 
7548                                         Context->getConstantExprShl(CC, Op1),
7549                                         V1->getName()+".mask");
7550             InsertNewInstBefore(XM, I); // X & (CC << C)
7551             
7552             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7553           }
7554           
7555           break;
7556         }
7557       }
7558       
7559       
7560       // If the operand is an bitwise operator with a constant RHS, and the
7561       // shift is the only use, we can pull it out of the shift.
7562       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7563         bool isValid = true;     // Valid only for And, Or, Xor
7564         bool highBitSet = false; // Transform if high bit of constant set?
7565         
7566         switch (Op0BO->getOpcode()) {
7567           default: isValid = false; break;   // Do not perform transform!
7568           case Instruction::Add:
7569             isValid = isLeftShift;
7570             break;
7571           case Instruction::Or:
7572           case Instruction::Xor:
7573             highBitSet = false;
7574             break;
7575           case Instruction::And:
7576             highBitSet = true;
7577             break;
7578         }
7579         
7580         // If this is a signed shift right, and the high bit is modified
7581         // by the logical operation, do not perform the transformation.
7582         // The highBitSet boolean indicates the value of the high bit of
7583         // the constant which would cause it to be modified for this
7584         // operation.
7585         //
7586         if (isValid && I.getOpcode() == Instruction::AShr)
7587           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7588         
7589         if (isValid) {
7590           Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
7591           
7592           Instruction *NewShift =
7593             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7594           InsertNewInstBefore(NewShift, I);
7595           NewShift->takeName(Op0BO);
7596           
7597           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7598                                         NewRHS);
7599         }
7600       }
7601     }
7602   }
7603   
7604   // Find out if this is a shift of a shift by a constant.
7605   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7606   if (ShiftOp && !ShiftOp->isShift())
7607     ShiftOp = 0;
7608   
7609   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7610     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7611     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7612     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7613     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7614     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7615     Value *X = ShiftOp->getOperand(0);
7616     
7617     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7618     
7619     const IntegerType *Ty = cast<IntegerType>(I.getType());
7620     
7621     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7622     if (I.getOpcode() == ShiftOp->getOpcode()) {
7623       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7624       // saturates.
7625       if (AmtSum >= TypeBits) {
7626         if (I.getOpcode() != Instruction::AShr)
7627           return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7628         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7629       }
7630       
7631       return BinaryOperator::Create(I.getOpcode(), X,
7632                                     Context->getConstantInt(Ty, AmtSum));
7633     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7634                I.getOpcode() == Instruction::AShr) {
7635       if (AmtSum >= TypeBits)
7636         return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7637       
7638       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7639       return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
7640     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7641                I.getOpcode() == Instruction::LShr) {
7642       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7643       if (AmtSum >= TypeBits)
7644         AmtSum = TypeBits-1;
7645       
7646       Instruction *Shift =
7647         BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
7648       InsertNewInstBefore(Shift, I);
7649
7650       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7651       return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7652     }
7653     
7654     // Okay, if we get here, one shift must be left, and the other shift must be
7655     // right.  See if the amounts are equal.
7656     if (ShiftAmt1 == ShiftAmt2) {
7657       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7658       if (I.getOpcode() == Instruction::Shl) {
7659         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7660         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7661       }
7662       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7663       if (I.getOpcode() == Instruction::LShr) {
7664         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7665         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7666       }
7667       // We can simplify ((X << C) >>s C) into a trunc + sext.
7668       // NOTE: we could do this for any C, but that would make 'unusual' integer
7669       // types.  For now, just stick to ones well-supported by the code
7670       // generators.
7671       const Type *SExtType = 0;
7672       switch (Ty->getBitWidth() - ShiftAmt1) {
7673       case 1  :
7674       case 8  :
7675       case 16 :
7676       case 32 :
7677       case 64 :
7678       case 128:
7679         SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
7680         break;
7681       default: break;
7682       }
7683       if (SExtType) {
7684         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7685         InsertNewInstBefore(NewTrunc, I);
7686         return new SExtInst(NewTrunc, Ty);
7687       }
7688       // Otherwise, we can't handle it yet.
7689     } else if (ShiftAmt1 < ShiftAmt2) {
7690       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7691       
7692       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7693       if (I.getOpcode() == Instruction::Shl) {
7694         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7695                ShiftOp->getOpcode() == Instruction::AShr);
7696         Instruction *Shift =
7697           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7698         InsertNewInstBefore(Shift, I);
7699         
7700         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7701         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7702       }
7703       
7704       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7705       if (I.getOpcode() == Instruction::LShr) {
7706         assert(ShiftOp->getOpcode() == Instruction::Shl);
7707         Instruction *Shift =
7708           BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
7709         InsertNewInstBefore(Shift, I);
7710         
7711         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7712         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7713       }
7714       
7715       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7716     } else {
7717       assert(ShiftAmt2 < ShiftAmt1);
7718       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7719
7720       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7721       if (I.getOpcode() == Instruction::Shl) {
7722         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7723                ShiftOp->getOpcode() == Instruction::AShr);
7724         Instruction *Shift =
7725           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7726                                  Context->getConstantInt(Ty, ShiftDiff));
7727         InsertNewInstBefore(Shift, I);
7728         
7729         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7730         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7731       }
7732       
7733       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7734       if (I.getOpcode() == Instruction::LShr) {
7735         assert(ShiftOp->getOpcode() == Instruction::Shl);
7736         Instruction *Shift =
7737           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7738         InsertNewInstBefore(Shift, I);
7739         
7740         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7741         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7742       }
7743       
7744       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7745     }
7746   }
7747   return 0;
7748 }
7749
7750
7751 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7752 /// expression.  If so, decompose it, returning some value X, such that Val is
7753 /// X*Scale+Offset.
7754 ///
7755 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7756                                         int &Offset, LLVMContext *Context) {
7757   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7758   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7759     Offset = CI->getZExtValue();
7760     Scale  = 0;
7761     return Context->getConstantInt(Type::Int32Ty, 0);
7762   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7763     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7764       if (I->getOpcode() == Instruction::Shl) {
7765         // This is a value scaled by '1 << the shift amt'.
7766         Scale = 1U << RHS->getZExtValue();
7767         Offset = 0;
7768         return I->getOperand(0);
7769       } else if (I->getOpcode() == Instruction::Mul) {
7770         // This value is scaled by 'RHS'.
7771         Scale = RHS->getZExtValue();
7772         Offset = 0;
7773         return I->getOperand(0);
7774       } else if (I->getOpcode() == Instruction::Add) {
7775         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7776         // where C1 is divisible by C2.
7777         unsigned SubScale;
7778         Value *SubVal = 
7779           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7780                                     Offset, Context);
7781         Offset += RHS->getZExtValue();
7782         Scale = SubScale;
7783         return SubVal;
7784       }
7785     }
7786   }
7787
7788   // Otherwise, we can't look past this.
7789   Scale = 1;
7790   Offset = 0;
7791   return Val;
7792 }
7793
7794
7795 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7796 /// try to eliminate the cast by moving the type information into the alloc.
7797 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7798                                                    AllocationInst &AI) {
7799   const PointerType *PTy = cast<PointerType>(CI.getType());
7800   
7801   // Remove any uses of AI that are dead.
7802   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7803   
7804   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7805     Instruction *User = cast<Instruction>(*UI++);
7806     if (isInstructionTriviallyDead(User)) {
7807       while (UI != E && *UI == User)
7808         ++UI; // If this instruction uses AI more than once, don't break UI.
7809       
7810       ++NumDeadInst;
7811       DOUT << "IC: DCE: " << *User;
7812       EraseInstFromFunction(*User);
7813     }
7814   }
7815   
7816   // Get the type really allocated and the type casted to.
7817   const Type *AllocElTy = AI.getAllocatedType();
7818   const Type *CastElTy = PTy->getElementType();
7819   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7820
7821   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7822   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7823   if (CastElTyAlign < AllocElTyAlign) return 0;
7824
7825   // If the allocation has multiple uses, only promote it if we are strictly
7826   // increasing the alignment of the resultant allocation.  If we keep it the
7827   // same, we open the door to infinite loops of various kinds.  (A reference
7828   // from a dbg.declare doesn't count as a use for this purpose.)
7829   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7830       CastElTyAlign == AllocElTyAlign) return 0;
7831
7832   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7833   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7834   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7835
7836   // See if we can satisfy the modulus by pulling a scale out of the array
7837   // size argument.
7838   unsigned ArraySizeScale;
7839   int ArrayOffset;
7840   Value *NumElements = // See if the array size is a decomposable linear expr.
7841     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7842                               ArrayOffset, Context);
7843  
7844   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7845   // do the xform.
7846   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7847       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7848
7849   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7850   Value *Amt = 0;
7851   if (Scale == 1) {
7852     Amt = NumElements;
7853   } else {
7854     // If the allocation size is constant, form a constant mul expression
7855     Amt = Context->getConstantInt(Type::Int32Ty, Scale);
7856     if (isa<ConstantInt>(NumElements))
7857       Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
7858                                  cast<ConstantInt>(Amt));
7859     // otherwise multiply the amount and the number of elements
7860     else {
7861       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7862       Amt = InsertNewInstBefore(Tmp, AI);
7863     }
7864   }
7865   
7866   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7867     Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
7868     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7869     Amt = InsertNewInstBefore(Tmp, AI);
7870   }
7871   
7872   AllocationInst *New;
7873   if (isa<MallocInst>(AI))
7874     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7875   else
7876     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7877   InsertNewInstBefore(New, AI);
7878   New->takeName(&AI);
7879   
7880   // If the allocation has one real use plus a dbg.declare, just remove the
7881   // declare.
7882   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7883     EraseInstFromFunction(*DI);
7884   }
7885   // If the allocation has multiple real uses, insert a cast and change all
7886   // things that used it to use the new cast.  This will also hack on CI, but it
7887   // will die soon.
7888   else if (!AI.hasOneUse()) {
7889     AddUsesToWorkList(AI);
7890     // New is the allocation instruction, pointer typed. AI is the original
7891     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7892     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7893     InsertNewInstBefore(NewCast, AI);
7894     AI.replaceAllUsesWith(NewCast);
7895   }
7896   return ReplaceInstUsesWith(CI, New);
7897 }
7898
7899 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7900 /// and return it as type Ty without inserting any new casts and without
7901 /// changing the computed value.  This is used by code that tries to decide
7902 /// whether promoting or shrinking integer operations to wider or smaller types
7903 /// will allow us to eliminate a truncate or extend.
7904 ///
7905 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7906 /// extension operation if Ty is larger.
7907 ///
7908 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7909 /// should return true if trunc(V) can be computed by computing V in the smaller
7910 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7911 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7912 /// efficiently truncated.
7913 ///
7914 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7915 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7916 /// the final result.
7917 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7918                                               unsigned CastOpc,
7919                                               int &NumCastsRemoved){
7920   // We can always evaluate constants in another type.
7921   if (isa<Constant>(V))
7922     return true;
7923   
7924   Instruction *I = dyn_cast<Instruction>(V);
7925   if (!I) return false;
7926   
7927   const Type *OrigTy = V->getType();
7928   
7929   // If this is an extension or truncate, we can often eliminate it.
7930   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7931     // If this is a cast from the destination type, we can trivially eliminate
7932     // it, and this will remove a cast overall.
7933     if (I->getOperand(0)->getType() == Ty) {
7934       // If the first operand is itself a cast, and is eliminable, do not count
7935       // this as an eliminable cast.  We would prefer to eliminate those two
7936       // casts first.
7937       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7938         ++NumCastsRemoved;
7939       return true;
7940     }
7941   }
7942
7943   // We can't extend or shrink something that has multiple uses: doing so would
7944   // require duplicating the instruction in general, which isn't profitable.
7945   if (!I->hasOneUse()) return false;
7946
7947   unsigned Opc = I->getOpcode();
7948   switch (Opc) {
7949   case Instruction::Add:
7950   case Instruction::Sub:
7951   case Instruction::Mul:
7952   case Instruction::And:
7953   case Instruction::Or:
7954   case Instruction::Xor:
7955     // These operators can all arbitrarily be extended or truncated.
7956     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7957                                       NumCastsRemoved) &&
7958            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7959                                       NumCastsRemoved);
7960
7961   case Instruction::Shl:
7962     // If we are truncating the result of this SHL, and if it's a shift of a
7963     // constant amount, we can always perform a SHL in a smaller type.
7964     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7965       uint32_t BitWidth = Ty->getScalarSizeInBits();
7966       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7967           CI->getLimitedValue(BitWidth) < BitWidth)
7968         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7969                                           NumCastsRemoved);
7970     }
7971     break;
7972   case Instruction::LShr:
7973     // If this is a truncate of a logical shr, we can truncate it to a smaller
7974     // lshr iff we know that the bits we would otherwise be shifting in are
7975     // already zeros.
7976     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7977       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7978       uint32_t BitWidth = Ty->getScalarSizeInBits();
7979       if (BitWidth < OrigBitWidth &&
7980           MaskedValueIsZero(I->getOperand(0),
7981             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7982           CI->getLimitedValue(BitWidth) < BitWidth) {
7983         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7984                                           NumCastsRemoved);
7985       }
7986     }
7987     break;
7988   case Instruction::ZExt:
7989   case Instruction::SExt:
7990   case Instruction::Trunc:
7991     // If this is the same kind of case as our original (e.g. zext+zext), we
7992     // can safely replace it.  Note that replacing it does not reduce the number
7993     // of casts in the input.
7994     if (Opc == CastOpc)
7995       return true;
7996
7997     // sext (zext ty1), ty2 -> zext ty2
7998     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7999       return true;
8000     break;
8001   case Instruction::Select: {
8002     SelectInst *SI = cast<SelectInst>(I);
8003     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8004                                       NumCastsRemoved) &&
8005            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8006                                       NumCastsRemoved);
8007   }
8008   case Instruction::PHI: {
8009     // We can change a phi if we can change all operands.
8010     PHINode *PN = cast<PHINode>(I);
8011     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8012       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8013                                       NumCastsRemoved))
8014         return false;
8015     return true;
8016   }
8017   default:
8018     // TODO: Can handle more cases here.
8019     break;
8020   }
8021   
8022   return false;
8023 }
8024
8025 /// EvaluateInDifferentType - Given an expression that 
8026 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8027 /// evaluate the expression.
8028 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8029                                              bool isSigned) {
8030   if (Constant *C = dyn_cast<Constant>(V))
8031     return Context->getConstantExprIntegerCast(C, Ty,
8032                                                isSigned /*Sext or ZExt*/);
8033
8034   // Otherwise, it must be an instruction.
8035   Instruction *I = cast<Instruction>(V);
8036   Instruction *Res = 0;
8037   unsigned Opc = I->getOpcode();
8038   switch (Opc) {
8039   case Instruction::Add:
8040   case Instruction::Sub:
8041   case Instruction::Mul:
8042   case Instruction::And:
8043   case Instruction::Or:
8044   case Instruction::Xor:
8045   case Instruction::AShr:
8046   case Instruction::LShr:
8047   case Instruction::Shl: {
8048     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8049     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8050     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8051     break;
8052   }    
8053   case Instruction::Trunc:
8054   case Instruction::ZExt:
8055   case Instruction::SExt:
8056     // If the source type of the cast is the type we're trying for then we can
8057     // just return the source.  There's no need to insert it because it is not
8058     // new.
8059     if (I->getOperand(0)->getType() == Ty)
8060       return I->getOperand(0);
8061     
8062     // Otherwise, must be the same type of cast, so just reinsert a new one.
8063     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8064                            Ty);
8065     break;
8066   case Instruction::Select: {
8067     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8068     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8069     Res = SelectInst::Create(I->getOperand(0), True, False);
8070     break;
8071   }
8072   case Instruction::PHI: {
8073     PHINode *OPN = cast<PHINode>(I);
8074     PHINode *NPN = PHINode::Create(Ty);
8075     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8076       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8077       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8078     }
8079     Res = NPN;
8080     break;
8081   }
8082   default: 
8083     // TODO: Can handle more cases here.
8084     LLVM_UNREACHABLE("Unreachable!");
8085     break;
8086   }
8087   
8088   Res->takeName(I);
8089   return InsertNewInstBefore(Res, *I);
8090 }
8091
8092 /// @brief Implement the transforms common to all CastInst visitors.
8093 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8094   Value *Src = CI.getOperand(0);
8095
8096   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8097   // eliminate it now.
8098   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8099     if (Instruction::CastOps opc = 
8100         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8101       // The first cast (CSrc) is eliminable so we need to fix up or replace
8102       // the second cast (CI). CSrc will then have a good chance of being dead.
8103       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8104     }
8105   }
8106
8107   // If we are casting a select then fold the cast into the select
8108   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8109     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8110       return NV;
8111
8112   // If we are casting a PHI then fold the cast into the PHI
8113   if (isa<PHINode>(Src))
8114     if (Instruction *NV = FoldOpIntoPhi(CI))
8115       return NV;
8116   
8117   return 0;
8118 }
8119
8120 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8121 /// or not there is a sequence of GEP indices into the type that will land us at
8122 /// the specified offset.  If so, fill them into NewIndices and return the
8123 /// resultant element type, otherwise return null.
8124 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8125                                        SmallVectorImpl<Value*> &NewIndices,
8126                                        const TargetData *TD,
8127                                        LLVMContext *Context) {
8128   if (!Ty->isSized()) return 0;
8129   
8130   // Start with the index over the outer type.  Note that the type size
8131   // might be zero (even if the offset isn't zero) if the indexed type
8132   // is something like [0 x {int, int}]
8133   const Type *IntPtrTy = TD->getIntPtrType();
8134   int64_t FirstIdx = 0;
8135   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8136     FirstIdx = Offset/TySize;
8137     Offset -= FirstIdx*TySize;
8138     
8139     // Handle hosts where % returns negative instead of values [0..TySize).
8140     if (Offset < 0) {
8141       --FirstIdx;
8142       Offset += TySize;
8143       assert(Offset >= 0);
8144     }
8145     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8146   }
8147   
8148   NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
8149     
8150   // Index into the types.  If we fail, set OrigBase to null.
8151   while (Offset) {
8152     // Indexing into tail padding between struct/array elements.
8153     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8154       return 0;
8155     
8156     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8157       const StructLayout *SL = TD->getStructLayout(STy);
8158       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8159              "Offset must stay within the indexed type");
8160       
8161       unsigned Elt = SL->getElementContainingOffset(Offset);
8162       NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
8163       
8164       Offset -= SL->getElementOffset(Elt);
8165       Ty = STy->getElementType(Elt);
8166     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8167       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8168       assert(EltSize && "Cannot index into a zero-sized array");
8169       NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
8170       Offset %= EltSize;
8171       Ty = AT->getElementType();
8172     } else {
8173       // Otherwise, we can't index into the middle of this atomic type, bail.
8174       return 0;
8175     }
8176   }
8177   
8178   return Ty;
8179 }
8180
8181 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8182 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8183   Value *Src = CI.getOperand(0);
8184   
8185   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8186     // If casting the result of a getelementptr instruction with no offset, turn
8187     // this into a cast of the original pointer!
8188     if (GEP->hasAllZeroIndices()) {
8189       // Changing the cast operand is usually not a good idea but it is safe
8190       // here because the pointer operand is being replaced with another 
8191       // pointer operand so the opcode doesn't need to change.
8192       AddToWorkList(GEP);
8193       CI.setOperand(0, GEP->getOperand(0));
8194       return &CI;
8195     }
8196     
8197     // If the GEP has a single use, and the base pointer is a bitcast, and the
8198     // GEP computes a constant offset, see if we can convert these three
8199     // instructions into fewer.  This typically happens with unions and other
8200     // non-type-safe code.
8201     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8202       if (GEP->hasAllConstantIndices()) {
8203         // We are guaranteed to get a constant from EmitGEPOffset.
8204         ConstantInt *OffsetV =
8205                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8206         int64_t Offset = OffsetV->getSExtValue();
8207         
8208         // Get the base pointer input of the bitcast, and the type it points to.
8209         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8210         const Type *GEPIdxTy =
8211           cast<PointerType>(OrigBase->getType())->getElementType();
8212         SmallVector<Value*, 8> NewIndices;
8213         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8214           // If we were able to index down into an element, create the GEP
8215           // and bitcast the result.  This eliminates one bitcast, potentially
8216           // two.
8217           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8218                                                         NewIndices.begin(),
8219                                                         NewIndices.end(), "");
8220           InsertNewInstBefore(NGEP, CI);
8221           NGEP->takeName(GEP);
8222           
8223           if (isa<BitCastInst>(CI))
8224             return new BitCastInst(NGEP, CI.getType());
8225           assert(isa<PtrToIntInst>(CI));
8226           return new PtrToIntInst(NGEP, CI.getType());
8227         }
8228       }      
8229     }
8230   }
8231     
8232   return commonCastTransforms(CI);
8233 }
8234
8235 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8236 /// type like i42.  We don't want to introduce operations on random non-legal
8237 /// integer types where they don't already exist in the code.  In the future,
8238 /// we should consider making this based off target-data, so that 32-bit targets
8239 /// won't get i64 operations etc.
8240 static bool isSafeIntegerType(const Type *Ty) {
8241   switch (Ty->getPrimitiveSizeInBits()) {
8242   case 8:
8243   case 16:
8244   case 32:
8245   case 64:
8246     return true;
8247   default: 
8248     return false;
8249   }
8250 }
8251
8252 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
8253 /// integer types. This function implements the common transforms for all those
8254 /// cases.
8255 /// @brief Implement the transforms common to CastInst with integer operands
8256 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8257   if (Instruction *Result = commonCastTransforms(CI))
8258     return Result;
8259
8260   Value *Src = CI.getOperand(0);
8261   const Type *SrcTy = Src->getType();
8262   const Type *DestTy = CI.getType();
8263   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8264   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8265
8266   // See if we can simplify any instructions used by the LHS whose sole 
8267   // purpose is to compute bits we don't care about.
8268   if (SimplifyDemandedInstructionBits(CI))
8269     return &CI;
8270
8271   // If the source isn't an instruction or has more than one use then we
8272   // can't do anything more. 
8273   Instruction *SrcI = dyn_cast<Instruction>(Src);
8274   if (!SrcI || !Src->hasOneUse())
8275     return 0;
8276
8277   // Attempt to propagate the cast into the instruction for int->int casts.
8278   int NumCastsRemoved = 0;
8279   if (!isa<BitCastInst>(CI) &&
8280       // Only do this if the dest type is a simple type, don't convert the
8281       // expression tree to something weird like i93 unless the source is also
8282       // strange.
8283       (isSafeIntegerType(DestTy->getScalarType()) ||
8284        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8285       CanEvaluateInDifferentType(SrcI, DestTy,
8286                                  CI.getOpcode(), NumCastsRemoved)) {
8287     // If this cast is a truncate, evaluting in a different type always
8288     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8289     // we need to do an AND to maintain the clear top-part of the computation,
8290     // so we require that the input have eliminated at least one cast.  If this
8291     // is a sign extension, we insert two new casts (to do the extension) so we
8292     // require that two casts have been eliminated.
8293     bool DoXForm = false;
8294     bool JustReplace = false;
8295     switch (CI.getOpcode()) {
8296     default:
8297       // All the others use floating point so we shouldn't actually 
8298       // get here because of the check above.
8299       LLVM_UNREACHABLE("Unknown cast type");
8300     case Instruction::Trunc:
8301       DoXForm = true;
8302       break;
8303     case Instruction::ZExt: {
8304       DoXForm = NumCastsRemoved >= 1;
8305       if (!DoXForm && 0) {
8306         // If it's unnecessary to issue an AND to clear the high bits, it's
8307         // always profitable to do this xform.
8308         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8309         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8310         if (MaskedValueIsZero(TryRes, Mask))
8311           return ReplaceInstUsesWith(CI, TryRes);
8312         
8313         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8314           if (TryI->use_empty())
8315             EraseInstFromFunction(*TryI);
8316       }
8317       break;
8318     }
8319     case Instruction::SExt: {
8320       DoXForm = NumCastsRemoved >= 2;
8321       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8322         // If we do not have to emit the truncate + sext pair, then it's always
8323         // profitable to do this xform.
8324         //
8325         // It's not safe to eliminate the trunc + sext pair if one of the
8326         // eliminated cast is a truncate. e.g.
8327         // t2 = trunc i32 t1 to i16
8328         // t3 = sext i16 t2 to i32
8329         // !=
8330         // i32 t1
8331         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8332         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8333         if (NumSignBits > (DestBitSize - SrcBitSize))
8334           return ReplaceInstUsesWith(CI, TryRes);
8335         
8336         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8337           if (TryI->use_empty())
8338             EraseInstFromFunction(*TryI);
8339       }
8340       break;
8341     }
8342     }
8343     
8344     if (DoXForm) {
8345       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8346            << " cast: " << CI;
8347       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8348                                            CI.getOpcode() == Instruction::SExt);
8349       if (JustReplace)
8350         // Just replace this cast with the result.
8351         return ReplaceInstUsesWith(CI, Res);
8352
8353       assert(Res->getType() == DestTy);
8354       switch (CI.getOpcode()) {
8355       default: LLVM_UNREACHABLE("Unknown cast type!");
8356       case Instruction::Trunc:
8357       case Instruction::BitCast:
8358         // Just replace this cast with the result.
8359         return ReplaceInstUsesWith(CI, Res);
8360       case Instruction::ZExt: {
8361         assert(SrcBitSize < DestBitSize && "Not a zext?");
8362
8363         // If the high bits are already zero, just replace this cast with the
8364         // result.
8365         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8366         if (MaskedValueIsZero(Res, Mask))
8367           return ReplaceInstUsesWith(CI, Res);
8368
8369         // We need to emit an AND to clear the high bits.
8370         Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
8371                                                             SrcBitSize));
8372         return BinaryOperator::CreateAnd(Res, C);
8373       }
8374       case Instruction::SExt: {
8375         // If the high bits are already filled with sign bit, just replace this
8376         // cast with the result.
8377         unsigned NumSignBits = ComputeNumSignBits(Res);
8378         if (NumSignBits > (DestBitSize - SrcBitSize))
8379           return ReplaceInstUsesWith(CI, Res);
8380
8381         // We need to emit a cast to truncate, then a cast to sext.
8382         return CastInst::Create(Instruction::SExt,
8383             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8384                              CI), DestTy);
8385       }
8386       }
8387     }
8388   }
8389   
8390   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8391   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8392
8393   switch (SrcI->getOpcode()) {
8394   case Instruction::Add:
8395   case Instruction::Mul:
8396   case Instruction::And:
8397   case Instruction::Or:
8398   case Instruction::Xor:
8399     // If we are discarding information, rewrite.
8400     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8401       // Don't insert two casts if they cannot be eliminated.  We allow 
8402       // two casts to be inserted if the sizes are the same.  This could 
8403       // only be converting signedness, which is a noop.
8404       if (DestBitSize == SrcBitSize || 
8405           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8406           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8407         Instruction::CastOps opcode = CI.getOpcode();
8408         Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8409         Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8410         return BinaryOperator::Create(
8411             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8412       }
8413     }
8414
8415     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8416     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8417         SrcI->getOpcode() == Instruction::Xor &&
8418         Op1 == Context->getConstantIntTrue() &&
8419         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8420       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8421       return BinaryOperator::CreateXor(New,
8422                                       Context->getConstantInt(CI.getType(), 1));
8423     }
8424     break;
8425   case Instruction::SDiv:
8426   case Instruction::UDiv:
8427   case Instruction::SRem:
8428   case Instruction::URem:
8429     // If we are just changing the sign, rewrite.
8430     if (DestBitSize == SrcBitSize) {
8431       // Don't insert two casts if they cannot be eliminated.  We allow 
8432       // two casts to be inserted if the sizes are the same.  This could 
8433       // only be converting signedness, which is a noop.
8434       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
8435           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8436         Value *Op0c = InsertCastBefore(Instruction::BitCast, 
8437                                        Op0, DestTy, *SrcI);
8438         Value *Op1c = InsertCastBefore(Instruction::BitCast, 
8439                                        Op1, DestTy, *SrcI);
8440         return BinaryOperator::Create(
8441           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8442       }
8443     }
8444     break;
8445
8446   case Instruction::Shl:
8447     // Allow changing the sign of the source operand.  Do not allow 
8448     // changing the size of the shift, UNLESS the shift amount is a 
8449     // constant.  We must not change variable sized shifts to a smaller 
8450     // size, because it is undefined to shift more bits out than exist 
8451     // in the value.
8452     if (DestBitSize == SrcBitSize ||
8453         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8454       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8455           Instruction::BitCast : Instruction::Trunc);
8456       Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8457       Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8458       return BinaryOperator::CreateShl(Op0c, Op1c);
8459     }
8460     break;
8461   case Instruction::AShr:
8462     // If this is a signed shr, and if all bits shifted in are about to be
8463     // truncated off, turn it into an unsigned shr to allow greater
8464     // simplifications.
8465     if (DestBitSize < SrcBitSize &&
8466         isa<ConstantInt>(Op1)) {
8467       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8468       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8469         // Insert the new logical shift right.
8470         return BinaryOperator::CreateLShr(Op0, Op1);
8471       }
8472     }
8473     break;
8474   }
8475   return 0;
8476 }
8477
8478 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8479   if (Instruction *Result = commonIntCastTransforms(CI))
8480     return Result;
8481   
8482   Value *Src = CI.getOperand(0);
8483   const Type *Ty = CI.getType();
8484   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8485   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8486
8487   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8488   if (DestBitWidth == 1 &&
8489       isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
8490     Constant *One = Context->getConstantInt(Src->getType(), 1);
8491     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8492     Value *Zero = Context->getNullValue(Src->getType());
8493     return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
8494   }
8495
8496   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8497   ConstantInt *ShAmtV = 0;
8498   Value *ShiftOp = 0;
8499   if (Src->hasOneUse() &&
8500       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
8501     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8502     
8503     // Get a mask for the bits shifting in.
8504     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8505     if (MaskedValueIsZero(ShiftOp, Mask)) {
8506       if (ShAmt >= DestBitWidth)        // All zeros.
8507         return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
8508       
8509       // Okay, we can shrink this.  Truncate the input, then return a new
8510       // shift.
8511       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8512       Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
8513       return BinaryOperator::CreateLShr(V1, V2);
8514     }
8515   }
8516   
8517   return 0;
8518 }
8519
8520 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8521 /// in order to eliminate the icmp.
8522 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8523                                              bool DoXform) {
8524   // If we are just checking for a icmp eq of a single bit and zext'ing it
8525   // to an integer, then shift the bit to the appropriate place and then
8526   // cast to integer to avoid the comparison.
8527   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8528     const APInt &Op1CV = Op1C->getValue();
8529       
8530     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8531     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8532     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8533         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8534       if (!DoXform) return ICI;
8535
8536       Value *In = ICI->getOperand(0);
8537       Value *Sh = Context->getConstantInt(In->getType(),
8538                                    In->getType()->getScalarSizeInBits()-1);
8539       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8540                                                         In->getName()+".lobit"),
8541                                CI);
8542       if (In->getType() != CI.getType())
8543         In = CastInst::CreateIntegerCast(In, CI.getType(),
8544                                          false/*ZExt*/, "tmp", &CI);
8545
8546       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8547         Constant *One = Context->getConstantInt(In->getType(), 1);
8548         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8549                                                          In->getName()+".not"),
8550                                  CI);
8551       }
8552
8553       return ReplaceInstUsesWith(CI, In);
8554     }
8555       
8556       
8557       
8558     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8559     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8560     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8561     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8562     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8563     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8564     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8565     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8566     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8567         // This only works for EQ and NE
8568         ICI->isEquality()) {
8569       // If Op1C some other power of two, convert:
8570       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8571       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8572       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8573       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8574         
8575       APInt KnownZeroMask(~KnownZero);
8576       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8577         if (!DoXform) return ICI;
8578
8579         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8580         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8581           // (X&4) == 2 --> false
8582           // (X&4) != 2 --> true
8583           Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8584           Res = Context->getConstantExprZExt(Res, CI.getType());
8585           return ReplaceInstUsesWith(CI, Res);
8586         }
8587           
8588         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8589         Value *In = ICI->getOperand(0);
8590         if (ShiftAmt) {
8591           // Perform a logical shr by shiftamt.
8592           // Insert the shift to put the result in the low bit.
8593           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8594                               Context->getConstantInt(In->getType(), ShiftAmt),
8595                                                    In->getName()+".lobit"), CI);
8596         }
8597           
8598         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8599           Constant *One = Context->getConstantInt(In->getType(), 1);
8600           In = BinaryOperator::CreateXor(In, One, "tmp");
8601           InsertNewInstBefore(cast<Instruction>(In), CI);
8602         }
8603           
8604         if (CI.getType() == In->getType())
8605           return ReplaceInstUsesWith(CI, In);
8606         else
8607           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8608       }
8609     }
8610   }
8611
8612   return 0;
8613 }
8614
8615 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8616   // If one of the common conversion will work ..
8617   if (Instruction *Result = commonIntCastTransforms(CI))
8618     return Result;
8619
8620   Value *Src = CI.getOperand(0);
8621
8622   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8623   // types and if the sizes are just right we can convert this into a logical
8624   // 'and' which will be much cheaper than the pair of casts.
8625   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8626     // Get the sizes of the types involved.  We know that the intermediate type
8627     // will be smaller than A or C, but don't know the relation between A and C.
8628     Value *A = CSrc->getOperand(0);
8629     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8630     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8631     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8632     // If we're actually extending zero bits, then if
8633     // SrcSize <  DstSize: zext(a & mask)
8634     // SrcSize == DstSize: a & mask
8635     // SrcSize  > DstSize: trunc(a) & mask
8636     if (SrcSize < DstSize) {
8637       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8638       Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
8639       Instruction *And =
8640         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8641       InsertNewInstBefore(And, CI);
8642       return new ZExtInst(And, CI.getType());
8643     } else if (SrcSize == DstSize) {
8644       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8645       return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
8646                                                            AndValue));
8647     } else if (SrcSize > DstSize) {
8648       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8649       InsertNewInstBefore(Trunc, CI);
8650       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8651       return BinaryOperator::CreateAnd(Trunc, 
8652                                        Context->getConstantInt(Trunc->getType(),
8653                                                                AndValue));
8654     }
8655   }
8656
8657   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8658     return transformZExtICmp(ICI, CI);
8659
8660   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8661   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8662     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8663     // of the (zext icmp) will be transformed.
8664     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8665     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8666     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8667         (transformZExtICmp(LHS, CI, false) ||
8668          transformZExtICmp(RHS, CI, false))) {
8669       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8670       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8671       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8672     }
8673   }
8674
8675   // zext(trunc(t) & C) -> (t & zext(C)).
8676   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8677     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8678       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8679         Value *TI0 = TI->getOperand(0);
8680         if (TI0->getType() == CI.getType())
8681           return
8682             BinaryOperator::CreateAnd(TI0,
8683                                 Context->getConstantExprZExt(C, CI.getType()));
8684       }
8685
8686   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8687   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8688     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8689       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8690         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8691             And->getOperand(1) == C)
8692           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8693             Value *TI0 = TI->getOperand(0);
8694             if (TI0->getType() == CI.getType()) {
8695               Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
8696               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8697               InsertNewInstBefore(NewAnd, *And);
8698               return BinaryOperator::CreateXor(NewAnd, ZC);
8699             }
8700           }
8701
8702   return 0;
8703 }
8704
8705 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8706   if (Instruction *I = commonIntCastTransforms(CI))
8707     return I;
8708   
8709   Value *Src = CI.getOperand(0);
8710   
8711   // Canonicalize sign-extend from i1 to a select.
8712   if (Src->getType() == Type::Int1Ty)
8713     return SelectInst::Create(Src,
8714                               Context->getConstantIntAllOnesValue(CI.getType()),
8715                               Context->getNullValue(CI.getType()));
8716
8717   // See if the value being truncated is already sign extended.  If so, just
8718   // eliminate the trunc/sext pair.
8719   if (getOpcode(Src) == Instruction::Trunc) {
8720     Value *Op = cast<User>(Src)->getOperand(0);
8721     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8722     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8723     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8724     unsigned NumSignBits = ComputeNumSignBits(Op);
8725
8726     if (OpBits == DestBits) {
8727       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8728       // bits, it is already ready.
8729       if (NumSignBits > DestBits-MidBits)
8730         return ReplaceInstUsesWith(CI, Op);
8731     } else if (OpBits < DestBits) {
8732       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8733       // bits, just sext from i32.
8734       if (NumSignBits > OpBits-MidBits)
8735         return new SExtInst(Op, CI.getType(), "tmp");
8736     } else {
8737       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8738       // bits, just truncate to i32.
8739       if (NumSignBits > OpBits-MidBits)
8740         return new TruncInst(Op, CI.getType(), "tmp");
8741     }
8742   }
8743
8744   // If the input is a shl/ashr pair of a same constant, then this is a sign
8745   // extension from a smaller value.  If we could trust arbitrary bitwidth
8746   // integers, we could turn this into a truncate to the smaller bit and then
8747   // use a sext for the whole extension.  Since we don't, look deeper and check
8748   // for a truncate.  If the source and dest are the same type, eliminate the
8749   // trunc and extend and just do shifts.  For example, turn:
8750   //   %a = trunc i32 %i to i8
8751   //   %b = shl i8 %a, 6
8752   //   %c = ashr i8 %b, 6
8753   //   %d = sext i8 %c to i32
8754   // into:
8755   //   %a = shl i32 %i, 30
8756   //   %d = ashr i32 %a, 30
8757   Value *A = 0;
8758   ConstantInt *BA = 0, *CA = 0;
8759   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8760                         m_ConstantInt(CA)), *Context) &&
8761       BA == CA && isa<TruncInst>(A)) {
8762     Value *I = cast<TruncInst>(A)->getOperand(0);
8763     if (I->getType() == CI.getType()) {
8764       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8765       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8766       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8767       Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
8768       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8769                                                         CI.getName()), CI);
8770       return BinaryOperator::CreateAShr(I, ShAmtV);
8771     }
8772   }
8773   
8774   return 0;
8775 }
8776
8777 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8778 /// in the specified FP type without changing its value.
8779 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8780                               LLVMContext *Context) {
8781   bool losesInfo;
8782   APFloat F = CFP->getValueAPF();
8783   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8784   if (!losesInfo)
8785     return Context->getConstantFP(F);
8786   return 0;
8787 }
8788
8789 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8790 /// through it until we get the source value.
8791 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8792   if (Instruction *I = dyn_cast<Instruction>(V))
8793     if (I->getOpcode() == Instruction::FPExt)
8794       return LookThroughFPExtensions(I->getOperand(0), Context);
8795   
8796   // If this value is a constant, return the constant in the smallest FP type
8797   // that can accurately represent it.  This allows us to turn
8798   // (float)((double)X+2.0) into x+2.0f.
8799   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8800     if (CFP->getType() == Type::PPC_FP128Ty)
8801       return V;  // No constant folding of this.
8802     // See if the value can be truncated to float and then reextended.
8803     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8804       return V;
8805     if (CFP->getType() == Type::DoubleTy)
8806       return V;  // Won't shrink.
8807     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8808       return V;
8809     // Don't try to shrink to various long double types.
8810   }
8811   
8812   return V;
8813 }
8814
8815 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8816   if (Instruction *I = commonCastTransforms(CI))
8817     return I;
8818   
8819   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8820   // smaller than the destination type, we can eliminate the truncate by doing
8821   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8822   // many builtins (sqrt, etc).
8823   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8824   if (OpI && OpI->hasOneUse()) {
8825     switch (OpI->getOpcode()) {
8826     default: break;
8827     case Instruction::FAdd:
8828     case Instruction::FSub:
8829     case Instruction::FMul:
8830     case Instruction::FDiv:
8831     case Instruction::FRem:
8832       const Type *SrcTy = OpI->getType();
8833       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8834       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8835       if (LHSTrunc->getType() != SrcTy && 
8836           RHSTrunc->getType() != SrcTy) {
8837         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8838         // If the source types were both smaller than the destination type of
8839         // the cast, do this xform.
8840         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8841             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8842           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8843                                       CI.getType(), CI);
8844           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8845                                       CI.getType(), CI);
8846           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8847         }
8848       }
8849       break;  
8850     }
8851   }
8852   return 0;
8853 }
8854
8855 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8856   return commonCastTransforms(CI);
8857 }
8858
8859 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8860   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8861   if (OpI == 0)
8862     return commonCastTransforms(FI);
8863
8864   // fptoui(uitofp(X)) --> X
8865   // fptoui(sitofp(X)) --> X
8866   // This is safe if the intermediate type has enough bits in its mantissa to
8867   // accurately represent all values of X.  For example, do not do this with
8868   // i64->float->i64.  This is also safe for sitofp case, because any negative
8869   // 'X' value would cause an undefined result for the fptoui. 
8870   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8871       OpI->getOperand(0)->getType() == FI.getType() &&
8872       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8873                     OpI->getType()->getFPMantissaWidth())
8874     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8875
8876   return commonCastTransforms(FI);
8877 }
8878
8879 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8880   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8881   if (OpI == 0)
8882     return commonCastTransforms(FI);
8883   
8884   // fptosi(sitofp(X)) --> X
8885   // fptosi(uitofp(X)) --> X
8886   // This is safe if the intermediate type has enough bits in its mantissa to
8887   // accurately represent all values of X.  For example, do not do this with
8888   // i64->float->i64.  This is also safe for sitofp case, because any negative
8889   // 'X' value would cause an undefined result for the fptoui. 
8890   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8891       OpI->getOperand(0)->getType() == FI.getType() &&
8892       (int)FI.getType()->getScalarSizeInBits() <=
8893                     OpI->getType()->getFPMantissaWidth())
8894     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8895   
8896   return commonCastTransforms(FI);
8897 }
8898
8899 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8900   return commonCastTransforms(CI);
8901 }
8902
8903 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8904   return commonCastTransforms(CI);
8905 }
8906
8907 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8908   // If the destination integer type is smaller than the intptr_t type for
8909   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8910   // trunc to be exposed to other transforms.  Don't do this for extending
8911   // ptrtoint's, because we don't know if the target sign or zero extends its
8912   // pointers.
8913   if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8914     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8915                                                     TD->getIntPtrType(),
8916                                                     "tmp"), CI);
8917     return new TruncInst(P, CI.getType());
8918   }
8919   
8920   return commonPointerCastTransforms(CI);
8921 }
8922
8923 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8924   // If the source integer type is larger than the intptr_t type for
8925   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8926   // allows the trunc to be exposed to other transforms.  Don't do this for
8927   // extending inttoptr's, because we don't know if the target sign or zero
8928   // extends to pointers.
8929   if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
8930       TD->getPointerSizeInBits()) {
8931     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8932                                                  TD->getIntPtrType(),
8933                                                  "tmp"), CI);
8934     return new IntToPtrInst(P, CI.getType());
8935   }
8936   
8937   if (Instruction *I = commonCastTransforms(CI))
8938     return I;
8939   
8940   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8941   if (!DestPointee->isSized()) return 0;
8942
8943   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8944   ConstantInt *Cst;
8945   Value *X;
8946   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8947                                     m_ConstantInt(Cst)), *Context)) {
8948     // If the source and destination operands have the same type, see if this
8949     // is a single-index GEP.
8950     if (X->getType() == CI.getType()) {
8951       // Get the size of the pointee type.
8952       uint64_t Size = TD->getTypeAllocSize(DestPointee);
8953
8954       // Convert the constant to intptr type.
8955       APInt Offset = Cst->getValue();
8956       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8957
8958       // If Offset is evenly divisible by Size, we can do this xform.
8959       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8960         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8961         return GetElementPtrInst::Create(X, Context->getConstantInt(Offset));
8962       }
8963     }
8964     // TODO: Could handle other cases, e.g. where add is indexing into field of
8965     // struct etc.
8966   } else if (CI.getOperand(0)->hasOneUse() &&
8967              match(CI.getOperand(0), m_Add(m_Value(X),
8968                    m_ConstantInt(Cst)), *Context)) {
8969     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8970     // "inttoptr+GEP" instead of "add+intptr".
8971     
8972     // Get the size of the pointee type.
8973     uint64_t Size = TD->getTypeAllocSize(DestPointee);
8974     
8975     // Convert the constant to intptr type.
8976     APInt Offset = Cst->getValue();
8977     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8978     
8979     // If Offset is evenly divisible by Size, we can do this xform.
8980     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8981       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8982       
8983       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8984                                                             "tmp"), CI);
8985       return GetElementPtrInst::Create(P,
8986                                        Context->getConstantInt(Offset), "tmp");
8987     }
8988   }
8989   return 0;
8990 }
8991
8992 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8993   // If the operands are integer typed then apply the integer transforms,
8994   // otherwise just apply the common ones.
8995   Value *Src = CI.getOperand(0);
8996   const Type *SrcTy = Src->getType();
8997   const Type *DestTy = CI.getType();
8998
8999   if (SrcTy->isInteger() && DestTy->isInteger()) {
9000     if (Instruction *Result = commonIntCastTransforms(CI))
9001       return Result;
9002   } else if (isa<PointerType>(SrcTy)) {
9003     if (Instruction *I = commonPointerCastTransforms(CI))
9004       return I;
9005   } else {
9006     if (Instruction *Result = commonCastTransforms(CI))
9007       return Result;
9008   }
9009
9010
9011   // Get rid of casts from one type to the same type. These are useless and can
9012   // be replaced by the operand.
9013   if (DestTy == Src->getType())
9014     return ReplaceInstUsesWith(CI, Src);
9015
9016   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
9017     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9018     const Type *DstElTy = DstPTy->getElementType();
9019     const Type *SrcElTy = SrcPTy->getElementType();
9020     
9021     // If the address spaces don't match, don't eliminate the bitcast, which is
9022     // required for changing types.
9023     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9024       return 0;
9025     
9026     // If we are casting a malloc or alloca to a pointer to a type of the same
9027     // size, rewrite the allocation instruction to allocate the "right" type.
9028     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
9029       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9030         return V;
9031     
9032     // If the source and destination are pointers, and this cast is equivalent
9033     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
9034     // This can enhance SROA and other transforms that want type-safe pointers.
9035     Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
9036     unsigned NumZeros = 0;
9037     while (SrcElTy != DstElTy && 
9038            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9039            SrcElTy->getNumContainedTypes() /* not "{}" */) {
9040       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9041       ++NumZeros;
9042     }
9043
9044     // If we found a path from the src to dest, create the getelementptr now.
9045     if (SrcElTy == DstElTy) {
9046       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
9047       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
9048                                        ((Instruction*) NULL));
9049     }
9050   }
9051
9052   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9053     if (SVI->hasOneUse()) {
9054       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9055       // a bitconvert to a vector with the same # elts.
9056       if (isa<VectorType>(DestTy) && 
9057           cast<VectorType>(DestTy)->getNumElements() ==
9058                 SVI->getType()->getNumElements() &&
9059           SVI->getType()->getNumElements() ==
9060             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9061         CastInst *Tmp;
9062         // If either of the operands is a cast from CI.getType(), then
9063         // evaluating the shuffle in the casted destination's type will allow
9064         // us to eliminate at least one cast.
9065         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9066              Tmp->getOperand(0)->getType() == DestTy) ||
9067             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9068              Tmp->getOperand(0)->getType() == DestTy)) {
9069           Value *LHS = InsertCastBefore(Instruction::BitCast,
9070                                         SVI->getOperand(0), DestTy, CI);
9071           Value *RHS = InsertCastBefore(Instruction::BitCast,
9072                                         SVI->getOperand(1), DestTy, CI);
9073           // Return a new shuffle vector.  Use the same element ID's, as we
9074           // know the vector types match #elts.
9075           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9076         }
9077       }
9078     }
9079   }
9080   return 0;
9081 }
9082
9083 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9084 ///   %C = or %A, %B
9085 ///   %D = select %cond, %C, %A
9086 /// into:
9087 ///   %C = select %cond, %B, 0
9088 ///   %D = or %A, %C
9089 ///
9090 /// Assuming that the specified instruction is an operand to the select, return
9091 /// a bitmask indicating which operands of this instruction are foldable if they
9092 /// equal the other incoming value of the select.
9093 ///
9094 static unsigned GetSelectFoldableOperands(Instruction *I) {
9095   switch (I->getOpcode()) {
9096   case Instruction::Add:
9097   case Instruction::Mul:
9098   case Instruction::And:
9099   case Instruction::Or:
9100   case Instruction::Xor:
9101     return 3;              // Can fold through either operand.
9102   case Instruction::Sub:   // Can only fold on the amount subtracted.
9103   case Instruction::Shl:   // Can only fold on the shift amount.
9104   case Instruction::LShr:
9105   case Instruction::AShr:
9106     return 1;
9107   default:
9108     return 0;              // Cannot fold
9109   }
9110 }
9111
9112 /// GetSelectFoldableConstant - For the same transformation as the previous
9113 /// function, return the identity constant that goes into the select.
9114 static Constant *GetSelectFoldableConstant(Instruction *I,
9115                                            LLVMContext *Context) {
9116   switch (I->getOpcode()) {
9117   default: LLVM_UNREACHABLE("This cannot happen!");
9118   case Instruction::Add:
9119   case Instruction::Sub:
9120   case Instruction::Or:
9121   case Instruction::Xor:
9122   case Instruction::Shl:
9123   case Instruction::LShr:
9124   case Instruction::AShr:
9125     return Context->getNullValue(I->getType());
9126   case Instruction::And:
9127     return Context->getAllOnesValue(I->getType());
9128   case Instruction::Mul:
9129     return Context->getConstantInt(I->getType(), 1);
9130   }
9131 }
9132
9133 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9134 /// have the same opcode and only one use each.  Try to simplify this.
9135 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9136                                           Instruction *FI) {
9137   if (TI->getNumOperands() == 1) {
9138     // If this is a non-volatile load or a cast from the same type,
9139     // merge.
9140     if (TI->isCast()) {
9141       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9142         return 0;
9143     } else {
9144       return 0;  // unknown unary op.
9145     }
9146
9147     // Fold this by inserting a select from the input values.
9148     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9149                                            FI->getOperand(0), SI.getName()+".v");
9150     InsertNewInstBefore(NewSI, SI);
9151     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9152                             TI->getType());
9153   }
9154
9155   // Only handle binary operators here.
9156   if (!isa<BinaryOperator>(TI))
9157     return 0;
9158
9159   // Figure out if the operations have any operands in common.
9160   Value *MatchOp, *OtherOpT, *OtherOpF;
9161   bool MatchIsOpZero;
9162   if (TI->getOperand(0) == FI->getOperand(0)) {
9163     MatchOp  = TI->getOperand(0);
9164     OtherOpT = TI->getOperand(1);
9165     OtherOpF = FI->getOperand(1);
9166     MatchIsOpZero = true;
9167   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9168     MatchOp  = TI->getOperand(1);
9169     OtherOpT = TI->getOperand(0);
9170     OtherOpF = FI->getOperand(0);
9171     MatchIsOpZero = false;
9172   } else if (!TI->isCommutative()) {
9173     return 0;
9174   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9175     MatchOp  = TI->getOperand(0);
9176     OtherOpT = TI->getOperand(1);
9177     OtherOpF = FI->getOperand(0);
9178     MatchIsOpZero = true;
9179   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9180     MatchOp  = TI->getOperand(1);
9181     OtherOpT = TI->getOperand(0);
9182     OtherOpF = FI->getOperand(1);
9183     MatchIsOpZero = true;
9184   } else {
9185     return 0;
9186   }
9187
9188   // If we reach here, they do have operations in common.
9189   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9190                                          OtherOpF, SI.getName()+".v");
9191   InsertNewInstBefore(NewSI, SI);
9192
9193   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9194     if (MatchIsOpZero)
9195       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9196     else
9197       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9198   }
9199   LLVM_UNREACHABLE("Shouldn't get here");
9200   return 0;
9201 }
9202
9203 static bool isSelect01(Constant *C1, Constant *C2) {
9204   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9205   if (!C1I)
9206     return false;
9207   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9208   if (!C2I)
9209     return false;
9210   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9211 }
9212
9213 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9214 /// facilitate further optimization.
9215 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9216                                             Value *FalseVal) {
9217   // See the comment above GetSelectFoldableOperands for a description of the
9218   // transformation we are doing here.
9219   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9220     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9221         !isa<Constant>(FalseVal)) {
9222       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9223         unsigned OpToFold = 0;
9224         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9225           OpToFold = 1;
9226         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9227           OpToFold = 2;
9228         }
9229
9230         if (OpToFold) {
9231           Constant *C = GetSelectFoldableConstant(TVI, Context);
9232           Value *OOp = TVI->getOperand(2-OpToFold);
9233           // Avoid creating select between 2 constants unless it's selecting
9234           // between 0 and 1.
9235           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9236             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9237             InsertNewInstBefore(NewSel, SI);
9238             NewSel->takeName(TVI);
9239             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9240               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9241             LLVM_UNREACHABLE("Unknown instruction!!");
9242           }
9243         }
9244       }
9245     }
9246   }
9247
9248   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9249     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9250         !isa<Constant>(TrueVal)) {
9251       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9252         unsigned OpToFold = 0;
9253         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9254           OpToFold = 1;
9255         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9256           OpToFold = 2;
9257         }
9258
9259         if (OpToFold) {
9260           Constant *C = GetSelectFoldableConstant(FVI, Context);
9261           Value *OOp = FVI->getOperand(2-OpToFold);
9262           // Avoid creating select between 2 constants unless it's selecting
9263           // between 0 and 1.
9264           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9265             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9266             InsertNewInstBefore(NewSel, SI);
9267             NewSel->takeName(FVI);
9268             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9269               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9270             LLVM_UNREACHABLE("Unknown instruction!!");
9271           }
9272         }
9273       }
9274     }
9275   }
9276
9277   return 0;
9278 }
9279
9280 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9281 /// ICmpInst as its first operand.
9282 ///
9283 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9284                                                    ICmpInst *ICI) {
9285   bool Changed = false;
9286   ICmpInst::Predicate Pred = ICI->getPredicate();
9287   Value *CmpLHS = ICI->getOperand(0);
9288   Value *CmpRHS = ICI->getOperand(1);
9289   Value *TrueVal = SI.getTrueValue();
9290   Value *FalseVal = SI.getFalseValue();
9291
9292   // Check cases where the comparison is with a constant that
9293   // can be adjusted to fit the min/max idiom. We may edit ICI in
9294   // place here, so make sure the select is the only user.
9295   if (ICI->hasOneUse())
9296     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9297       switch (Pred) {
9298       default: break;
9299       case ICmpInst::ICMP_ULT:
9300       case ICmpInst::ICMP_SLT: {
9301         // X < MIN ? T : F  -->  F
9302         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9303           return ReplaceInstUsesWith(SI, FalseVal);
9304         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9305         Constant *AdjustedRHS = SubOne(CI, Context);
9306         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9307             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9308           Pred = ICmpInst::getSwappedPredicate(Pred);
9309           CmpRHS = AdjustedRHS;
9310           std::swap(FalseVal, TrueVal);
9311           ICI->setPredicate(Pred);
9312           ICI->setOperand(1, CmpRHS);
9313           SI.setOperand(1, TrueVal);
9314           SI.setOperand(2, FalseVal);
9315           Changed = true;
9316         }
9317         break;
9318       }
9319       case ICmpInst::ICMP_UGT:
9320       case ICmpInst::ICMP_SGT: {
9321         // X > MAX ? T : F  -->  F
9322         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9323           return ReplaceInstUsesWith(SI, FalseVal);
9324         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9325         Constant *AdjustedRHS = AddOne(CI, Context);
9326         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9327             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9328           Pred = ICmpInst::getSwappedPredicate(Pred);
9329           CmpRHS = AdjustedRHS;
9330           std::swap(FalseVal, TrueVal);
9331           ICI->setPredicate(Pred);
9332           ICI->setOperand(1, CmpRHS);
9333           SI.setOperand(1, TrueVal);
9334           SI.setOperand(2, FalseVal);
9335           Changed = true;
9336         }
9337         break;
9338       }
9339       }
9340
9341       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9342       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9343       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9344       if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9345           match(FalseVal, m_ConstantInt<0>(), *Context))
9346         Pred = ICI->getPredicate();
9347       else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9348                match(FalseVal, m_ConstantInt<-1>(), *Context))
9349         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9350       
9351       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9352         // If we are just checking for a icmp eq of a single bit and zext'ing it
9353         // to an integer, then shift the bit to the appropriate place and then
9354         // cast to integer to avoid the comparison.
9355         const APInt &Op1CV = CI->getValue();
9356     
9357         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9358         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9359         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9360             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9361           Value *In = ICI->getOperand(0);
9362           Value *Sh = Context->getConstantInt(In->getType(),
9363                                        In->getType()->getScalarSizeInBits()-1);
9364           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9365                                                           In->getName()+".lobit"),
9366                                    *ICI);
9367           if (In->getType() != SI.getType())
9368             In = CastInst::CreateIntegerCast(In, SI.getType(),
9369                                              true/*SExt*/, "tmp", ICI);
9370     
9371           if (Pred == ICmpInst::ICMP_SGT)
9372             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9373                                        In->getName()+".not"), *ICI);
9374     
9375           return ReplaceInstUsesWith(SI, In);
9376         }
9377       }
9378     }
9379
9380   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9381     // Transform (X == Y) ? X : Y  -> Y
9382     if (Pred == ICmpInst::ICMP_EQ)
9383       return ReplaceInstUsesWith(SI, FalseVal);
9384     // Transform (X != Y) ? X : Y  -> X
9385     if (Pred == ICmpInst::ICMP_NE)
9386       return ReplaceInstUsesWith(SI, TrueVal);
9387     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9388
9389   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9390     // Transform (X == Y) ? Y : X  -> X
9391     if (Pred == ICmpInst::ICMP_EQ)
9392       return ReplaceInstUsesWith(SI, FalseVal);
9393     // Transform (X != Y) ? Y : X  -> Y
9394     if (Pred == ICmpInst::ICMP_NE)
9395       return ReplaceInstUsesWith(SI, TrueVal);
9396     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9397   }
9398
9399   /// NOTE: if we wanted to, this is where to detect integer ABS
9400
9401   return Changed ? &SI : 0;
9402 }
9403
9404 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9405   Value *CondVal = SI.getCondition();
9406   Value *TrueVal = SI.getTrueValue();
9407   Value *FalseVal = SI.getFalseValue();
9408
9409   // select true, X, Y  -> X
9410   // select false, X, Y -> Y
9411   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9412     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9413
9414   // select C, X, X -> X
9415   if (TrueVal == FalseVal)
9416     return ReplaceInstUsesWith(SI, TrueVal);
9417
9418   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9419     return ReplaceInstUsesWith(SI, FalseVal);
9420   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9421     return ReplaceInstUsesWith(SI, TrueVal);
9422   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9423     if (isa<Constant>(TrueVal))
9424       return ReplaceInstUsesWith(SI, TrueVal);
9425     else
9426       return ReplaceInstUsesWith(SI, FalseVal);
9427   }
9428
9429   if (SI.getType() == Type::Int1Ty) {
9430     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9431       if (C->getZExtValue()) {
9432         // Change: A = select B, true, C --> A = or B, C
9433         return BinaryOperator::CreateOr(CondVal, FalseVal);
9434       } else {
9435         // Change: A = select B, false, C --> A = and !B, C
9436         Value *NotCond =
9437           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9438                                              "not."+CondVal->getName()), SI);
9439         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9440       }
9441     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9442       if (C->getZExtValue() == false) {
9443         // Change: A = select B, C, false --> A = and B, C
9444         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9445       } else {
9446         // Change: A = select B, C, true --> A = or !B, C
9447         Value *NotCond =
9448           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9449                                              "not."+CondVal->getName()), SI);
9450         return BinaryOperator::CreateOr(NotCond, TrueVal);
9451       }
9452     }
9453     
9454     // select a, b, a  -> a&b
9455     // select a, a, b  -> a|b
9456     if (CondVal == TrueVal)
9457       return BinaryOperator::CreateOr(CondVal, FalseVal);
9458     else if (CondVal == FalseVal)
9459       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9460   }
9461
9462   // Selecting between two integer constants?
9463   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9464     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9465       // select C, 1, 0 -> zext C to int
9466       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9467         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9468       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9469         // select C, 0, 1 -> zext !C to int
9470         Value *NotCond =
9471           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9472                                                "not."+CondVal->getName()), SI);
9473         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9474       }
9475
9476       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9477         // If one of the constants is zero (we know they can't both be) and we
9478         // have an icmp instruction with zero, and we have an 'and' with the
9479         // non-constant value, eliminate this whole mess.  This corresponds to
9480         // cases like this: ((X & 27) ? 27 : 0)
9481         if (TrueValC->isZero() || FalseValC->isZero())
9482           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9483               cast<Constant>(IC->getOperand(1))->isNullValue())
9484             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9485               if (ICA->getOpcode() == Instruction::And &&
9486                   isa<ConstantInt>(ICA->getOperand(1)) &&
9487                   (ICA->getOperand(1) == TrueValC ||
9488                    ICA->getOperand(1) == FalseValC) &&
9489                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9490                 // Okay, now we know that everything is set up, we just don't
9491                 // know whether we have a icmp_ne or icmp_eq and whether the 
9492                 // true or false val is the zero.
9493                 bool ShouldNotVal = !TrueValC->isZero();
9494                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9495                 Value *V = ICA;
9496                 if (ShouldNotVal)
9497                   V = InsertNewInstBefore(BinaryOperator::Create(
9498                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9499                 return ReplaceInstUsesWith(SI, V);
9500               }
9501       }
9502     }
9503
9504   // See if we are selecting two values based on a comparison of the two values.
9505   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9506     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9507       // Transform (X == Y) ? X : Y  -> Y
9508       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9509         // This is not safe in general for floating point:  
9510         // consider X== -0, Y== +0.
9511         // It becomes safe if either operand is a nonzero constant.
9512         ConstantFP *CFPt, *CFPf;
9513         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9514               !CFPt->getValueAPF().isZero()) ||
9515             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9516              !CFPf->getValueAPF().isZero()))
9517         return ReplaceInstUsesWith(SI, FalseVal);
9518       }
9519       // Transform (X != Y) ? X : Y  -> X
9520       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9521         return ReplaceInstUsesWith(SI, TrueVal);
9522       // NOTE: if we wanted to, this is where to detect MIN/MAX
9523
9524     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9525       // Transform (X == Y) ? Y : X  -> X
9526       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9527         // This is not safe in general for floating point:  
9528         // consider X== -0, Y== +0.
9529         // It becomes safe if either operand is a nonzero constant.
9530         ConstantFP *CFPt, *CFPf;
9531         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9532               !CFPt->getValueAPF().isZero()) ||
9533             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9534              !CFPf->getValueAPF().isZero()))
9535           return ReplaceInstUsesWith(SI, FalseVal);
9536       }
9537       // Transform (X != Y) ? Y : X  -> Y
9538       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9539         return ReplaceInstUsesWith(SI, TrueVal);
9540       // NOTE: if we wanted to, this is where to detect MIN/MAX
9541     }
9542     // NOTE: if we wanted to, this is where to detect ABS
9543   }
9544
9545   // See if we are selecting two values based on a comparison of the two values.
9546   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9547     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9548       return Result;
9549
9550   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9551     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9552       if (TI->hasOneUse() && FI->hasOneUse()) {
9553         Instruction *AddOp = 0, *SubOp = 0;
9554
9555         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9556         if (TI->getOpcode() == FI->getOpcode())
9557           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9558             return IV;
9559
9560         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9561         // even legal for FP.
9562         if ((TI->getOpcode() == Instruction::Sub &&
9563              FI->getOpcode() == Instruction::Add) ||
9564             (TI->getOpcode() == Instruction::FSub &&
9565              FI->getOpcode() == Instruction::FAdd)) {
9566           AddOp = FI; SubOp = TI;
9567         } else if ((FI->getOpcode() == Instruction::Sub &&
9568                     TI->getOpcode() == Instruction::Add) ||
9569                    (FI->getOpcode() == Instruction::FSub &&
9570                     TI->getOpcode() == Instruction::FAdd)) {
9571           AddOp = TI; SubOp = FI;
9572         }
9573
9574         if (AddOp) {
9575           Value *OtherAddOp = 0;
9576           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9577             OtherAddOp = AddOp->getOperand(1);
9578           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9579             OtherAddOp = AddOp->getOperand(0);
9580           }
9581
9582           if (OtherAddOp) {
9583             // So at this point we know we have (Y -> OtherAddOp):
9584             //        select C, (add X, Y), (sub X, Z)
9585             Value *NegVal;  // Compute -Z
9586             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9587               NegVal = Context->getConstantExprNeg(C);
9588             } else {
9589               NegVal = InsertNewInstBefore(
9590                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
9591             }
9592
9593             Value *NewTrueOp = OtherAddOp;
9594             Value *NewFalseOp = NegVal;
9595             if (AddOp != TI)
9596               std::swap(NewTrueOp, NewFalseOp);
9597             Instruction *NewSel =
9598               SelectInst::Create(CondVal, NewTrueOp,
9599                                  NewFalseOp, SI.getName() + ".p");
9600
9601             NewSel = InsertNewInstBefore(NewSel, SI);
9602             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9603           }
9604         }
9605       }
9606
9607   // See if we can fold the select into one of our operands.
9608   if (SI.getType()->isInteger()) {
9609     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9610     if (FoldI)
9611       return FoldI;
9612   }
9613
9614   if (BinaryOperator::isNot(CondVal)) {
9615     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9616     SI.setOperand(1, FalseVal);
9617     SI.setOperand(2, TrueVal);
9618     return &SI;
9619   }
9620
9621   return 0;
9622 }
9623
9624 /// EnforceKnownAlignment - If the specified pointer points to an object that
9625 /// we control, modify the object's alignment to PrefAlign. This isn't
9626 /// often possible though. If alignment is important, a more reliable approach
9627 /// is to simply align all global variables and allocation instructions to
9628 /// their preferred alignment from the beginning.
9629 ///
9630 static unsigned EnforceKnownAlignment(Value *V,
9631                                       unsigned Align, unsigned PrefAlign) {
9632
9633   User *U = dyn_cast<User>(V);
9634   if (!U) return Align;
9635
9636   switch (getOpcode(U)) {
9637   default: break;
9638   case Instruction::BitCast:
9639     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9640   case Instruction::GetElementPtr: {
9641     // If all indexes are zero, it is just the alignment of the base pointer.
9642     bool AllZeroOperands = true;
9643     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9644       if (!isa<Constant>(*i) ||
9645           !cast<Constant>(*i)->isNullValue()) {
9646         AllZeroOperands = false;
9647         break;
9648       }
9649
9650     if (AllZeroOperands) {
9651       // Treat this like a bitcast.
9652       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9653     }
9654     break;
9655   }
9656   }
9657
9658   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9659     // If there is a large requested alignment and we can, bump up the alignment
9660     // of the global.
9661     if (!GV->isDeclaration()) {
9662       if (GV->getAlignment() >= PrefAlign)
9663         Align = GV->getAlignment();
9664       else {
9665         GV->setAlignment(PrefAlign);
9666         Align = PrefAlign;
9667       }
9668     }
9669   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9670     // If there is a requested alignment and if this is an alloca, round up.  We
9671     // don't do this for malloc, because some systems can't respect the request.
9672     if (isa<AllocaInst>(AI)) {
9673       if (AI->getAlignment() >= PrefAlign)
9674         Align = AI->getAlignment();
9675       else {
9676         AI->setAlignment(PrefAlign);
9677         Align = PrefAlign;
9678       }
9679     }
9680   }
9681
9682   return Align;
9683 }
9684
9685 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9686 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9687 /// and it is more than the alignment of the ultimate object, see if we can
9688 /// increase the alignment of the ultimate object, making this check succeed.
9689 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9690                                                   unsigned PrefAlign) {
9691   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9692                       sizeof(PrefAlign) * CHAR_BIT;
9693   APInt Mask = APInt::getAllOnesValue(BitWidth);
9694   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9695   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9696   unsigned TrailZ = KnownZero.countTrailingOnes();
9697   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9698
9699   if (PrefAlign > Align)
9700     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9701   
9702     // We don't need to make any adjustment.
9703   return Align;
9704 }
9705
9706 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9707   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9708   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9709   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9710   unsigned CopyAlign = MI->getAlignment();
9711
9712   if (CopyAlign < MinAlign) {
9713     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(), 
9714                                              MinAlign, false));
9715     return MI;
9716   }
9717   
9718   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9719   // load/store.
9720   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9721   if (MemOpLength == 0) return 0;
9722   
9723   // Source and destination pointer types are always "i8*" for intrinsic.  See
9724   // if the size is something we can handle with a single primitive load/store.
9725   // A single load+store correctly handles overlapping memory in the memmove
9726   // case.
9727   unsigned Size = MemOpLength->getZExtValue();
9728   if (Size == 0) return MI;  // Delete this mem transfer.
9729   
9730   if (Size > 8 || (Size&(Size-1)))
9731     return 0;  // If not 1/2/4/8 bytes, exit.
9732   
9733   // Use an integer load+store unless we can find something better.
9734   Type *NewPtrTy =
9735                 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
9736   
9737   // Memcpy forces the use of i8* for the source and destination.  That means
9738   // that if you're using memcpy to move one double around, you'll get a cast
9739   // from double* to i8*.  We'd much rather use a double load+store rather than
9740   // an i64 load+store, here because this improves the odds that the source or
9741   // dest address will be promotable.  See if we can find a better type than the
9742   // integer datatype.
9743   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9744     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9745     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9746       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9747       // down through these levels if so.
9748       while (!SrcETy->isSingleValueType()) {
9749         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9750           if (STy->getNumElements() == 1)
9751             SrcETy = STy->getElementType(0);
9752           else
9753             break;
9754         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9755           if (ATy->getNumElements() == 1)
9756             SrcETy = ATy->getElementType();
9757           else
9758             break;
9759         } else
9760           break;
9761       }
9762       
9763       if (SrcETy->isSingleValueType())
9764         NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
9765     }
9766   }
9767   
9768   
9769   // If the memcpy/memmove provides better alignment info than we can
9770   // infer, use it.
9771   SrcAlign = std::max(SrcAlign, CopyAlign);
9772   DstAlign = std::max(DstAlign, CopyAlign);
9773   
9774   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9775   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9776   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9777   InsertNewInstBefore(L, *MI);
9778   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9779
9780   // Set the size of the copy to 0, it will be deleted on the next iteration.
9781   MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
9782   return MI;
9783 }
9784
9785 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9786   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9787   if (MI->getAlignment() < Alignment) {
9788     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9789                                              Alignment, false));
9790     return MI;
9791   }
9792   
9793   // Extract the length and alignment and fill if they are constant.
9794   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9795   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9796   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9797     return 0;
9798   uint64_t Len = LenC->getZExtValue();
9799   Alignment = MI->getAlignment();
9800   
9801   // If the length is zero, this is a no-op
9802   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9803   
9804   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9805   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9806     const Type *ITy = Context->getIntegerType(Len*8);  // n=1 -> i8.
9807     
9808     Value *Dest = MI->getDest();
9809     Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
9810
9811     // Alignment 0 is identity for alignment 1 for memset, but not store.
9812     if (Alignment == 0) Alignment = 1;
9813     
9814     // Extract the fill value and store.
9815     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9816     InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9817                                       Dest, false, Alignment), *MI);
9818     
9819     // Set the size of the copy to 0, it will be deleted on the next iteration.
9820     MI->setLength(Context->getNullValue(LenC->getType()));
9821     return MI;
9822   }
9823
9824   return 0;
9825 }
9826
9827
9828 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9829 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9830 /// the heavy lifting.
9831 ///
9832 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9833   // If the caller function is nounwind, mark the call as nounwind, even if the
9834   // callee isn't.
9835   if (CI.getParent()->getParent()->doesNotThrow() &&
9836       !CI.doesNotThrow()) {
9837     CI.setDoesNotThrow();
9838     return &CI;
9839   }
9840   
9841   
9842   
9843   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9844   if (!II) return visitCallSite(&CI);
9845   
9846   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9847   // visitCallSite.
9848   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9849     bool Changed = false;
9850
9851     // memmove/cpy/set of zero bytes is a noop.
9852     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9853       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9854
9855       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9856         if (CI->getZExtValue() == 1) {
9857           // Replace the instruction with just byte operations.  We would
9858           // transform other cases to loads/stores, but we don't know if
9859           // alignment is sufficient.
9860         }
9861     }
9862
9863     // If we have a memmove and the source operation is a constant global,
9864     // then the source and dest pointers can't alias, so we can change this
9865     // into a call to memcpy.
9866     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9867       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9868         if (GVSrc->isConstant()) {
9869           Module *M = CI.getParent()->getParent()->getParent();
9870           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9871           const Type *Tys[1];
9872           Tys[0] = CI.getOperand(3)->getType();
9873           CI.setOperand(0, 
9874                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9875           Changed = true;
9876         }
9877
9878       // memmove(x,x,size) -> noop.
9879       if (MMI->getSource() == MMI->getDest())
9880         return EraseInstFromFunction(CI);
9881     }
9882
9883     // If we can determine a pointer alignment that is bigger than currently
9884     // set, update the alignment.
9885     if (isa<MemTransferInst>(MI)) {
9886       if (Instruction *I = SimplifyMemTransfer(MI))
9887         return I;
9888     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9889       if (Instruction *I = SimplifyMemSet(MSI))
9890         return I;
9891     }
9892           
9893     if (Changed) return II;
9894   }
9895   
9896   switch (II->getIntrinsicID()) {
9897   default: break;
9898   case Intrinsic::bswap:
9899     // bswap(bswap(x)) -> x
9900     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9901       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9902         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9903     break;
9904   case Intrinsic::ppc_altivec_lvx:
9905   case Intrinsic::ppc_altivec_lvxl:
9906   case Intrinsic::x86_sse_loadu_ps:
9907   case Intrinsic::x86_sse2_loadu_pd:
9908   case Intrinsic::x86_sse2_loadu_dq:
9909     // Turn PPC lvx     -> load if the pointer is known aligned.
9910     // Turn X86 loadups -> load if the pointer is known aligned.
9911     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9912       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9913                                    Context->getPointerTypeUnqual(II->getType()),
9914                                        CI);
9915       return new LoadInst(Ptr);
9916     }
9917     break;
9918   case Intrinsic::ppc_altivec_stvx:
9919   case Intrinsic::ppc_altivec_stvxl:
9920     // Turn stvx -> store if the pointer is known aligned.
9921     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9922       const Type *OpPtrTy = 
9923         Context->getPointerTypeUnqual(II->getOperand(1)->getType());
9924       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9925       return new StoreInst(II->getOperand(1), Ptr);
9926     }
9927     break;
9928   case Intrinsic::x86_sse_storeu_ps:
9929   case Intrinsic::x86_sse2_storeu_pd:
9930   case Intrinsic::x86_sse2_storeu_dq:
9931     // Turn X86 storeu -> store if the pointer is known aligned.
9932     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9933       const Type *OpPtrTy = 
9934         Context->getPointerTypeUnqual(II->getOperand(2)->getType());
9935       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9936       return new StoreInst(II->getOperand(2), Ptr);
9937     }
9938     break;
9939     
9940   case Intrinsic::x86_sse_cvttss2si: {
9941     // These intrinsics only demands the 0th element of its input vector.  If
9942     // we can simplify the input based on that, do so now.
9943     unsigned VWidth =
9944       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9945     APInt DemandedElts(VWidth, 1);
9946     APInt UndefElts(VWidth, 0);
9947     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9948                                               UndefElts)) {
9949       II->setOperand(1, V);
9950       return II;
9951     }
9952     break;
9953   }
9954     
9955   case Intrinsic::ppc_altivec_vperm:
9956     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9957     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9958       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9959       
9960       // Check that all of the elements are integer constants or undefs.
9961       bool AllEltsOk = true;
9962       for (unsigned i = 0; i != 16; ++i) {
9963         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9964             !isa<UndefValue>(Mask->getOperand(i))) {
9965           AllEltsOk = false;
9966           break;
9967         }
9968       }
9969       
9970       if (AllEltsOk) {
9971         // Cast the input vectors to byte vectors.
9972         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9973         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9974         Value *Result = Context->getUndef(Op0->getType());
9975         
9976         // Only extract each element once.
9977         Value *ExtractedElts[32];
9978         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9979         
9980         for (unsigned i = 0; i != 16; ++i) {
9981           if (isa<UndefValue>(Mask->getOperand(i)))
9982             continue;
9983           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9984           Idx &= 31;  // Match the hardware behavior.
9985           
9986           if (ExtractedElts[Idx] == 0) {
9987             Instruction *Elt = 
9988               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9989             InsertNewInstBefore(Elt, CI);
9990             ExtractedElts[Idx] = Elt;
9991           }
9992         
9993           // Insert this value into the result vector.
9994           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9995                                              i, "tmp");
9996           InsertNewInstBefore(cast<Instruction>(Result), CI);
9997         }
9998         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9999       }
10000     }
10001     break;
10002
10003   case Intrinsic::stackrestore: {
10004     // If the save is right next to the restore, remove the restore.  This can
10005     // happen when variable allocas are DCE'd.
10006     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10007       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10008         BasicBlock::iterator BI = SS;
10009         if (&*++BI == II)
10010           return EraseInstFromFunction(CI);
10011       }
10012     }
10013     
10014     // Scan down this block to see if there is another stack restore in the
10015     // same block without an intervening call/alloca.
10016     BasicBlock::iterator BI = II;
10017     TerminatorInst *TI = II->getParent()->getTerminator();
10018     bool CannotRemove = false;
10019     for (++BI; &*BI != TI; ++BI) {
10020       if (isa<AllocaInst>(BI)) {
10021         CannotRemove = true;
10022         break;
10023       }
10024       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10025         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10026           // If there is a stackrestore below this one, remove this one.
10027           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10028             return EraseInstFromFunction(CI);
10029           // Otherwise, ignore the intrinsic.
10030         } else {
10031           // If we found a non-intrinsic call, we can't remove the stack
10032           // restore.
10033           CannotRemove = true;
10034           break;
10035         }
10036       }
10037     }
10038     
10039     // If the stack restore is in a return/unwind block and if there are no
10040     // allocas or calls between the restore and the return, nuke the restore.
10041     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10042       return EraseInstFromFunction(CI);
10043     break;
10044   }
10045   }
10046
10047   return visitCallSite(II);
10048 }
10049
10050 // InvokeInst simplification
10051 //
10052 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10053   return visitCallSite(&II);
10054 }
10055
10056 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10057 /// passed through the varargs area, we can eliminate the use of the cast.
10058 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10059                                          const CastInst * const CI,
10060                                          const TargetData * const TD,
10061                                          const int ix) {
10062   if (!CI->isLosslessCast())
10063     return false;
10064
10065   // The size of ByVal arguments is derived from the type, so we
10066   // can't change to a type with a different size.  If the size were
10067   // passed explicitly we could avoid this check.
10068   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10069     return true;
10070
10071   const Type* SrcTy = 
10072             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10073   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10074   if (!SrcTy->isSized() || !DstTy->isSized())
10075     return false;
10076   if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10077     return false;
10078   return true;
10079 }
10080
10081 // visitCallSite - Improvements for call and invoke instructions.
10082 //
10083 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10084   bool Changed = false;
10085
10086   // If the callee is a constexpr cast of a function, attempt to move the cast
10087   // to the arguments of the call/invoke.
10088   if (transformConstExprCastCall(CS)) return 0;
10089
10090   Value *Callee = CS.getCalledValue();
10091
10092   if (Function *CalleeF = dyn_cast<Function>(Callee))
10093     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10094       Instruction *OldCall = CS.getInstruction();
10095       // If the call and callee calling conventions don't match, this call must
10096       // be unreachable, as the call is undefined.
10097       new StoreInst(Context->getConstantIntTrue(),
10098                 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), 
10099                                   OldCall);
10100       if (!OldCall->use_empty())
10101         OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
10102       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10103         return EraseInstFromFunction(*OldCall);
10104       return 0;
10105     }
10106
10107   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10108     // This instruction is not reachable, just remove it.  We insert a store to
10109     // undef so that we know that this code is not reachable, despite the fact
10110     // that we can't modify the CFG here.
10111     new StoreInst(Context->getConstantIntTrue(),
10112                Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10113                   CS.getInstruction());
10114
10115     if (!CS.getInstruction()->use_empty())
10116       CS.getInstruction()->
10117         replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
10118
10119     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10120       // Don't break the CFG, insert a dummy cond branch.
10121       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10122                          Context->getConstantIntTrue(), II);
10123     }
10124     return EraseInstFromFunction(*CS.getInstruction());
10125   }
10126
10127   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10128     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10129       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10130         return transformCallThroughTrampoline(CS);
10131
10132   const PointerType *PTy = cast<PointerType>(Callee->getType());
10133   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10134   if (FTy->isVarArg()) {
10135     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10136     // See if we can optimize any arguments passed through the varargs area of
10137     // the call.
10138     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10139            E = CS.arg_end(); I != E; ++I, ++ix) {
10140       CastInst *CI = dyn_cast<CastInst>(*I);
10141       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10142         *I = CI->getOperand(0);
10143         Changed = true;
10144       }
10145     }
10146   }
10147
10148   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10149     // Inline asm calls cannot throw - mark them 'nounwind'.
10150     CS.setDoesNotThrow();
10151     Changed = true;
10152   }
10153
10154   return Changed ? CS.getInstruction() : 0;
10155 }
10156
10157 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10158 // attempt to move the cast to the arguments of the call/invoke.
10159 //
10160 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10161   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10162   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10163   if (CE->getOpcode() != Instruction::BitCast || 
10164       !isa<Function>(CE->getOperand(0)))
10165     return false;
10166   Function *Callee = cast<Function>(CE->getOperand(0));
10167   Instruction *Caller = CS.getInstruction();
10168   const AttrListPtr &CallerPAL = CS.getAttributes();
10169
10170   // Okay, this is a cast from a function to a different type.  Unless doing so
10171   // would cause a type conversion of one of our arguments, change this call to
10172   // be a direct call with arguments casted to the appropriate types.
10173   //
10174   const FunctionType *FT = Callee->getFunctionType();
10175   const Type *OldRetTy = Caller->getType();
10176   const Type *NewRetTy = FT->getReturnType();
10177
10178   if (isa<StructType>(NewRetTy))
10179     return false; // TODO: Handle multiple return values.
10180
10181   // Check to see if we are changing the return type...
10182   if (OldRetTy != NewRetTy) {
10183     if (Callee->isDeclaration() &&
10184         // Conversion is ok if changing from one pointer type to another or from
10185         // a pointer to an integer of the same size.
10186         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
10187           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
10188       return false;   // Cannot transform this return value.
10189
10190     if (!Caller->use_empty() &&
10191         // void -> non-void is handled specially
10192         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10193       return false;   // Cannot transform this return value.
10194
10195     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10196       Attributes RAttrs = CallerPAL.getRetAttributes();
10197       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10198         return false;   // Attribute not compatible with transformed value.
10199     }
10200
10201     // If the callsite is an invoke instruction, and the return value is used by
10202     // a PHI node in a successor, we cannot change the return type of the call
10203     // because there is no place to put the cast instruction (without breaking
10204     // the critical edge).  Bail out in this case.
10205     if (!Caller->use_empty())
10206       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10207         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10208              UI != E; ++UI)
10209           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10210             if (PN->getParent() == II->getNormalDest() ||
10211                 PN->getParent() == II->getUnwindDest())
10212               return false;
10213   }
10214
10215   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10216   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10217
10218   CallSite::arg_iterator AI = CS.arg_begin();
10219   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10220     const Type *ParamTy = FT->getParamType(i);
10221     const Type *ActTy = (*AI)->getType();
10222
10223     if (!CastInst::isCastable(ActTy, ParamTy))
10224       return false;   // Cannot transform this parameter value.
10225
10226     if (CallerPAL.getParamAttributes(i + 1) 
10227         & Attribute::typeIncompatible(ParamTy))
10228       return false;   // Attribute not compatible with transformed value.
10229
10230     // Converting from one pointer type to another or between a pointer and an
10231     // integer of the same size is safe even if we do not have a body.
10232     bool isConvertible = ActTy == ParamTy ||
10233       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10234        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
10235     if (Callee->isDeclaration() && !isConvertible) return false;
10236   }
10237
10238   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10239       Callee->isDeclaration())
10240     return false;   // Do not delete arguments unless we have a function body.
10241
10242   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10243       !CallerPAL.isEmpty())
10244     // In this case we have more arguments than the new function type, but we
10245     // won't be dropping them.  Check that these extra arguments have attributes
10246     // that are compatible with being a vararg call argument.
10247     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10248       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10249         break;
10250       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10251       if (PAttrs & Attribute::VarArgsIncompatible)
10252         return false;
10253     }
10254
10255   // Okay, we decided that this is a safe thing to do: go ahead and start
10256   // inserting cast instructions as necessary...
10257   std::vector<Value*> Args;
10258   Args.reserve(NumActualArgs);
10259   SmallVector<AttributeWithIndex, 8> attrVec;
10260   attrVec.reserve(NumCommonArgs);
10261
10262   // Get any return attributes.
10263   Attributes RAttrs = CallerPAL.getRetAttributes();
10264
10265   // If the return value is not being used, the type may not be compatible
10266   // with the existing attributes.  Wipe out any problematic attributes.
10267   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10268
10269   // Add the new return attributes.
10270   if (RAttrs)
10271     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10272
10273   AI = CS.arg_begin();
10274   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10275     const Type *ParamTy = FT->getParamType(i);
10276     if ((*AI)->getType() == ParamTy) {
10277       Args.push_back(*AI);
10278     } else {
10279       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10280           false, ParamTy, false);
10281       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10282       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10283     }
10284
10285     // Add any parameter attributes.
10286     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10287       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10288   }
10289
10290   // If the function takes more arguments than the call was taking, add them
10291   // now...
10292   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10293     Args.push_back(Context->getNullValue(FT->getParamType(i)));
10294
10295   // If we are removing arguments to the function, emit an obnoxious warning...
10296   if (FT->getNumParams() < NumActualArgs) {
10297     if (!FT->isVarArg()) {
10298       cerr << "WARNING: While resolving call to function '"
10299            << Callee->getName() << "' arguments were dropped!\n";
10300     } else {
10301       // Add all of the arguments in their promoted form to the arg list...
10302       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10303         const Type *PTy = getPromotedType((*AI)->getType());
10304         if (PTy != (*AI)->getType()) {
10305           // Must promote to pass through va_arg area!
10306           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10307                                                                 PTy, false);
10308           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10309           InsertNewInstBefore(Cast, *Caller);
10310           Args.push_back(Cast);
10311         } else {
10312           Args.push_back(*AI);
10313         }
10314
10315         // Add any parameter attributes.
10316         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10317           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10318       }
10319     }
10320   }
10321
10322   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10323     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10324
10325   if (NewRetTy == Type::VoidTy)
10326     Caller->setName("");   // Void type should not have a name.
10327
10328   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10329
10330   Instruction *NC;
10331   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10332     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10333                             Args.begin(), Args.end(),
10334                             Caller->getName(), Caller);
10335     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10336     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10337   } else {
10338     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10339                           Caller->getName(), Caller);
10340     CallInst *CI = cast<CallInst>(Caller);
10341     if (CI->isTailCall())
10342       cast<CallInst>(NC)->setTailCall();
10343     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10344     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10345   }
10346
10347   // Insert a cast of the return type as necessary.
10348   Value *NV = NC;
10349   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10350     if (NV->getType() != Type::VoidTy) {
10351       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10352                                                             OldRetTy, false);
10353       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10354
10355       // If this is an invoke instruction, we should insert it after the first
10356       // non-phi, instruction in the normal successor block.
10357       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10358         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10359         InsertNewInstBefore(NC, *I);
10360       } else {
10361         // Otherwise, it's a call, just insert cast right after the call instr
10362         InsertNewInstBefore(NC, *Caller);
10363       }
10364       AddUsersToWorkList(*Caller);
10365     } else {
10366       NV = Context->getUndef(Caller->getType());
10367     }
10368   }
10369
10370   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10371     Caller->replaceAllUsesWith(NV);
10372   Caller->eraseFromParent();
10373   RemoveFromWorkList(Caller);
10374   return true;
10375 }
10376
10377 // transformCallThroughTrampoline - Turn a call to a function created by the
10378 // init_trampoline intrinsic into a direct call to the underlying function.
10379 //
10380 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10381   Value *Callee = CS.getCalledValue();
10382   const PointerType *PTy = cast<PointerType>(Callee->getType());
10383   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10384   const AttrListPtr &Attrs = CS.getAttributes();
10385
10386   // If the call already has the 'nest' attribute somewhere then give up -
10387   // otherwise 'nest' would occur twice after splicing in the chain.
10388   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10389     return 0;
10390
10391   IntrinsicInst *Tramp =
10392     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10393
10394   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10395   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10396   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10397
10398   const AttrListPtr &NestAttrs = NestF->getAttributes();
10399   if (!NestAttrs.isEmpty()) {
10400     unsigned NestIdx = 1;
10401     const Type *NestTy = 0;
10402     Attributes NestAttr = Attribute::None;
10403
10404     // Look for a parameter marked with the 'nest' attribute.
10405     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10406          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10407       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10408         // Record the parameter type and any other attributes.
10409         NestTy = *I;
10410         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10411         break;
10412       }
10413
10414     if (NestTy) {
10415       Instruction *Caller = CS.getInstruction();
10416       std::vector<Value*> NewArgs;
10417       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10418
10419       SmallVector<AttributeWithIndex, 8> NewAttrs;
10420       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10421
10422       // Insert the nest argument into the call argument list, which may
10423       // mean appending it.  Likewise for attributes.
10424
10425       // Add any result attributes.
10426       if (Attributes Attr = Attrs.getRetAttributes())
10427         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10428
10429       {
10430         unsigned Idx = 1;
10431         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10432         do {
10433           if (Idx == NestIdx) {
10434             // Add the chain argument and attributes.
10435             Value *NestVal = Tramp->getOperand(3);
10436             if (NestVal->getType() != NestTy)
10437               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10438             NewArgs.push_back(NestVal);
10439             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10440           }
10441
10442           if (I == E)
10443             break;
10444
10445           // Add the original argument and attributes.
10446           NewArgs.push_back(*I);
10447           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10448             NewAttrs.push_back
10449               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10450
10451           ++Idx, ++I;
10452         } while (1);
10453       }
10454
10455       // Add any function attributes.
10456       if (Attributes Attr = Attrs.getFnAttributes())
10457         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10458
10459       // The trampoline may have been bitcast to a bogus type (FTy).
10460       // Handle this by synthesizing a new function type, equal to FTy
10461       // with the chain parameter inserted.
10462
10463       std::vector<const Type*> NewTypes;
10464       NewTypes.reserve(FTy->getNumParams()+1);
10465
10466       // Insert the chain's type into the list of parameter types, which may
10467       // mean appending it.
10468       {
10469         unsigned Idx = 1;
10470         FunctionType::param_iterator I = FTy->param_begin(),
10471           E = FTy->param_end();
10472
10473         do {
10474           if (Idx == NestIdx)
10475             // Add the chain's type.
10476             NewTypes.push_back(NestTy);
10477
10478           if (I == E)
10479             break;
10480
10481           // Add the original type.
10482           NewTypes.push_back(*I);
10483
10484           ++Idx, ++I;
10485         } while (1);
10486       }
10487
10488       // Replace the trampoline call with a direct call.  Let the generic
10489       // code sort out any function type mismatches.
10490       FunctionType *NewFTy =
10491                        Context->getFunctionType(FTy->getReturnType(), NewTypes, 
10492                                                 FTy->isVarArg());
10493       Constant *NewCallee =
10494         NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10495         NestF : Context->getConstantExprBitCast(NestF, 
10496                                          Context->getPointerTypeUnqual(NewFTy));
10497       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10498
10499       Instruction *NewCaller;
10500       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10501         NewCaller = InvokeInst::Create(NewCallee,
10502                                        II->getNormalDest(), II->getUnwindDest(),
10503                                        NewArgs.begin(), NewArgs.end(),
10504                                        Caller->getName(), Caller);
10505         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10506         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10507       } else {
10508         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10509                                      Caller->getName(), Caller);
10510         if (cast<CallInst>(Caller)->isTailCall())
10511           cast<CallInst>(NewCaller)->setTailCall();
10512         cast<CallInst>(NewCaller)->
10513           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10514         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10515       }
10516       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10517         Caller->replaceAllUsesWith(NewCaller);
10518       Caller->eraseFromParent();
10519       RemoveFromWorkList(Caller);
10520       return 0;
10521     }
10522   }
10523
10524   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10525   // parameter, there is no need to adjust the argument list.  Let the generic
10526   // code sort out any function type mismatches.
10527   Constant *NewCallee =
10528     NestF->getType() == PTy ? NestF : 
10529                               Context->getConstantExprBitCast(NestF, PTy);
10530   CS.setCalledFunction(NewCallee);
10531   return CS.getInstruction();
10532 }
10533
10534 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10535 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10536 /// and a single binop.
10537 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10538   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10539   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10540   unsigned Opc = FirstInst->getOpcode();
10541   Value *LHSVal = FirstInst->getOperand(0);
10542   Value *RHSVal = FirstInst->getOperand(1);
10543     
10544   const Type *LHSType = LHSVal->getType();
10545   const Type *RHSType = RHSVal->getType();
10546   
10547   // Scan to see if all operands are the same opcode, all have one use, and all
10548   // kill their operands (i.e. the operands have one use).
10549   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10550     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10551     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10552         // Verify type of the LHS matches so we don't fold cmp's of different
10553         // types or GEP's with different index types.
10554         I->getOperand(0)->getType() != LHSType ||
10555         I->getOperand(1)->getType() != RHSType)
10556       return 0;
10557
10558     // If they are CmpInst instructions, check their predicates
10559     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10560       if (cast<CmpInst>(I)->getPredicate() !=
10561           cast<CmpInst>(FirstInst)->getPredicate())
10562         return 0;
10563     
10564     // Keep track of which operand needs a phi node.
10565     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10566     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10567   }
10568   
10569   // Otherwise, this is safe to transform!
10570   
10571   Value *InLHS = FirstInst->getOperand(0);
10572   Value *InRHS = FirstInst->getOperand(1);
10573   PHINode *NewLHS = 0, *NewRHS = 0;
10574   if (LHSVal == 0) {
10575     NewLHS = PHINode::Create(LHSType,
10576                              FirstInst->getOperand(0)->getName() + ".pn");
10577     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10578     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10579     InsertNewInstBefore(NewLHS, PN);
10580     LHSVal = NewLHS;
10581   }
10582   
10583   if (RHSVal == 0) {
10584     NewRHS = PHINode::Create(RHSType,
10585                              FirstInst->getOperand(1)->getName() + ".pn");
10586     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10587     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10588     InsertNewInstBefore(NewRHS, PN);
10589     RHSVal = NewRHS;
10590   }
10591   
10592   // Add all operands to the new PHIs.
10593   if (NewLHS || NewRHS) {
10594     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10595       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10596       if (NewLHS) {
10597         Value *NewInLHS = InInst->getOperand(0);
10598         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10599       }
10600       if (NewRHS) {
10601         Value *NewInRHS = InInst->getOperand(1);
10602         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10603       }
10604     }
10605   }
10606     
10607   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10608     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10609   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10610   return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10611                          LHSVal, RHSVal);
10612 }
10613
10614 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10615   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10616   
10617   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10618                                         FirstInst->op_end());
10619   // This is true if all GEP bases are allocas and if all indices into them are
10620   // constants.
10621   bool AllBasePointersAreAllocas = true;
10622   
10623   // Scan to see if all operands are the same opcode, all have one use, and all
10624   // kill their operands (i.e. the operands have one use).
10625   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10626     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10627     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10628       GEP->getNumOperands() != FirstInst->getNumOperands())
10629       return 0;
10630
10631     // Keep track of whether or not all GEPs are of alloca pointers.
10632     if (AllBasePointersAreAllocas &&
10633         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10634          !GEP->hasAllConstantIndices()))
10635       AllBasePointersAreAllocas = false;
10636     
10637     // Compare the operand lists.
10638     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10639       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10640         continue;
10641       
10642       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10643       // if one of the PHIs has a constant for the index.  The index may be
10644       // substantially cheaper to compute for the constants, so making it a
10645       // variable index could pessimize the path.  This also handles the case
10646       // for struct indices, which must always be constant.
10647       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10648           isa<ConstantInt>(GEP->getOperand(op)))
10649         return 0;
10650       
10651       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10652         return 0;
10653       FixedOperands[op] = 0;  // Needs a PHI.
10654     }
10655   }
10656   
10657   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10658   // bother doing this transformation.  At best, this will just save a bit of
10659   // offset calculation, but all the predecessors will have to materialize the
10660   // stack address into a register anyway.  We'd actually rather *clone* the
10661   // load up into the predecessors so that we have a load of a gep of an alloca,
10662   // which can usually all be folded into the load.
10663   if (AllBasePointersAreAllocas)
10664     return 0;
10665   
10666   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10667   // that is variable.
10668   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10669   
10670   bool HasAnyPHIs = false;
10671   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10672     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10673     Value *FirstOp = FirstInst->getOperand(i);
10674     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10675                                      FirstOp->getName()+".pn");
10676     InsertNewInstBefore(NewPN, PN);
10677     
10678     NewPN->reserveOperandSpace(e);
10679     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10680     OperandPhis[i] = NewPN;
10681     FixedOperands[i] = NewPN;
10682     HasAnyPHIs = true;
10683   }
10684
10685   
10686   // Add all operands to the new PHIs.
10687   if (HasAnyPHIs) {
10688     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10689       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10690       BasicBlock *InBB = PN.getIncomingBlock(i);
10691       
10692       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10693         if (PHINode *OpPhi = OperandPhis[op])
10694           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10695     }
10696   }
10697   
10698   Value *Base = FixedOperands[0];
10699   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10700                                    FixedOperands.end());
10701 }
10702
10703
10704 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10705 /// sink the load out of the block that defines it.  This means that it must be
10706 /// obvious the value of the load is not changed from the point of the load to
10707 /// the end of the block it is in.
10708 ///
10709 /// Finally, it is safe, but not profitable, to sink a load targetting a
10710 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10711 /// to a register.
10712 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10713   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10714   
10715   for (++BBI; BBI != E; ++BBI)
10716     if (BBI->mayWriteToMemory())
10717       return false;
10718   
10719   // Check for non-address taken alloca.  If not address-taken already, it isn't
10720   // profitable to do this xform.
10721   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10722     bool isAddressTaken = false;
10723     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10724          UI != E; ++UI) {
10725       if (isa<LoadInst>(UI)) continue;
10726       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10727         // If storing TO the alloca, then the address isn't taken.
10728         if (SI->getOperand(1) == AI) continue;
10729       }
10730       isAddressTaken = true;
10731       break;
10732     }
10733     
10734     if (!isAddressTaken && AI->isStaticAlloca())
10735       return false;
10736   }
10737   
10738   // If this load is a load from a GEP with a constant offset from an alloca,
10739   // then we don't want to sink it.  In its present form, it will be
10740   // load [constant stack offset].  Sinking it will cause us to have to
10741   // materialize the stack addresses in each predecessor in a register only to
10742   // do a shared load from register in the successor.
10743   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10744     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10745       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10746         return false;
10747   
10748   return true;
10749 }
10750
10751
10752 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10753 // operator and they all are only used by the PHI, PHI together their
10754 // inputs, and do the operation once, to the result of the PHI.
10755 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10756   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10757
10758   // Scan the instruction, looking for input operations that can be folded away.
10759   // If all input operands to the phi are the same instruction (e.g. a cast from
10760   // the same type or "+42") we can pull the operation through the PHI, reducing
10761   // code size and simplifying code.
10762   Constant *ConstantOp = 0;
10763   const Type *CastSrcTy = 0;
10764   bool isVolatile = false;
10765   if (isa<CastInst>(FirstInst)) {
10766     CastSrcTy = FirstInst->getOperand(0)->getType();
10767   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10768     // Can fold binop, compare or shift here if the RHS is a constant, 
10769     // otherwise call FoldPHIArgBinOpIntoPHI.
10770     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10771     if (ConstantOp == 0)
10772       return FoldPHIArgBinOpIntoPHI(PN);
10773   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10774     isVolatile = LI->isVolatile();
10775     // We can't sink the load if the loaded value could be modified between the
10776     // load and the PHI.
10777     if (LI->getParent() != PN.getIncomingBlock(0) ||
10778         !isSafeAndProfitableToSinkLoad(LI))
10779       return 0;
10780     
10781     // If the PHI is of volatile loads and the load block has multiple
10782     // successors, sinking it would remove a load of the volatile value from
10783     // the path through the other successor.
10784     if (isVolatile &&
10785         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10786       return 0;
10787     
10788   } else if (isa<GetElementPtrInst>(FirstInst)) {
10789     return FoldPHIArgGEPIntoPHI(PN);
10790   } else {
10791     return 0;  // Cannot fold this operation.
10792   }
10793
10794   // Check to see if all arguments are the same operation.
10795   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10796     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10797     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10798     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10799       return 0;
10800     if (CastSrcTy) {
10801       if (I->getOperand(0)->getType() != CastSrcTy)
10802         return 0;  // Cast operation must match.
10803     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10804       // We can't sink the load if the loaded value could be modified between 
10805       // the load and the PHI.
10806       if (LI->isVolatile() != isVolatile ||
10807           LI->getParent() != PN.getIncomingBlock(i) ||
10808           !isSafeAndProfitableToSinkLoad(LI))
10809         return 0;
10810       
10811       // If the PHI is of volatile loads and the load block has multiple
10812       // successors, sinking it would remove a load of the volatile value from
10813       // the path through the other successor.
10814       if (isVolatile &&
10815           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10816         return 0;
10817       
10818     } else if (I->getOperand(1) != ConstantOp) {
10819       return 0;
10820     }
10821   }
10822
10823   // Okay, they are all the same operation.  Create a new PHI node of the
10824   // correct type, and PHI together all of the LHS's of the instructions.
10825   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10826                                    PN.getName()+".in");
10827   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10828
10829   Value *InVal = FirstInst->getOperand(0);
10830   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10831
10832   // Add all operands to the new PHI.
10833   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10834     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10835     if (NewInVal != InVal)
10836       InVal = 0;
10837     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10838   }
10839
10840   Value *PhiVal;
10841   if (InVal) {
10842     // The new PHI unions all of the same values together.  This is really
10843     // common, so we handle it intelligently here for compile-time speed.
10844     PhiVal = InVal;
10845     delete NewPN;
10846   } else {
10847     InsertNewInstBefore(NewPN, PN);
10848     PhiVal = NewPN;
10849   }
10850
10851   // Insert and return the new operation.
10852   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10853     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10854   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10855     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10856   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10857     return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10858                            PhiVal, ConstantOp);
10859   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10860   
10861   // If this was a volatile load that we are merging, make sure to loop through
10862   // and mark all the input loads as non-volatile.  If we don't do this, we will
10863   // insert a new volatile load and the old ones will not be deletable.
10864   if (isVolatile)
10865     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10866       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10867   
10868   return new LoadInst(PhiVal, "", isVolatile);
10869 }
10870
10871 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10872 /// that is dead.
10873 static bool DeadPHICycle(PHINode *PN,
10874                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10875   if (PN->use_empty()) return true;
10876   if (!PN->hasOneUse()) return false;
10877
10878   // Remember this node, and if we find the cycle, return.
10879   if (!PotentiallyDeadPHIs.insert(PN))
10880     return true;
10881   
10882   // Don't scan crazily complex things.
10883   if (PotentiallyDeadPHIs.size() == 16)
10884     return false;
10885
10886   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10887     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10888
10889   return false;
10890 }
10891
10892 /// PHIsEqualValue - Return true if this phi node is always equal to
10893 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10894 ///   z = some value; x = phi (y, z); y = phi (x, z)
10895 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10896                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10897   // See if we already saw this PHI node.
10898   if (!ValueEqualPHIs.insert(PN))
10899     return true;
10900   
10901   // Don't scan crazily complex things.
10902   if (ValueEqualPHIs.size() == 16)
10903     return false;
10904  
10905   // Scan the operands to see if they are either phi nodes or are equal to
10906   // the value.
10907   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10908     Value *Op = PN->getIncomingValue(i);
10909     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10910       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10911         return false;
10912     } else if (Op != NonPhiInVal)
10913       return false;
10914   }
10915   
10916   return true;
10917 }
10918
10919
10920 // PHINode simplification
10921 //
10922 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10923   // If LCSSA is around, don't mess with Phi nodes
10924   if (MustPreserveLCSSA) return 0;
10925   
10926   if (Value *V = PN.hasConstantValue())
10927     return ReplaceInstUsesWith(PN, V);
10928
10929   // If all PHI operands are the same operation, pull them through the PHI,
10930   // reducing code size.
10931   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10932       isa<Instruction>(PN.getIncomingValue(1)) &&
10933       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10934       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10935       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10936       // than themselves more than once.
10937       PN.getIncomingValue(0)->hasOneUse())
10938     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10939       return Result;
10940
10941   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10942   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10943   // PHI)... break the cycle.
10944   if (PN.hasOneUse()) {
10945     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10946     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10947       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10948       PotentiallyDeadPHIs.insert(&PN);
10949       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10950         return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10951     }
10952    
10953     // If this phi has a single use, and if that use just computes a value for
10954     // the next iteration of a loop, delete the phi.  This occurs with unused
10955     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10956     // common case here is good because the only other things that catch this
10957     // are induction variable analysis (sometimes) and ADCE, which is only run
10958     // late.
10959     if (PHIUser->hasOneUse() &&
10960         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10961         PHIUser->use_back() == &PN) {
10962       return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10963     }
10964   }
10965
10966   // We sometimes end up with phi cycles that non-obviously end up being the
10967   // same value, for example:
10968   //   z = some value; x = phi (y, z); y = phi (x, z)
10969   // where the phi nodes don't necessarily need to be in the same block.  Do a
10970   // quick check to see if the PHI node only contains a single non-phi value, if
10971   // so, scan to see if the phi cycle is actually equal to that value.
10972   {
10973     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10974     // Scan for the first non-phi operand.
10975     while (InValNo != NumOperandVals && 
10976            isa<PHINode>(PN.getIncomingValue(InValNo)))
10977       ++InValNo;
10978
10979     if (InValNo != NumOperandVals) {
10980       Value *NonPhiInVal = PN.getOperand(InValNo);
10981       
10982       // Scan the rest of the operands to see if there are any conflicts, if so
10983       // there is no need to recursively scan other phis.
10984       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10985         Value *OpVal = PN.getIncomingValue(InValNo);
10986         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10987           break;
10988       }
10989       
10990       // If we scanned over all operands, then we have one unique value plus
10991       // phi values.  Scan PHI nodes to see if they all merge in each other or
10992       // the value.
10993       if (InValNo == NumOperandVals) {
10994         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10995         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10996           return ReplaceInstUsesWith(PN, NonPhiInVal);
10997       }
10998     }
10999   }
11000   return 0;
11001 }
11002
11003 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
11004                                    Instruction *InsertPoint,
11005                                    InstCombiner *IC) {
11006   unsigned PtrSize = DTy->getScalarSizeInBits();
11007   unsigned VTySize = V->getType()->getScalarSizeInBits();
11008   // We must cast correctly to the pointer type. Ensure that we
11009   // sign extend the integer value if it is smaller as this is
11010   // used for address computation.
11011   Instruction::CastOps opcode = 
11012      (VTySize < PtrSize ? Instruction::SExt :
11013       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
11014   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
11015 }
11016
11017
11018 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11019   Value *PtrOp = GEP.getOperand(0);
11020   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
11021   // If so, eliminate the noop.
11022   if (GEP.getNumOperands() == 1)
11023     return ReplaceInstUsesWith(GEP, PtrOp);
11024
11025   if (isa<UndefValue>(GEP.getOperand(0)))
11026     return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
11027
11028   bool HasZeroPointerIndex = false;
11029   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11030     HasZeroPointerIndex = C->isNullValue();
11031
11032   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11033     return ReplaceInstUsesWith(GEP, PtrOp);
11034
11035   // Eliminate unneeded casts for indices.
11036   bool MadeChange = false;
11037   
11038   gep_type_iterator GTI = gep_type_begin(GEP);
11039   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11040        i != e; ++i, ++GTI) {
11041     if (isa<SequentialType>(*GTI)) {
11042       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
11043         if (CI->getOpcode() == Instruction::ZExt ||
11044             CI->getOpcode() == Instruction::SExt) {
11045           const Type *SrcTy = CI->getOperand(0)->getType();
11046           // We can eliminate a cast from i32 to i64 iff the target 
11047           // is a 32-bit pointer target.
11048           if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
11049             MadeChange = true;
11050             *i = CI->getOperand(0);
11051           }
11052         }
11053       }
11054       // If we are using a wider index than needed for this platform, shrink it
11055       // to what we need.  If narrower, sign-extend it to what we need.
11056       // If the incoming value needs a cast instruction,
11057       // insert it.  This explicit cast can make subsequent optimizations more
11058       // obvious.
11059       Value *Op = *i;
11060       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
11061         if (Constant *C = dyn_cast<Constant>(Op)) {
11062           *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
11063           MadeChange = true;
11064         } else {
11065           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11066                                 GEP);
11067           *i = Op;
11068           MadeChange = true;
11069         }
11070       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11071         if (Constant *C = dyn_cast<Constant>(Op)) {
11072           *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
11073           MadeChange = true;
11074         } else {
11075           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11076                                 GEP);
11077           *i = Op;
11078           MadeChange = true;
11079         }
11080       }
11081     }
11082   }
11083   if (MadeChange) return &GEP;
11084
11085   // Combine Indices - If the source pointer to this getelementptr instruction
11086   // is a getelementptr instruction, combine the indices of the two
11087   // getelementptr instructions into a single instruction.
11088   //
11089   SmallVector<Value*, 8> SrcGEPOperands;
11090   if (User *Src = dyn_castGetElementPtr(PtrOp))
11091     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11092
11093   if (!SrcGEPOperands.empty()) {
11094     // Note that if our source is a gep chain itself that we wait for that
11095     // chain to be resolved before we perform this transformation.  This
11096     // avoids us creating a TON of code in some cases.
11097     //
11098     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11099         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11100       return 0;   // Wait until our source is folded to completion.
11101
11102     SmallVector<Value*, 8> Indices;
11103
11104     // Find out whether the last index in the source GEP is a sequential idx.
11105     bool EndsWithSequential = false;
11106     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11107            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11108       EndsWithSequential = !isa<StructType>(*I);
11109
11110     // Can we combine the two pointer arithmetics offsets?
11111     if (EndsWithSequential) {
11112       // Replace: gep (gep %P, long B), long A, ...
11113       // With:    T = long A+B; gep %P, T, ...
11114       //
11115       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11116       if (SO1 == Context->getNullValue(SO1->getType())) {
11117         Sum = GO1;
11118       } else if (GO1 == Context->getNullValue(GO1->getType())) {
11119         Sum = SO1;
11120       } else {
11121         // If they aren't the same type, convert both to an integer of the
11122         // target's pointer size.
11123         if (SO1->getType() != GO1->getType()) {
11124           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11125             SO1 =
11126                 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
11127           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11128             GO1 =
11129                 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
11130           } else {
11131             unsigned PS = TD->getPointerSizeInBits();
11132             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11133               // Convert GO1 to SO1's type.
11134               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11135
11136             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11137               // Convert SO1 to GO1's type.
11138               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11139             } else {
11140               const Type *PT = TD->getIntPtrType();
11141               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11142               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11143             }
11144           }
11145         }
11146         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11147           Sum = Context->getConstantExprAdd(cast<Constant>(SO1), 
11148                                             cast<Constant>(GO1));
11149         else {
11150           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11151           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11152         }
11153       }
11154
11155       // Recycle the GEP we already have if possible.
11156       if (SrcGEPOperands.size() == 2) {
11157         GEP.setOperand(0, SrcGEPOperands[0]);
11158         GEP.setOperand(1, Sum);
11159         return &GEP;
11160       } else {
11161         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11162                        SrcGEPOperands.end()-1);
11163         Indices.push_back(Sum);
11164         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11165       }
11166     } else if (isa<Constant>(*GEP.idx_begin()) &&
11167                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11168                SrcGEPOperands.size() != 1) {
11169       // Otherwise we can do the fold if the first index of the GEP is a zero
11170       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11171                      SrcGEPOperands.end());
11172       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11173     }
11174
11175     if (!Indices.empty())
11176       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11177                                        Indices.end(), GEP.getName());
11178
11179   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11180     // GEP of global variable.  If all of the indices for this GEP are
11181     // constants, we can promote this to a constexpr instead of an instruction.
11182
11183     // Scan for nonconstants...
11184     SmallVector<Constant*, 8> Indices;
11185     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11186     for (; I != E && isa<Constant>(*I); ++I)
11187       Indices.push_back(cast<Constant>(*I));
11188
11189     if (I == E) {  // If they are all constants...
11190       Constant *CE = Context->getConstantExprGetElementPtr(GV,
11191                                                     &Indices[0],Indices.size());
11192
11193       // Replace all uses of the GEP with the new constexpr...
11194       return ReplaceInstUsesWith(GEP, CE);
11195     }
11196   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11197     if (!isa<PointerType>(X->getType())) {
11198       // Not interesting.  Source pointer must be a cast from pointer.
11199     } else if (HasZeroPointerIndex) {
11200       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11201       // into     : GEP [10 x i8]* X, i32 0, ...
11202       //
11203       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11204       //           into     : GEP i8* X, ...
11205       // 
11206       // This occurs when the program declares an array extern like "int X[];"
11207       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11208       const PointerType *XTy = cast<PointerType>(X->getType());
11209       if (const ArrayType *CATy =
11210           dyn_cast<ArrayType>(CPTy->getElementType())) {
11211         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11212         if (CATy->getElementType() == XTy->getElementType()) {
11213           // -> GEP i8* X, ...
11214           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11215           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11216                                            GEP.getName());
11217         } else if (const ArrayType *XATy =
11218                  dyn_cast<ArrayType>(XTy->getElementType())) {
11219           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11220           if (CATy->getElementType() == XATy->getElementType()) {
11221             // -> GEP [10 x i8]* X, i32 0, ...
11222             // At this point, we know that the cast source type is a pointer
11223             // to an array of the same type as the destination pointer
11224             // array.  Because the array type is never stepped over (there
11225             // is a leading zero) we can fold the cast into this GEP.
11226             GEP.setOperand(0, X);
11227             return &GEP;
11228           }
11229         }
11230       }
11231     } else if (GEP.getNumOperands() == 2) {
11232       // Transform things like:
11233       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11234       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11235       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11236       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11237       if (isa<ArrayType>(SrcElTy) &&
11238           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11239           TD->getTypeAllocSize(ResElTy)) {
11240         Value *Idx[2];
11241         Idx[0] = Context->getNullValue(Type::Int32Ty);
11242         Idx[1] = GEP.getOperand(1);
11243         Value *V = InsertNewInstBefore(
11244                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11245         // V and GEP are both pointer types --> BitCast
11246         return new BitCastInst(V, GEP.getType());
11247       }
11248       
11249       // Transform things like:
11250       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11251       //   (where tmp = 8*tmp2) into:
11252       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11253       
11254       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11255         uint64_t ArrayEltSize =
11256             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11257         
11258         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11259         // allow either a mul, shift, or constant here.
11260         Value *NewIdx = 0;
11261         ConstantInt *Scale = 0;
11262         if (ArrayEltSize == 1) {
11263           NewIdx = GEP.getOperand(1);
11264           Scale = 
11265                Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
11266         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11267           NewIdx = Context->getConstantInt(CI->getType(), 1);
11268           Scale = CI;
11269         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11270           if (Inst->getOpcode() == Instruction::Shl &&
11271               isa<ConstantInt>(Inst->getOperand(1))) {
11272             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11273             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11274             Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
11275                                      1ULL << ShAmtVal);
11276             NewIdx = Inst->getOperand(0);
11277           } else if (Inst->getOpcode() == Instruction::Mul &&
11278                      isa<ConstantInt>(Inst->getOperand(1))) {
11279             Scale = cast<ConstantInt>(Inst->getOperand(1));
11280             NewIdx = Inst->getOperand(0);
11281           }
11282         }
11283         
11284         // If the index will be to exactly the right offset with the scale taken
11285         // out, perform the transformation. Note, we don't know whether Scale is
11286         // signed or not. We'll use unsigned version of division/modulo
11287         // operation after making sure Scale doesn't have the sign bit set.
11288         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11289             Scale->getZExtValue() % ArrayEltSize == 0) {
11290           Scale = Context->getConstantInt(Scale->getType(),
11291                                    Scale->getZExtValue() / ArrayEltSize);
11292           if (Scale->getZExtValue() != 1) {
11293             Constant *C =
11294                    Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
11295                                                        false /*ZExt*/);
11296             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11297             NewIdx = InsertNewInstBefore(Sc, GEP);
11298           }
11299
11300           // Insert the new GEP instruction.
11301           Value *Idx[2];
11302           Idx[0] = Context->getNullValue(Type::Int32Ty);
11303           Idx[1] = NewIdx;
11304           Instruction *NewGEP =
11305             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11306           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11307           // The NewGEP must be pointer typed, so must the old one -> BitCast
11308           return new BitCastInst(NewGEP, GEP.getType());
11309         }
11310       }
11311     }
11312   }
11313   
11314   /// See if we can simplify:
11315   ///   X = bitcast A to B*
11316   ///   Y = gep X, <...constant indices...>
11317   /// into a gep of the original struct.  This is important for SROA and alias
11318   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11319   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11320     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11321       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11322       // a constant back from EmitGEPOffset.
11323       ConstantInt *OffsetV =
11324                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11325       int64_t Offset = OffsetV->getSExtValue();
11326       
11327       // If this GEP instruction doesn't move the pointer, just replace the GEP
11328       // with a bitcast of the real input to the dest type.
11329       if (Offset == 0) {
11330         // If the bitcast is of an allocation, and the allocation will be
11331         // converted to match the type of the cast, don't touch this.
11332         if (isa<AllocationInst>(BCI->getOperand(0))) {
11333           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11334           if (Instruction *I = visitBitCast(*BCI)) {
11335             if (I != BCI) {
11336               I->takeName(BCI);
11337               BCI->getParent()->getInstList().insert(BCI, I);
11338               ReplaceInstUsesWith(*BCI, I);
11339             }
11340             return &GEP;
11341           }
11342         }
11343         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11344       }
11345       
11346       // Otherwise, if the offset is non-zero, we need to find out if there is a
11347       // field at Offset in 'A's type.  If so, we can pull the cast through the
11348       // GEP.
11349       SmallVector<Value*, 8> NewIndices;
11350       const Type *InTy =
11351         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11352       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11353         Instruction *NGEP =
11354            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11355                                      NewIndices.end());
11356         if (NGEP->getType() == GEP.getType()) return NGEP;
11357         InsertNewInstBefore(NGEP, GEP);
11358         NGEP->takeName(&GEP);
11359         return new BitCastInst(NGEP, GEP.getType());
11360       }
11361     }
11362   }    
11363     
11364   return 0;
11365 }
11366
11367 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11368   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11369   if (AI.isArrayAllocation()) {  // Check C != 1
11370     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11371       const Type *NewTy = 
11372         Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
11373       AllocationInst *New = 0;
11374
11375       // Create and insert the replacement instruction...
11376       if (isa<MallocInst>(AI))
11377         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11378       else {
11379         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11380         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11381       }
11382
11383       InsertNewInstBefore(New, AI);
11384
11385       // Scan to the end of the allocation instructions, to skip over a block of
11386       // allocas if possible...also skip interleaved debug info
11387       //
11388       BasicBlock::iterator It = New;
11389       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11390
11391       // Now that I is pointing to the first non-allocation-inst in the block,
11392       // insert our getelementptr instruction...
11393       //
11394       Value *NullIdx = Context->getNullValue(Type::Int32Ty);
11395       Value *Idx[2];
11396       Idx[0] = NullIdx;
11397       Idx[1] = NullIdx;
11398       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11399                                            New->getName()+".sub", It);
11400
11401       // Now make everything use the getelementptr instead of the original
11402       // allocation.
11403       return ReplaceInstUsesWith(AI, V);
11404     } else if (isa<UndefValue>(AI.getArraySize())) {
11405       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11406     }
11407   }
11408
11409   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11410     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11411     // Note that we only do this for alloca's, because malloc should allocate
11412     // and return a unique pointer, even for a zero byte allocation.
11413     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11414       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11415
11416     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11417     if (AI.getAlignment() == 0)
11418       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11419   }
11420
11421   return 0;
11422 }
11423
11424 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11425   Value *Op = FI.getOperand(0);
11426
11427   // free undef -> unreachable.
11428   if (isa<UndefValue>(Op)) {
11429     // Insert a new store to null because we cannot modify the CFG here.
11430     new StoreInst(Context->getConstantIntTrue(),
11431            Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
11432     return EraseInstFromFunction(FI);
11433   }
11434   
11435   // If we have 'free null' delete the instruction.  This can happen in stl code
11436   // when lots of inlining happens.
11437   if (isa<ConstantPointerNull>(Op))
11438     return EraseInstFromFunction(FI);
11439   
11440   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11441   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11442     FI.setOperand(0, CI->getOperand(0));
11443     return &FI;
11444   }
11445   
11446   // Change free (gep X, 0,0,0,0) into free(X)
11447   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11448     if (GEPI->hasAllZeroIndices()) {
11449       AddToWorkList(GEPI);
11450       FI.setOperand(0, GEPI->getOperand(0));
11451       return &FI;
11452     }
11453   }
11454   
11455   // Change free(malloc) into nothing, if the malloc has a single use.
11456   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11457     if (MI->hasOneUse()) {
11458       EraseInstFromFunction(FI);
11459       return EraseInstFromFunction(*MI);
11460     }
11461
11462   return 0;
11463 }
11464
11465
11466 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11467 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11468                                         const TargetData *TD) {
11469   User *CI = cast<User>(LI.getOperand(0));
11470   Value *CastOp = CI->getOperand(0);
11471   LLVMContext *Context = IC.getContext();
11472
11473   if (TD) {
11474     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11475       // Instead of loading constant c string, use corresponding integer value
11476       // directly if string length is small enough.
11477       std::string Str;
11478       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11479         unsigned len = Str.length();
11480         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11481         unsigned numBits = Ty->getPrimitiveSizeInBits();
11482         // Replace LI with immediate integer store.
11483         if ((numBits >> 3) == len + 1) {
11484           APInt StrVal(numBits, 0);
11485           APInt SingleChar(numBits, 0);
11486           if (TD->isLittleEndian()) {
11487             for (signed i = len-1; i >= 0; i--) {
11488               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11489               StrVal = (StrVal << 8) | SingleChar;
11490             }
11491           } else {
11492             for (unsigned i = 0; i < len; i++) {
11493               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11494               StrVal = (StrVal << 8) | SingleChar;
11495             }
11496             // Append NULL at the end.
11497             SingleChar = 0;
11498             StrVal = (StrVal << 8) | SingleChar;
11499           }
11500           Value *NL = Context->getConstantInt(StrVal);
11501           return IC.ReplaceInstUsesWith(LI, NL);
11502         }
11503       }
11504     }
11505   }
11506
11507   const PointerType *DestTy = cast<PointerType>(CI->getType());
11508   const Type *DestPTy = DestTy->getElementType();
11509   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11510
11511     // If the address spaces don't match, don't eliminate the cast.
11512     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11513       return 0;
11514
11515     const Type *SrcPTy = SrcTy->getElementType();
11516
11517     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11518          isa<VectorType>(DestPTy)) {
11519       // If the source is an array, the code below will not succeed.  Check to
11520       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11521       // constants.
11522       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11523         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11524           if (ASrcTy->getNumElements() != 0) {
11525             Value *Idxs[2];
11526             Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11527             CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
11528             SrcTy = cast<PointerType>(CastOp->getType());
11529             SrcPTy = SrcTy->getElementType();
11530           }
11531
11532       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11533             isa<VectorType>(SrcPTy)) &&
11534           // Do not allow turning this into a load of an integer, which is then
11535           // casted to a pointer, this pessimizes pointer analysis a lot.
11536           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11537           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11538                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11539
11540         // Okay, we are casting from one integer or pointer type to another of
11541         // the same size.  Instead of casting the pointer before the load, cast
11542         // the result of the loaded value.
11543         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11544                                                              CI->getName(),
11545                                                          LI.isVolatile()),LI);
11546         // Now cast the result of the load.
11547         return new BitCastInst(NewLoad, LI.getType());
11548       }
11549     }
11550   }
11551   return 0;
11552 }
11553
11554 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11555   Value *Op = LI.getOperand(0);
11556
11557   // Attempt to improve the alignment.
11558   unsigned KnownAlign =
11559     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11560   if (KnownAlign >
11561       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11562                                 LI.getAlignment()))
11563     LI.setAlignment(KnownAlign);
11564
11565   // load (cast X) --> cast (load X) iff safe
11566   if (isa<CastInst>(Op))
11567     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11568       return Res;
11569
11570   // None of the following transforms are legal for volatile loads.
11571   if (LI.isVolatile()) return 0;
11572   
11573   // Do really simple store-to-load forwarding and load CSE, to catch cases
11574   // where there are several consequtive memory accesses to the same location,
11575   // separated by a few arithmetic operations.
11576   BasicBlock::iterator BBI = &LI;
11577   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11578     return ReplaceInstUsesWith(LI, AvailableVal);
11579
11580   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11581     const Value *GEPI0 = GEPI->getOperand(0);
11582     // TODO: Consider a target hook for valid address spaces for this xform.
11583     if (isa<ConstantPointerNull>(GEPI0) &&
11584         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11585       // Insert a new store to null instruction before the load to indicate
11586       // that this code is not reachable.  We do this instead of inserting
11587       // an unreachable instruction directly because we cannot modify the
11588       // CFG.
11589       new StoreInst(Context->getUndef(LI.getType()),
11590                     Context->getNullValue(Op->getType()), &LI);
11591       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11592     }
11593   } 
11594
11595   if (Constant *C = dyn_cast<Constant>(Op)) {
11596     // load null/undef -> undef
11597     // TODO: Consider a target hook for valid address spaces for this xform.
11598     if (isa<UndefValue>(C) || (C->isNullValue() && 
11599         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11600       // Insert a new store to null instruction before the load to indicate that
11601       // this code is not reachable.  We do this instead of inserting an
11602       // unreachable instruction directly because we cannot modify the CFG.
11603       new StoreInst(Context->getUndef(LI.getType()),
11604                     Context->getNullValue(Op->getType()), &LI);
11605       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11606     }
11607
11608     // Instcombine load (constant global) into the value loaded.
11609     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11610       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11611         return ReplaceInstUsesWith(LI, GV->getInitializer());
11612
11613     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11614     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11615       if (CE->getOpcode() == Instruction::GetElementPtr) {
11616         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11617           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11618             if (Constant *V = 
11619                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11620                                                       Context))
11621               return ReplaceInstUsesWith(LI, V);
11622         if (CE->getOperand(0)->isNullValue()) {
11623           // Insert a new store to null instruction before the load to indicate
11624           // that this code is not reachable.  We do this instead of inserting
11625           // an unreachable instruction directly because we cannot modify the
11626           // CFG.
11627           new StoreInst(Context->getUndef(LI.getType()),
11628                         Context->getNullValue(Op->getType()), &LI);
11629           return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11630         }
11631
11632       } else if (CE->isCast()) {
11633         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11634           return Res;
11635       }
11636     }
11637   }
11638     
11639   // If this load comes from anywhere in a constant global, and if the global
11640   // is all undef or zero, we know what it loads.
11641   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11642     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11643       if (GV->getInitializer()->isNullValue())
11644         return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
11645       else if (isa<UndefValue>(GV->getInitializer()))
11646         return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11647     }
11648   }
11649
11650   if (Op->hasOneUse()) {
11651     // Change select and PHI nodes to select values instead of addresses: this
11652     // helps alias analysis out a lot, allows many others simplifications, and
11653     // exposes redundancy in the code.
11654     //
11655     // Note that we cannot do the transformation unless we know that the
11656     // introduced loads cannot trap!  Something like this is valid as long as
11657     // the condition is always false: load (select bool %C, int* null, int* %G),
11658     // but it would not be valid if we transformed it to load from null
11659     // unconditionally.
11660     //
11661     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11662       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11663       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11664           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11665         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11666                                      SI->getOperand(1)->getName()+".val"), LI);
11667         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11668                                      SI->getOperand(2)->getName()+".val"), LI);
11669         return SelectInst::Create(SI->getCondition(), V1, V2);
11670       }
11671
11672       // load (select (cond, null, P)) -> load P
11673       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11674         if (C->isNullValue()) {
11675           LI.setOperand(0, SI->getOperand(2));
11676           return &LI;
11677         }
11678
11679       // load (select (cond, P, null)) -> load P
11680       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11681         if (C->isNullValue()) {
11682           LI.setOperand(0, SI->getOperand(1));
11683           return &LI;
11684         }
11685     }
11686   }
11687   return 0;
11688 }
11689
11690 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11691 /// when possible.  This makes it generally easy to do alias analysis and/or
11692 /// SROA/mem2reg of the memory object.
11693 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11694   User *CI = cast<User>(SI.getOperand(1));
11695   Value *CastOp = CI->getOperand(0);
11696   LLVMContext *Context = IC.getContext();
11697
11698   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11699   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11700   if (SrcTy == 0) return 0;
11701   
11702   const Type *SrcPTy = SrcTy->getElementType();
11703
11704   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11705     return 0;
11706   
11707   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11708   /// to its first element.  This allows us to handle things like:
11709   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11710   /// on 32-bit hosts.
11711   SmallVector<Value*, 4> NewGEPIndices;
11712   
11713   // If the source is an array, the code below will not succeed.  Check to
11714   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11715   // constants.
11716   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11717     // Index through pointer.
11718     Constant *Zero = Context->getNullValue(Type::Int32Ty);
11719     NewGEPIndices.push_back(Zero);
11720     
11721     while (1) {
11722       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11723         if (!STy->getNumElements()) /* Struct can be empty {} */
11724           break;
11725         NewGEPIndices.push_back(Zero);
11726         SrcPTy = STy->getElementType(0);
11727       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11728         NewGEPIndices.push_back(Zero);
11729         SrcPTy = ATy->getElementType();
11730       } else {
11731         break;
11732       }
11733     }
11734     
11735     SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
11736   }
11737
11738   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11739     return 0;
11740   
11741   // If the pointers point into different address spaces or if they point to
11742   // values with different sizes, we can't do the transformation.
11743   if (SrcTy->getAddressSpace() != 
11744         cast<PointerType>(CI->getType())->getAddressSpace() ||
11745       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11746       IC.getTargetData().getTypeSizeInBits(DestPTy))
11747     return 0;
11748
11749   // Okay, we are casting from one integer or pointer type to another of
11750   // the same size.  Instead of casting the pointer before 
11751   // the store, cast the value to be stored.
11752   Value *NewCast;
11753   Value *SIOp0 = SI.getOperand(0);
11754   Instruction::CastOps opcode = Instruction::BitCast;
11755   const Type* CastSrcTy = SIOp0->getType();
11756   const Type* CastDstTy = SrcPTy;
11757   if (isa<PointerType>(CastDstTy)) {
11758     if (CastSrcTy->isInteger())
11759       opcode = Instruction::IntToPtr;
11760   } else if (isa<IntegerType>(CastDstTy)) {
11761     if (isa<PointerType>(SIOp0->getType()))
11762       opcode = Instruction::PtrToInt;
11763   }
11764   
11765   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11766   // emit a GEP to index into its first field.
11767   if (!NewGEPIndices.empty()) {
11768     if (Constant *C = dyn_cast<Constant>(CastOp))
11769       CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0], 
11770                                               NewGEPIndices.size());
11771     else
11772       CastOp = IC.InsertNewInstBefore(
11773               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11774                                         NewGEPIndices.end()), SI);
11775   }
11776   
11777   if (Constant *C = dyn_cast<Constant>(SIOp0))
11778     NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
11779   else
11780     NewCast = IC.InsertNewInstBefore(
11781       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11782       SI);
11783   return new StoreInst(NewCast, CastOp);
11784 }
11785
11786 /// equivalentAddressValues - Test if A and B will obviously have the same
11787 /// value. This includes recognizing that %t0 and %t1 will have the same
11788 /// value in code like this:
11789 ///   %t0 = getelementptr \@a, 0, 3
11790 ///   store i32 0, i32* %t0
11791 ///   %t1 = getelementptr \@a, 0, 3
11792 ///   %t2 = load i32* %t1
11793 ///
11794 static bool equivalentAddressValues(Value *A, Value *B) {
11795   // Test if the values are trivially equivalent.
11796   if (A == B) return true;
11797   
11798   // Test if the values come form identical arithmetic instructions.
11799   if (isa<BinaryOperator>(A) ||
11800       isa<CastInst>(A) ||
11801       isa<PHINode>(A) ||
11802       isa<GetElementPtrInst>(A))
11803     if (Instruction *BI = dyn_cast<Instruction>(B))
11804       if (cast<Instruction>(A)->isIdenticalTo(BI))
11805         return true;
11806   
11807   // Otherwise they may not be equivalent.
11808   return false;
11809 }
11810
11811 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11812 // return the llvm.dbg.declare.
11813 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11814   if (!V->hasNUses(2))
11815     return 0;
11816   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11817        UI != E; ++UI) {
11818     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11819       return DI;
11820     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11821       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11822         return DI;
11823       }
11824   }
11825   return 0;
11826 }
11827
11828 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11829   Value *Val = SI.getOperand(0);
11830   Value *Ptr = SI.getOperand(1);
11831
11832   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11833     EraseInstFromFunction(SI);
11834     ++NumCombined;
11835     return 0;
11836   }
11837   
11838   // If the RHS is an alloca with a single use, zapify the store, making the
11839   // alloca dead.
11840   // If the RHS is an alloca with a two uses, the other one being a 
11841   // llvm.dbg.declare, zapify the store and the declare, making the
11842   // alloca dead.  We must do this to prevent declare's from affecting
11843   // codegen.
11844   if (!SI.isVolatile()) {
11845     if (Ptr->hasOneUse()) {
11846       if (isa<AllocaInst>(Ptr)) {
11847         EraseInstFromFunction(SI);
11848         ++NumCombined;
11849         return 0;
11850       }
11851       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11852         if (isa<AllocaInst>(GEP->getOperand(0))) {
11853           if (GEP->getOperand(0)->hasOneUse()) {
11854             EraseInstFromFunction(SI);
11855             ++NumCombined;
11856             return 0;
11857           }
11858           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11859             EraseInstFromFunction(*DI);
11860             EraseInstFromFunction(SI);
11861             ++NumCombined;
11862             return 0;
11863           }
11864         }
11865       }
11866     }
11867     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11868       EraseInstFromFunction(*DI);
11869       EraseInstFromFunction(SI);
11870       ++NumCombined;
11871       return 0;
11872     }
11873   }
11874
11875   // Attempt to improve the alignment.
11876   unsigned KnownAlign =
11877     GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11878   if (KnownAlign >
11879       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11880                                 SI.getAlignment()))
11881     SI.setAlignment(KnownAlign);
11882
11883   // Do really simple DSE, to catch cases where there are several consecutive
11884   // stores to the same location, separated by a few arithmetic operations. This
11885   // situation often occurs with bitfield accesses.
11886   BasicBlock::iterator BBI = &SI;
11887   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11888        --ScanInsts) {
11889     --BBI;
11890     // Don't count debug info directives, lest they affect codegen,
11891     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11892     // It is necessary for correctness to skip those that feed into a
11893     // llvm.dbg.declare, as these are not present when debugging is off.
11894     if (isa<DbgInfoIntrinsic>(BBI) ||
11895         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11896       ScanInsts++;
11897       continue;
11898     }    
11899     
11900     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11901       // Prev store isn't volatile, and stores to the same location?
11902       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11903                                                           SI.getOperand(1))) {
11904         ++NumDeadStore;
11905         ++BBI;
11906         EraseInstFromFunction(*PrevSI);
11907         continue;
11908       }
11909       break;
11910     }
11911     
11912     // If this is a load, we have to stop.  However, if the loaded value is from
11913     // the pointer we're loading and is producing the pointer we're storing,
11914     // then *this* store is dead (X = load P; store X -> P).
11915     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11916       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11917           !SI.isVolatile()) {
11918         EraseInstFromFunction(SI);
11919         ++NumCombined;
11920         return 0;
11921       }
11922       // Otherwise, this is a load from some other location.  Stores before it
11923       // may not be dead.
11924       break;
11925     }
11926     
11927     // Don't skip over loads or things that can modify memory.
11928     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11929       break;
11930   }
11931   
11932   
11933   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11934
11935   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11936   if (isa<ConstantPointerNull>(Ptr) &&
11937       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11938     if (!isa<UndefValue>(Val)) {
11939       SI.setOperand(0, Context->getUndef(Val->getType()));
11940       if (Instruction *U = dyn_cast<Instruction>(Val))
11941         AddToWorkList(U);  // Dropped a use.
11942       ++NumCombined;
11943     }
11944     return 0;  // Do not modify these!
11945   }
11946
11947   // store undef, Ptr -> noop
11948   if (isa<UndefValue>(Val)) {
11949     EraseInstFromFunction(SI);
11950     ++NumCombined;
11951     return 0;
11952   }
11953
11954   // If the pointer destination is a cast, see if we can fold the cast into the
11955   // source instead.
11956   if (isa<CastInst>(Ptr))
11957     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11958       return Res;
11959   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11960     if (CE->isCast())
11961       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11962         return Res;
11963
11964   
11965   // If this store is the last instruction in the basic block (possibly
11966   // excepting debug info instructions and the pointer bitcasts that feed
11967   // into them), and if the block ends with an unconditional branch, try
11968   // to move it to the successor block.
11969   BBI = &SI; 
11970   do {
11971     ++BBI;
11972   } while (isa<DbgInfoIntrinsic>(BBI) ||
11973            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11974   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11975     if (BI->isUnconditional())
11976       if (SimplifyStoreAtEndOfBlock(SI))
11977         return 0;  // xform done!
11978   
11979   return 0;
11980 }
11981
11982 /// SimplifyStoreAtEndOfBlock - Turn things like:
11983 ///   if () { *P = v1; } else { *P = v2 }
11984 /// into a phi node with a store in the successor.
11985 ///
11986 /// Simplify things like:
11987 ///   *P = v1; if () { *P = v2; }
11988 /// into a phi node with a store in the successor.
11989 ///
11990 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11991   BasicBlock *StoreBB = SI.getParent();
11992   
11993   // Check to see if the successor block has exactly two incoming edges.  If
11994   // so, see if the other predecessor contains a store to the same location.
11995   // if so, insert a PHI node (if needed) and move the stores down.
11996   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11997   
11998   // Determine whether Dest has exactly two predecessors and, if so, compute
11999   // the other predecessor.
12000   pred_iterator PI = pred_begin(DestBB);
12001   BasicBlock *OtherBB = 0;
12002   if (*PI != StoreBB)
12003     OtherBB = *PI;
12004   ++PI;
12005   if (PI == pred_end(DestBB))
12006     return false;
12007   
12008   if (*PI != StoreBB) {
12009     if (OtherBB)
12010       return false;
12011     OtherBB = *PI;
12012   }
12013   if (++PI != pred_end(DestBB))
12014     return false;
12015
12016   // Bail out if all the relevant blocks aren't distinct (this can happen,
12017   // for example, if SI is in an infinite loop)
12018   if (StoreBB == DestBB || OtherBB == DestBB)
12019     return false;
12020
12021   // Verify that the other block ends in a branch and is not otherwise empty.
12022   BasicBlock::iterator BBI = OtherBB->getTerminator();
12023   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12024   if (!OtherBr || BBI == OtherBB->begin())
12025     return false;
12026   
12027   // If the other block ends in an unconditional branch, check for the 'if then
12028   // else' case.  there is an instruction before the branch.
12029   StoreInst *OtherStore = 0;
12030   if (OtherBr->isUnconditional()) {
12031     --BBI;
12032     // Skip over debugging info.
12033     while (isa<DbgInfoIntrinsic>(BBI) ||
12034            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12035       if (BBI==OtherBB->begin())
12036         return false;
12037       --BBI;
12038     }
12039     // If this isn't a store, or isn't a store to the same location, bail out.
12040     OtherStore = dyn_cast<StoreInst>(BBI);
12041     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12042       return false;
12043   } else {
12044     // Otherwise, the other block ended with a conditional branch. If one of the
12045     // destinations is StoreBB, then we have the if/then case.
12046     if (OtherBr->getSuccessor(0) != StoreBB && 
12047         OtherBr->getSuccessor(1) != StoreBB)
12048       return false;
12049     
12050     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12051     // if/then triangle.  See if there is a store to the same ptr as SI that
12052     // lives in OtherBB.
12053     for (;; --BBI) {
12054       // Check to see if we find the matching store.
12055       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12056         if (OtherStore->getOperand(1) != SI.getOperand(1))
12057           return false;
12058         break;
12059       }
12060       // If we find something that may be using or overwriting the stored
12061       // value, or if we run out of instructions, we can't do the xform.
12062       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12063           BBI == OtherBB->begin())
12064         return false;
12065     }
12066     
12067     // In order to eliminate the store in OtherBr, we have to
12068     // make sure nothing reads or overwrites the stored value in
12069     // StoreBB.
12070     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12071       // FIXME: This should really be AA driven.
12072       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12073         return false;
12074     }
12075   }
12076   
12077   // Insert a PHI node now if we need it.
12078   Value *MergedVal = OtherStore->getOperand(0);
12079   if (MergedVal != SI.getOperand(0)) {
12080     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12081     PN->reserveOperandSpace(2);
12082     PN->addIncoming(SI.getOperand(0), SI.getParent());
12083     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12084     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12085   }
12086   
12087   // Advance to a place where it is safe to insert the new store and
12088   // insert it.
12089   BBI = DestBB->getFirstNonPHI();
12090   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12091                                     OtherStore->isVolatile()), *BBI);
12092   
12093   // Nuke the old stores.
12094   EraseInstFromFunction(SI);
12095   EraseInstFromFunction(*OtherStore);
12096   ++NumCombined;
12097   return true;
12098 }
12099
12100
12101 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12102   // Change br (not X), label True, label False to: br X, label False, True
12103   Value *X = 0;
12104   BasicBlock *TrueDest;
12105   BasicBlock *FalseDest;
12106   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
12107       !isa<Constant>(X)) {
12108     // Swap Destinations and condition...
12109     BI.setCondition(X);
12110     BI.setSuccessor(0, FalseDest);
12111     BI.setSuccessor(1, TrueDest);
12112     return &BI;
12113   }
12114
12115   // Cannonicalize fcmp_one -> fcmp_oeq
12116   FCmpInst::Predicate FPred; Value *Y;
12117   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12118                              TrueDest, FalseDest), *Context))
12119     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12120          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12121       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12122       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12123       Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12124       NewSCC->takeName(I);
12125       // Swap Destinations and condition...
12126       BI.setCondition(NewSCC);
12127       BI.setSuccessor(0, FalseDest);
12128       BI.setSuccessor(1, TrueDest);
12129       RemoveFromWorkList(I);
12130       I->eraseFromParent();
12131       AddToWorkList(NewSCC);
12132       return &BI;
12133     }
12134
12135   // Cannonicalize icmp_ne -> icmp_eq
12136   ICmpInst::Predicate IPred;
12137   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12138                       TrueDest, FalseDest), *Context))
12139     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12140          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12141          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12142       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12143       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12144       Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12145       NewSCC->takeName(I);
12146       // Swap Destinations and condition...
12147       BI.setCondition(NewSCC);
12148       BI.setSuccessor(0, FalseDest);
12149       BI.setSuccessor(1, TrueDest);
12150       RemoveFromWorkList(I);
12151       I->eraseFromParent();;
12152       AddToWorkList(NewSCC);
12153       return &BI;
12154     }
12155
12156   return 0;
12157 }
12158
12159 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12160   Value *Cond = SI.getCondition();
12161   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12162     if (I->getOpcode() == Instruction::Add)
12163       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12164         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12165         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12166           SI.setOperand(i,
12167                    Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
12168                                                 AddRHS));
12169         SI.setOperand(0, I->getOperand(0));
12170         AddToWorkList(I);
12171         return &SI;
12172       }
12173   }
12174   return 0;
12175 }
12176
12177 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12178   Value *Agg = EV.getAggregateOperand();
12179
12180   if (!EV.hasIndices())
12181     return ReplaceInstUsesWith(EV, Agg);
12182
12183   if (Constant *C = dyn_cast<Constant>(Agg)) {
12184     if (isa<UndefValue>(C))
12185       return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
12186       
12187     if (isa<ConstantAggregateZero>(C))
12188       return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
12189
12190     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12191       // Extract the element indexed by the first index out of the constant
12192       Value *V = C->getOperand(*EV.idx_begin());
12193       if (EV.getNumIndices() > 1)
12194         // Extract the remaining indices out of the constant indexed by the
12195         // first index
12196         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12197       else
12198         return ReplaceInstUsesWith(EV, V);
12199     }
12200     return 0; // Can't handle other constants
12201   } 
12202   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12203     // We're extracting from an insertvalue instruction, compare the indices
12204     const unsigned *exti, *exte, *insi, *inse;
12205     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12206          exte = EV.idx_end(), inse = IV->idx_end();
12207          exti != exte && insi != inse;
12208          ++exti, ++insi) {
12209       if (*insi != *exti)
12210         // The insert and extract both reference distinctly different elements.
12211         // This means the extract is not influenced by the insert, and we can
12212         // replace the aggregate operand of the extract with the aggregate
12213         // operand of the insert. i.e., replace
12214         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12215         // %E = extractvalue { i32, { i32 } } %I, 0
12216         // with
12217         // %E = extractvalue { i32, { i32 } } %A, 0
12218         return ExtractValueInst::Create(IV->getAggregateOperand(),
12219                                         EV.idx_begin(), EV.idx_end());
12220     }
12221     if (exti == exte && insi == inse)
12222       // Both iterators are at the end: Index lists are identical. Replace
12223       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12224       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12225       // with "i32 42"
12226       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12227     if (exti == exte) {
12228       // The extract list is a prefix of the insert list. i.e. replace
12229       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12230       // %E = extractvalue { i32, { i32 } } %I, 1
12231       // with
12232       // %X = extractvalue { i32, { i32 } } %A, 1
12233       // %E = insertvalue { i32 } %X, i32 42, 0
12234       // by switching the order of the insert and extract (though the
12235       // insertvalue should be left in, since it may have other uses).
12236       Value *NewEV = InsertNewInstBefore(
12237         ExtractValueInst::Create(IV->getAggregateOperand(),
12238                                  EV.idx_begin(), EV.idx_end()),
12239         EV);
12240       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12241                                      insi, inse);
12242     }
12243     if (insi == inse)
12244       // The insert list is a prefix of the extract list
12245       // We can simply remove the common indices from the extract and make it
12246       // operate on the inserted value instead of the insertvalue result.
12247       // i.e., replace
12248       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12249       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12250       // with
12251       // %E extractvalue { i32 } { i32 42 }, 0
12252       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12253                                       exti, exte);
12254   }
12255   // Can't simplify extracts from other values. Note that nested extracts are
12256   // already simplified implicitely by the above (extract ( extract (insert) )
12257   // will be translated into extract ( insert ( extract ) ) first and then just
12258   // the value inserted, if appropriate).
12259   return 0;
12260 }
12261
12262 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12263 /// is to leave as a vector operation.
12264 static bool CheapToScalarize(Value *V, bool isConstant) {
12265   if (isa<ConstantAggregateZero>(V)) 
12266     return true;
12267   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12268     if (isConstant) return true;
12269     // If all elts are the same, we can extract.
12270     Constant *Op0 = C->getOperand(0);
12271     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12272       if (C->getOperand(i) != Op0)
12273         return false;
12274     return true;
12275   }
12276   Instruction *I = dyn_cast<Instruction>(V);
12277   if (!I) return false;
12278   
12279   // Insert element gets simplified to the inserted element or is deleted if
12280   // this is constant idx extract element and its a constant idx insertelt.
12281   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12282       isa<ConstantInt>(I->getOperand(2)))
12283     return true;
12284   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12285     return true;
12286   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12287     if (BO->hasOneUse() &&
12288         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12289          CheapToScalarize(BO->getOperand(1), isConstant)))
12290       return true;
12291   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12292     if (CI->hasOneUse() &&
12293         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12294          CheapToScalarize(CI->getOperand(1), isConstant)))
12295       return true;
12296   
12297   return false;
12298 }
12299
12300 /// Read and decode a shufflevector mask.
12301 ///
12302 /// It turns undef elements into values that are larger than the number of
12303 /// elements in the input.
12304 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12305   unsigned NElts = SVI->getType()->getNumElements();
12306   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12307     return std::vector<unsigned>(NElts, 0);
12308   if (isa<UndefValue>(SVI->getOperand(2)))
12309     return std::vector<unsigned>(NElts, 2*NElts);
12310
12311   std::vector<unsigned> Result;
12312   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12313   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12314     if (isa<UndefValue>(*i))
12315       Result.push_back(NElts*2);  // undef -> 8
12316     else
12317       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12318   return Result;
12319 }
12320
12321 /// FindScalarElement - Given a vector and an element number, see if the scalar
12322 /// value is already around as a register, for example if it were inserted then
12323 /// extracted from the vector.
12324 static Value *FindScalarElement(Value *V, unsigned EltNo,
12325                                 LLVMContext *Context) {
12326   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12327   const VectorType *PTy = cast<VectorType>(V->getType());
12328   unsigned Width = PTy->getNumElements();
12329   if (EltNo >= Width)  // Out of range access.
12330     return Context->getUndef(PTy->getElementType());
12331   
12332   if (isa<UndefValue>(V))
12333     return Context->getUndef(PTy->getElementType());
12334   else if (isa<ConstantAggregateZero>(V))
12335     return Context->getNullValue(PTy->getElementType());
12336   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12337     return CP->getOperand(EltNo);
12338   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12339     // If this is an insert to a variable element, we don't know what it is.
12340     if (!isa<ConstantInt>(III->getOperand(2))) 
12341       return 0;
12342     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12343     
12344     // If this is an insert to the element we are looking for, return the
12345     // inserted value.
12346     if (EltNo == IIElt) 
12347       return III->getOperand(1);
12348     
12349     // Otherwise, the insertelement doesn't modify the value, recurse on its
12350     // vector input.
12351     return FindScalarElement(III->getOperand(0), EltNo, Context);
12352   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12353     unsigned LHSWidth =
12354       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12355     unsigned InEl = getShuffleMask(SVI)[EltNo];
12356     if (InEl < LHSWidth)
12357       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12358     else if (InEl < LHSWidth*2)
12359       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12360     else
12361       return Context->getUndef(PTy->getElementType());
12362   }
12363   
12364   // Otherwise, we don't know.
12365   return 0;
12366 }
12367
12368 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12369   // If vector val is undef, replace extract with scalar undef.
12370   if (isa<UndefValue>(EI.getOperand(0)))
12371     return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12372
12373   // If vector val is constant 0, replace extract with scalar 0.
12374   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12375     return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
12376   
12377   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12378     // If vector val is constant with all elements the same, replace EI with
12379     // that element. When the elements are not identical, we cannot replace yet
12380     // (we do that below, but only when the index is constant).
12381     Constant *op0 = C->getOperand(0);
12382     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12383       if (C->getOperand(i) != op0) {
12384         op0 = 0; 
12385         break;
12386       }
12387     if (op0)
12388       return ReplaceInstUsesWith(EI, op0);
12389   }
12390   
12391   // If extracting a specified index from the vector, see if we can recursively
12392   // find a previously computed scalar that was inserted into the vector.
12393   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12394     unsigned IndexVal = IdxC->getZExtValue();
12395     unsigned VectorWidth = 
12396       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12397       
12398     // If this is extracting an invalid index, turn this into undef, to avoid
12399     // crashing the code below.
12400     if (IndexVal >= VectorWidth)
12401       return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12402     
12403     // This instruction only demands the single element from the input vector.
12404     // If the input vector has a single use, simplify it based on this use
12405     // property.
12406     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12407       APInt UndefElts(VectorWidth, 0);
12408       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12409       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12410                                                 DemandedMask, UndefElts)) {
12411         EI.setOperand(0, V);
12412         return &EI;
12413       }
12414     }
12415     
12416     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12417       return ReplaceInstUsesWith(EI, Elt);
12418     
12419     // If the this extractelement is directly using a bitcast from a vector of
12420     // the same number of elements, see if we can find the source element from
12421     // it.  In this case, we will end up needing to bitcast the scalars.
12422     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12423       if (const VectorType *VT = 
12424               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12425         if (VT->getNumElements() == VectorWidth)
12426           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12427                                              IndexVal, Context))
12428             return new BitCastInst(Elt, EI.getType());
12429     }
12430   }
12431   
12432   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12433     if (I->hasOneUse()) {
12434       // Push extractelement into predecessor operation if legal and
12435       // profitable to do so
12436       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12437         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12438         if (CheapToScalarize(BO, isConstantElt)) {
12439           ExtractElementInst *newEI0 = 
12440             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12441                                    EI.getName()+".lhs");
12442           ExtractElementInst *newEI1 =
12443             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12444                                    EI.getName()+".rhs");
12445           InsertNewInstBefore(newEI0, EI);
12446           InsertNewInstBefore(newEI1, EI);
12447           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12448         }
12449       } else if (isa<LoadInst>(I)) {
12450         unsigned AS = 
12451           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12452         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12453                                   Context->getPointerType(EI.getType(), AS),EI);
12454         GetElementPtrInst *GEP =
12455           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12456         InsertNewInstBefore(GEP, EI);
12457         return new LoadInst(GEP);
12458       }
12459     }
12460     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12461       // Extracting the inserted element?
12462       if (IE->getOperand(2) == EI.getOperand(1))
12463         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12464       // If the inserted and extracted elements are constants, they must not
12465       // be the same value, extract from the pre-inserted value instead.
12466       if (isa<Constant>(IE->getOperand(2)) &&
12467           isa<Constant>(EI.getOperand(1))) {
12468         AddUsesToWorkList(EI);
12469         EI.setOperand(0, IE->getOperand(0));
12470         return &EI;
12471       }
12472     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12473       // If this is extracting an element from a shufflevector, figure out where
12474       // it came from and extract from the appropriate input element instead.
12475       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12476         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12477         Value *Src;
12478         unsigned LHSWidth =
12479           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12480
12481         if (SrcIdx < LHSWidth)
12482           Src = SVI->getOperand(0);
12483         else if (SrcIdx < LHSWidth*2) {
12484           SrcIdx -= LHSWidth;
12485           Src = SVI->getOperand(1);
12486         } else {
12487           return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12488         }
12489         return new ExtractElementInst(Src, SrcIdx);
12490       }
12491     }
12492   }
12493   return 0;
12494 }
12495
12496 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12497 /// elements from either LHS or RHS, return the shuffle mask and true. 
12498 /// Otherwise, return false.
12499 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12500                                          std::vector<Constant*> &Mask,
12501                                          LLVMContext *Context) {
12502   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12503          "Invalid CollectSingleShuffleElements");
12504   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12505
12506   if (isa<UndefValue>(V)) {
12507     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12508     return true;
12509   } else if (V == LHS) {
12510     for (unsigned i = 0; i != NumElts; ++i)
12511       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12512     return true;
12513   } else if (V == RHS) {
12514     for (unsigned i = 0; i != NumElts; ++i)
12515       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
12516     return true;
12517   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12518     // If this is an insert of an extract from some other vector, include it.
12519     Value *VecOp    = IEI->getOperand(0);
12520     Value *ScalarOp = IEI->getOperand(1);
12521     Value *IdxOp    = IEI->getOperand(2);
12522     
12523     if (!isa<ConstantInt>(IdxOp))
12524       return false;
12525     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12526     
12527     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12528       // Okay, we can handle this if the vector we are insertinting into is
12529       // transitively ok.
12530       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12531         // If so, update the mask to reflect the inserted undef.
12532         Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
12533         return true;
12534       }      
12535     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12536       if (isa<ConstantInt>(EI->getOperand(1)) &&
12537           EI->getOperand(0)->getType() == V->getType()) {
12538         unsigned ExtractedIdx =
12539           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12540         
12541         // This must be extracting from either LHS or RHS.
12542         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12543           // Okay, we can handle this if the vector we are insertinting into is
12544           // transitively ok.
12545           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12546             // If so, update the mask to reflect the inserted value.
12547             if (EI->getOperand(0) == LHS) {
12548               Mask[InsertedIdx % NumElts] = 
12549                  Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12550             } else {
12551               assert(EI->getOperand(0) == RHS);
12552               Mask[InsertedIdx % NumElts] = 
12553                 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
12554               
12555             }
12556             return true;
12557           }
12558         }
12559       }
12560     }
12561   }
12562   // TODO: Handle shufflevector here!
12563   
12564   return false;
12565 }
12566
12567 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12568 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12569 /// that computes V and the LHS value of the shuffle.
12570 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12571                                      Value *&RHS, LLVMContext *Context) {
12572   assert(isa<VectorType>(V->getType()) && 
12573          (RHS == 0 || V->getType() == RHS->getType()) &&
12574          "Invalid shuffle!");
12575   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12576
12577   if (isa<UndefValue>(V)) {
12578     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12579     return V;
12580   } else if (isa<ConstantAggregateZero>(V)) {
12581     Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
12582     return V;
12583   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12584     // If this is an insert of an extract from some other vector, include it.
12585     Value *VecOp    = IEI->getOperand(0);
12586     Value *ScalarOp = IEI->getOperand(1);
12587     Value *IdxOp    = IEI->getOperand(2);
12588     
12589     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12590       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12591           EI->getOperand(0)->getType() == V->getType()) {
12592         unsigned ExtractedIdx =
12593           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12594         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12595         
12596         // Either the extracted from or inserted into vector must be RHSVec,
12597         // otherwise we'd end up with a shuffle of three inputs.
12598         if (EI->getOperand(0) == RHS || RHS == 0) {
12599           RHS = EI->getOperand(0);
12600           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12601           Mask[InsertedIdx % NumElts] = 
12602             Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
12603           return V;
12604         }
12605         
12606         if (VecOp == RHS) {
12607           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12608                                             RHS, Context);
12609           // Everything but the extracted element is replaced with the RHS.
12610           for (unsigned i = 0; i != NumElts; ++i) {
12611             if (i != InsertedIdx)
12612               Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
12613           }
12614           return V;
12615         }
12616         
12617         // If this insertelement is a chain that comes from exactly these two
12618         // vectors, return the vector and the effective shuffle.
12619         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12620                                          Context))
12621           return EI->getOperand(0);
12622         
12623       }
12624     }
12625   }
12626   // TODO: Handle shufflevector here!
12627   
12628   // Otherwise, can't do anything fancy.  Return an identity vector.
12629   for (unsigned i = 0; i != NumElts; ++i)
12630     Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12631   return V;
12632 }
12633
12634 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12635   Value *VecOp    = IE.getOperand(0);
12636   Value *ScalarOp = IE.getOperand(1);
12637   Value *IdxOp    = IE.getOperand(2);
12638   
12639   // Inserting an undef or into an undefined place, remove this.
12640   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12641     ReplaceInstUsesWith(IE, VecOp);
12642   
12643   // If the inserted element was extracted from some other vector, and if the 
12644   // indexes are constant, try to turn this into a shufflevector operation.
12645   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12646     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12647         EI->getOperand(0)->getType() == IE.getType()) {
12648       unsigned NumVectorElts = IE.getType()->getNumElements();
12649       unsigned ExtractedIdx =
12650         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12651       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12652       
12653       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12654         return ReplaceInstUsesWith(IE, VecOp);
12655       
12656       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12657         return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
12658       
12659       // If we are extracting a value from a vector, then inserting it right
12660       // back into the same place, just use the input vector.
12661       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12662         return ReplaceInstUsesWith(IE, VecOp);      
12663       
12664       // We could theoretically do this for ANY input.  However, doing so could
12665       // turn chains of insertelement instructions into a chain of shufflevector
12666       // instructions, and right now we do not merge shufflevectors.  As such,
12667       // only do this in a situation where it is clear that there is benefit.
12668       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12669         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12670         // the values of VecOp, except then one read from EIOp0.
12671         // Build a new shuffle mask.
12672         std::vector<Constant*> Mask;
12673         if (isa<UndefValue>(VecOp))
12674           Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
12675         else {
12676           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12677           Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
12678                                                        NumVectorElts));
12679         } 
12680         Mask[InsertedIdx] = 
12681                            Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12682         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12683                                      Context->getConstantVector(Mask));
12684       }
12685       
12686       // If this insertelement isn't used by some other insertelement, turn it
12687       // (and any insertelements it points to), into one big shuffle.
12688       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12689         std::vector<Constant*> Mask;
12690         Value *RHS = 0;
12691         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12692         if (RHS == 0) RHS = Context->getUndef(LHS->getType());
12693         // We now have a shuffle of LHS, RHS, Mask.
12694         return new ShuffleVectorInst(LHS, RHS,
12695                                      Context->getConstantVector(Mask));
12696       }
12697     }
12698   }
12699
12700   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12701   APInt UndefElts(VWidth, 0);
12702   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12703   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12704     return &IE;
12705
12706   return 0;
12707 }
12708
12709
12710 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12711   Value *LHS = SVI.getOperand(0);
12712   Value *RHS = SVI.getOperand(1);
12713   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12714
12715   bool MadeChange = false;
12716
12717   // Undefined shuffle mask -> undefined value.
12718   if (isa<UndefValue>(SVI.getOperand(2)))
12719     return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
12720
12721   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12722
12723   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12724     return 0;
12725
12726   APInt UndefElts(VWidth, 0);
12727   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12728   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12729     LHS = SVI.getOperand(0);
12730     RHS = SVI.getOperand(1);
12731     MadeChange = true;
12732   }
12733   
12734   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12735   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12736   if (LHS == RHS || isa<UndefValue>(LHS)) {
12737     if (isa<UndefValue>(LHS) && LHS == RHS) {
12738       // shuffle(undef,undef,mask) -> undef.
12739       return ReplaceInstUsesWith(SVI, LHS);
12740     }
12741     
12742     // Remap any references to RHS to use LHS.
12743     std::vector<Constant*> Elts;
12744     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12745       if (Mask[i] >= 2*e)
12746         Elts.push_back(Context->getUndef(Type::Int32Ty));
12747       else {
12748         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12749             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12750           Mask[i] = 2*e;     // Turn into undef.
12751           Elts.push_back(Context->getUndef(Type::Int32Ty));
12752         } else {
12753           Mask[i] = Mask[i] % e;  // Force to LHS.
12754           Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
12755         }
12756       }
12757     }
12758     SVI.setOperand(0, SVI.getOperand(1));
12759     SVI.setOperand(1, Context->getUndef(RHS->getType()));
12760     SVI.setOperand(2, Context->getConstantVector(Elts));
12761     LHS = SVI.getOperand(0);
12762     RHS = SVI.getOperand(1);
12763     MadeChange = true;
12764   }
12765   
12766   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12767   bool isLHSID = true, isRHSID = true;
12768     
12769   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12770     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12771     // Is this an identity shuffle of the LHS value?
12772     isLHSID &= (Mask[i] == i);
12773       
12774     // Is this an identity shuffle of the RHS value?
12775     isRHSID &= (Mask[i]-e == i);
12776   }
12777
12778   // Eliminate identity shuffles.
12779   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12780   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12781   
12782   // If the LHS is a shufflevector itself, see if we can combine it with this
12783   // one without producing an unusual shuffle.  Here we are really conservative:
12784   // we are absolutely afraid of producing a shuffle mask not in the input
12785   // program, because the code gen may not be smart enough to turn a merged
12786   // shuffle into two specific shuffles: it may produce worse code.  As such,
12787   // we only merge two shuffles if the result is one of the two input shuffle
12788   // masks.  In this case, merging the shuffles just removes one instruction,
12789   // which we know is safe.  This is good for things like turning:
12790   // (splat(splat)) -> splat.
12791   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12792     if (isa<UndefValue>(RHS)) {
12793       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12794
12795       std::vector<unsigned> NewMask;
12796       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12797         if (Mask[i] >= 2*e)
12798           NewMask.push_back(2*e);
12799         else
12800           NewMask.push_back(LHSMask[Mask[i]]);
12801       
12802       // If the result mask is equal to the src shuffle or this shuffle mask, do
12803       // the replacement.
12804       if (NewMask == LHSMask || NewMask == Mask) {
12805         unsigned LHSInNElts =
12806           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12807         std::vector<Constant*> Elts;
12808         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12809           if (NewMask[i] >= LHSInNElts*2) {
12810             Elts.push_back(Context->getUndef(Type::Int32Ty));
12811           } else {
12812             Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
12813           }
12814         }
12815         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12816                                      LHSSVI->getOperand(1),
12817                                      Context->getConstantVector(Elts));
12818       }
12819     }
12820   }
12821
12822   return MadeChange ? &SVI : 0;
12823 }
12824
12825
12826
12827
12828 /// TryToSinkInstruction - Try to move the specified instruction from its
12829 /// current block into the beginning of DestBlock, which can only happen if it's
12830 /// safe to move the instruction past all of the instructions between it and the
12831 /// end of its block.
12832 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12833   assert(I->hasOneUse() && "Invariants didn't hold!");
12834
12835   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12836   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12837     return false;
12838
12839   // Do not sink alloca instructions out of the entry block.
12840   if (isa<AllocaInst>(I) && I->getParent() ==
12841         &DestBlock->getParent()->getEntryBlock())
12842     return false;
12843
12844   // We can only sink load instructions if there is nothing between the load and
12845   // the end of block that could change the value.
12846   if (I->mayReadFromMemory()) {
12847     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12848          Scan != E; ++Scan)
12849       if (Scan->mayWriteToMemory())
12850         return false;
12851   }
12852
12853   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12854
12855   CopyPrecedingStopPoint(I, InsertPos);
12856   I->moveBefore(InsertPos);
12857   ++NumSunkInst;
12858   return true;
12859 }
12860
12861
12862 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12863 /// all reachable code to the worklist.
12864 ///
12865 /// This has a couple of tricks to make the code faster and more powerful.  In
12866 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12867 /// them to the worklist (this significantly speeds up instcombine on code where
12868 /// many instructions are dead or constant).  Additionally, if we find a branch
12869 /// whose condition is a known constant, we only visit the reachable successors.
12870 ///
12871 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12872                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12873                                        InstCombiner &IC,
12874                                        const TargetData *TD) {
12875   SmallVector<BasicBlock*, 256> Worklist;
12876   Worklist.push_back(BB);
12877
12878   while (!Worklist.empty()) {
12879     BB = Worklist.back();
12880     Worklist.pop_back();
12881     
12882     // We have now visited this block!  If we've already been here, ignore it.
12883     if (!Visited.insert(BB)) continue;
12884
12885     DbgInfoIntrinsic *DBI_Prev = NULL;
12886     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12887       Instruction *Inst = BBI++;
12888       
12889       // DCE instruction if trivially dead.
12890       if (isInstructionTriviallyDead(Inst)) {
12891         ++NumDeadInst;
12892         DOUT << "IC: DCE: " << *Inst;
12893         Inst->eraseFromParent();
12894         continue;
12895       }
12896       
12897       // ConstantProp instruction if trivially constant.
12898       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12899         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12900         Inst->replaceAllUsesWith(C);
12901         ++NumConstProp;
12902         Inst->eraseFromParent();
12903         continue;
12904       }
12905      
12906       // If there are two consecutive llvm.dbg.stoppoint calls then
12907       // it is likely that the optimizer deleted code in between these
12908       // two intrinsics. 
12909       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12910       if (DBI_Next) {
12911         if (DBI_Prev
12912             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12913             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12914           IC.RemoveFromWorkList(DBI_Prev);
12915           DBI_Prev->eraseFromParent();
12916         }
12917         DBI_Prev = DBI_Next;
12918       } else {
12919         DBI_Prev = 0;
12920       }
12921
12922       IC.AddToWorkList(Inst);
12923     }
12924
12925     // Recursively visit successors.  If this is a branch or switch on a
12926     // constant, only visit the reachable successor.
12927     TerminatorInst *TI = BB->getTerminator();
12928     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12929       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12930         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12931         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12932         Worklist.push_back(ReachableBB);
12933         continue;
12934       }
12935     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12936       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12937         // See if this is an explicit destination.
12938         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12939           if (SI->getCaseValue(i) == Cond) {
12940             BasicBlock *ReachableBB = SI->getSuccessor(i);
12941             Worklist.push_back(ReachableBB);
12942             continue;
12943           }
12944         
12945         // Otherwise it is the default destination.
12946         Worklist.push_back(SI->getSuccessor(0));
12947         continue;
12948       }
12949     }
12950     
12951     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12952       Worklist.push_back(TI->getSuccessor(i));
12953   }
12954 }
12955
12956 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12957   bool Changed = false;
12958   TD = &getAnalysis<TargetData>();
12959   
12960   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12961              << F.getNameStr() << "\n");
12962
12963   {
12964     // Do a depth-first traversal of the function, populate the worklist with
12965     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12966     // track of which blocks we visit.
12967     SmallPtrSet<BasicBlock*, 64> Visited;
12968     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12969
12970     // Do a quick scan over the function.  If we find any blocks that are
12971     // unreachable, remove any instructions inside of them.  This prevents
12972     // the instcombine code from having to deal with some bad special cases.
12973     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12974       if (!Visited.count(BB)) {
12975         Instruction *Term = BB->getTerminator();
12976         while (Term != BB->begin()) {   // Remove instrs bottom-up
12977           BasicBlock::iterator I = Term; --I;
12978
12979           DOUT << "IC: DCE: " << *I;
12980           // A debug intrinsic shouldn't force another iteration if we weren't
12981           // going to do one without it.
12982           if (!isa<DbgInfoIntrinsic>(I)) {
12983             ++NumDeadInst;
12984             Changed = true;
12985           }
12986           if (!I->use_empty())
12987             I->replaceAllUsesWith(Context->getUndef(I->getType()));
12988           I->eraseFromParent();
12989         }
12990       }
12991   }
12992
12993   while (!Worklist.empty()) {
12994     Instruction *I = RemoveOneFromWorkList();
12995     if (I == 0) continue;  // skip null values.
12996
12997     // Check to see if we can DCE the instruction.
12998     if (isInstructionTriviallyDead(I)) {
12999       // Add operands to the worklist.
13000       if (I->getNumOperands() < 4)
13001         AddUsesToWorkList(*I);
13002       ++NumDeadInst;
13003
13004       DOUT << "IC: DCE: " << *I;
13005
13006       I->eraseFromParent();
13007       RemoveFromWorkList(I);
13008       Changed = true;
13009       continue;
13010     }
13011
13012     // Instruction isn't dead, see if we can constant propagate it.
13013     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
13014       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
13015
13016       // Add operands to the worklist.
13017       AddUsesToWorkList(*I);
13018       ReplaceInstUsesWith(*I, C);
13019
13020       ++NumConstProp;
13021       I->eraseFromParent();
13022       RemoveFromWorkList(I);
13023       Changed = true;
13024       continue;
13025     }
13026
13027     if (TD &&
13028         (I->getType()->getTypeID() == Type::VoidTyID ||
13029          I->isTrapping())) {
13030       // See if we can constant fold its operands.
13031       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13032         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
13033           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
13034                                   F.getContext(), TD))
13035             if (NewC != CE) {
13036               i->set(NewC);
13037               Changed = true;
13038             }
13039     }
13040
13041     // See if we can trivially sink this instruction to a successor basic block.
13042     if (I->hasOneUse()) {
13043       BasicBlock *BB = I->getParent();
13044       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13045       if (UserParent != BB) {
13046         bool UserIsSuccessor = false;
13047         // See if the user is one of our successors.
13048         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13049           if (*SI == UserParent) {
13050             UserIsSuccessor = true;
13051             break;
13052           }
13053
13054         // If the user is one of our immediate successors, and if that successor
13055         // only has us as a predecessors (we'd have to split the critical edge
13056         // otherwise), we can keep going.
13057         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13058             next(pred_begin(UserParent)) == pred_end(UserParent))
13059           // Okay, the CFG is simple enough, try to sink this instruction.
13060           Changed |= TryToSinkInstruction(I, UserParent);
13061       }
13062     }
13063
13064     // Now that we have an instruction, try combining it to simplify it...
13065 #ifndef NDEBUG
13066     std::string OrigI;
13067 #endif
13068     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13069     if (Instruction *Result = visit(*I)) {
13070       ++NumCombined;
13071       // Should we replace the old instruction with a new one?
13072       if (Result != I) {
13073         DOUT << "IC: Old = " << *I
13074              << "    New = " << *Result;
13075
13076         // Everything uses the new instruction now.
13077         I->replaceAllUsesWith(Result);
13078
13079         // Push the new instruction and any users onto the worklist.
13080         AddToWorkList(Result);
13081         AddUsersToWorkList(*Result);
13082
13083         // Move the name to the new instruction first.
13084         Result->takeName(I);
13085
13086         // Insert the new instruction into the basic block...
13087         BasicBlock *InstParent = I->getParent();
13088         BasicBlock::iterator InsertPos = I;
13089
13090         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13091           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13092             ++InsertPos;
13093
13094         InstParent->getInstList().insert(InsertPos, Result);
13095
13096         // Make sure that we reprocess all operands now that we reduced their
13097         // use counts.
13098         AddUsesToWorkList(*I);
13099
13100         // Instructions can end up on the worklist more than once.  Make sure
13101         // we do not process an instruction that has been deleted.
13102         RemoveFromWorkList(I);
13103
13104         // Erase the old instruction.
13105         InstParent->getInstList().erase(I);
13106       } else {
13107 #ifndef NDEBUG
13108         DOUT << "IC: Mod = " << OrigI
13109              << "    New = " << *I;
13110 #endif
13111
13112         // If the instruction was modified, it's possible that it is now dead.
13113         // if so, remove it.
13114         if (isInstructionTriviallyDead(I)) {
13115           // Make sure we process all operands now that we are reducing their
13116           // use counts.
13117           AddUsesToWorkList(*I);
13118
13119           // Instructions may end up in the worklist more than once.  Erase all
13120           // occurrences of this instruction.
13121           RemoveFromWorkList(I);
13122           I->eraseFromParent();
13123         } else {
13124           AddToWorkList(I);
13125           AddUsersToWorkList(*I);
13126         }
13127       }
13128       Changed = true;
13129     }
13130   }
13131
13132   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13133     
13134   // Do an explicit clear, this shrinks the map if needed.
13135   WorklistMap.clear();
13136   return Changed;
13137 }
13138
13139
13140 bool InstCombiner::runOnFunction(Function &F) {
13141   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13142   
13143   bool EverMadeChange = false;
13144
13145   // Iterate while there is work to do.
13146   unsigned Iteration = 0;
13147   while (DoOneIteration(F, Iteration++))
13148     EverMadeChange = true;
13149   return EverMadeChange;
13150 }
13151
13152 FunctionPass *llvm::createInstructionCombiningPass() {
13153   return new InstCombiner();
13154 }