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