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