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