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