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