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