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