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