Consider expression "0.0 - X" as the negation of X if
[oota-llvm.git] / lib / Transforms / InstCombine / 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 "InstCombine.h"
39 #include "llvm-c/Initialization.h"
40 #include "llvm/ADT/SmallPtrSet.h"
41 #include "llvm/ADT/Statistic.h"
42 #include "llvm/ADT/StringSwitch.h"
43 #include "llvm/Analysis/ConstantFolding.h"
44 #include "llvm/Analysis/InstructionSimplify.h"
45 #include "llvm/Analysis/MemoryBuiltins.h"
46 #include "llvm/IR/DataLayout.h"
47 #include "llvm/IR/IntrinsicInst.h"
48 #include "llvm/Support/CFG.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/GetElementPtrTypeIterator.h"
52 #include "llvm/Support/PatternMatch.h"
53 #include "llvm/Support/ValueHandle.h"
54 #include "llvm/Target/TargetLibraryInfo.h"
55 #include "llvm/Transforms/Utils/Local.h"
56 #include <algorithm>
57 #include <climits>
58 using namespace llvm;
59 using namespace llvm::PatternMatch;
60
61 STATISTIC(NumCombined , "Number of insts combined");
62 STATISTIC(NumConstProp, "Number of constant folds");
63 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
64 STATISTIC(NumSunkInst , "Number of instructions sunk");
65 STATISTIC(NumExpand,    "Number of expansions");
66 STATISTIC(NumFactor   , "Number of factorizations");
67 STATISTIC(NumReassoc  , "Number of reassociations");
68
69 static cl::opt<bool> UnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
70                                    cl::init(false),
71                                    cl::desc("Enable unsafe double to float "
72                                             "shrinking for math lib calls"));
73
74 // Initialization Routines
75 void llvm::initializeInstCombine(PassRegistry &Registry) {
76   initializeInstCombinerPass(Registry);
77 }
78
79 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
80   initializeInstCombine(*unwrap(R));
81 }
82
83 char InstCombiner::ID = 0;
84 INITIALIZE_PASS_BEGIN(InstCombiner, "instcombine",
85                 "Combine redundant instructions", false, false)
86 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
87 INITIALIZE_PASS_END(InstCombiner, "instcombine",
88                 "Combine redundant instructions", false, false)
89
90 void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
91   AU.setPreservesCFG();
92   AU.addRequired<TargetLibraryInfo>();
93 }
94
95
96 Value *InstCombiner::EmitGEPOffset(User *GEP) {
97   return llvm::EmitGEPOffset(Builder, *getDataLayout(), GEP);
98 }
99
100 /// ShouldChangeType - Return true if it is desirable to convert a computation
101 /// from 'From' to 'To'.  We don't want to convert from a legal to an illegal
102 /// type for example, or from a smaller to a larger illegal type.
103 bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
104   assert(From->isIntegerTy() && To->isIntegerTy());
105
106   // If we don't have TD, we don't know if the source/dest are legal.
107   if (!TD) return false;
108
109   unsigned FromWidth = From->getPrimitiveSizeInBits();
110   unsigned ToWidth = To->getPrimitiveSizeInBits();
111   bool FromLegal = TD->isLegalInteger(FromWidth);
112   bool ToLegal = TD->isLegalInteger(ToWidth);
113
114   // If this is a legal integer from type, and the result would be an illegal
115   // type, don't do the transformation.
116   if (FromLegal && !ToLegal)
117     return false;
118
119   // Otherwise, if both are illegal, do not increase the size of the result. We
120   // do allow things like i160 -> i64, but not i64 -> i160.
121   if (!FromLegal && !ToLegal && ToWidth > FromWidth)
122     return false;
123
124   return true;
125 }
126
127 // Return true, if No Signed Wrap should be maintained for I.
128 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
129 // where both B and C should be ConstantInts, results in a constant that does
130 // not overflow. This function only handles the Add and Sub opcodes. For
131 // all other opcodes, the function conservatively returns false.
132 static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
133   OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
134   if (!OBO || !OBO->hasNoSignedWrap()) {
135     return false;
136   }
137
138   // We reason about Add and Sub Only.
139   Instruction::BinaryOps Opcode = I.getOpcode();
140   if (Opcode != Instruction::Add &&
141       Opcode != Instruction::Sub) {
142     return false;
143   }
144
145   ConstantInt *CB = dyn_cast<ConstantInt>(B);
146   ConstantInt *CC = dyn_cast<ConstantInt>(C);
147
148   if (!CB || !CC) {
149     return false;
150   }
151
152   const APInt &BVal = CB->getValue();
153   const APInt &CVal = CC->getValue();
154   bool Overflow = false;
155
156   if (Opcode == Instruction::Add) {
157     BVal.sadd_ov(CVal, Overflow);
158   } else {
159     BVal.ssub_ov(CVal, Overflow);
160   }
161
162   return !Overflow;
163 }
164
165 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
166 /// operators which are associative or commutative:
167 //
168 //  Commutative operators:
169 //
170 //  1. Order operands such that they are listed from right (least complex) to
171 //     left (most complex).  This puts constants before unary operators before
172 //     binary operators.
173 //
174 //  Associative operators:
175 //
176 //  2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
177 //  3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
178 //
179 //  Associative and commutative operators:
180 //
181 //  4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
182 //  5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
183 //  6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
184 //     if C1 and C2 are constants.
185 //
186 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
187   Instruction::BinaryOps Opcode = I.getOpcode();
188   bool Changed = false;
189
190   do {
191     // Order operands such that they are listed from right (least complex) to
192     // left (most complex).  This puts constants before unary operators before
193     // binary operators.
194     if (I.isCommutative() && getComplexity(I.getOperand(0)) <
195         getComplexity(I.getOperand(1)))
196       Changed = !I.swapOperands();
197
198     BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
199     BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
200
201     if (I.isAssociative()) {
202       // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
203       if (Op0 && Op0->getOpcode() == Opcode) {
204         Value *A = Op0->getOperand(0);
205         Value *B = Op0->getOperand(1);
206         Value *C = I.getOperand(1);
207
208         // Does "B op C" simplify?
209         if (Value *V = SimplifyBinOp(Opcode, B, C, TD)) {
210           // It simplifies to V.  Form "A op V".
211           I.setOperand(0, A);
212           I.setOperand(1, V);
213           // Conservatively clear the optional flags, since they may not be
214           // preserved by the reassociation.
215           if (MaintainNoSignedWrap(I, B, C) &&
216               (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
217             // Note: this is only valid because SimplifyBinOp doesn't look at
218             // the operands to Op0.
219             I.clearSubclassOptionalData();
220             I.setHasNoSignedWrap(true);
221           } else {
222             I.clearSubclassOptionalData();
223           }
224
225           Changed = true;
226           ++NumReassoc;
227           continue;
228         }
229       }
230
231       // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
232       if (Op1 && Op1->getOpcode() == Opcode) {
233         Value *A = I.getOperand(0);
234         Value *B = Op1->getOperand(0);
235         Value *C = Op1->getOperand(1);
236
237         // Does "A op B" simplify?
238         if (Value *V = SimplifyBinOp(Opcode, A, B, TD)) {
239           // It simplifies to V.  Form "V op C".
240           I.setOperand(0, V);
241           I.setOperand(1, C);
242           // Conservatively clear the optional flags, since they may not be
243           // preserved by the reassociation.
244           I.clearSubclassOptionalData();
245           Changed = true;
246           ++NumReassoc;
247           continue;
248         }
249       }
250     }
251
252     if (I.isAssociative() && I.isCommutative()) {
253       // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
254       if (Op0 && Op0->getOpcode() == Opcode) {
255         Value *A = Op0->getOperand(0);
256         Value *B = Op0->getOperand(1);
257         Value *C = I.getOperand(1);
258
259         // Does "C op A" simplify?
260         if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
261           // It simplifies to V.  Form "V op B".
262           I.setOperand(0, V);
263           I.setOperand(1, B);
264           // Conservatively clear the optional flags, since they may not be
265           // preserved by the reassociation.
266           I.clearSubclassOptionalData();
267           Changed = true;
268           ++NumReassoc;
269           continue;
270         }
271       }
272
273       // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
274       if (Op1 && Op1->getOpcode() == Opcode) {
275         Value *A = I.getOperand(0);
276         Value *B = Op1->getOperand(0);
277         Value *C = Op1->getOperand(1);
278
279         // Does "C op A" simplify?
280         if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
281           // It simplifies to V.  Form "B op V".
282           I.setOperand(0, B);
283           I.setOperand(1, V);
284           // Conservatively clear the optional flags, since they may not be
285           // preserved by the reassociation.
286           I.clearSubclassOptionalData();
287           Changed = true;
288           ++NumReassoc;
289           continue;
290         }
291       }
292
293       // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
294       // if C1 and C2 are constants.
295       if (Op0 && Op1 &&
296           Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
297           isa<Constant>(Op0->getOperand(1)) &&
298           isa<Constant>(Op1->getOperand(1)) &&
299           Op0->hasOneUse() && Op1->hasOneUse()) {
300         Value *A = Op0->getOperand(0);
301         Constant *C1 = cast<Constant>(Op0->getOperand(1));
302         Value *B = Op1->getOperand(0);
303         Constant *C2 = cast<Constant>(Op1->getOperand(1));
304
305         Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
306         BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
307         InsertNewInstWith(New, I);
308         New->takeName(Op1);
309         I.setOperand(0, New);
310         I.setOperand(1, Folded);
311         // Conservatively clear the optional flags, since they may not be
312         // preserved by the reassociation.
313         I.clearSubclassOptionalData();
314
315         Changed = true;
316         continue;
317       }
318     }
319
320     // No further simplifications.
321     return Changed;
322   } while (1);
323 }
324
325 /// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
326 /// "(X LOp Y) ROp (X LOp Z)".
327 static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
328                                      Instruction::BinaryOps ROp) {
329   switch (LOp) {
330   default:
331     return false;
332
333   case Instruction::And:
334     // And distributes over Or and Xor.
335     switch (ROp) {
336     default:
337       return false;
338     case Instruction::Or:
339     case Instruction::Xor:
340       return true;
341     }
342
343   case Instruction::Mul:
344     // Multiplication distributes over addition and subtraction.
345     switch (ROp) {
346     default:
347       return false;
348     case Instruction::Add:
349     case Instruction::Sub:
350       return true;
351     }
352
353   case Instruction::Or:
354     // Or distributes over And.
355     switch (ROp) {
356     default:
357       return false;
358     case Instruction::And:
359       return true;
360     }
361   }
362 }
363
364 /// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
365 /// "(X ROp Z) LOp (Y ROp Z)".
366 static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
367                                      Instruction::BinaryOps ROp) {
368   if (Instruction::isCommutative(ROp))
369     return LeftDistributesOverRight(ROp, LOp);
370   // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
371   // but this requires knowing that the addition does not overflow and other
372   // such subtleties.
373   return false;
374 }
375
376 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
377 /// which some other binary operation distributes over either by factorizing
378 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
379 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
380 /// a win).  Returns the simplified value, or null if it didn't simplify.
381 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
382   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
383   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
384   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
385   Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); // op
386
387   // Factorization.
388   if (Op0 && Op1 && Op0->getOpcode() == Op1->getOpcode()) {
389     // The instruction has the form "(A op' B) op (C op' D)".  Try to factorize
390     // a common term.
391     Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
392     Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
393     Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
394
395     // Does "X op' Y" always equal "Y op' X"?
396     bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
397
398     // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
399     if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
400       // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
401       // commutative case, "(A op' B) op (C op' A)"?
402       if (A == C || (InnerCommutative && A == D)) {
403         if (A != C)
404           std::swap(C, D);
405         // Consider forming "A op' (B op D)".
406         // If "B op D" simplifies then it can be formed with no cost.
407         Value *V = SimplifyBinOp(TopLevelOpcode, B, D, TD);
408         // If "B op D" doesn't simplify then only go on if both of the existing
409         // operations "A op' B" and "C op' D" will be zapped as no longer used.
410         if (!V && Op0->hasOneUse() && Op1->hasOneUse())
411           V = Builder->CreateBinOp(TopLevelOpcode, B, D, Op1->getName());
412         if (V) {
413           ++NumFactor;
414           V = Builder->CreateBinOp(InnerOpcode, A, V);
415           V->takeName(&I);
416           return V;
417         }
418       }
419
420     // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
421     if (RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
422       // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
423       // commutative case, "(A op' B) op (B op' D)"?
424       if (B == D || (InnerCommutative && B == C)) {
425         if (B != D)
426           std::swap(C, D);
427         // Consider forming "(A op C) op' B".
428         // If "A op C" simplifies then it can be formed with no cost.
429         Value *V = SimplifyBinOp(TopLevelOpcode, A, C, TD);
430         // If "A op C" doesn't simplify then only go on if both of the existing
431         // operations "A op' B" and "C op' D" will be zapped as no longer used.
432         if (!V && Op0->hasOneUse() && Op1->hasOneUse())
433           V = Builder->CreateBinOp(TopLevelOpcode, A, C, Op0->getName());
434         if (V) {
435           ++NumFactor;
436           V = Builder->CreateBinOp(InnerOpcode, V, B);
437           V->takeName(&I);
438           return V;
439         }
440       }
441   }
442
443   // Expansion.
444   if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
445     // The instruction has the form "(A op' B) op C".  See if expanding it out
446     // to "(A op C) op' (B op C)" results in simplifications.
447     Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
448     Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
449
450     // Do "A op C" and "B op C" both simplify?
451     if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, TD))
452       if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, TD)) {
453         // They do! Return "L op' R".
454         ++NumExpand;
455         // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
456         if ((L == A && R == B) ||
457             (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
458           return Op0;
459         // Otherwise return "L op' R" if it simplifies.
460         if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
461           return V;
462         // Otherwise, create a new instruction.
463         C = Builder->CreateBinOp(InnerOpcode, L, R);
464         C->takeName(&I);
465         return C;
466       }
467   }
468
469   if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
470     // The instruction has the form "A op (B op' C)".  See if expanding it out
471     // to "(A op B) op' (A op C)" results in simplifications.
472     Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
473     Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
474
475     // Do "A op B" and "A op C" both simplify?
476     if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, TD))
477       if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, TD)) {
478         // They do! Return "L op' R".
479         ++NumExpand;
480         // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
481         if ((L == B && R == C) ||
482             (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
483           return Op1;
484         // Otherwise return "L op' R" if it simplifies.
485         if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
486           return V;
487         // Otherwise, create a new instruction.
488         A = Builder->CreateBinOp(InnerOpcode, L, R);
489         A->takeName(&I);
490         return A;
491       }
492   }
493
494   return 0;
495 }
496
497 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
498 // if the LHS is a constant zero (which is the 'negate' form).
499 //
500 Value *InstCombiner::dyn_castNegVal(Value *V) const {
501   if (BinaryOperator::isNeg(V))
502     return BinaryOperator::getNegArgument(V);
503
504   // Constants can be considered to be negated values if they can be folded.
505   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
506     return ConstantExpr::getNeg(C);
507
508   if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
509     if (C->getType()->getElementType()->isIntegerTy())
510       return ConstantExpr::getNeg(C);
511
512   return 0;
513 }
514
515 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
516 // instruction if the LHS is a constant negative zero (which is the 'negate'
517 // form).
518 //
519 Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
520   if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
521     return BinaryOperator::getFNegArgument(V);
522
523   // Constants can be considered to be negated values if they can be folded.
524   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
525     return ConstantExpr::getFNeg(C);
526
527   if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
528     if (C->getType()->getElementType()->isFloatingPointTy())
529       return ConstantExpr::getFNeg(C);
530
531   return 0;
532 }
533
534 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
535                                              InstCombiner *IC) {
536   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
537     return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
538   }
539
540   // Figure out if the constant is the left or the right argument.
541   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
542   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
543
544   if (Constant *SOC = dyn_cast<Constant>(SO)) {
545     if (ConstIsRHS)
546       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
547     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
548   }
549
550   Value *Op0 = SO, *Op1 = ConstOperand;
551   if (!ConstIsRHS)
552     std::swap(Op0, Op1);
553
554   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
555     return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
556                                     SO->getName()+".op");
557   if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
558     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
559                                    SO->getName()+".cmp");
560   if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
561     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
562                                    SO->getName()+".cmp");
563   llvm_unreachable("Unknown binary instruction type!");
564 }
565
566 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
567 // constant as the other operand, try to fold the binary operator into the
568 // select arguments.  This also works for Cast instructions, which obviously do
569 // not have a second operand.
570 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
571   // Don't modify shared select instructions
572   if (!SI->hasOneUse()) return 0;
573   Value *TV = SI->getOperand(1);
574   Value *FV = SI->getOperand(2);
575
576   if (isa<Constant>(TV) || isa<Constant>(FV)) {
577     // Bool selects with constant operands can be folded to logical ops.
578     if (SI->getType()->isIntegerTy(1)) return 0;
579
580     // If it's a bitcast involving vectors, make sure it has the same number of
581     // elements on both sides.
582     if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
583       VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
584       VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
585
586       // Verify that either both or neither are vectors.
587       if ((SrcTy == NULL) != (DestTy == NULL)) return 0;
588       // If vectors, verify that they have the same number of elements.
589       if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
590         return 0;
591     }
592
593     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
594     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
595
596     return SelectInst::Create(SI->getCondition(),
597                               SelectTrueVal, SelectFalseVal);
598   }
599   return 0;
600 }
601
602
603 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
604 /// has a PHI node as operand #0, see if we can fold the instruction into the
605 /// PHI (which is only possible if all operands to the PHI are constants).
606 ///
607 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
608   PHINode *PN = cast<PHINode>(I.getOperand(0));
609   unsigned NumPHIValues = PN->getNumIncomingValues();
610   if (NumPHIValues == 0)
611     return 0;
612
613   // We normally only transform phis with a single use.  However, if a PHI has
614   // multiple uses and they are all the same operation, we can fold *all* of the
615   // uses into the PHI.
616   if (!PN->hasOneUse()) {
617     // Walk the use list for the instruction, comparing them to I.
618     for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
619          UI != E; ++UI) {
620       Instruction *User = cast<Instruction>(*UI);
621       if (User != &I && !I.isIdenticalTo(User))
622         return 0;
623     }
624     // Otherwise, we can replace *all* users with the new PHI we form.
625   }
626
627   // Check to see if all of the operands of the PHI are simple constants
628   // (constantint/constantfp/undef).  If there is one non-constant value,
629   // remember the BB it is in.  If there is more than one or if *it* is a PHI,
630   // bail out.  We don't do arbitrary constant expressions here because moving
631   // their computation can be expensive without a cost model.
632   BasicBlock *NonConstBB = 0;
633   for (unsigned i = 0; i != NumPHIValues; ++i) {
634     Value *InVal = PN->getIncomingValue(i);
635     if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
636       continue;
637
638     if (isa<PHINode>(InVal)) return 0;  // Itself a phi.
639     if (NonConstBB) return 0;  // More than one non-const value.
640
641     NonConstBB = PN->getIncomingBlock(i);
642
643     // If the InVal is an invoke at the end of the pred block, then we can't
644     // insert a computation after it without breaking the edge.
645     if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
646       if (II->getParent() == NonConstBB)
647         return 0;
648
649     // If the incoming non-constant value is in I's block, we will remove one
650     // instruction, but insert another equivalent one, leading to infinite
651     // instcombine.
652     if (NonConstBB == I.getParent())
653       return 0;
654   }
655
656   // If there is exactly one non-constant value, we can insert a copy of the
657   // operation in that block.  However, if this is a critical edge, we would be
658   // inserting the computation one some other paths (e.g. inside a loop).  Only
659   // do this if the pred block is unconditionally branching into the phi block.
660   if (NonConstBB != 0) {
661     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
662     if (!BI || !BI->isUnconditional()) return 0;
663   }
664
665   // Okay, we can do the transformation: create the new PHI node.
666   PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
667   InsertNewInstBefore(NewPN, *PN);
668   NewPN->takeName(PN);
669
670   // If we are going to have to insert a new computation, do so right before the
671   // predecessors terminator.
672   if (NonConstBB)
673     Builder->SetInsertPoint(NonConstBB->getTerminator());
674
675   // Next, add all of the operands to the PHI.
676   if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
677     // We only currently try to fold the condition of a select when it is a phi,
678     // not the true/false values.
679     Value *TrueV = SI->getTrueValue();
680     Value *FalseV = SI->getFalseValue();
681     BasicBlock *PhiTransBB = PN->getParent();
682     for (unsigned i = 0; i != NumPHIValues; ++i) {
683       BasicBlock *ThisBB = PN->getIncomingBlock(i);
684       Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
685       Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
686       Value *InV = 0;
687       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
688         InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
689       else
690         InV = Builder->CreateSelect(PN->getIncomingValue(i),
691                                     TrueVInPred, FalseVInPred, "phitmp");
692       NewPN->addIncoming(InV, ThisBB);
693     }
694   } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
695     Constant *C = cast<Constant>(I.getOperand(1));
696     for (unsigned i = 0; i != NumPHIValues; ++i) {
697       Value *InV = 0;
698       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
699         InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
700       else if (isa<ICmpInst>(CI))
701         InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
702                                   C, "phitmp");
703       else
704         InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
705                                   C, "phitmp");
706       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
707     }
708   } else if (I.getNumOperands() == 2) {
709     Constant *C = cast<Constant>(I.getOperand(1));
710     for (unsigned i = 0; i != NumPHIValues; ++i) {
711       Value *InV = 0;
712       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
713         InV = ConstantExpr::get(I.getOpcode(), InC, C);
714       else
715         InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
716                                    PN->getIncomingValue(i), C, "phitmp");
717       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
718     }
719   } else {
720     CastInst *CI = cast<CastInst>(&I);
721     Type *RetTy = CI->getType();
722     for (unsigned i = 0; i != NumPHIValues; ++i) {
723       Value *InV;
724       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
725         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
726       else
727         InV = Builder->CreateCast(CI->getOpcode(),
728                                 PN->getIncomingValue(i), I.getType(), "phitmp");
729       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
730     }
731   }
732
733   for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
734        UI != E; ) {
735     Instruction *User = cast<Instruction>(*UI++);
736     if (User == &I) continue;
737     ReplaceInstUsesWith(*User, NewPN);
738     EraseInstFromFunction(*User);
739   }
740   return ReplaceInstUsesWith(I, NewPN);
741 }
742
743 /// FindElementAtOffset - Given a type and a constant offset, determine whether
744 /// or not there is a sequence of GEP indices into the type that will land us at
745 /// the specified offset.  If so, fill them into NewIndices and return the
746 /// resultant element type, otherwise return null.
747 Type *InstCombiner::FindElementAtOffset(Type *Ty, int64_t Offset,
748                                           SmallVectorImpl<Value*> &NewIndices) {
749   if (!TD) return 0;
750   if (!Ty->isSized()) return 0;
751
752   // Start with the index over the outer type.  Note that the type size
753   // might be zero (even if the offset isn't zero) if the indexed type
754   // is something like [0 x {int, int}]
755   Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
756   int64_t FirstIdx = 0;
757   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
758     FirstIdx = Offset/TySize;
759     Offset -= FirstIdx*TySize;
760
761     // Handle hosts where % returns negative instead of values [0..TySize).
762     if (Offset < 0) {
763       --FirstIdx;
764       Offset += TySize;
765       assert(Offset >= 0);
766     }
767     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
768   }
769
770   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
771
772   // Index into the types.  If we fail, set OrigBase to null.
773   while (Offset) {
774     // Indexing into tail padding between struct/array elements.
775     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
776       return 0;
777
778     if (StructType *STy = dyn_cast<StructType>(Ty)) {
779       const StructLayout *SL = TD->getStructLayout(STy);
780       assert(Offset < (int64_t)SL->getSizeInBytes() &&
781              "Offset must stay within the indexed type");
782
783       unsigned Elt = SL->getElementContainingOffset(Offset);
784       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
785                                             Elt));
786
787       Offset -= SL->getElementOffset(Elt);
788       Ty = STy->getElementType(Elt);
789     } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
790       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
791       assert(EltSize && "Cannot index into a zero-sized array");
792       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
793       Offset %= EltSize;
794       Ty = AT->getElementType();
795     } else {
796       // Otherwise, we can't index into the middle of this atomic type, bail.
797       return 0;
798     }
799   }
800
801   return Ty;
802 }
803
804 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
805   // If this GEP has only 0 indices, it is the same pointer as
806   // Src. If Src is not a trivial GEP too, don't combine
807   // the indices.
808   if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
809       !Src.hasOneUse())
810     return false;
811   return true;
812 }
813
814 /// Descale - Return a value X such that Val = X * Scale, or null if none.  If
815 /// the multiplication is known not to overflow then NoSignedWrap is set.
816 Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
817   assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
818   assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
819          Scale.getBitWidth() && "Scale not compatible with value!");
820
821   // If Val is zero or Scale is one then Val = Val * Scale.
822   if (match(Val, m_Zero()) || Scale == 1) {
823     NoSignedWrap = true;
824     return Val;
825   }
826
827   // If Scale is zero then it does not divide Val.
828   if (Scale.isMinValue())
829     return 0;
830
831   // Look through chains of multiplications, searching for a constant that is
832   // divisible by Scale.  For example, descaling X*(Y*(Z*4)) by a factor of 4
833   // will find the constant factor 4 and produce X*(Y*Z).  Descaling X*(Y*8) by
834   // a factor of 4 will produce X*(Y*2).  The principle of operation is to bore
835   // down from Val:
836   //
837   //     Val = M1 * X          ||   Analysis starts here and works down
838   //      M1 = M2 * Y          ||   Doesn't descend into terms with more
839   //      M2 =  Z * 4          \/   than one use
840   //
841   // Then to modify a term at the bottom:
842   //
843   //     Val = M1 * X
844   //      M1 =  Z * Y          ||   Replaced M2 with Z
845   //
846   // Then to work back up correcting nsw flags.
847
848   // Op - the term we are currently analyzing.  Starts at Val then drills down.
849   // Replaced with its descaled value before exiting from the drill down loop.
850   Value *Op = Val;
851
852   // Parent - initially null, but after drilling down notes where Op came from.
853   // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
854   // 0'th operand of Val.
855   std::pair<Instruction*, unsigned> Parent;
856
857   // RequireNoSignedWrap - Set if the transform requires a descaling at deeper
858   // levels that doesn't overflow.
859   bool RequireNoSignedWrap = false;
860
861   // logScale - log base 2 of the scale.  Negative if not a power of 2.
862   int32_t logScale = Scale.exactLogBase2();
863
864   for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
865
866     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
867       // If Op is a constant divisible by Scale then descale to the quotient.
868       APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
869       APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
870       if (!Remainder.isMinValue())
871         // Not divisible by Scale.
872         return 0;
873       // Replace with the quotient in the parent.
874       Op = ConstantInt::get(CI->getType(), Quotient);
875       NoSignedWrap = true;
876       break;
877     }
878
879     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
880
881       if (BO->getOpcode() == Instruction::Mul) {
882         // Multiplication.
883         NoSignedWrap = BO->hasNoSignedWrap();
884         if (RequireNoSignedWrap && !NoSignedWrap)
885           return 0;
886
887         // There are three cases for multiplication: multiplication by exactly
888         // the scale, multiplication by a constant different to the scale, and
889         // multiplication by something else.
890         Value *LHS = BO->getOperand(0);
891         Value *RHS = BO->getOperand(1);
892
893         if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
894           // Multiplication by a constant.
895           if (CI->getValue() == Scale) {
896             // Multiplication by exactly the scale, replace the multiplication
897             // by its left-hand side in the parent.
898             Op = LHS;
899             break;
900           }
901
902           // Otherwise drill down into the constant.
903           if (!Op->hasOneUse())
904             return 0;
905
906           Parent = std::make_pair(BO, 1);
907           continue;
908         }
909
910         // Multiplication by something else. Drill down into the left-hand side
911         // since that's where the reassociate pass puts the good stuff.
912         if (!Op->hasOneUse())
913           return 0;
914
915         Parent = std::make_pair(BO, 0);
916         continue;
917       }
918
919       if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
920           isa<ConstantInt>(BO->getOperand(1))) {
921         // Multiplication by a power of 2.
922         NoSignedWrap = BO->hasNoSignedWrap();
923         if (RequireNoSignedWrap && !NoSignedWrap)
924           return 0;
925
926         Value *LHS = BO->getOperand(0);
927         int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
928           getLimitedValue(Scale.getBitWidth());
929         // Op = LHS << Amt.
930
931         if (Amt == logScale) {
932           // Multiplication by exactly the scale, replace the multiplication
933           // by its left-hand side in the parent.
934           Op = LHS;
935           break;
936         }
937         if (Amt < logScale || !Op->hasOneUse())
938           return 0;
939
940         // Multiplication by more than the scale.  Reduce the multiplying amount
941         // by the scale in the parent.
942         Parent = std::make_pair(BO, 1);
943         Op = ConstantInt::get(BO->getType(), Amt - logScale);
944         break;
945       }
946     }
947
948     if (!Op->hasOneUse())
949       return 0;
950
951     if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
952       if (Cast->getOpcode() == Instruction::SExt) {
953         // Op is sign-extended from a smaller type, descale in the smaller type.
954         unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
955         APInt SmallScale = Scale.trunc(SmallSize);
956         // Suppose Op = sext X, and we descale X as Y * SmallScale.  We want to
957         // descale Op as (sext Y) * Scale.  In order to have
958         //   sext (Y * SmallScale) = (sext Y) * Scale
959         // some conditions need to hold however: SmallScale must sign-extend to
960         // Scale and the multiplication Y * SmallScale should not overflow.
961         if (SmallScale.sext(Scale.getBitWidth()) != Scale)
962           // SmallScale does not sign-extend to Scale.
963           return 0;
964         assert(SmallScale.exactLogBase2() == logScale);
965         // Require that Y * SmallScale must not overflow.
966         RequireNoSignedWrap = true;
967
968         // Drill down through the cast.
969         Parent = std::make_pair(Cast, 0);
970         Scale = SmallScale;
971         continue;
972       }
973
974       if (Cast->getOpcode() == Instruction::Trunc) {
975         // Op is truncated from a larger type, descale in the larger type.
976         // Suppose Op = trunc X, and we descale X as Y * sext Scale.  Then
977         //   trunc (Y * sext Scale) = (trunc Y) * Scale
978         // always holds.  However (trunc Y) * Scale may overflow even if
979         // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
980         // from this point up in the expression (see later).
981         if (RequireNoSignedWrap)
982           return 0;
983
984         // Drill down through the cast.
985         unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
986         Parent = std::make_pair(Cast, 0);
987         Scale = Scale.sext(LargeSize);
988         if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
989           logScale = -1;
990         assert(Scale.exactLogBase2() == logScale);
991         continue;
992       }
993     }
994
995     // Unsupported expression, bail out.
996     return 0;
997   }
998
999   // We know that we can successfully descale, so from here on we can safely
1000   // modify the IR.  Op holds the descaled version of the deepest term in the
1001   // expression.  NoSignedWrap is 'true' if multiplying Op by Scale is known
1002   // not to overflow.
1003
1004   if (!Parent.first)
1005     // The expression only had one term.
1006     return Op;
1007
1008   // Rewrite the parent using the descaled version of its operand.
1009   assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1010   assert(Op != Parent.first->getOperand(Parent.second) &&
1011          "Descaling was a no-op?");
1012   Parent.first->setOperand(Parent.second, Op);
1013   Worklist.Add(Parent.first);
1014
1015   // Now work back up the expression correcting nsw flags.  The logic is based
1016   // on the following observation: if X * Y is known not to overflow as a signed
1017   // multiplication, and Y is replaced by a value Z with smaller absolute value,
1018   // then X * Z will not overflow as a signed multiplication either.  As we work
1019   // our way up, having NoSignedWrap 'true' means that the descaled value at the
1020   // current level has strictly smaller absolute value than the original.
1021   Instruction *Ancestor = Parent.first;
1022   do {
1023     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1024       // If the multiplication wasn't nsw then we can't say anything about the
1025       // value of the descaled multiplication, and we have to clear nsw flags
1026       // from this point on up.
1027       bool OpNoSignedWrap = BO->hasNoSignedWrap();
1028       NoSignedWrap &= OpNoSignedWrap;
1029       if (NoSignedWrap != OpNoSignedWrap) {
1030         BO->setHasNoSignedWrap(NoSignedWrap);
1031         Worklist.Add(Ancestor);
1032       }
1033     } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1034       // The fact that the descaled input to the trunc has smaller absolute
1035       // value than the original input doesn't tell us anything useful about
1036       // the absolute values of the truncations.
1037       NoSignedWrap = false;
1038     }
1039     assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1040            "Failed to keep proper track of nsw flags while drilling down?");
1041
1042     if (Ancestor == Val)
1043       // Got to the top, all done!
1044       return Val;
1045
1046     // Move up one level in the expression.
1047     assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
1048     Ancestor = Ancestor->use_back();
1049   } while (1);
1050 }
1051
1052 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1053   SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1054
1055   if (Value *V = SimplifyGEPInst(Ops, TD))
1056     return ReplaceInstUsesWith(GEP, V);
1057
1058   Value *PtrOp = GEP.getOperand(0);
1059
1060   // Eliminate unneeded casts for indices, and replace indices which displace
1061   // by multiples of a zero size type with zero.
1062   if (TD) {
1063     bool MadeChange = false;
1064     Type *IntPtrTy = TD->getIntPtrType(GEP.getPointerOperandType());
1065
1066     gep_type_iterator GTI = gep_type_begin(GEP);
1067     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
1068          I != E; ++I, ++GTI) {
1069       // Skip indices into struct types.
1070       SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
1071       if (!SeqTy) continue;
1072
1073       // If the element type has zero size then any index over it is equivalent
1074       // to an index of zero, so replace it with zero if it is not zero already.
1075       if (SeqTy->getElementType()->isSized() &&
1076           TD->getTypeAllocSize(SeqTy->getElementType()) == 0)
1077         if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1078           *I = Constant::getNullValue(IntPtrTy);
1079           MadeChange = true;
1080         }
1081
1082       Type *IndexTy = (*I)->getType();
1083       if (IndexTy != IntPtrTy) {
1084         // If we are using a wider index than needed for this platform, shrink
1085         // it to what we need.  If narrower, sign-extend it to what we need.
1086         // This explicit cast can make subsequent optimizations more obvious.
1087         *I = Builder->CreateIntCast(*I, IntPtrTy, true);
1088         MadeChange = true;
1089       }
1090     }
1091     if (MadeChange) return &GEP;
1092   }
1093
1094   // Combine Indices - If the source pointer to this getelementptr instruction
1095   // is a getelementptr instruction, combine the indices of the two
1096   // getelementptr instructions into a single instruction.
1097   //
1098   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
1099     if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
1100       return 0;
1101
1102     // Note that if our source is a gep chain itself then we wait for that
1103     // chain to be resolved before we perform this transformation.  This
1104     // avoids us creating a TON of code in some cases.
1105     if (GEPOperator *SrcGEP =
1106           dyn_cast<GEPOperator>(Src->getOperand(0)))
1107       if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
1108         return 0;   // Wait until our source is folded to completion.
1109
1110     SmallVector<Value*, 8> Indices;
1111
1112     // Find out whether the last index in the source GEP is a sequential idx.
1113     bool EndsWithSequential = false;
1114     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1115          I != E; ++I)
1116       EndsWithSequential = !(*I)->isStructTy();
1117
1118     // Can we combine the two pointer arithmetics offsets?
1119     if (EndsWithSequential) {
1120       // Replace: gep (gep %P, long B), long A, ...
1121       // With:    T = long A+B; gep %P, T, ...
1122       //
1123       Value *Sum;
1124       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1125       Value *GO1 = GEP.getOperand(1);
1126       if (SO1 == Constant::getNullValue(SO1->getType())) {
1127         Sum = GO1;
1128       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
1129         Sum = SO1;
1130       } else {
1131         // If they aren't the same type, then the input hasn't been processed
1132         // by the loop above yet (which canonicalizes sequential index types to
1133         // intptr_t).  Just avoid transforming this until the input has been
1134         // normalized.
1135         if (SO1->getType() != GO1->getType())
1136           return 0;
1137         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
1138       }
1139
1140       // Update the GEP in place if possible.
1141       if (Src->getNumOperands() == 2) {
1142         GEP.setOperand(0, Src->getOperand(0));
1143         GEP.setOperand(1, Sum);
1144         return &GEP;
1145       }
1146       Indices.append(Src->op_begin()+1, Src->op_end()-1);
1147       Indices.push_back(Sum);
1148       Indices.append(GEP.op_begin()+2, GEP.op_end());
1149     } else if (isa<Constant>(*GEP.idx_begin()) &&
1150                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
1151                Src->getNumOperands() != 1) {
1152       // Otherwise we can do the fold if the first index of the GEP is a zero
1153       Indices.append(Src->op_begin()+1, Src->op_end());
1154       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
1155     }
1156
1157     if (!Indices.empty())
1158       return (GEP.isInBounds() && Src->isInBounds()) ?
1159         GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices,
1160                                           GEP.getName()) :
1161         GetElementPtrInst::Create(Src->getOperand(0), Indices, GEP.getName());
1162   }
1163
1164   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
1165   Value *StrippedPtr = PtrOp->stripPointerCasts();
1166   PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
1167
1168   // We do not handle pointer-vector geps here.
1169   if (!StrippedPtrTy)
1170     return 0;
1171
1172   if (StrippedPtr != PtrOp &&
1173     StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) {
1174
1175     bool HasZeroPointerIndex = false;
1176     if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1177       HasZeroPointerIndex = C->isZero();
1178
1179     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1180     // into     : GEP [10 x i8]* X, i32 0, ...
1181     //
1182     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1183     //           into     : GEP i8* X, ...
1184     //
1185     // This occurs when the program declares an array extern like "int X[];"
1186     if (HasZeroPointerIndex) {
1187       PointerType *CPTy = cast<PointerType>(PtrOp->getType());
1188       if (ArrayType *CATy =
1189           dyn_cast<ArrayType>(CPTy->getElementType())) {
1190         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
1191         if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
1192           // -> GEP i8* X, ...
1193           SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
1194           GetElementPtrInst *Res =
1195             GetElementPtrInst::Create(StrippedPtr, Idx, GEP.getName());
1196           Res->setIsInBounds(GEP.isInBounds());
1197           return Res;
1198         }
1199
1200         if (ArrayType *XATy =
1201               dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
1202           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
1203           if (CATy->getElementType() == XATy->getElementType()) {
1204             // -> GEP [10 x i8]* X, i32 0, ...
1205             // At this point, we know that the cast source type is a pointer
1206             // to an array of the same type as the destination pointer
1207             // array.  Because the array type is never stepped over (there
1208             // is a leading zero) we can fold the cast into this GEP.
1209             GEP.setOperand(0, StrippedPtr);
1210             return &GEP;
1211           }
1212         }
1213       }
1214     } else if (GEP.getNumOperands() == 2) {
1215       // Transform things like:
1216       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1217       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
1218       Type *SrcElTy = StrippedPtrTy->getElementType();
1219       Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
1220       if (TD && SrcElTy->isArrayTy() &&
1221           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
1222           TD->getTypeAllocSize(ResElTy)) {
1223         Value *Idx[2];
1224         Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
1225         Idx[1] = GEP.getOperand(1);
1226         Value *NewGEP = GEP.isInBounds() ?
1227           Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
1228           Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
1229         // V and GEP are both pointer types --> BitCast
1230         return new BitCastInst(NewGEP, GEP.getType());
1231       }
1232
1233       // Transform things like:
1234       // %V = mul i64 %N, 4
1235       // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1236       // into:  %t1 = getelementptr i32* %arr, i32 %N; bitcast
1237       if (TD && ResElTy->isSized() && SrcElTy->isSized()) {
1238         // Check that changing the type amounts to dividing the index by a scale
1239         // factor.
1240         uint64_t ResSize = TD->getTypeAllocSize(ResElTy);
1241         uint64_t SrcSize = TD->getTypeAllocSize(SrcElTy);
1242         if (ResSize && SrcSize % ResSize == 0) {
1243           Value *Idx = GEP.getOperand(1);
1244           unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1245           uint64_t Scale = SrcSize / ResSize;
1246
1247           // Earlier transforms ensure that the index has type IntPtrType, which
1248           // considerably simplifies the logic by eliminating implicit casts.
1249           assert(Idx->getType() == TD->getIntPtrType(GEP.getContext()) &&
1250                  "Index not cast to pointer width?");
1251
1252           bool NSW;
1253           if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1254             // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1255             // If the multiplication NewIdx * Scale may overflow then the new
1256             // GEP may not be "inbounds".
1257             Value *NewGEP = GEP.isInBounds() && NSW ?
1258               Builder->CreateInBoundsGEP(StrippedPtr, NewIdx, GEP.getName()) :
1259               Builder->CreateGEP(StrippedPtr, NewIdx, GEP.getName());
1260             // The NewGEP must be pointer typed, so must the old one -> BitCast
1261             return new BitCastInst(NewGEP, GEP.getType());
1262           }
1263         }
1264       }
1265
1266       // Similarly, transform things like:
1267       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
1268       //   (where tmp = 8*tmp2) into:
1269       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
1270       if (TD && ResElTy->isSized() && SrcElTy->isSized() &&
1271           SrcElTy->isArrayTy()) {
1272         // Check that changing to the array element type amounts to dividing the
1273         // index by a scale factor.
1274         uint64_t ResSize = TD->getTypeAllocSize(ResElTy);
1275         uint64_t ArrayEltSize =
1276           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
1277         if (ResSize && ArrayEltSize % ResSize == 0) {
1278           Value *Idx = GEP.getOperand(1);
1279           unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1280           uint64_t Scale = ArrayEltSize / ResSize;
1281
1282           // Earlier transforms ensure that the index has type IntPtrType, which
1283           // considerably simplifies the logic by eliminating implicit casts.
1284           assert(Idx->getType() == TD->getIntPtrType(GEP.getContext()) &&
1285                  "Index not cast to pointer width?");
1286
1287           bool NSW;
1288           if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1289             // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1290             // If the multiplication NewIdx * Scale may overflow then the new
1291             // GEP may not be "inbounds".
1292             Value *Off[2];
1293             Off[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
1294             Off[1] = NewIdx;
1295             Value *NewGEP = GEP.isInBounds() && NSW ?
1296               Builder->CreateInBoundsGEP(StrippedPtr, Off, GEP.getName()) :
1297               Builder->CreateGEP(StrippedPtr, Off, GEP.getName());
1298             // The NewGEP must be pointer typed, so must the old one -> BitCast
1299             return new BitCastInst(NewGEP, GEP.getType());
1300           }
1301         }
1302       }
1303     }
1304   }
1305
1306   /// See if we can simplify:
1307   ///   X = bitcast A* to B*
1308   ///   Y = gep X, <...constant indices...>
1309   /// into a gep of the original struct.  This is important for SROA and alias
1310   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
1311   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1312     APInt Offset(TD ? TD->getPointerSizeInBits() : 1, 0);
1313     if (TD &&
1314         !isa<BitCastInst>(BCI->getOperand(0)) &&
1315         GEP.accumulateConstantOffset(*TD, Offset) &&
1316         StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) {
1317
1318       // If this GEP instruction doesn't move the pointer, just replace the GEP
1319       // with a bitcast of the real input to the dest type.
1320       if (!Offset) {
1321         // If the bitcast is of an allocation, and the allocation will be
1322         // converted to match the type of the cast, don't touch this.
1323         if (isa<AllocaInst>(BCI->getOperand(0)) ||
1324             isAllocationFn(BCI->getOperand(0), TLI)) {
1325           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1326           if (Instruction *I = visitBitCast(*BCI)) {
1327             if (I != BCI) {
1328               I->takeName(BCI);
1329               BCI->getParent()->getInstList().insert(BCI, I);
1330               ReplaceInstUsesWith(*BCI, I);
1331             }
1332             return &GEP;
1333           }
1334         }
1335         return new BitCastInst(BCI->getOperand(0), GEP.getType());
1336       }
1337
1338       // Otherwise, if the offset is non-zero, we need to find out if there is a
1339       // field at Offset in 'A's type.  If so, we can pull the cast through the
1340       // GEP.
1341       SmallVector<Value*, 8> NewIndices;
1342       Type *InTy =
1343         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
1344       if (FindElementAtOffset(InTy, Offset.getSExtValue(), NewIndices)) {
1345         Value *NGEP = GEP.isInBounds() ?
1346           Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices) :
1347           Builder->CreateGEP(BCI->getOperand(0), NewIndices);
1348
1349         if (NGEP->getType() == GEP.getType())
1350           return ReplaceInstUsesWith(GEP, NGEP);
1351         NGEP->takeName(&GEP);
1352         return new BitCastInst(NGEP, GEP.getType());
1353       }
1354     }
1355   }
1356
1357   return 0;
1358 }
1359
1360
1361
1362 static bool
1363 isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
1364                      const TargetLibraryInfo *TLI) {
1365   SmallVector<Instruction*, 4> Worklist;
1366   Worklist.push_back(AI);
1367
1368   do {
1369     Instruction *PI = Worklist.pop_back_val();
1370     for (Value::use_iterator UI = PI->use_begin(), UE = PI->use_end(); UI != UE;
1371          ++UI) {
1372       Instruction *I = cast<Instruction>(*UI);
1373       switch (I->getOpcode()) {
1374       default:
1375         // Give up the moment we see something we can't handle.
1376         return false;
1377
1378       case Instruction::BitCast:
1379       case Instruction::GetElementPtr:
1380         Users.push_back(I);
1381         Worklist.push_back(I);
1382         continue;
1383
1384       case Instruction::ICmp: {
1385         ICmpInst *ICI = cast<ICmpInst>(I);
1386         // We can fold eq/ne comparisons with null to false/true, respectively.
1387         if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1)))
1388           return false;
1389         Users.push_back(I);
1390         continue;
1391       }
1392
1393       case Instruction::Call:
1394         // Ignore no-op and store intrinsics.
1395         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1396           switch (II->getIntrinsicID()) {
1397           default:
1398             return false;
1399
1400           case Intrinsic::memmove:
1401           case Intrinsic::memcpy:
1402           case Intrinsic::memset: {
1403             MemIntrinsic *MI = cast<MemIntrinsic>(II);
1404             if (MI->isVolatile() || MI->getRawDest() != PI)
1405               return false;
1406           }
1407           // fall through
1408           case Intrinsic::dbg_declare:
1409           case Intrinsic::dbg_value:
1410           case Intrinsic::invariant_start:
1411           case Intrinsic::invariant_end:
1412           case Intrinsic::lifetime_start:
1413           case Intrinsic::lifetime_end:
1414           case Intrinsic::objectsize:
1415             Users.push_back(I);
1416             continue;
1417           }
1418         }
1419
1420         if (isFreeCall(I, TLI)) {
1421           Users.push_back(I);
1422           continue;
1423         }
1424         return false;
1425
1426       case Instruction::Store: {
1427         StoreInst *SI = cast<StoreInst>(I);
1428         if (SI->isVolatile() || SI->getPointerOperand() != PI)
1429           return false;
1430         Users.push_back(I);
1431         continue;
1432       }
1433       }
1434       llvm_unreachable("missing a return?");
1435     }
1436   } while (!Worklist.empty());
1437   return true;
1438 }
1439
1440 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
1441   // If we have a malloc call which is only used in any amount of comparisons
1442   // to null and free calls, delete the calls and replace the comparisons with
1443   // true or false as appropriate.
1444   SmallVector<WeakVH, 64> Users;
1445   if (isAllocSiteRemovable(&MI, Users, TLI)) {
1446     for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1447       Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1448       if (!I) continue;
1449
1450       if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
1451         ReplaceInstUsesWith(*C,
1452                             ConstantInt::get(Type::getInt1Ty(C->getContext()),
1453                                              C->isFalseWhenEqual()));
1454       } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
1455         ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
1456       } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1457         if (II->getIntrinsicID() == Intrinsic::objectsize) {
1458           ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
1459           uint64_t DontKnow = CI->isZero() ? -1ULL : 0;
1460           ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow));
1461         }
1462       }
1463       EraseInstFromFunction(*I);
1464     }
1465
1466     if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
1467       // Replace invoke with a NOP intrinsic to maintain the original CFG
1468       Module *M = II->getParent()->getParent()->getParent();
1469       Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
1470       InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
1471                          ArrayRef<Value *>(), "", II->getParent());
1472     }
1473     return EraseInstFromFunction(MI);
1474   }
1475   return 0;
1476 }
1477
1478 /// \brief Move the call to free before a NULL test.
1479 ///
1480 /// Check if this free is accessed after its argument has been test
1481 /// against NULL (property 0).
1482 /// If yes, it is legal to move this call in its predecessor block.
1483 ///
1484 /// The move is performed only if the block containing the call to free
1485 /// will be removed, i.e.:
1486 /// 1. it has only one predecessor P, and P has two successors
1487 /// 2. it contains the call and an unconditional branch
1488 /// 3. its successor is the same as its predecessor's successor
1489 ///
1490 /// The profitability is out-of concern here and this function should
1491 /// be called only if the caller knows this transformation would be
1492 /// profitable (e.g., for code size).
1493 static Instruction *
1494 tryToMoveFreeBeforeNullTest(CallInst &FI) {
1495   Value *Op = FI.getArgOperand(0);
1496   BasicBlock *FreeInstrBB = FI.getParent();
1497   BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
1498
1499   // Validate part of constraint #1: Only one predecessor
1500   // FIXME: We can extend the number of predecessor, but in that case, we
1501   //        would duplicate the call to free in each predecessor and it may
1502   //        not be profitable even for code size.
1503   if (!PredBB)
1504     return 0;
1505
1506   // Validate constraint #2: Does this block contains only the call to
1507   //                         free and an unconditional branch?
1508   // FIXME: We could check if we can speculate everything in the
1509   //        predecessor block
1510   if (FreeInstrBB->size() != 2)
1511     return 0;
1512   BasicBlock *SuccBB;
1513   if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
1514     return 0;
1515
1516   // Validate the rest of constraint #1 by matching on the pred branch.
1517   TerminatorInst *TI = PredBB->getTerminator();
1518   BasicBlock *TrueBB, *FalseBB;
1519   ICmpInst::Predicate Pred;
1520   if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
1521     return 0;
1522   if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
1523     return 0;
1524
1525   // Validate constraint #3: Ensure the null case just falls through.
1526   if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
1527     return 0;
1528   assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
1529          "Broken CFG: missing edge from predecessor to successor");
1530
1531   FI.moveBefore(TI);
1532   return &FI;
1533 }
1534
1535
1536 Instruction *InstCombiner::visitFree(CallInst &FI) {
1537   Value *Op = FI.getArgOperand(0);
1538
1539   // free undef -> unreachable.
1540   if (isa<UndefValue>(Op)) {
1541     // Insert a new store to null because we cannot modify the CFG here.
1542     Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
1543                          UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
1544     return EraseInstFromFunction(FI);
1545   }
1546
1547   // If we have 'free null' delete the instruction.  This can happen in stl code
1548   // when lots of inlining happens.
1549   if (isa<ConstantPointerNull>(Op))
1550     return EraseInstFromFunction(FI);
1551
1552   // If we optimize for code size, try to move the call to free before the null
1553   // test so that simplify cfg can remove the empty block and dead code
1554   // elimination the branch. I.e., helps to turn something like:
1555   // if (foo) free(foo);
1556   // into
1557   // free(foo);
1558   if (MinimizeSize)
1559     if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
1560       return I;
1561
1562   return 0;
1563 }
1564
1565
1566
1567 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1568   // Change br (not X), label True, label False to: br X, label False, True
1569   Value *X = 0;
1570   BasicBlock *TrueDest;
1571   BasicBlock *FalseDest;
1572   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
1573       !isa<Constant>(X)) {
1574     // Swap Destinations and condition...
1575     BI.setCondition(X);
1576     BI.swapSuccessors();
1577     return &BI;
1578   }
1579
1580   // Cannonicalize fcmp_one -> fcmp_oeq
1581   FCmpInst::Predicate FPred; Value *Y;
1582   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
1583                              TrueDest, FalseDest)) &&
1584       BI.getCondition()->hasOneUse())
1585     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
1586         FPred == FCmpInst::FCMP_OGE) {
1587       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
1588       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
1589
1590       // Swap Destinations and condition.
1591       BI.swapSuccessors();
1592       Worklist.Add(Cond);
1593       return &BI;
1594     }
1595
1596   // Cannonicalize icmp_ne -> icmp_eq
1597   ICmpInst::Predicate IPred;
1598   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
1599                       TrueDest, FalseDest)) &&
1600       BI.getCondition()->hasOneUse())
1601     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
1602         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
1603         IPred == ICmpInst::ICMP_SGE) {
1604       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
1605       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
1606       // Swap Destinations and condition.
1607       BI.swapSuccessors();
1608       Worklist.Add(Cond);
1609       return &BI;
1610     }
1611
1612   return 0;
1613 }
1614
1615 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
1616   Value *Cond = SI.getCondition();
1617   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
1618     if (I->getOpcode() == Instruction::Add)
1619       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1620         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
1621         // Skip the first item since that's the default case.
1622         for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
1623              i != e; ++i) {
1624           ConstantInt* CaseVal = i.getCaseValue();
1625           Constant* NewCaseVal = ConstantExpr::getSub(cast<Constant>(CaseVal),
1626                                                       AddRHS);
1627           assert(isa<ConstantInt>(NewCaseVal) &&
1628                  "Result of expression should be constant");
1629           i.setValue(cast<ConstantInt>(NewCaseVal));
1630         }
1631         SI.setCondition(I->getOperand(0));
1632         Worklist.Add(I);
1633         return &SI;
1634       }
1635   }
1636   return 0;
1637 }
1638
1639 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
1640   Value *Agg = EV.getAggregateOperand();
1641
1642   if (!EV.hasIndices())
1643     return ReplaceInstUsesWith(EV, Agg);
1644
1645   if (Constant *C = dyn_cast<Constant>(Agg)) {
1646     if (Constant *C2 = C->getAggregateElement(*EV.idx_begin())) {
1647       if (EV.getNumIndices() == 0)
1648         return ReplaceInstUsesWith(EV, C2);
1649       // Extract the remaining indices out of the constant indexed by the
1650       // first index
1651       return ExtractValueInst::Create(C2, EV.getIndices().slice(1));
1652     }
1653     return 0; // Can't handle other constants
1654   }
1655
1656   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
1657     // We're extracting from an insertvalue instruction, compare the indices
1658     const unsigned *exti, *exte, *insi, *inse;
1659     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
1660          exte = EV.idx_end(), inse = IV->idx_end();
1661          exti != exte && insi != inse;
1662          ++exti, ++insi) {
1663       if (*insi != *exti)
1664         // The insert and extract both reference distinctly different elements.
1665         // This means the extract is not influenced by the insert, and we can
1666         // replace the aggregate operand of the extract with the aggregate
1667         // operand of the insert. i.e., replace
1668         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1669         // %E = extractvalue { i32, { i32 } } %I, 0
1670         // with
1671         // %E = extractvalue { i32, { i32 } } %A, 0
1672         return ExtractValueInst::Create(IV->getAggregateOperand(),
1673                                         EV.getIndices());
1674     }
1675     if (exti == exte && insi == inse)
1676       // Both iterators are at the end: Index lists are identical. Replace
1677       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1678       // %C = extractvalue { i32, { i32 } } %B, 1, 0
1679       // with "i32 42"
1680       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
1681     if (exti == exte) {
1682       // The extract list is a prefix of the insert list. i.e. replace
1683       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1684       // %E = extractvalue { i32, { i32 } } %I, 1
1685       // with
1686       // %X = extractvalue { i32, { i32 } } %A, 1
1687       // %E = insertvalue { i32 } %X, i32 42, 0
1688       // by switching the order of the insert and extract (though the
1689       // insertvalue should be left in, since it may have other uses).
1690       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
1691                                                  EV.getIndices());
1692       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
1693                                      makeArrayRef(insi, inse));
1694     }
1695     if (insi == inse)
1696       // The insert list is a prefix of the extract list
1697       // We can simply remove the common indices from the extract and make it
1698       // operate on the inserted value instead of the insertvalue result.
1699       // i.e., replace
1700       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1701       // %E = extractvalue { i32, { i32 } } %I, 1, 0
1702       // with
1703       // %E extractvalue { i32 } { i32 42 }, 0
1704       return ExtractValueInst::Create(IV->getInsertedValueOperand(),
1705                                       makeArrayRef(exti, exte));
1706   }
1707   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
1708     // We're extracting from an intrinsic, see if we're the only user, which
1709     // allows us to simplify multiple result intrinsics to simpler things that
1710     // just get one value.
1711     if (II->hasOneUse()) {
1712       // Check if we're grabbing the overflow bit or the result of a 'with
1713       // overflow' intrinsic.  If it's the latter we can remove the intrinsic
1714       // and replace it with a traditional binary instruction.
1715       switch (II->getIntrinsicID()) {
1716       case Intrinsic::uadd_with_overflow:
1717       case Intrinsic::sadd_with_overflow:
1718         if (*EV.idx_begin() == 0) {  // Normal result.
1719           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1720           ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
1721           EraseInstFromFunction(*II);
1722           return BinaryOperator::CreateAdd(LHS, RHS);
1723         }
1724
1725         // If the normal result of the add is dead, and the RHS is a constant,
1726         // we can transform this into a range comparison.
1727         // overflow = uadd a, -4  -->  overflow = icmp ugt a, 3
1728         if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
1729           if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
1730             return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
1731                                 ConstantExpr::getNot(CI));
1732         break;
1733       case Intrinsic::usub_with_overflow:
1734       case Intrinsic::ssub_with_overflow:
1735         if (*EV.idx_begin() == 0) {  // Normal result.
1736           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1737           ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
1738           EraseInstFromFunction(*II);
1739           return BinaryOperator::CreateSub(LHS, RHS);
1740         }
1741         break;
1742       case Intrinsic::umul_with_overflow:
1743       case Intrinsic::smul_with_overflow:
1744         if (*EV.idx_begin() == 0) {  // Normal result.
1745           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1746           ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
1747           EraseInstFromFunction(*II);
1748           return BinaryOperator::CreateMul(LHS, RHS);
1749         }
1750         break;
1751       default:
1752         break;
1753       }
1754     }
1755   }
1756   if (LoadInst *L = dyn_cast<LoadInst>(Agg))
1757     // If the (non-volatile) load only has one use, we can rewrite this to a
1758     // load from a GEP. This reduces the size of the load.
1759     // FIXME: If a load is used only by extractvalue instructions then this
1760     //        could be done regardless of having multiple uses.
1761     if (L->isSimple() && L->hasOneUse()) {
1762       // extractvalue has integer indices, getelementptr has Value*s. Convert.
1763       SmallVector<Value*, 4> Indices;
1764       // Prefix an i32 0 since we need the first element.
1765       Indices.push_back(Builder->getInt32(0));
1766       for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
1767             I != E; ++I)
1768         Indices.push_back(Builder->getInt32(*I));
1769
1770       // We need to insert these at the location of the old load, not at that of
1771       // the extractvalue.
1772       Builder->SetInsertPoint(L->getParent(), L);
1773       Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices);
1774       // Returning the load directly will cause the main loop to insert it in
1775       // the wrong spot, so use ReplaceInstUsesWith().
1776       return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
1777     }
1778   // We could simplify extracts from other values. Note that nested extracts may
1779   // already be simplified implicitly by the above: extract (extract (insert) )
1780   // will be translated into extract ( insert ( extract ) ) first and then just
1781   // the value inserted, if appropriate. Similarly for extracts from single-use
1782   // loads: extract (extract (load)) will be translated to extract (load (gep))
1783   // and if again single-use then via load (gep (gep)) to load (gep).
1784   // However, double extracts from e.g. function arguments or return values
1785   // aren't handled yet.
1786   return 0;
1787 }
1788
1789 enum Personality_Type {
1790   Unknown_Personality,
1791   GNU_Ada_Personality,
1792   GNU_CXX_Personality,
1793   GNU_ObjC_Personality
1794 };
1795
1796 /// RecognizePersonality - See if the given exception handling personality
1797 /// function is one that we understand.  If so, return a description of it;
1798 /// otherwise return Unknown_Personality.
1799 static Personality_Type RecognizePersonality(Value *Pers) {
1800   Function *F = dyn_cast<Function>(Pers->stripPointerCasts());
1801   if (!F)
1802     return Unknown_Personality;
1803   return StringSwitch<Personality_Type>(F->getName())
1804     .Case("__gnat_eh_personality", GNU_Ada_Personality)
1805     .Case("__gxx_personality_v0",  GNU_CXX_Personality)
1806     .Case("__objc_personality_v0", GNU_ObjC_Personality)
1807     .Default(Unknown_Personality);
1808 }
1809
1810 /// isCatchAll - Return 'true' if the given typeinfo will match anything.
1811 static bool isCatchAll(Personality_Type Personality, Constant *TypeInfo) {
1812   switch (Personality) {
1813   case Unknown_Personality:
1814     return false;
1815   case GNU_Ada_Personality:
1816     // While __gnat_all_others_value will match any Ada exception, it doesn't
1817     // match foreign exceptions (or didn't, before gcc-4.7).
1818     return false;
1819   case GNU_CXX_Personality:
1820   case GNU_ObjC_Personality:
1821     return TypeInfo->isNullValue();
1822   }
1823   llvm_unreachable("Unknown personality!");
1824 }
1825
1826 static bool shorter_filter(const Value *LHS, const Value *RHS) {
1827   return
1828     cast<ArrayType>(LHS->getType())->getNumElements()
1829   <
1830     cast<ArrayType>(RHS->getType())->getNumElements();
1831 }
1832
1833 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
1834   // The logic here should be correct for any real-world personality function.
1835   // However if that turns out not to be true, the offending logic can always
1836   // be conditioned on the personality function, like the catch-all logic is.
1837   Personality_Type Personality = RecognizePersonality(LI.getPersonalityFn());
1838
1839   // Simplify the list of clauses, eg by removing repeated catch clauses
1840   // (these are often created by inlining).
1841   bool MakeNewInstruction = false; // If true, recreate using the following:
1842   SmallVector<Value *, 16> NewClauses; // - Clauses for the new instruction;
1843   bool CleanupFlag = LI.isCleanup();   // - The new instruction is a cleanup.
1844
1845   SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
1846   for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
1847     bool isLastClause = i + 1 == e;
1848     if (LI.isCatch(i)) {
1849       // A catch clause.
1850       Value *CatchClause = LI.getClause(i);
1851       Constant *TypeInfo = cast<Constant>(CatchClause->stripPointerCasts());
1852
1853       // If we already saw this clause, there is no point in having a second
1854       // copy of it.
1855       if (AlreadyCaught.insert(TypeInfo)) {
1856         // This catch clause was not already seen.
1857         NewClauses.push_back(CatchClause);
1858       } else {
1859         // Repeated catch clause - drop the redundant copy.
1860         MakeNewInstruction = true;
1861       }
1862
1863       // If this is a catch-all then there is no point in keeping any following
1864       // clauses or marking the landingpad as having a cleanup.
1865       if (isCatchAll(Personality, TypeInfo)) {
1866         if (!isLastClause)
1867           MakeNewInstruction = true;
1868         CleanupFlag = false;
1869         break;
1870       }
1871     } else {
1872       // A filter clause.  If any of the filter elements were already caught
1873       // then they can be dropped from the filter.  It is tempting to try to
1874       // exploit the filter further by saying that any typeinfo that does not
1875       // occur in the filter can't be caught later (and thus can be dropped).
1876       // However this would be wrong, since typeinfos can match without being
1877       // equal (for example if one represents a C++ class, and the other some
1878       // class derived from it).
1879       assert(LI.isFilter(i) && "Unsupported landingpad clause!");
1880       Value *FilterClause = LI.getClause(i);
1881       ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
1882       unsigned NumTypeInfos = FilterType->getNumElements();
1883
1884       // An empty filter catches everything, so there is no point in keeping any
1885       // following clauses or marking the landingpad as having a cleanup.  By
1886       // dealing with this case here the following code is made a bit simpler.
1887       if (!NumTypeInfos) {
1888         NewClauses.push_back(FilterClause);
1889         if (!isLastClause)
1890           MakeNewInstruction = true;
1891         CleanupFlag = false;
1892         break;
1893       }
1894
1895       bool MakeNewFilter = false; // If true, make a new filter.
1896       SmallVector<Constant *, 16> NewFilterElts; // New elements.
1897       if (isa<ConstantAggregateZero>(FilterClause)) {
1898         // Not an empty filter - it contains at least one null typeinfo.
1899         assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
1900         Constant *TypeInfo =
1901           Constant::getNullValue(FilterType->getElementType());
1902         // If this typeinfo is a catch-all then the filter can never match.
1903         if (isCatchAll(Personality, TypeInfo)) {
1904           // Throw the filter away.
1905           MakeNewInstruction = true;
1906           continue;
1907         }
1908
1909         // There is no point in having multiple copies of this typeinfo, so
1910         // discard all but the first copy if there is more than one.
1911         NewFilterElts.push_back(TypeInfo);
1912         if (NumTypeInfos > 1)
1913           MakeNewFilter = true;
1914       } else {
1915         ConstantArray *Filter = cast<ConstantArray>(FilterClause);
1916         SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
1917         NewFilterElts.reserve(NumTypeInfos);
1918
1919         // Remove any filter elements that were already caught or that already
1920         // occurred in the filter.  While there, see if any of the elements are
1921         // catch-alls.  If so, the filter can be discarded.
1922         bool SawCatchAll = false;
1923         for (unsigned j = 0; j != NumTypeInfos; ++j) {
1924           Value *Elt = Filter->getOperand(j);
1925           Constant *TypeInfo = cast<Constant>(Elt->stripPointerCasts());
1926           if (isCatchAll(Personality, TypeInfo)) {
1927             // This element is a catch-all.  Bail out, noting this fact.
1928             SawCatchAll = true;
1929             break;
1930           }
1931           if (AlreadyCaught.count(TypeInfo))
1932             // Already caught by an earlier clause, so having it in the filter
1933             // is pointless.
1934             continue;
1935           // There is no point in having multiple copies of the same typeinfo in
1936           // a filter, so only add it if we didn't already.
1937           if (SeenInFilter.insert(TypeInfo))
1938             NewFilterElts.push_back(cast<Constant>(Elt));
1939         }
1940         // A filter containing a catch-all cannot match anything by definition.
1941         if (SawCatchAll) {
1942           // Throw the filter away.
1943           MakeNewInstruction = true;
1944           continue;
1945         }
1946
1947         // If we dropped something from the filter, make a new one.
1948         if (NewFilterElts.size() < NumTypeInfos)
1949           MakeNewFilter = true;
1950       }
1951       if (MakeNewFilter) {
1952         FilterType = ArrayType::get(FilterType->getElementType(),
1953                                     NewFilterElts.size());
1954         FilterClause = ConstantArray::get(FilterType, NewFilterElts);
1955         MakeNewInstruction = true;
1956       }
1957
1958       NewClauses.push_back(FilterClause);
1959
1960       // If the new filter is empty then it will catch everything so there is
1961       // no point in keeping any following clauses or marking the landingpad
1962       // as having a cleanup.  The case of the original filter being empty was
1963       // already handled above.
1964       if (MakeNewFilter && !NewFilterElts.size()) {
1965         assert(MakeNewInstruction && "New filter but not a new instruction!");
1966         CleanupFlag = false;
1967         break;
1968       }
1969     }
1970   }
1971
1972   // If several filters occur in a row then reorder them so that the shortest
1973   // filters come first (those with the smallest number of elements).  This is
1974   // advantageous because shorter filters are more likely to match, speeding up
1975   // unwinding, but mostly because it increases the effectiveness of the other
1976   // filter optimizations below.
1977   for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
1978     unsigned j;
1979     // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
1980     for (j = i; j != e; ++j)
1981       if (!isa<ArrayType>(NewClauses[j]->getType()))
1982         break;
1983
1984     // Check whether the filters are already sorted by length.  We need to know
1985     // if sorting them is actually going to do anything so that we only make a
1986     // new landingpad instruction if it does.
1987     for (unsigned k = i; k + 1 < j; ++k)
1988       if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
1989         // Not sorted, so sort the filters now.  Doing an unstable sort would be
1990         // correct too but reordering filters pointlessly might confuse users.
1991         std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
1992                          shorter_filter);
1993         MakeNewInstruction = true;
1994         break;
1995       }
1996
1997     // Look for the next batch of filters.
1998     i = j + 1;
1999   }
2000
2001   // If typeinfos matched if and only if equal, then the elements of a filter L
2002   // that occurs later than a filter F could be replaced by the intersection of
2003   // the elements of F and L.  In reality two typeinfos can match without being
2004   // equal (for example if one represents a C++ class, and the other some class
2005   // derived from it) so it would be wrong to perform this transform in general.
2006   // However the transform is correct and useful if F is a subset of L.  In that
2007   // case L can be replaced by F, and thus removed altogether since repeating a
2008   // filter is pointless.  So here we look at all pairs of filters F and L where
2009   // L follows F in the list of clauses, and remove L if every element of F is
2010   // an element of L.  This can occur when inlining C++ functions with exception
2011   // specifications.
2012   for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2013     // Examine each filter in turn.
2014     Value *Filter = NewClauses[i];
2015     ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2016     if (!FTy)
2017       // Not a filter - skip it.
2018       continue;
2019     unsigned FElts = FTy->getNumElements();
2020     // Examine each filter following this one.  Doing this backwards means that
2021     // we don't have to worry about filters disappearing under us when removed.
2022     for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2023       Value *LFilter = NewClauses[j];
2024       ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2025       if (!LTy)
2026         // Not a filter - skip it.
2027         continue;
2028       // If Filter is a subset of LFilter, i.e. every element of Filter is also
2029       // an element of LFilter, then discard LFilter.
2030       SmallVector<Value *, 16>::iterator J = NewClauses.begin() + j;
2031       // If Filter is empty then it is a subset of LFilter.
2032       if (!FElts) {
2033         // Discard LFilter.
2034         NewClauses.erase(J);
2035         MakeNewInstruction = true;
2036         // Move on to the next filter.
2037         continue;
2038       }
2039       unsigned LElts = LTy->getNumElements();
2040       // If Filter is longer than LFilter then it cannot be a subset of it.
2041       if (FElts > LElts)
2042         // Move on to the next filter.
2043         continue;
2044       // At this point we know that LFilter has at least one element.
2045       if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
2046         // Filter is a subset of LFilter iff Filter contains only zeros (as we
2047         // already know that Filter is not longer than LFilter).
2048         if (isa<ConstantAggregateZero>(Filter)) {
2049           assert(FElts <= LElts && "Should have handled this case earlier!");
2050           // Discard LFilter.
2051           NewClauses.erase(J);
2052           MakeNewInstruction = true;
2053         }
2054         // Move on to the next filter.
2055         continue;
2056       }
2057       ConstantArray *LArray = cast<ConstantArray>(LFilter);
2058       if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2059         // Since Filter is non-empty and contains only zeros, it is a subset of
2060         // LFilter iff LFilter contains a zero.
2061         assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2062         for (unsigned l = 0; l != LElts; ++l)
2063           if (LArray->getOperand(l)->isNullValue()) {
2064             // LFilter contains a zero - discard it.
2065             NewClauses.erase(J);
2066             MakeNewInstruction = true;
2067             break;
2068           }
2069         // Move on to the next filter.
2070         continue;
2071       }
2072       // At this point we know that both filters are ConstantArrays.  Loop over
2073       // operands to see whether every element of Filter is also an element of
2074       // LFilter.  Since filters tend to be short this is probably faster than
2075       // using a method that scales nicely.
2076       ConstantArray *FArray = cast<ConstantArray>(Filter);
2077       bool AllFound = true;
2078       for (unsigned f = 0; f != FElts; ++f) {
2079         Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2080         AllFound = false;
2081         for (unsigned l = 0; l != LElts; ++l) {
2082           Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2083           if (LTypeInfo == FTypeInfo) {
2084             AllFound = true;
2085             break;
2086           }
2087         }
2088         if (!AllFound)
2089           break;
2090       }
2091       if (AllFound) {
2092         // Discard LFilter.
2093         NewClauses.erase(J);
2094         MakeNewInstruction = true;
2095       }
2096       // Move on to the next filter.
2097     }
2098   }
2099
2100   // If we changed any of the clauses, replace the old landingpad instruction
2101   // with a new one.
2102   if (MakeNewInstruction) {
2103     LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
2104                                                  LI.getPersonalityFn(),
2105                                                  NewClauses.size());
2106     for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2107       NLI->addClause(NewClauses[i]);
2108     // A landing pad with no clauses must have the cleanup flag set.  It is
2109     // theoretically possible, though highly unlikely, that we eliminated all
2110     // clauses.  If so, force the cleanup flag to true.
2111     if (NewClauses.empty())
2112       CleanupFlag = true;
2113     NLI->setCleanup(CleanupFlag);
2114     return NLI;
2115   }
2116
2117   // Even if none of the clauses changed, we may nonetheless have understood
2118   // that the cleanup flag is pointless.  Clear it if so.
2119   if (LI.isCleanup() != CleanupFlag) {
2120     assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2121     LI.setCleanup(CleanupFlag);
2122     return &LI;
2123   }
2124
2125   return 0;
2126 }
2127
2128
2129
2130
2131 /// TryToSinkInstruction - Try to move the specified instruction from its
2132 /// current block into the beginning of DestBlock, which can only happen if it's
2133 /// safe to move the instruction past all of the instructions between it and the
2134 /// end of its block.
2135 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2136   assert(I->hasOneUse() && "Invariants didn't hold!");
2137
2138   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
2139   if (isa<PHINode>(I) || isa<LandingPadInst>(I) || I->mayHaveSideEffects() ||
2140       isa<TerminatorInst>(I))
2141     return false;
2142
2143   // Do not sink alloca instructions out of the entry block.
2144   if (isa<AllocaInst>(I) && I->getParent() ==
2145         &DestBlock->getParent()->getEntryBlock())
2146     return false;
2147
2148   // We can only sink load instructions if there is nothing between the load and
2149   // the end of block that could change the value.
2150   if (I->mayReadFromMemory()) {
2151     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
2152          Scan != E; ++Scan)
2153       if (Scan->mayWriteToMemory())
2154         return false;
2155   }
2156
2157   BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
2158   I->moveBefore(InsertPos);
2159   ++NumSunkInst;
2160   return true;
2161 }
2162
2163
2164 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
2165 /// all reachable code to the worklist.
2166 ///
2167 /// This has a couple of tricks to make the code faster and more powerful.  In
2168 /// particular, we constant fold and DCE instructions as we go, to avoid adding
2169 /// them to the worklist (this significantly speeds up instcombine on code where
2170 /// many instructions are dead or constant).  Additionally, if we find a branch
2171 /// whose condition is a known constant, we only visit the reachable successors.
2172 ///
2173 static bool AddReachableCodeToWorklist(BasicBlock *BB,
2174                                        SmallPtrSet<BasicBlock*, 64> &Visited,
2175                                        InstCombiner &IC,
2176                                        const DataLayout *TD,
2177                                        const TargetLibraryInfo *TLI) {
2178   bool MadeIRChange = false;
2179   SmallVector<BasicBlock*, 256> Worklist;
2180   Worklist.push_back(BB);
2181
2182   SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
2183   DenseMap<ConstantExpr*, Constant*> FoldedConstants;
2184
2185   do {
2186     BB = Worklist.pop_back_val();
2187
2188     // We have now visited this block!  If we've already been here, ignore it.
2189     if (!Visited.insert(BB)) continue;
2190
2191     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
2192       Instruction *Inst = BBI++;
2193
2194       // DCE instruction if trivially dead.
2195       if (isInstructionTriviallyDead(Inst, TLI)) {
2196         ++NumDeadInst;
2197         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
2198         Inst->eraseFromParent();
2199         continue;
2200       }
2201
2202       // ConstantProp instruction if trivially constant.
2203       if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
2204         if (Constant *C = ConstantFoldInstruction(Inst, TD, TLI)) {
2205           DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
2206                        << *Inst << '\n');
2207           Inst->replaceAllUsesWith(C);
2208           ++NumConstProp;
2209           Inst->eraseFromParent();
2210           continue;
2211         }
2212
2213       if (TD) {
2214         // See if we can constant fold its operands.
2215         for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
2216              i != e; ++i) {
2217           ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
2218           if (CE == 0) continue;
2219
2220           Constant*& FoldRes = FoldedConstants[CE];
2221           if (!FoldRes)
2222             FoldRes = ConstantFoldConstantExpression(CE, TD, TLI);
2223           if (!FoldRes)
2224             FoldRes = CE;
2225
2226           if (FoldRes != CE) {
2227             *i = FoldRes;
2228             MadeIRChange = true;
2229           }
2230         }
2231       }
2232
2233       InstrsForInstCombineWorklist.push_back(Inst);
2234     }
2235
2236     // Recursively visit successors.  If this is a branch or switch on a
2237     // constant, only visit the reachable successor.
2238     TerminatorInst *TI = BB->getTerminator();
2239     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2240       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
2241         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
2242         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
2243         Worklist.push_back(ReachableBB);
2244         continue;
2245       }
2246     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2247       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
2248         // See if this is an explicit destination.
2249         for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
2250              i != e; ++i)
2251           if (i.getCaseValue() == Cond) {
2252             BasicBlock *ReachableBB = i.getCaseSuccessor();
2253             Worklist.push_back(ReachableBB);
2254             continue;
2255           }
2256
2257         // Otherwise it is the default destination.
2258         Worklist.push_back(SI->getDefaultDest());
2259         continue;
2260       }
2261     }
2262
2263     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
2264       Worklist.push_back(TI->getSuccessor(i));
2265   } while (!Worklist.empty());
2266
2267   // Once we've found all of the instructions to add to instcombine's worklist,
2268   // add them in reverse order.  This way instcombine will visit from the top
2269   // of the function down.  This jives well with the way that it adds all uses
2270   // of instructions to the worklist after doing a transformation, thus avoiding
2271   // some N^2 behavior in pathological cases.
2272   IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
2273                               InstrsForInstCombineWorklist.size());
2274
2275   return MadeIRChange;
2276 }
2277
2278 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
2279   MadeIRChange = false;
2280
2281   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
2282                << F.getName() << "\n");
2283
2284   {
2285     // Do a depth-first traversal of the function, populate the worklist with
2286     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
2287     // track of which blocks we visit.
2288     SmallPtrSet<BasicBlock*, 64> Visited;
2289     MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD,
2290                                                TLI);
2291
2292     // Do a quick scan over the function.  If we find any blocks that are
2293     // unreachable, remove any instructions inside of them.  This prevents
2294     // the instcombine code from having to deal with some bad special cases.
2295     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2296       if (Visited.count(BB)) continue;
2297
2298       // Delete the instructions backwards, as it has a reduced likelihood of
2299       // having to update as many def-use and use-def chains.
2300       Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
2301       while (EndInst != BB->begin()) {
2302         // Delete the next to last instruction.
2303         BasicBlock::iterator I = EndInst;
2304         Instruction *Inst = --I;
2305         if (!Inst->use_empty())
2306           Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
2307         if (isa<LandingPadInst>(Inst)) {
2308           EndInst = Inst;
2309           continue;
2310         }
2311         if (!isa<DbgInfoIntrinsic>(Inst)) {
2312           ++NumDeadInst;
2313           MadeIRChange = true;
2314         }
2315         Inst->eraseFromParent();
2316       }
2317     }
2318   }
2319
2320   while (!Worklist.isEmpty()) {
2321     Instruction *I = Worklist.RemoveOne();
2322     if (I == 0) continue;  // skip null values.
2323
2324     // Check to see if we can DCE the instruction.
2325     if (isInstructionTriviallyDead(I, TLI)) {
2326       DEBUG(errs() << "IC: DCE: " << *I << '\n');
2327       EraseInstFromFunction(*I);
2328       ++NumDeadInst;
2329       MadeIRChange = true;
2330       continue;
2331     }
2332
2333     // Instruction isn't dead, see if we can constant propagate it.
2334     if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
2335       if (Constant *C = ConstantFoldInstruction(I, TD, TLI)) {
2336         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
2337
2338         // Add operands to the worklist.
2339         ReplaceInstUsesWith(*I, C);
2340         ++NumConstProp;
2341         EraseInstFromFunction(*I);
2342         MadeIRChange = true;
2343         continue;
2344       }
2345
2346     // See if we can trivially sink this instruction to a successor basic block.
2347     if (I->hasOneUse()) {
2348       BasicBlock *BB = I->getParent();
2349       Instruction *UserInst = cast<Instruction>(I->use_back());
2350       BasicBlock *UserParent;
2351
2352       // Get the block the use occurs in.
2353       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
2354         UserParent = PN->getIncomingBlock(I->use_begin().getUse());
2355       else
2356         UserParent = UserInst->getParent();
2357
2358       if (UserParent != BB) {
2359         bool UserIsSuccessor = false;
2360         // See if the user is one of our successors.
2361         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2362           if (*SI == UserParent) {
2363             UserIsSuccessor = true;
2364             break;
2365           }
2366
2367         // If the user is one of our immediate successors, and if that successor
2368         // only has us as a predecessors (we'd have to split the critical edge
2369         // otherwise), we can keep going.
2370         if (UserIsSuccessor && UserParent->getSinglePredecessor())
2371           // Okay, the CFG is simple enough, try to sink this instruction.
2372           MadeIRChange |= TryToSinkInstruction(I, UserParent);
2373       }
2374     }
2375
2376     // Now that we have an instruction, try combining it to simplify it.
2377     Builder->SetInsertPoint(I->getParent(), I);
2378     Builder->SetCurrentDebugLocation(I->getDebugLoc());
2379
2380 #ifndef NDEBUG
2381     std::string OrigI;
2382 #endif
2383     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
2384     DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
2385
2386     if (Instruction *Result = visit(*I)) {
2387       ++NumCombined;
2388       // Should we replace the old instruction with a new one?
2389       if (Result != I) {
2390         DEBUG(errs() << "IC: Old = " << *I << '\n'
2391                      << "    New = " << *Result << '\n');
2392
2393         if (!I->getDebugLoc().isUnknown())
2394           Result->setDebugLoc(I->getDebugLoc());
2395         // Everything uses the new instruction now.
2396         I->replaceAllUsesWith(Result);
2397
2398         // Move the name to the new instruction first.
2399         Result->takeName(I);
2400
2401         // Push the new instruction and any users onto the worklist.
2402         Worklist.Add(Result);
2403         Worklist.AddUsersToWorkList(*Result);
2404
2405         // Insert the new instruction into the basic block...
2406         BasicBlock *InstParent = I->getParent();
2407         BasicBlock::iterator InsertPos = I;
2408
2409         // If we replace a PHI with something that isn't a PHI, fix up the
2410         // insertion point.
2411         if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2412           InsertPos = InstParent->getFirstInsertionPt();
2413
2414         InstParent->getInstList().insert(InsertPos, Result);
2415
2416         EraseInstFromFunction(*I);
2417       } else {
2418 #ifndef NDEBUG
2419         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
2420                      << "    New = " << *I << '\n');
2421 #endif
2422
2423         // If the instruction was modified, it's possible that it is now dead.
2424         // if so, remove it.
2425         if (isInstructionTriviallyDead(I, TLI)) {
2426           EraseInstFromFunction(*I);
2427         } else {
2428           Worklist.Add(I);
2429           Worklist.AddUsersToWorkList(*I);
2430         }
2431       }
2432       MadeIRChange = true;
2433     }
2434   }
2435
2436   Worklist.Zap();
2437   return MadeIRChange;
2438 }
2439
2440 namespace {
2441 class InstCombinerLibCallSimplifier : public LibCallSimplifier {
2442   InstCombiner *IC;
2443 public:
2444   InstCombinerLibCallSimplifier(const DataLayout *TD,
2445                                 const TargetLibraryInfo *TLI,
2446                                 InstCombiner *IC)
2447     : LibCallSimplifier(TD, TLI, UnsafeFPShrink) {
2448     this->IC = IC;
2449   }
2450
2451   /// replaceAllUsesWith - override so that instruction replacement
2452   /// can be defined in terms of the instruction combiner framework.
2453   virtual void replaceAllUsesWith(Instruction *I, Value *With) const {
2454     IC->ReplaceInstUsesWith(*I, With);
2455   }
2456 };
2457 }
2458
2459 bool InstCombiner::runOnFunction(Function &F) {
2460   TD = getAnalysisIfAvailable<DataLayout>();
2461   TLI = &getAnalysis<TargetLibraryInfo>();
2462   // Minimizing size?
2463   MinimizeSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
2464                                                 Attribute::MinSize);
2465
2466   /// Builder - This is an IRBuilder that automatically inserts new
2467   /// instructions into the worklist when they are created.
2468   IRBuilder<true, TargetFolder, InstCombineIRInserter>
2469     TheBuilder(F.getContext(), TargetFolder(TD),
2470                InstCombineIRInserter(Worklist));
2471   Builder = &TheBuilder;
2472
2473   InstCombinerLibCallSimplifier TheSimplifier(TD, TLI, this);
2474   Simplifier = &TheSimplifier;
2475
2476   bool EverMadeChange = false;
2477
2478   // Lower dbg.declare intrinsics otherwise their value may be clobbered
2479   // by instcombiner.
2480   EverMadeChange = LowerDbgDeclare(F);
2481
2482   // Iterate while there is work to do.
2483   unsigned Iteration = 0;
2484   while (DoOneIteration(F, Iteration++))
2485     EverMadeChange = true;
2486
2487   Builder = 0;
2488   return EverMadeChange;
2489 }
2490
2491 FunctionPass *llvm::createInstructionCombiningPass() {
2492   return new InstCombiner();
2493 }