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