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