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   if (auto *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1949     Value *SrcOp = BCI->getOperand(0);
1950     PointerType *SrcType = cast<PointerType>(BCI->getSrcTy());
1951     Type *SrcEltType = SrcType->getElementType();
1952 
1953     // GEP directly using the source operand if this GEP is accessing an element
1954     // of a bitcasted pointer to vector or array of the same dimensions:
1955     // gep (bitcast <c x ty>* X to [c x ty]*), Y, Z --> gep X, Y, Z
1956     // gep (bitcast [c x ty]* X to <c x ty>*), Y, Z --> gep X, Y, Z
1957     auto areMatchingArrayAndVecTypes = [](Type *ArrTy, Type *VecTy) {
1958       return ArrTy->getArrayElementType() == VecTy->getVectorElementType() &&
1959              ArrTy->getArrayNumElements() == VecTy->getVectorNumElements();
1960     };
1961     if (GEP.getNumOperands() == 3 &&
1962         ((GEPEltType->isArrayTy() && SrcEltType->isVectorTy() &&
1963           areMatchingArrayAndVecTypes(GEPEltType, SrcEltType)) ||
1964          (GEPEltType->isVectorTy() && SrcEltType->isArrayTy() &&
1965           areMatchingArrayAndVecTypes(SrcEltType, GEPEltType)))) {
1966       GEP.setOperand(0, SrcOp);
1967       GEP.setSourceElementType(SrcEltType);
1968       return &GEP;
1969     }
1970 
1971     // See if we can simplify:
1972     //   X = bitcast A* to B*
1973     //   Y = gep X, <...constant indices...>
1974     // into a gep of the original struct. This is important for SROA and alias
1975     // analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
1976     unsigned OffsetBits = DL.getIndexTypeSizeInBits(GEPType);
1977     APInt Offset(OffsetBits, 0);
1978     if (!isa<BitCastInst>(SrcOp) && GEP.accumulateConstantOffset(DL, Offset)) {
1979       // If this GEP instruction doesn't move the pointer, just replace the GEP
1980       // with a bitcast of the real input to the dest type.
1981       if (!Offset) {
1982         // If the bitcast is of an allocation, and the allocation will be
1983         // converted to match the type of the cast, don't touch this.
1984         if (isa<AllocaInst>(SrcOp) || isAllocationFn(SrcOp, &TLI)) {
1985           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1986           if (Instruction *I = visitBitCast(*BCI)) {
1987             if (I != BCI) {
1988               I->takeName(BCI);
1989               BCI->getParent()->getInstList().insert(BCI->getIterator(), I);
1990               replaceInstUsesWith(*BCI, I);
1991             }
1992             return &GEP;
1993           }
1994         }
1995 
1996         if (SrcType->getPointerAddressSpace() != GEP.getAddressSpace())
1997           return new AddrSpaceCastInst(SrcOp, GEPType);
1998         return new BitCastInst(SrcOp, GEPType);
1999       }
2000 
2001       // Otherwise, if the offset is non-zero, we need to find out if there is a
2002       // field at Offset in 'A's type.  If so, we can pull the cast through the
2003       // GEP.
2004       SmallVector<Value*, 8> NewIndices;
2005       if (FindElementAtOffset(SrcType, Offset.getSExtValue(), NewIndices)) {
2006         Value *NGEP =
2007             GEP.isInBounds()
2008                 ? Builder.CreateInBoundsGEP(nullptr, SrcOp, NewIndices)
2009                 : Builder.CreateGEP(nullptr, SrcOp, NewIndices);
2010 
2011         if (NGEP->getType() == GEPType)
2012           return replaceInstUsesWith(GEP, NGEP);
2013         NGEP->takeName(&GEP);
2014 
2015         if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
2016           return new AddrSpaceCastInst(NGEP, GEPType);
2017         return new BitCastInst(NGEP, GEPType);
2018       }
2019     }
2020   }
2021 
2022   if (!GEP.isInBounds()) {
2023     unsigned IdxWidth =
2024         DL.getIndexSizeInBits(PtrOp->getType()->getPointerAddressSpace());
2025     APInt BasePtrOffset(IdxWidth, 0);
2026     Value *UnderlyingPtrOp =
2027             PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL,
2028                                                              BasePtrOffset);
2029     if (auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) {
2030       if (GEP.accumulateConstantOffset(DL, BasePtrOffset) &&
2031           BasePtrOffset.isNonNegative()) {
2032         APInt AllocSize(IdxWidth, DL.getTypeAllocSize(AI->getAllocatedType()));
2033         if (BasePtrOffset.ule(AllocSize)) {
2034           return GetElementPtrInst::CreateInBounds(
2035               PtrOp, makeArrayRef(Ops).slice(1), GEP.getName());
2036         }
2037       }
2038     }
2039   }
2040 
2041   return nullptr;
2042 }
2043 
2044 static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI,
2045                                          Instruction *AI) {
2046   if (isa<ConstantPointerNull>(V))
2047     return true;
2048   if (auto *LI = dyn_cast<LoadInst>(V))
2049     return isa<GlobalVariable>(LI->getPointerOperand());
2050   // Two distinct allocations will never be equal.
2051   // We rely on LookThroughBitCast in isAllocLikeFn being false, since looking
2052   // through bitcasts of V can cause
2053   // the result statement below to be true, even when AI and V (ex:
2054   // i8* ->i32* ->i8* of AI) are the same allocations.
2055   return isAllocLikeFn(V, TLI) && V != AI;
2056 }
2057 
2058 static bool isAllocSiteRemovable(Instruction *AI,
2059                                  SmallVectorImpl<WeakTrackingVH> &Users,
2060                                  const TargetLibraryInfo *TLI) {
2061   SmallVector<Instruction*, 4> Worklist;
2062   Worklist.push_back(AI);
2063 
2064   do {
2065     Instruction *PI = Worklist.pop_back_val();
2066     for (User *U : PI->users()) {
2067       Instruction *I = cast<Instruction>(U);
2068       switch (I->getOpcode()) {
2069       default:
2070         // Give up the moment we see something we can't handle.
2071         return false;
2072 
2073       case Instruction::AddrSpaceCast:
2074       case Instruction::BitCast:
2075       case Instruction::GetElementPtr:
2076         Users.emplace_back(I);
2077         Worklist.push_back(I);
2078         continue;
2079 
2080       case Instruction::ICmp: {
2081         ICmpInst *ICI = cast<ICmpInst>(I);
2082         // We can fold eq/ne comparisons with null to false/true, respectively.
2083         // We also fold comparisons in some conditions provided the alloc has
2084         // not escaped (see isNeverEqualToUnescapedAlloc).
2085         if (!ICI->isEquality())
2086           return false;
2087         unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0;
2088         if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI))
2089           return false;
2090         Users.emplace_back(I);
2091         continue;
2092       }
2093 
2094       case Instruction::Call:
2095         // Ignore no-op and store intrinsics.
2096         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2097           switch (II->getIntrinsicID()) {
2098           default:
2099             return false;
2100 
2101           case Intrinsic::memmove:
2102           case Intrinsic::memcpy:
2103           case Intrinsic::memset: {
2104             MemIntrinsic *MI = cast<MemIntrinsic>(II);
2105             if (MI->isVolatile() || MI->getRawDest() != PI)
2106               return false;
2107             LLVM_FALLTHROUGH;
2108           }
2109           case Intrinsic::invariant_start:
2110           case Intrinsic::invariant_end:
2111           case Intrinsic::lifetime_start:
2112           case Intrinsic::lifetime_end:
2113           case Intrinsic::objectsize:
2114             Users.emplace_back(I);
2115             continue;
2116           }
2117         }
2118 
2119         if (isFreeCall(I, TLI)) {
2120           Users.emplace_back(I);
2121           continue;
2122         }
2123         return false;
2124 
2125       case Instruction::Store: {
2126         StoreInst *SI = cast<StoreInst>(I);
2127         if (SI->isVolatile() || SI->getPointerOperand() != PI)
2128           return false;
2129         Users.emplace_back(I);
2130         continue;
2131       }
2132       }
2133       llvm_unreachable("missing a return?");
2134     }
2135   } while (!Worklist.empty());
2136   return true;
2137 }
2138 
2139 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
2140   // If we have a malloc call which is only used in any amount of comparisons
2141   // to null and free calls, delete the calls and replace the comparisons with
2142   // true or false as appropriate.
2143   SmallVector<WeakTrackingVH, 64> Users;
2144 
2145   // If we are removing an alloca with a dbg.declare, insert dbg.value calls
2146   // before each store.
2147   TinyPtrVector<DbgInfoIntrinsic *> DIIs;
2148   std::unique_ptr<DIBuilder> DIB;
2149   if (isa<AllocaInst>(MI)) {
2150     DIIs = FindDbgAddrUses(&MI);
2151     DIB.reset(new DIBuilder(*MI.getModule(), /*AllowUnresolved=*/false));
2152   }
2153 
2154   if (isAllocSiteRemovable(&MI, Users, &TLI)) {
2155     for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2156       // Lowering all @llvm.objectsize calls first because they may
2157       // use a bitcast/GEP of the alloca we are removing.
2158       if (!Users[i])
2159        continue;
2160 
2161       Instruction *I = cast<Instruction>(&*Users[i]);
2162 
2163       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2164         if (II->getIntrinsicID() == Intrinsic::objectsize) {
2165           ConstantInt *Result = lowerObjectSizeCall(II, DL, &TLI,
2166                                                     /*MustSucceed=*/true);
2167           replaceInstUsesWith(*I, Result);
2168           eraseInstFromFunction(*I);
2169           Users[i] = nullptr; // Skip examining in the next loop.
2170         }
2171       }
2172     }
2173     for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2174       if (!Users[i])
2175         continue;
2176 
2177       Instruction *I = cast<Instruction>(&*Users[i]);
2178 
2179       if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
2180         replaceInstUsesWith(*C,
2181                             ConstantInt::get(Type::getInt1Ty(C->getContext()),
2182                                              C->isFalseWhenEqual()));
2183       } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I) ||
2184                  isa<AddrSpaceCastInst>(I)) {
2185         replaceInstUsesWith(*I, UndefValue::get(I->getType()));
2186       } else if (auto *SI = dyn_cast<StoreInst>(I)) {
2187         for (auto *DII : DIIs)
2188           ConvertDebugDeclareToDebugValue(DII, SI, *DIB);
2189       }
2190       eraseInstFromFunction(*I);
2191     }
2192 
2193     if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
2194       // Replace invoke with a NOP intrinsic to maintain the original CFG
2195       Module *M = II->getModule();
2196       Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
2197       InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
2198                          None, "", II->getParent());
2199     }
2200 
2201     for (auto *DII : DIIs)
2202       eraseInstFromFunction(*DII);
2203 
2204     return eraseInstFromFunction(MI);
2205   }
2206   return nullptr;
2207 }
2208 
2209 /// \brief Move the call to free before a NULL test.
2210 ///
2211 /// Check if this free is accessed after its argument has been test
2212 /// against NULL (property 0).
2213 /// If yes, it is legal to move this call in its predecessor block.
2214 ///
2215 /// The move is performed only if the block containing the call to free
2216 /// will be removed, i.e.:
2217 /// 1. it has only one predecessor P, and P has two successors
2218 /// 2. it contains the call and an unconditional branch
2219 /// 3. its successor is the same as its predecessor's successor
2220 ///
2221 /// The profitability is out-of concern here and this function should
2222 /// be called only if the caller knows this transformation would be
2223 /// profitable (e.g., for code size).
2224 static Instruction *
2225 tryToMoveFreeBeforeNullTest(CallInst &FI) {
2226   Value *Op = FI.getArgOperand(0);
2227   BasicBlock *FreeInstrBB = FI.getParent();
2228   BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
2229 
2230   // Validate part of constraint #1: Only one predecessor
2231   // FIXME: We can extend the number of predecessor, but in that case, we
2232   //        would duplicate the call to free in each predecessor and it may
2233   //        not be profitable even for code size.
2234   if (!PredBB)
2235     return nullptr;
2236 
2237   // Validate constraint #2: Does this block contains only the call to
2238   //                         free and an unconditional branch?
2239   // FIXME: We could check if we can speculate everything in the
2240   //        predecessor block
2241   if (FreeInstrBB->size() != 2)
2242     return nullptr;
2243   BasicBlock *SuccBB;
2244   if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
2245     return nullptr;
2246 
2247   // Validate the rest of constraint #1 by matching on the pred branch.
2248   TerminatorInst *TI = PredBB->getTerminator();
2249   BasicBlock *TrueBB, *FalseBB;
2250   ICmpInst::Predicate Pred;
2251   if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
2252     return nullptr;
2253   if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2254     return nullptr;
2255 
2256   // Validate constraint #3: Ensure the null case just falls through.
2257   if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
2258     return nullptr;
2259   assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
2260          "Broken CFG: missing edge from predecessor to successor");
2261 
2262   FI.moveBefore(TI);
2263   return &FI;
2264 }
2265 
2266 Instruction *InstCombiner::visitFree(CallInst &FI) {
2267   Value *Op = FI.getArgOperand(0);
2268 
2269   // free undef -> unreachable.
2270   if (isa<UndefValue>(Op)) {
2271     // Insert a new store to null because we cannot modify the CFG here.
2272     Builder.CreateStore(ConstantInt::getTrue(FI.getContext()),
2273                         UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
2274     return eraseInstFromFunction(FI);
2275   }
2276 
2277   // If we have 'free null' delete the instruction.  This can happen in stl code
2278   // when lots of inlining happens.
2279   if (isa<ConstantPointerNull>(Op))
2280     return eraseInstFromFunction(FI);
2281 
2282   // If we optimize for code size, try to move the call to free before the null
2283   // test so that simplify cfg can remove the empty block and dead code
2284   // elimination the branch. I.e., helps to turn something like:
2285   // if (foo) free(foo);
2286   // into
2287   // free(foo);
2288   if (MinimizeSize)
2289     if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
2290       return I;
2291 
2292   return nullptr;
2293 }
2294 
2295 Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
2296   if (RI.getNumOperands() == 0) // ret void
2297     return nullptr;
2298 
2299   Value *ResultOp = RI.getOperand(0);
2300   Type *VTy = ResultOp->getType();
2301   if (!VTy->isIntegerTy())
2302     return nullptr;
2303 
2304   // There might be assume intrinsics dominating this return that completely
2305   // determine the value. If so, constant fold it.
2306   KnownBits Known = computeKnownBits(ResultOp, 0, &RI);
2307   if (Known.isConstant())
2308     RI.setOperand(0, Constant::getIntegerValue(VTy, Known.getConstant()));
2309 
2310   return nullptr;
2311 }
2312 
2313 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2314   // Change br (not X), label True, label False to: br X, label False, True
2315   Value *X = nullptr;
2316   BasicBlock *TrueDest;
2317   BasicBlock *FalseDest;
2318   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
2319       !isa<Constant>(X)) {
2320     // Swap Destinations and condition...
2321     BI.setCondition(X);
2322     BI.swapSuccessors();
2323     return &BI;
2324   }
2325 
2326   // If the condition is irrelevant, remove the use so that other
2327   // transforms on the condition become more effective.
2328   if (BI.isConditional() && !isa<ConstantInt>(BI.getCondition()) &&
2329       BI.getSuccessor(0) == BI.getSuccessor(1)) {
2330     BI.setCondition(ConstantInt::getFalse(BI.getCondition()->getType()));
2331     return &BI;
2332   }
2333 
2334   // Canonicalize, for example, icmp_ne -> icmp_eq or fcmp_one -> fcmp_oeq.
2335   CmpInst::Predicate Pred;
2336   if (match(&BI, m_Br(m_OneUse(m_Cmp(Pred, m_Value(), m_Value())), TrueDest,
2337                       FalseDest)) &&
2338       !isCanonicalPredicate(Pred)) {
2339     // Swap destinations and condition.
2340     CmpInst *Cond = cast<CmpInst>(BI.getCondition());
2341     Cond->setPredicate(CmpInst::getInversePredicate(Pred));
2342     BI.swapSuccessors();
2343     Worklist.Add(Cond);
2344     return &BI;
2345   }
2346 
2347   return nullptr;
2348 }
2349 
2350 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2351   Value *Cond = SI.getCondition();
2352   Value *Op0;
2353   ConstantInt *AddRHS;
2354   if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) {
2355     // Change 'switch (X+4) case 1:' into 'switch (X) case -3'.
2356     for (auto Case : SI.cases()) {
2357       Constant *NewCase = ConstantExpr::getSub(Case.getCaseValue(), AddRHS);
2358       assert(isa<ConstantInt>(NewCase) &&
2359              "Result of expression should be constant");
2360       Case.setValue(cast<ConstantInt>(NewCase));
2361     }
2362     SI.setCondition(Op0);
2363     return &SI;
2364   }
2365 
2366   KnownBits Known = computeKnownBits(Cond, 0, &SI);
2367   unsigned LeadingKnownZeros = Known.countMinLeadingZeros();
2368   unsigned LeadingKnownOnes = Known.countMinLeadingOnes();
2369 
2370   // Compute the number of leading bits we can ignore.
2371   // TODO: A better way to determine this would use ComputeNumSignBits().
2372   for (auto &C : SI.cases()) {
2373     LeadingKnownZeros = std::min(
2374         LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2375     LeadingKnownOnes = std::min(
2376         LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2377   }
2378 
2379   unsigned NewWidth = Known.getBitWidth() - std::max(LeadingKnownZeros, LeadingKnownOnes);
2380 
2381   // Shrink the condition operand if the new type is smaller than the old type.
2382   // This may produce a non-standard type for the switch, but that's ok because
2383   // the backend should extend back to a legal type for the target.
2384   if (NewWidth > 0 && NewWidth < Known.getBitWidth()) {
2385     IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2386     Builder.SetInsertPoint(&SI);
2387     Value *NewCond = Builder.CreateTrunc(Cond, Ty, "trunc");
2388     SI.setCondition(NewCond);
2389 
2390     for (auto Case : SI.cases()) {
2391       APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth);
2392       Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));
2393     }
2394     return &SI;
2395   }
2396 
2397   return nullptr;
2398 }
2399 
2400 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
2401   Value *Agg = EV.getAggregateOperand();
2402 
2403   if (!EV.hasIndices())
2404     return replaceInstUsesWith(EV, Agg);
2405 
2406   if (Value *V = SimplifyExtractValueInst(Agg, EV.getIndices(),
2407                                           SQ.getWithInstruction(&EV)))
2408     return replaceInstUsesWith(EV, V);
2409 
2410   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2411     // We're extracting from an insertvalue instruction, compare the indices
2412     const unsigned *exti, *exte, *insi, *inse;
2413     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2414          exte = EV.idx_end(), inse = IV->idx_end();
2415          exti != exte && insi != inse;
2416          ++exti, ++insi) {
2417       if (*insi != *exti)
2418         // The insert and extract both reference distinctly different elements.
2419         // This means the extract is not influenced by the insert, and we can
2420         // replace the aggregate operand of the extract with the aggregate
2421         // operand of the insert. i.e., replace
2422         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2423         // %E = extractvalue { i32, { i32 } } %I, 0
2424         // with
2425         // %E = extractvalue { i32, { i32 } } %A, 0
2426         return ExtractValueInst::Create(IV->getAggregateOperand(),
2427                                         EV.getIndices());
2428     }
2429     if (exti == exte && insi == inse)
2430       // Both iterators are at the end: Index lists are identical. Replace
2431       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2432       // %C = extractvalue { i32, { i32 } } %B, 1, 0
2433       // with "i32 42"
2434       return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
2435     if (exti == exte) {
2436       // The extract list is a prefix of the insert list. i.e. replace
2437       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2438       // %E = extractvalue { i32, { i32 } } %I, 1
2439       // with
2440       // %X = extractvalue { i32, { i32 } } %A, 1
2441       // %E = insertvalue { i32 } %X, i32 42, 0
2442       // by switching the order of the insert and extract (though the
2443       // insertvalue should be left in, since it may have other uses).
2444       Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(),
2445                                                 EV.getIndices());
2446       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
2447                                      makeArrayRef(insi, inse));
2448     }
2449     if (insi == inse)
2450       // The insert list is a prefix of the extract list
2451       // We can simply remove the common indices from the extract and make it
2452       // operate on the inserted value instead of the insertvalue result.
2453       // i.e., replace
2454       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2455       // %E = extractvalue { i32, { i32 } } %I, 1, 0
2456       // with
2457       // %E extractvalue { i32 } { i32 42 }, 0
2458       return ExtractValueInst::Create(IV->getInsertedValueOperand(),
2459                                       makeArrayRef(exti, exte));
2460   }
2461   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2462     // We're extracting from an intrinsic, see if we're the only user, which
2463     // allows us to simplify multiple result intrinsics to simpler things that
2464     // just get one value.
2465     if (II->hasOneUse()) {
2466       // Check if we're grabbing the overflow bit or the result of a 'with
2467       // overflow' intrinsic.  If it's the latter we can remove the intrinsic
2468       // and replace it with a traditional binary instruction.
2469       switch (II->getIntrinsicID()) {
2470       case Intrinsic::uadd_with_overflow:
2471       case Intrinsic::sadd_with_overflow:
2472         if (*EV.idx_begin() == 0) {  // Normal result.
2473           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2474           replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2475           eraseInstFromFunction(*II);
2476           return BinaryOperator::CreateAdd(LHS, RHS);
2477         }
2478 
2479         // If the normal result of the add is dead, and the RHS is a constant,
2480         // we can transform this into a range comparison.
2481         // overflow = uadd a, -4  -->  overflow = icmp ugt a, 3
2482         if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2483           if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2484             return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2485                                 ConstantExpr::getNot(CI));
2486         break;
2487       case Intrinsic::usub_with_overflow:
2488       case Intrinsic::ssub_with_overflow:
2489         if (*EV.idx_begin() == 0) {  // Normal result.
2490           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2491           replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2492           eraseInstFromFunction(*II);
2493           return BinaryOperator::CreateSub(LHS, RHS);
2494         }
2495         break;
2496       case Intrinsic::umul_with_overflow:
2497       case Intrinsic::smul_with_overflow:
2498         if (*EV.idx_begin() == 0) {  // Normal result.
2499           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2500           replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2501           eraseInstFromFunction(*II);
2502           return BinaryOperator::CreateMul(LHS, RHS);
2503         }
2504         break;
2505       default:
2506         break;
2507       }
2508     }
2509   }
2510   if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2511     // If the (non-volatile) load only has one use, we can rewrite this to a
2512     // load from a GEP. This reduces the size of the load. If a load is used
2513     // only by extractvalue instructions then this either must have been
2514     // optimized before, or it is a struct with padding, in which case we
2515     // don't want to do the transformation as it loses padding knowledge.
2516     if (L->isSimple() && L->hasOneUse()) {
2517       // extractvalue has integer indices, getelementptr has Value*s. Convert.
2518       SmallVector<Value*, 4> Indices;
2519       // Prefix an i32 0 since we need the first element.
2520       Indices.push_back(Builder.getInt32(0));
2521       for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2522             I != E; ++I)
2523         Indices.push_back(Builder.getInt32(*I));
2524 
2525       // We need to insert these at the location of the old load, not at that of
2526       // the extractvalue.
2527       Builder.SetInsertPoint(L);
2528       Value *GEP = Builder.CreateInBoundsGEP(L->getType(),
2529                                              L->getPointerOperand(), Indices);
2530       Instruction *NL = Builder.CreateLoad(GEP);
2531       // Whatever aliasing information we had for the orignal load must also
2532       // hold for the smaller load, so propagate the annotations.
2533       AAMDNodes Nodes;
2534       L->getAAMetadata(Nodes);
2535       NL->setAAMetadata(Nodes);
2536       // Returning the load directly will cause the main loop to insert it in
2537       // the wrong spot, so use replaceInstUsesWith().
2538       return replaceInstUsesWith(EV, NL);
2539     }
2540   // We could simplify extracts from other values. Note that nested extracts may
2541   // already be simplified implicitly by the above: extract (extract (insert) )
2542   // will be translated into extract ( insert ( extract ) ) first and then just
2543   // the value inserted, if appropriate. Similarly for extracts from single-use
2544   // loads: extract (extract (load)) will be translated to extract (load (gep))
2545   // and if again single-use then via load (gep (gep)) to load (gep).
2546   // However, double extracts from e.g. function arguments or return values
2547   // aren't handled yet.
2548   return nullptr;
2549 }
2550 
2551 /// Return 'true' if the given typeinfo will match anything.
2552 static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
2553   switch (Personality) {
2554   case EHPersonality::GNU_C:
2555   case EHPersonality::GNU_C_SjLj:
2556   case EHPersonality::Rust:
2557     // The GCC C EH and Rust personality only exists to support cleanups, so
2558     // it's not clear what the semantics of catch clauses are.
2559     return false;
2560   case EHPersonality::Unknown:
2561     return false;
2562   case EHPersonality::GNU_Ada:
2563     // While __gnat_all_others_value will match any Ada exception, it doesn't
2564     // match foreign exceptions (or didn't, before gcc-4.7).
2565     return false;
2566   case EHPersonality::GNU_CXX:
2567   case EHPersonality::GNU_CXX_SjLj:
2568   case EHPersonality::GNU_ObjC:
2569   case EHPersonality::MSVC_X86SEH:
2570   case EHPersonality::MSVC_Win64SEH:
2571   case EHPersonality::MSVC_CXX:
2572   case EHPersonality::CoreCLR:
2573     return TypeInfo->isNullValue();
2574   }
2575   llvm_unreachable("invalid enum");
2576 }
2577 
2578 static bool shorter_filter(const Value *LHS, const Value *RHS) {
2579   return
2580     cast<ArrayType>(LHS->getType())->getNumElements()
2581   <
2582     cast<ArrayType>(RHS->getType())->getNumElements();
2583 }
2584 
2585 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2586   // The logic here should be correct for any real-world personality function.
2587   // However if that turns out not to be true, the offending logic can always
2588   // be conditioned on the personality function, like the catch-all logic is.
2589   EHPersonality Personality =
2590       classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
2591 
2592   // Simplify the list of clauses, eg by removing repeated catch clauses
2593   // (these are often created by inlining).
2594   bool MakeNewInstruction = false; // If true, recreate using the following:
2595   SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
2596   bool CleanupFlag = LI.isCleanup();   // - The new instruction is a cleanup.
2597 
2598   SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2599   for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2600     bool isLastClause = i + 1 == e;
2601     if (LI.isCatch(i)) {
2602       // A catch clause.
2603       Constant *CatchClause = LI.getClause(i);
2604       Constant *TypeInfo = CatchClause->stripPointerCasts();
2605 
2606       // If we already saw this clause, there is no point in having a second
2607       // copy of it.
2608       if (AlreadyCaught.insert(TypeInfo).second) {
2609         // This catch clause was not already seen.
2610         NewClauses.push_back(CatchClause);
2611       } else {
2612         // Repeated catch clause - drop the redundant copy.
2613         MakeNewInstruction = true;
2614       }
2615 
2616       // If this is a catch-all then there is no point in keeping any following
2617       // clauses or marking the landingpad as having a cleanup.
2618       if (isCatchAll(Personality, TypeInfo)) {
2619         if (!isLastClause)
2620           MakeNewInstruction = true;
2621         CleanupFlag = false;
2622         break;
2623       }
2624     } else {
2625       // A filter clause.  If any of the filter elements were already caught
2626       // then they can be dropped from the filter.  It is tempting to try to
2627       // exploit the filter further by saying that any typeinfo that does not
2628       // occur in the filter can't be caught later (and thus can be dropped).
2629       // However this would be wrong, since typeinfos can match without being
2630       // equal (for example if one represents a C++ class, and the other some
2631       // class derived from it).
2632       assert(LI.isFilter(i) && "Unsupported landingpad clause!");
2633       Constant *FilterClause = LI.getClause(i);
2634       ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2635       unsigned NumTypeInfos = FilterType->getNumElements();
2636 
2637       // An empty filter catches everything, so there is no point in keeping any
2638       // following clauses or marking the landingpad as having a cleanup.  By
2639       // dealing with this case here the following code is made a bit simpler.
2640       if (!NumTypeInfos) {
2641         NewClauses.push_back(FilterClause);
2642         if (!isLastClause)
2643           MakeNewInstruction = true;
2644         CleanupFlag = false;
2645         break;
2646       }
2647 
2648       bool MakeNewFilter = false; // If true, make a new filter.
2649       SmallVector<Constant *, 16> NewFilterElts; // New elements.
2650       if (isa<ConstantAggregateZero>(FilterClause)) {
2651         // Not an empty filter - it contains at least one null typeinfo.
2652         assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2653         Constant *TypeInfo =
2654           Constant::getNullValue(FilterType->getElementType());
2655         // If this typeinfo is a catch-all then the filter can never match.
2656         if (isCatchAll(Personality, TypeInfo)) {
2657           // Throw the filter away.
2658           MakeNewInstruction = true;
2659           continue;
2660         }
2661 
2662         // There is no point in having multiple copies of this typeinfo, so
2663         // discard all but the first copy if there is more than one.
2664         NewFilterElts.push_back(TypeInfo);
2665         if (NumTypeInfos > 1)
2666           MakeNewFilter = true;
2667       } else {
2668         ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2669         SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2670         NewFilterElts.reserve(NumTypeInfos);
2671 
2672         // Remove any filter elements that were already caught or that already
2673         // occurred in the filter.  While there, see if any of the elements are
2674         // catch-alls.  If so, the filter can be discarded.
2675         bool SawCatchAll = false;
2676         for (unsigned j = 0; j != NumTypeInfos; ++j) {
2677           Constant *Elt = Filter->getOperand(j);
2678           Constant *TypeInfo = Elt->stripPointerCasts();
2679           if (isCatchAll(Personality, TypeInfo)) {
2680             // This element is a catch-all.  Bail out, noting this fact.
2681             SawCatchAll = true;
2682             break;
2683           }
2684 
2685           // Even if we've seen a type in a catch clause, we don't want to
2686           // remove it from the filter.  An unexpected type handler may be
2687           // set up for a call site which throws an exception of the same
2688           // type caught.  In order for the exception thrown by the unexpected
2689           // handler to propagate correctly, the filter must be correctly
2690           // described for the call site.
2691           //
2692           // Example:
2693           //
2694           // void unexpected() { throw 1;}
2695           // void foo() throw (int) {
2696           //   std::set_unexpected(unexpected);
2697           //   try {
2698           //     throw 2.0;
2699           //   } catch (int i) {}
2700           // }
2701 
2702           // There is no point in having multiple copies of the same typeinfo in
2703           // a filter, so only add it if we didn't already.
2704           if (SeenInFilter.insert(TypeInfo).second)
2705             NewFilterElts.push_back(cast<Constant>(Elt));
2706         }
2707         // A filter containing a catch-all cannot match anything by definition.
2708         if (SawCatchAll) {
2709           // Throw the filter away.
2710           MakeNewInstruction = true;
2711           continue;
2712         }
2713 
2714         // If we dropped something from the filter, make a new one.
2715         if (NewFilterElts.size() < NumTypeInfos)
2716           MakeNewFilter = true;
2717       }
2718       if (MakeNewFilter) {
2719         FilterType = ArrayType::get(FilterType->getElementType(),
2720                                     NewFilterElts.size());
2721         FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2722         MakeNewInstruction = true;
2723       }
2724 
2725       NewClauses.push_back(FilterClause);
2726 
2727       // If the new filter is empty then it will catch everything so there is
2728       // no point in keeping any following clauses or marking the landingpad
2729       // as having a cleanup.  The case of the original filter being empty was
2730       // already handled above.
2731       if (MakeNewFilter && !NewFilterElts.size()) {
2732         assert(MakeNewInstruction && "New filter but not a new instruction!");
2733         CleanupFlag = false;
2734         break;
2735       }
2736     }
2737   }
2738 
2739   // If several filters occur in a row then reorder them so that the shortest
2740   // filters come first (those with the smallest number of elements).  This is
2741   // advantageous because shorter filters are more likely to match, speeding up
2742   // unwinding, but mostly because it increases the effectiveness of the other
2743   // filter optimizations below.
2744   for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2745     unsigned j;
2746     // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2747     for (j = i; j != e; ++j)
2748       if (!isa<ArrayType>(NewClauses[j]->getType()))
2749         break;
2750 
2751     // Check whether the filters are already sorted by length.  We need to know
2752     // if sorting them is actually going to do anything so that we only make a
2753     // new landingpad instruction if it does.
2754     for (unsigned k = i; k + 1 < j; ++k)
2755       if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2756         // Not sorted, so sort the filters now.  Doing an unstable sort would be
2757         // correct too but reordering filters pointlessly might confuse users.
2758         std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2759                          shorter_filter);
2760         MakeNewInstruction = true;
2761         break;
2762       }
2763 
2764     // Look for the next batch of filters.
2765     i = j + 1;
2766   }
2767 
2768   // If typeinfos matched if and only if equal, then the elements of a filter L
2769   // that occurs later than a filter F could be replaced by the intersection of
2770   // the elements of F and L.  In reality two typeinfos can match without being
2771   // equal (for example if one represents a C++ class, and the other some class
2772   // derived from it) so it would be wrong to perform this transform in general.
2773   // However the transform is correct and useful if F is a subset of L.  In that
2774   // case L can be replaced by F, and thus removed altogether since repeating a
2775   // filter is pointless.  So here we look at all pairs of filters F and L where
2776   // L follows F in the list of clauses, and remove L if every element of F is
2777   // an element of L.  This can occur when inlining C++ functions with exception
2778   // specifications.
2779   for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2780     // Examine each filter in turn.
2781     Value *Filter = NewClauses[i];
2782     ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2783     if (!FTy)
2784       // Not a filter - skip it.
2785       continue;
2786     unsigned FElts = FTy->getNumElements();
2787     // Examine each filter following this one.  Doing this backwards means that
2788     // we don't have to worry about filters disappearing under us when removed.
2789     for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2790       Value *LFilter = NewClauses[j];
2791       ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2792       if (!LTy)
2793         // Not a filter - skip it.
2794         continue;
2795       // If Filter is a subset of LFilter, i.e. every element of Filter is also
2796       // an element of LFilter, then discard LFilter.
2797       SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
2798       // If Filter is empty then it is a subset of LFilter.
2799       if (!FElts) {
2800         // Discard LFilter.
2801         NewClauses.erase(J);
2802         MakeNewInstruction = true;
2803         // Move on to the next filter.
2804         continue;
2805       }
2806       unsigned LElts = LTy->getNumElements();
2807       // If Filter is longer than LFilter then it cannot be a subset of it.
2808       if (FElts > LElts)
2809         // Move on to the next filter.
2810         continue;
2811       // At this point we know that LFilter has at least one element.
2812       if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
2813         // Filter is a subset of LFilter iff Filter contains only zeros (as we
2814         // already know that Filter is not longer than LFilter).
2815         if (isa<ConstantAggregateZero>(Filter)) {
2816           assert(FElts <= LElts && "Should have handled this case earlier!");
2817           // Discard LFilter.
2818           NewClauses.erase(J);
2819           MakeNewInstruction = true;
2820         }
2821         // Move on to the next filter.
2822         continue;
2823       }
2824       ConstantArray *LArray = cast<ConstantArray>(LFilter);
2825       if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2826         // Since Filter is non-empty and contains only zeros, it is a subset of
2827         // LFilter iff LFilter contains a zero.
2828         assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2829         for (unsigned l = 0; l != LElts; ++l)
2830           if (LArray->getOperand(l)->isNullValue()) {
2831             // LFilter contains a zero - discard it.
2832             NewClauses.erase(J);
2833             MakeNewInstruction = true;
2834             break;
2835           }
2836         // Move on to the next filter.
2837         continue;
2838       }
2839       // At this point we know that both filters are ConstantArrays.  Loop over
2840       // operands to see whether every element of Filter is also an element of
2841       // LFilter.  Since filters tend to be short this is probably faster than
2842       // using a method that scales nicely.
2843       ConstantArray *FArray = cast<ConstantArray>(Filter);
2844       bool AllFound = true;
2845       for (unsigned f = 0; f != FElts; ++f) {
2846         Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2847         AllFound = false;
2848         for (unsigned l = 0; l != LElts; ++l) {
2849           Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2850           if (LTypeInfo == FTypeInfo) {
2851             AllFound = true;
2852             break;
2853           }
2854         }
2855         if (!AllFound)
2856           break;
2857       }
2858       if (AllFound) {
2859         // Discard LFilter.
2860         NewClauses.erase(J);
2861         MakeNewInstruction = true;
2862       }
2863       // Move on to the next filter.
2864     }
2865   }
2866 
2867   // If we changed any of the clauses, replace the old landingpad instruction
2868   // with a new one.
2869   if (MakeNewInstruction) {
2870     LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
2871                                                  NewClauses.size());
2872     for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2873       NLI->addClause(NewClauses[i]);
2874     // A landing pad with no clauses must have the cleanup flag set.  It is
2875     // theoretically possible, though highly unlikely, that we eliminated all
2876     // clauses.  If so, force the cleanup flag to true.
2877     if (NewClauses.empty())
2878       CleanupFlag = true;
2879     NLI->setCleanup(CleanupFlag);
2880     return NLI;
2881   }
2882 
2883   // Even if none of the clauses changed, we may nonetheless have understood
2884   // that the cleanup flag is pointless.  Clear it if so.
2885   if (LI.isCleanup() != CleanupFlag) {
2886     assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2887     LI.setCleanup(CleanupFlag);
2888     return &LI;
2889   }
2890 
2891   return nullptr;
2892 }
2893 
2894 /// Try to move the specified instruction from its current block into the
2895 /// beginning of DestBlock, which can only happen if it's safe to move the
2896 /// instruction past all of the instructions between it and the end of its
2897 /// block.
2898 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2899   assert(I->hasOneUse() && "Invariants didn't hold!");
2900   BasicBlock *SrcBlock = I->getParent();
2901 
2902   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
2903   if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() ||
2904       isa<TerminatorInst>(I))
2905     return false;
2906 
2907   // Do not sink alloca instructions out of the entry block.
2908   if (isa<AllocaInst>(I) && I->getParent() ==
2909         &DestBlock->getParent()->getEntryBlock())
2910     return false;
2911 
2912   // Do not sink into catchswitch blocks.
2913   if (isa<CatchSwitchInst>(DestBlock->getTerminator()))
2914     return false;
2915 
2916   // Do not sink convergent call instructions.
2917   if (auto *CI = dyn_cast<CallInst>(I)) {
2918     if (CI->isConvergent())
2919       return false;
2920   }
2921   // We can only sink load instructions if there is nothing between the load and
2922   // the end of block that could change the value.
2923   if (I->mayReadFromMemory()) {
2924     for (BasicBlock::iterator Scan = I->getIterator(),
2925                               E = I->getParent()->end();
2926          Scan != E; ++Scan)
2927       if (Scan->mayWriteToMemory())
2928         return false;
2929   }
2930   BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
2931   I->moveBefore(&*InsertPos);
2932   ++NumSunkInst;
2933 
2934   // Also sink all related debug uses from the source basic block. Otherwise we
2935   // get debug use before the def.
2936   SmallVector<DbgInfoIntrinsic *, 1> DbgUsers;
2937   findDbgUsers(DbgUsers, I);
2938   for (auto *DII : DbgUsers) {
2939     if (DII->getParent() == SrcBlock) {
2940       DII->moveBefore(&*InsertPos);
2941       DEBUG(dbgs() << "SINK: " << *DII << '\n');
2942     }
2943   }
2944   return true;
2945 }
2946 
2947 bool InstCombiner::run() {
2948   while (!Worklist.isEmpty()) {
2949     Instruction *I = Worklist.RemoveOne();
2950     if (I == nullptr) continue;  // skip null values.
2951 
2952     // Check to see if we can DCE the instruction.
2953     if (isInstructionTriviallyDead(I, &TLI)) {
2954       DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
2955       eraseInstFromFunction(*I);
2956       ++NumDeadInst;
2957       MadeIRChange = true;
2958       continue;
2959     }
2960 
2961     if (!DebugCounter::shouldExecute(VisitCounter))
2962       continue;
2963 
2964     // Instruction isn't dead, see if we can constant propagate it.
2965     if (!I->use_empty() &&
2966         (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) {
2967       if (Constant *C = ConstantFoldInstruction(I, DL, &TLI)) {
2968         DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
2969 
2970         // Add operands to the worklist.
2971         replaceInstUsesWith(*I, C);
2972         ++NumConstProp;
2973         if (isInstructionTriviallyDead(I, &TLI))
2974           eraseInstFromFunction(*I);
2975         MadeIRChange = true;
2976         continue;
2977       }
2978     }
2979 
2980     // In general, it is possible for computeKnownBits to determine all bits in
2981     // a value even when the operands are not all constants.
2982     Type *Ty = I->getType();
2983     if (ExpensiveCombines && !I->use_empty() && Ty->isIntOrIntVectorTy()) {
2984       KnownBits Known = computeKnownBits(I, /*Depth*/0, I);
2985       if (Known.isConstant()) {
2986         Constant *C = ConstantInt::get(Ty, Known.getConstant());
2987         DEBUG(dbgs() << "IC: ConstFold (all bits known) to: " << *C <<
2988                         " from: " << *I << '\n');
2989 
2990         // Add operands to the worklist.
2991         replaceInstUsesWith(*I, C);
2992         ++NumConstProp;
2993         if (isInstructionTriviallyDead(I, &TLI))
2994           eraseInstFromFunction(*I);
2995         MadeIRChange = true;
2996         continue;
2997       }
2998     }
2999 
3000     // See if we can trivially sink this instruction to a successor basic block.
3001     if (I->hasOneUse()) {
3002       BasicBlock *BB = I->getParent();
3003       Instruction *UserInst = cast<Instruction>(*I->user_begin());
3004       BasicBlock *UserParent;
3005 
3006       // Get the block the use occurs in.
3007       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
3008         UserParent = PN->getIncomingBlock(*I->use_begin());
3009       else
3010         UserParent = UserInst->getParent();
3011 
3012       if (UserParent != BB) {
3013         bool UserIsSuccessor = false;
3014         // See if the user is one of our successors.
3015         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
3016           if (*SI == UserParent) {
3017             UserIsSuccessor = true;
3018             break;
3019           }
3020 
3021         // If the user is one of our immediate successors, and if that successor
3022         // only has us as a predecessors (we'd have to split the critical edge
3023         // otherwise), we can keep going.
3024         if (UserIsSuccessor && UserParent->getUniquePredecessor()) {
3025           // Okay, the CFG is simple enough, try to sink this instruction.
3026           if (TryToSinkInstruction(I, UserParent)) {
3027             DEBUG(dbgs() << "IC: Sink: " << *I << '\n');
3028             MadeIRChange = true;
3029             // We'll add uses of the sunk instruction below, but since sinking
3030             // can expose opportunities for it's *operands* add them to the
3031             // worklist
3032             for (Use &U : I->operands())
3033               if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
3034                 Worklist.Add(OpI);
3035           }
3036         }
3037       }
3038     }
3039 
3040     // Now that we have an instruction, try combining it to simplify it.
3041     Builder.SetInsertPoint(I);
3042     Builder.SetCurrentDebugLocation(I->getDebugLoc());
3043 
3044 #ifndef NDEBUG
3045     std::string OrigI;
3046 #endif
3047     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
3048     DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
3049 
3050     if (Instruction *Result = visit(*I)) {
3051       ++NumCombined;
3052       // Should we replace the old instruction with a new one?
3053       if (Result != I) {
3054         DEBUG(dbgs() << "IC: Old = " << *I << '\n'
3055                      << "    New = " << *Result << '\n');
3056 
3057         if (I->getDebugLoc())
3058           Result->setDebugLoc(I->getDebugLoc());
3059         // Everything uses the new instruction now.
3060         I->replaceAllUsesWith(Result);
3061 
3062         // Move the name to the new instruction first.
3063         Result->takeName(I);
3064 
3065         // Push the new instruction and any users onto the worklist.
3066         Worklist.AddUsersToWorkList(*Result);
3067         Worklist.Add(Result);
3068 
3069         // Insert the new instruction into the basic block...
3070         BasicBlock *InstParent = I->getParent();
3071         BasicBlock::iterator InsertPos = I->getIterator();
3072 
3073         // If we replace a PHI with something that isn't a PHI, fix up the
3074         // insertion point.
3075         if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
3076           InsertPos = InstParent->getFirstInsertionPt();
3077 
3078         InstParent->getInstList().insert(InsertPos, Result);
3079 
3080         eraseInstFromFunction(*I);
3081       } else {
3082         DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
3083                      << "    New = " << *I << '\n');
3084 
3085         // If the instruction was modified, it's possible that it is now dead.
3086         // if so, remove it.
3087         if (isInstructionTriviallyDead(I, &TLI)) {
3088           eraseInstFromFunction(*I);
3089         } else {
3090           Worklist.AddUsersToWorkList(*I);
3091           Worklist.Add(I);
3092         }
3093       }
3094       MadeIRChange = true;
3095     }
3096   }
3097 
3098   Worklist.Zap();
3099   return MadeIRChange;
3100 }
3101 
3102 /// Walk the function in depth-first order, adding all reachable code to the
3103 /// worklist.
3104 ///
3105 /// This has a couple of tricks to make the code faster and more powerful.  In
3106 /// particular, we constant fold and DCE instructions as we go, to avoid adding
3107 /// them to the worklist (this significantly speeds up instcombine on code where
3108 /// many instructions are dead or constant).  Additionally, if we find a branch
3109 /// whose condition is a known constant, we only visit the reachable successors.
3110 static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL,
3111                                        SmallPtrSetImpl<BasicBlock *> &Visited,
3112                                        InstCombineWorklist &ICWorklist,
3113                                        const TargetLibraryInfo *TLI) {
3114   bool MadeIRChange = false;
3115   SmallVector<BasicBlock*, 256> Worklist;
3116   Worklist.push_back(BB);
3117 
3118   SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
3119   DenseMap<Constant *, Constant *> FoldedConstants;
3120 
3121   do {
3122     BB = Worklist.pop_back_val();
3123 
3124     // We have now visited this block!  If we've already been here, ignore it.
3125     if (!Visited.insert(BB).second)
3126       continue;
3127 
3128     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
3129       Instruction *Inst = &*BBI++;
3130 
3131       // DCE instruction if trivially dead.
3132       if (isInstructionTriviallyDead(Inst, TLI)) {
3133         ++NumDeadInst;
3134         DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
3135         salvageDebugInfo(*Inst);
3136         Inst->eraseFromParent();
3137         MadeIRChange = true;
3138         continue;
3139       }
3140 
3141       // ConstantProp instruction if trivially constant.
3142       if (!Inst->use_empty() &&
3143           (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0))))
3144         if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
3145           DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
3146                        << *Inst << '\n');
3147           Inst->replaceAllUsesWith(C);
3148           ++NumConstProp;
3149           if (isInstructionTriviallyDead(Inst, TLI))
3150             Inst->eraseFromParent();
3151           MadeIRChange = true;
3152           continue;
3153         }
3154 
3155       // See if we can constant fold its operands.
3156       for (Use &U : Inst->operands()) {
3157         if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U))
3158           continue;
3159 
3160         auto *C = cast<Constant>(U);
3161         Constant *&FoldRes = FoldedConstants[C];
3162         if (!FoldRes)
3163           FoldRes = ConstantFoldConstant(C, DL, TLI);
3164         if (!FoldRes)
3165           FoldRes = C;
3166 
3167         if (FoldRes != C) {
3168           DEBUG(dbgs() << "IC: ConstFold operand of: " << *Inst
3169                        << "\n    Old = " << *C
3170                        << "\n    New = " << *FoldRes << '\n');
3171           U = FoldRes;
3172           MadeIRChange = true;
3173         }
3174       }
3175 
3176       // Skip processing debug intrinsics in InstCombine. Processing these call instructions
3177       // consumes non-trivial amount of time and provides no value for the optimization.
3178       if (!isa<DbgInfoIntrinsic>(Inst))
3179         InstrsForInstCombineWorklist.push_back(Inst);
3180     }
3181 
3182     // Recursively visit successors.  If this is a branch or switch on a
3183     // constant, only visit the reachable successor.
3184     TerminatorInst *TI = BB->getTerminator();
3185     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3186       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
3187         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
3188         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
3189         Worklist.push_back(ReachableBB);
3190         continue;
3191       }
3192     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3193       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
3194         Worklist.push_back(SI->findCaseValue(Cond)->getCaseSuccessor());
3195         continue;
3196       }
3197     }
3198 
3199     for (BasicBlock *SuccBB : TI->successors())
3200       Worklist.push_back(SuccBB);
3201   } while (!Worklist.empty());
3202 
3203   // Once we've found all of the instructions to add to instcombine's worklist,
3204   // add them in reverse order.  This way instcombine will visit from the top
3205   // of the function down.  This jives well with the way that it adds all uses
3206   // of instructions to the worklist after doing a transformation, thus avoiding
3207   // some N^2 behavior in pathological cases.
3208   ICWorklist.AddInitialGroup(InstrsForInstCombineWorklist);
3209 
3210   return MadeIRChange;
3211 }
3212 
3213 /// \brief Populate the IC worklist from a function, and prune any dead basic
3214 /// blocks discovered in the process.
3215 ///
3216 /// This also does basic constant propagation and other forward fixing to make
3217 /// the combiner itself run much faster.
3218 static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
3219                                           TargetLibraryInfo *TLI,
3220                                           InstCombineWorklist &ICWorklist) {
3221   bool MadeIRChange = false;
3222 
3223   // Do a depth-first traversal of the function, populate the worklist with
3224   // the reachable instructions.  Ignore blocks that are not reachable.  Keep
3225   // track of which blocks we visit.
3226   SmallPtrSet<BasicBlock *, 32> Visited;
3227   MadeIRChange |=
3228       AddReachableCodeToWorklist(&F.front(), DL, Visited, ICWorklist, TLI);
3229 
3230   // Do a quick scan over the function.  If we find any blocks that are
3231   // unreachable, remove any instructions inside of them.  This prevents
3232   // the instcombine code from having to deal with some bad special cases.
3233   for (BasicBlock &BB : F) {
3234     if (Visited.count(&BB))
3235       continue;
3236 
3237     unsigned NumDeadInstInBB = removeAllNonTerminatorAndEHPadInstructions(&BB);
3238     MadeIRChange |= NumDeadInstInBB > 0;
3239     NumDeadInst += NumDeadInstInBB;
3240   }
3241 
3242   return MadeIRChange;
3243 }
3244 
3245 static bool combineInstructionsOverFunction(
3246     Function &F, InstCombineWorklist &Worklist, AliasAnalysis *AA,
3247     AssumptionCache &AC, TargetLibraryInfo &TLI, DominatorTree &DT,
3248     OptimizationRemarkEmitter &ORE, bool ExpensiveCombines = true,
3249     LoopInfo *LI = nullptr) {
3250   auto &DL = F.getParent()->getDataLayout();
3251   ExpensiveCombines |= EnableExpensiveCombines;
3252 
3253   /// Builder - This is an IRBuilder that automatically inserts new
3254   /// instructions into the worklist when they are created.
3255   IRBuilder<TargetFolder, IRBuilderCallbackInserter> Builder(
3256       F.getContext(), TargetFolder(DL),
3257       IRBuilderCallbackInserter([&Worklist, &AC](Instruction *I) {
3258         Worklist.Add(I);
3259         if (match(I, m_Intrinsic<Intrinsic::assume>()))
3260           AC.registerAssumption(cast<CallInst>(I));
3261       }));
3262 
3263   // Lower dbg.declare intrinsics otherwise their value may be clobbered
3264   // by instcombiner.
3265   bool MadeIRChange = false;
3266   if (ShouldLowerDbgDeclare)
3267     MadeIRChange = LowerDbgDeclare(F);
3268 
3269   // Iterate while there is work to do.
3270   int Iteration = 0;
3271   while (true) {
3272     ++Iteration;
3273     DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
3274                  << F.getName() << "\n");
3275 
3276     MadeIRChange |= prepareICWorklistFromFunction(F, DL, &TLI, Worklist);
3277 
3278     InstCombiner IC(Worklist, Builder, F.optForMinSize(), ExpensiveCombines, AA,
3279                     AC, TLI, DT, ORE, DL, LI);
3280     IC.MaxArraySizeForCombine = MaxArraySize;
3281 
3282     if (!IC.run())
3283       break;
3284   }
3285 
3286   return MadeIRChange || Iteration > 1;
3287 }
3288 
3289 PreservedAnalyses InstCombinePass::run(Function &F,
3290                                        FunctionAnalysisManager &AM) {
3291   auto &AC = AM.getResult<AssumptionAnalysis>(F);
3292   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3293   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
3294   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
3295 
3296   auto *LI = AM.getCachedResult<LoopAnalysis>(F);
3297 
3298   auto *AA = &AM.getResult<AAManager>(F);
3299   if (!combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, ORE,
3300                                        ExpensiveCombines, LI))
3301     // No changes, all analyses are preserved.
3302     return PreservedAnalyses::all();
3303 
3304   // Mark all the analyses that instcombine updates as preserved.
3305   PreservedAnalyses PA;
3306   PA.preserveSet<CFGAnalyses>();
3307   PA.preserve<AAManager>();
3308   PA.preserve<BasicAA>();
3309   PA.preserve<GlobalsAA>();
3310   return PA;
3311 }
3312 
3313 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
3314   AU.setPreservesCFG();
3315   AU.addRequired<AAResultsWrapperPass>();
3316   AU.addRequired<AssumptionCacheTracker>();
3317   AU.addRequired<TargetLibraryInfoWrapperPass>();
3318   AU.addRequired<DominatorTreeWrapperPass>();
3319   AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
3320   AU.addPreserved<DominatorTreeWrapperPass>();
3321   AU.addPreserved<AAResultsWrapperPass>();
3322   AU.addPreserved<BasicAAWrapperPass>();
3323   AU.addPreserved<GlobalsAAWrapperPass>();
3324 }
3325 
3326 bool InstructionCombiningPass::runOnFunction(Function &F) {
3327   if (skipFunction(F))
3328     return false;
3329 
3330   // Required analyses.
3331   auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3332   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3333   auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3334   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3335   auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
3336 
3337   // Optional analyses.
3338   auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3339   auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
3340 
3341   return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, ORE,
3342                                          ExpensiveCombines, LI);
3343 }
3344 
3345 char InstructionCombiningPass::ID = 0;
3346 
3347 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
3348                       "Combine redundant instructions", false, false)
3349 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3350 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3351 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3352 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3353 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3354 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
3355 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
3356                     "Combine redundant instructions", false, false)
3357 
3358 // Initialization Routines
3359 void llvm::initializeInstCombine(PassRegistry &Registry) {
3360   initializeInstructionCombiningPassPass(Registry);
3361 }
3362 
3363 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
3364   initializeInstructionCombiningPassPass(*unwrap(R));
3365 }
3366 
3367 FunctionPass *llvm::createInstructionCombiningPass(bool ExpensiveCombines) {
3368   return new InstructionCombiningPass(ExpensiveCombines);
3369 }
3370