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::foldOpWithConstantIntoOperand(BinaryOperator &I) {
1093   assert(isa<Constant>(I.getOperand(1)) && "Unexpected operand type");
1094 
1095   if (auto *Sel = dyn_cast<SelectInst>(I.getOperand(0))) {
1096     if (Instruction *NewSel = FoldOpIntoSelect(I, Sel))
1097       return NewSel;
1098   } else if (auto *PN = dyn_cast<PHINode>(I.getOperand(0))) {
1099     if (Instruction *NewPhi = foldOpIntoPhi(I, PN))
1100       return NewPhi;
1101   }
1102   return nullptr;
1103 }
1104 
1105 /// Given a pointer type and a constant offset, determine whether or not there
1106 /// is a sequence of GEP indices into the pointed type that will land us at the
1107 /// specified offset. If so, fill them into NewIndices and return the resultant
1108 /// element type, otherwise return null.
1109 Type *InstCombiner::FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
1110                                         SmallVectorImpl<Value *> &NewIndices) {
1111   Type *Ty = PtrTy->getElementType();
1112   if (!Ty->isSized())
1113     return nullptr;
1114 
1115   // Start with the index over the outer type.  Note that the type size
1116   // might be zero (even if the offset isn't zero) if the indexed type
1117   // is something like [0 x {int, int}]
1118   Type *IndexTy = DL.getIndexType(PtrTy);
1119   int64_t FirstIdx = 0;
1120   if (int64_t TySize = DL.getTypeAllocSize(Ty)) {
1121     FirstIdx = Offset/TySize;
1122     Offset -= FirstIdx*TySize;
1123 
1124     // Handle hosts where % returns negative instead of values [0..TySize).
1125     if (Offset < 0) {
1126       --FirstIdx;
1127       Offset += TySize;
1128       assert(Offset >= 0);
1129     }
1130     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
1131   }
1132 
1133   NewIndices.push_back(ConstantInt::get(IndexTy, FirstIdx));
1134 
1135   // Index into the types.  If we fail, set OrigBase to null.
1136   while (Offset) {
1137     // Indexing into tail padding between struct/array elements.
1138     if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty))
1139       return nullptr;
1140 
1141     if (StructType *STy = dyn_cast<StructType>(Ty)) {
1142       const StructLayout *SL = DL.getStructLayout(STy);
1143       assert(Offset < (int64_t)SL->getSizeInBytes() &&
1144              "Offset must stay within the indexed type");
1145 
1146       unsigned Elt = SL->getElementContainingOffset(Offset);
1147       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
1148                                             Elt));
1149 
1150       Offset -= SL->getElementOffset(Elt);
1151       Ty = STy->getElementType(Elt);
1152     } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
1153       uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType());
1154       assert(EltSize && "Cannot index into a zero-sized array");
1155       NewIndices.push_back(ConstantInt::get(IndexTy,Offset/EltSize));
1156       Offset %= EltSize;
1157       Ty = AT->getElementType();
1158     } else {
1159       // Otherwise, we can't index into the middle of this atomic type, bail.
1160       return nullptr;
1161     }
1162   }
1163 
1164   return Ty;
1165 }
1166 
1167 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
1168   // If this GEP has only 0 indices, it is the same pointer as
1169   // Src. If Src is not a trivial GEP too, don't combine
1170   // the indices.
1171   if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
1172       !Src.hasOneUse())
1173     return false;
1174   return true;
1175 }
1176 
1177 /// Return a value X such that Val = X * Scale, or null if none.
1178 /// If the multiplication is known not to overflow, then NoSignedWrap is set.
1179 Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
1180   assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
1181   assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
1182          Scale.getBitWidth() && "Scale not compatible with value!");
1183 
1184   // If Val is zero or Scale is one then Val = Val * Scale.
1185   if (match(Val, m_Zero()) || Scale == 1) {
1186     NoSignedWrap = true;
1187     return Val;
1188   }
1189 
1190   // If Scale is zero then it does not divide Val.
1191   if (Scale.isMinValue())
1192     return nullptr;
1193 
1194   // Look through chains of multiplications, searching for a constant that is
1195   // divisible by Scale.  For example, descaling X*(Y*(Z*4)) by a factor of 4
1196   // will find the constant factor 4 and produce X*(Y*Z).  Descaling X*(Y*8) by
1197   // a factor of 4 will produce X*(Y*2).  The principle of operation is to bore
1198   // down from Val:
1199   //
1200   //     Val = M1 * X          ||   Analysis starts here and works down
1201   //      M1 = M2 * Y          ||   Doesn't descend into terms with more
1202   //      M2 =  Z * 4          \/   than one use
1203   //
1204   // Then to modify a term at the bottom:
1205   //
1206   //     Val = M1 * X
1207   //      M1 =  Z * Y          ||   Replaced M2 with Z
1208   //
1209   // Then to work back up correcting nsw flags.
1210 
1211   // Op - the term we are currently analyzing.  Starts at Val then drills down.
1212   // Replaced with its descaled value before exiting from the drill down loop.
1213   Value *Op = Val;
1214 
1215   // Parent - initially null, but after drilling down notes where Op came from.
1216   // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
1217   // 0'th operand of Val.
1218   std::pair<Instruction *, unsigned> Parent;
1219 
1220   // Set if the transform requires a descaling at deeper levels that doesn't
1221   // overflow.
1222   bool RequireNoSignedWrap = false;
1223 
1224   // Log base 2 of the scale. Negative if not a power of 2.
1225   int32_t logScale = Scale.exactLogBase2();
1226 
1227   for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
1228     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1229       // If Op is a constant divisible by Scale then descale to the quotient.
1230       APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1231       APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1232       if (!Remainder.isMinValue())
1233         // Not divisible by Scale.
1234         return nullptr;
1235       // Replace with the quotient in the parent.
1236       Op = ConstantInt::get(CI->getType(), Quotient);
1237       NoSignedWrap = true;
1238       break;
1239     }
1240 
1241     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1242       if (BO->getOpcode() == Instruction::Mul) {
1243         // Multiplication.
1244         NoSignedWrap = BO->hasNoSignedWrap();
1245         if (RequireNoSignedWrap && !NoSignedWrap)
1246           return nullptr;
1247 
1248         // There are three cases for multiplication: multiplication by exactly
1249         // the scale, multiplication by a constant different to the scale, and
1250         // multiplication by something else.
1251         Value *LHS = BO->getOperand(0);
1252         Value *RHS = BO->getOperand(1);
1253 
1254         if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1255           // Multiplication by a constant.
1256           if (CI->getValue() == Scale) {
1257             // Multiplication by exactly the scale, replace the multiplication
1258             // by its left-hand side in the parent.
1259             Op = LHS;
1260             break;
1261           }
1262 
1263           // Otherwise drill down into the constant.
1264           if (!Op->hasOneUse())
1265             return nullptr;
1266 
1267           Parent = std::make_pair(BO, 1);
1268           continue;
1269         }
1270 
1271         // Multiplication by something else. Drill down into the left-hand side
1272         // since that's where the reassociate pass puts the good stuff.
1273         if (!Op->hasOneUse())
1274           return nullptr;
1275 
1276         Parent = std::make_pair(BO, 0);
1277         continue;
1278       }
1279 
1280       if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1281           isa<ConstantInt>(BO->getOperand(1))) {
1282         // Multiplication by a power of 2.
1283         NoSignedWrap = BO->hasNoSignedWrap();
1284         if (RequireNoSignedWrap && !NoSignedWrap)
1285           return nullptr;
1286 
1287         Value *LHS = BO->getOperand(0);
1288         int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1289           getLimitedValue(Scale.getBitWidth());
1290         // Op = LHS << Amt.
1291 
1292         if (Amt == logScale) {
1293           // Multiplication by exactly the scale, replace the multiplication
1294           // by its left-hand side in the parent.
1295           Op = LHS;
1296           break;
1297         }
1298         if (Amt < logScale || !Op->hasOneUse())
1299           return nullptr;
1300 
1301         // Multiplication by more than the scale.  Reduce the multiplying amount
1302         // by the scale in the parent.
1303         Parent = std::make_pair(BO, 1);
1304         Op = ConstantInt::get(BO->getType(), Amt - logScale);
1305         break;
1306       }
1307     }
1308 
1309     if (!Op->hasOneUse())
1310       return nullptr;
1311 
1312     if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1313       if (Cast->getOpcode() == Instruction::SExt) {
1314         // Op is sign-extended from a smaller type, descale in the smaller type.
1315         unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1316         APInt SmallScale = Scale.trunc(SmallSize);
1317         // Suppose Op = sext X, and we descale X as Y * SmallScale.  We want to
1318         // descale Op as (sext Y) * Scale.  In order to have
1319         //   sext (Y * SmallScale) = (sext Y) * Scale
1320         // some conditions need to hold however: SmallScale must sign-extend to
1321         // Scale and the multiplication Y * SmallScale should not overflow.
1322         if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1323           // SmallScale does not sign-extend to Scale.
1324           return nullptr;
1325         assert(SmallScale.exactLogBase2() == logScale);
1326         // Require that Y * SmallScale must not overflow.
1327         RequireNoSignedWrap = true;
1328 
1329         // Drill down through the cast.
1330         Parent = std::make_pair(Cast, 0);
1331         Scale = SmallScale;
1332         continue;
1333       }
1334 
1335       if (Cast->getOpcode() == Instruction::Trunc) {
1336         // Op is truncated from a larger type, descale in the larger type.
1337         // Suppose Op = trunc X, and we descale X as Y * sext Scale.  Then
1338         //   trunc (Y * sext Scale) = (trunc Y) * Scale
1339         // always holds.  However (trunc Y) * Scale may overflow even if
1340         // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1341         // from this point up in the expression (see later).
1342         if (RequireNoSignedWrap)
1343           return nullptr;
1344 
1345         // Drill down through the cast.
1346         unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1347         Parent = std::make_pair(Cast, 0);
1348         Scale = Scale.sext(LargeSize);
1349         if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1350           logScale = -1;
1351         assert(Scale.exactLogBase2() == logScale);
1352         continue;
1353       }
1354     }
1355 
1356     // Unsupported expression, bail out.
1357     return nullptr;
1358   }
1359 
1360   // If Op is zero then Val = Op * Scale.
1361   if (match(Op, m_Zero())) {
1362     NoSignedWrap = true;
1363     return Op;
1364   }
1365 
1366   // We know that we can successfully descale, so from here on we can safely
1367   // modify the IR.  Op holds the descaled version of the deepest term in the
1368   // expression.  NoSignedWrap is 'true' if multiplying Op by Scale is known
1369   // not to overflow.
1370 
1371   if (!Parent.first)
1372     // The expression only had one term.
1373     return Op;
1374 
1375   // Rewrite the parent using the descaled version of its operand.
1376   assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1377   assert(Op != Parent.first->getOperand(Parent.second) &&
1378          "Descaling was a no-op?");
1379   Parent.first->setOperand(Parent.second, Op);
1380   Worklist.Add(Parent.first);
1381 
1382   // Now work back up the expression correcting nsw flags.  The logic is based
1383   // on the following observation: if X * Y is known not to overflow as a signed
1384   // multiplication, and Y is replaced by a value Z with smaller absolute value,
1385   // then X * Z will not overflow as a signed multiplication either.  As we work
1386   // our way up, having NoSignedWrap 'true' means that the descaled value at the
1387   // current level has strictly smaller absolute value than the original.
1388   Instruction *Ancestor = Parent.first;
1389   do {
1390     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1391       // If the multiplication wasn't nsw then we can't say anything about the
1392       // value of the descaled multiplication, and we have to clear nsw flags
1393       // from this point on up.
1394       bool OpNoSignedWrap = BO->hasNoSignedWrap();
1395       NoSignedWrap &= OpNoSignedWrap;
1396       if (NoSignedWrap != OpNoSignedWrap) {
1397         BO->setHasNoSignedWrap(NoSignedWrap);
1398         Worklist.Add(Ancestor);
1399       }
1400     } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1401       // The fact that the descaled input to the trunc has smaller absolute
1402       // value than the original input doesn't tell us anything useful about
1403       // the absolute values of the truncations.
1404       NoSignedWrap = false;
1405     }
1406     assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1407            "Failed to keep proper track of nsw flags while drilling down?");
1408 
1409     if (Ancestor == Val)
1410       // Got to the top, all done!
1411       return Val;
1412 
1413     // Move up one level in the expression.
1414     assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
1415     Ancestor = Ancestor->user_back();
1416   } while (true);
1417 }
1418 
1419 /// \brief Creates node of binary operation with the same attributes as the
1420 /// specified one but with other operands.
1421 static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
1422                                  InstCombiner::BuilderTy &B) {
1423   Value *BO = B.CreateBinOp(Inst.getOpcode(), LHS, RHS);
1424   // If LHS and RHS are constant, BO won't be a binary operator.
1425   if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BO))
1426     NewBO->copyIRFlags(&Inst);
1427   return BO;
1428 }
1429 
1430 /// \brief Makes transformation of binary operation specific for vector types.
1431 /// \param Inst Binary operator to transform.
1432 /// \return Pointer to node that must replace the original binary operator, or
1433 ///         null pointer if no transformation was made.
1434 Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
1435   if (!Inst.getType()->isVectorTy()) return nullptr;
1436 
1437   // It may not be safe to reorder shuffles and things like div, urem, etc.
1438   // because we may trap when executing those ops on unknown vector elements.
1439   // See PR20059.
1440   if (!isSafeToSpeculativelyExecute(&Inst))
1441     return nullptr;
1442 
1443   unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
1444   Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1445   assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
1446   assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
1447 
1448   // If both arguments of the binary operation are shuffles that use the same
1449   // mask and shuffle within a single vector, move the shuffle after the binop:
1450   //   Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
1451   auto *LShuf = dyn_cast<ShuffleVectorInst>(LHS);
1452   auto *RShuf = dyn_cast<ShuffleVectorInst>(RHS);
1453   if (LShuf && RShuf && LShuf->getMask() == RShuf->getMask() &&
1454       isa<UndefValue>(LShuf->getOperand(1)) &&
1455       isa<UndefValue>(RShuf->getOperand(1)) &&
1456       LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType()) {
1457     Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
1458                                       RShuf->getOperand(0), Builder);
1459     return Builder.CreateShuffleVector(
1460         NewBO, UndefValue::get(NewBO->getType()), LShuf->getMask());
1461   }
1462 
1463   // If one argument is a shuffle within one vector, the other is a constant,
1464   // try moving the shuffle after the binary operation.
1465   ShuffleVectorInst *Shuffle = nullptr;
1466   Constant *C1 = nullptr;
1467   if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
1468   if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
1469   if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
1470   if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
1471   if (Shuffle && C1 &&
1472       (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
1473       isa<UndefValue>(Shuffle->getOperand(1)) &&
1474       Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
1475     SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
1476     // Find constant C2 that has property:
1477     //   shuffle(C2, ShMask) = C1
1478     // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
1479     // reorder is not possible.
1480     SmallVector<Constant*, 16> C2M(VWidth,
1481                                UndefValue::get(C1->getType()->getScalarType()));
1482     bool MayChange = true;
1483     for (unsigned I = 0; I < VWidth; ++I) {
1484       if (ShMask[I] >= 0) {
1485         assert(ShMask[I] < (int)VWidth);
1486         if (!isa<UndefValue>(C2M[ShMask[I]])) {
1487           MayChange = false;
1488           break;
1489         }
1490         C2M[ShMask[I]] = C1->getAggregateElement(I);
1491       }
1492     }
1493     if (MayChange) {
1494       Constant *C2 = ConstantVector::get(C2M);
1495       Value *NewLHS = isa<Constant>(LHS) ? C2 : Shuffle->getOperand(0);
1496       Value *NewRHS = isa<Constant>(LHS) ? Shuffle->getOperand(0) : C2;
1497       Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
1498       return Builder.CreateShuffleVector(NewBO,
1499           UndefValue::get(Inst.getType()), Shuffle->getMask());
1500     }
1501   }
1502 
1503   return nullptr;
1504 }
1505 
1506 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1507   SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1508 
1509   if (Value *V = SimplifyGEPInst(GEP.getSourceElementType(), Ops,
1510                                  SQ.getWithInstruction(&GEP)))
1511     return replaceInstUsesWith(GEP, V);
1512 
1513   Value *PtrOp = GEP.getOperand(0);
1514 
1515   // Eliminate unneeded casts for indices, and replace indices which displace
1516   // by multiples of a zero size type with zero.
1517   bool MadeChange = false;
1518 
1519   // Index width may not be the same width as pointer width.
1520   // Data layout chooses the right type based on supported integer types.
1521   Type *NewScalarIndexTy =
1522       DL.getIndexType(GEP.getPointerOperandType()->getScalarType());
1523 
1524   gep_type_iterator GTI = gep_type_begin(GEP);
1525   for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
1526        ++I, ++GTI) {
1527     // Skip indices into struct types.
1528     if (GTI.isStruct())
1529       continue;
1530 
1531     Type *IndexTy = (*I)->getType();
1532     Type *NewIndexType =
1533         IndexTy->isVectorTy()
1534             ? VectorType::get(NewScalarIndexTy, IndexTy->getVectorNumElements())
1535             : NewScalarIndexTy;
1536 
1537     // If the element type has zero size then any index over it is equivalent
1538     // to an index of zero, so replace it with zero if it is not zero already.
1539     Type *EltTy = GTI.getIndexedType();
1540     if (EltTy->isSized() && DL.getTypeAllocSize(EltTy) == 0)
1541       if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1542         *I = Constant::getNullValue(NewIndexType);
1543         MadeChange = true;
1544       }
1545 
1546     if (IndexTy != NewIndexType) {
1547       // If we are using a wider index than needed for this platform, shrink
1548       // it to what we need.  If narrower, sign-extend it to what we need.
1549       // This explicit cast can make subsequent optimizations more obvious.
1550       *I = Builder.CreateIntCast(*I, NewIndexType, true);
1551       MadeChange = true;
1552     }
1553   }
1554   if (MadeChange)
1555     return &GEP;
1556 
1557   // Check to see if the inputs to the PHI node are getelementptr instructions.
1558   if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1559     GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1560     if (!Op1)
1561       return nullptr;
1562 
1563     // Don't fold a GEP into itself through a PHI node. This can only happen
1564     // through the back-edge of a loop. Folding a GEP into itself means that
1565     // the value of the previous iteration needs to be stored in the meantime,
1566     // thus requiring an additional register variable to be live, but not
1567     // actually achieving anything (the GEP still needs to be executed once per
1568     // loop iteration).
1569     if (Op1 == &GEP)
1570       return nullptr;
1571 
1572     int DI = -1;
1573 
1574     for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1575       GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
1576       if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1577         return nullptr;
1578 
1579       // As for Op1 above, don't try to fold a GEP into itself.
1580       if (Op2 == &GEP)
1581         return nullptr;
1582 
1583       // Keep track of the type as we walk the GEP.
1584       Type *CurTy = nullptr;
1585 
1586       for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1587         if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1588           return nullptr;
1589 
1590         if (Op1->getOperand(J) != Op2->getOperand(J)) {
1591           if (DI == -1) {
1592             // We have not seen any differences yet in the GEPs feeding the
1593             // PHI yet, so we record this one if it is allowed to be a
1594             // variable.
1595 
1596             // The first two arguments can vary for any GEP, the rest have to be
1597             // static for struct slots
1598             if (J > 1 && CurTy->isStructTy())
1599               return nullptr;
1600 
1601             DI = J;
1602           } else {
1603             // The GEP is different by more than one input. While this could be
1604             // extended to support GEPs that vary by more than one variable it
1605             // doesn't make sense since it greatly increases the complexity and
1606             // would result in an R+R+R addressing mode which no backend
1607             // directly supports and would need to be broken into several
1608             // simpler instructions anyway.
1609             return nullptr;
1610           }
1611         }
1612 
1613         // Sink down a layer of the type for the next iteration.
1614         if (J > 0) {
1615           if (J == 1) {
1616             CurTy = Op1->getSourceElementType();
1617           } else if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
1618             CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1619           } else {
1620             CurTy = nullptr;
1621           }
1622         }
1623       }
1624     }
1625 
1626     // If not all GEPs are identical we'll have to create a new PHI node.
1627     // Check that the old PHI node has only one use so that it will get
1628     // removed.
1629     if (DI != -1 && !PN->hasOneUse())
1630       return nullptr;
1631 
1632     GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
1633     if (DI == -1) {
1634       // All the GEPs feeding the PHI are identical. Clone one down into our
1635       // BB so that it can be merged with the current GEP.
1636       GEP.getParent()->getInstList().insert(
1637           GEP.getParent()->getFirstInsertionPt(), NewGEP);
1638     } else {
1639       // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1640       // into the current block so it can be merged, and create a new PHI to
1641       // set that index.
1642       PHINode *NewPN;
1643       {
1644         IRBuilderBase::InsertPointGuard Guard(Builder);
1645         Builder.SetInsertPoint(PN);
1646         NewPN = Builder.CreatePHI(Op1->getOperand(DI)->getType(),
1647                                   PN->getNumOperands());
1648       }
1649 
1650       for (auto &I : PN->operands())
1651         NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1652                            PN->getIncomingBlock(I));
1653 
1654       NewGEP->setOperand(DI, NewPN);
1655       GEP.getParent()->getInstList().insert(
1656           GEP.getParent()->getFirstInsertionPt(), NewGEP);
1657       NewGEP->setOperand(DI, NewPN);
1658     }
1659 
1660     GEP.setOperand(0, NewGEP);
1661     PtrOp = NewGEP;
1662   }
1663 
1664   // Combine Indices - If the source pointer to this getelementptr instruction
1665   // is a getelementptr instruction, combine the indices of the two
1666   // getelementptr instructions into a single instruction.
1667   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
1668     if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
1669       return nullptr;
1670 
1671     // Note that if our source is a gep chain itself then we wait for that
1672     // chain to be resolved before we perform this transformation.  This
1673     // avoids us creating a TON of code in some cases.
1674     if (GEPOperator *SrcGEP =
1675           dyn_cast<GEPOperator>(Src->getOperand(0)))
1676       if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
1677         return nullptr;   // Wait until our source is folded to completion.
1678 
1679     SmallVector<Value*, 8> Indices;
1680 
1681     // Find out whether the last index in the source GEP is a sequential idx.
1682     bool EndsWithSequential = false;
1683     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1684          I != E; ++I)
1685       EndsWithSequential = I.isSequential();
1686 
1687     // Can we combine the two pointer arithmetics offsets?
1688     if (EndsWithSequential) {
1689       // Replace: gep (gep %P, long B), long A, ...
1690       // With:    T = long A+B; gep %P, T, ...
1691       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1692       Value *GO1 = GEP.getOperand(1);
1693 
1694       // If they aren't the same type, then the input hasn't been processed
1695       // by the loop above yet (which canonicalizes sequential index types to
1696       // intptr_t).  Just avoid transforming this until the input has been
1697       // normalized.
1698       if (SO1->getType() != GO1->getType())
1699         return nullptr;
1700 
1701       Value *Sum =
1702           SimplifyAddInst(GO1, SO1, false, false, SQ.getWithInstruction(&GEP));
1703       // Only do the combine when we are sure the cost after the
1704       // merge is never more than that before the merge.
1705       if (Sum == nullptr)
1706         return nullptr;
1707 
1708       // Update the GEP in place if possible.
1709       if (Src->getNumOperands() == 2) {
1710         GEP.setOperand(0, Src->getOperand(0));
1711         GEP.setOperand(1, Sum);
1712         return &GEP;
1713       }
1714       Indices.append(Src->op_begin()+1, Src->op_end()-1);
1715       Indices.push_back(Sum);
1716       Indices.append(GEP.op_begin()+2, GEP.op_end());
1717     } else if (isa<Constant>(*GEP.idx_begin()) &&
1718                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
1719                Src->getNumOperands() != 1) {
1720       // Otherwise we can do the fold if the first index of the GEP is a zero
1721       Indices.append(Src->op_begin()+1, Src->op_end());
1722       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
1723     }
1724 
1725     if (!Indices.empty())
1726       return GEP.isInBounds() && Src->isInBounds()
1727                  ? GetElementPtrInst::CreateInBounds(
1728                        Src->getSourceElementType(), Src->getOperand(0), Indices,
1729                        GEP.getName())
1730                  : GetElementPtrInst::Create(Src->getSourceElementType(),
1731                                              Src->getOperand(0), Indices,
1732                                              GEP.getName());
1733   }
1734 
1735   if (GEP.getNumIndices() == 1) {
1736     unsigned AS = GEP.getPointerAddressSpace();
1737     if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
1738         DL.getIndexSizeInBits(AS)) {
1739       Type *Ty = GEP.getSourceElementType();
1740       uint64_t TyAllocSize = DL.getTypeAllocSize(Ty);
1741 
1742       bool Matched = false;
1743       uint64_t C;
1744       Value *V = nullptr;
1745       if (TyAllocSize == 1) {
1746         V = GEP.getOperand(1);
1747         Matched = true;
1748       } else if (match(GEP.getOperand(1),
1749                        m_AShr(m_Value(V), m_ConstantInt(C)))) {
1750         if (TyAllocSize == 1ULL << C)
1751           Matched = true;
1752       } else if (match(GEP.getOperand(1),
1753                        m_SDiv(m_Value(V), m_ConstantInt(C)))) {
1754         if (TyAllocSize == C)
1755           Matched = true;
1756       }
1757 
1758       if (Matched) {
1759         // Canonicalize (gep i8* X, -(ptrtoint Y))
1760         // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
1761         // The GEP pattern is emitted by the SCEV expander for certain kinds of
1762         // pointer arithmetic.
1763         if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
1764           Operator *Index = cast<Operator>(V);
1765           Value *PtrToInt = Builder.CreatePtrToInt(PtrOp, Index->getType());
1766           Value *NewSub = Builder.CreateSub(PtrToInt, Index->getOperand(1));
1767           return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
1768         }
1769         // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
1770         // to (bitcast Y)
1771         Value *Y;
1772         if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
1773                            m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
1774           return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
1775                                                                GEP.getType());
1776         }
1777       }
1778     }
1779   }
1780 
1781   // We do not handle pointer-vector geps here.
1782   if (GEP.getType()->isVectorTy())
1783     return nullptr;
1784 
1785   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
1786   Value *StrippedPtr = PtrOp->stripPointerCasts();
1787   PointerType *StrippedPtrTy = cast<PointerType>(StrippedPtr->getType());
1788 
1789   if (StrippedPtr != PtrOp) {
1790     bool HasZeroPointerIndex = false;
1791     if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1792       HasZeroPointerIndex = C->isZero();
1793 
1794     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1795     // into     : GEP [10 x i8]* X, i32 0, ...
1796     //
1797     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1798     //           into     : GEP i8* X, ...
1799     //
1800     // This occurs when the program declares an array extern like "int X[];"
1801     if (HasZeroPointerIndex) {
1802       if (ArrayType *CATy =
1803           dyn_cast<ArrayType>(GEP.getSourceElementType())) {
1804         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
1805         if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
1806           // -> GEP i8* X, ...
1807           SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
1808           GetElementPtrInst *Res = GetElementPtrInst::Create(
1809               StrippedPtrTy->getElementType(), StrippedPtr, Idx, GEP.getName());
1810           Res->setIsInBounds(GEP.isInBounds());
1811           if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1812             return Res;
1813           // Insert Res, and create an addrspacecast.
1814           // e.g.,
1815           // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1816           // ->
1817           // %0 = GEP i8 addrspace(1)* X, ...
1818           // addrspacecast i8 addrspace(1)* %0 to i8*
1819           return new AddrSpaceCastInst(Builder.Insert(Res), GEP.getType());
1820         }
1821 
1822         if (ArrayType *XATy =
1823               dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
1824           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
1825           if (CATy->getElementType() == XATy->getElementType()) {
1826             // -> GEP [10 x i8]* X, i32 0, ...
1827             // At this point, we know that the cast source type is a pointer
1828             // to an array of the same type as the destination pointer
1829             // array.  Because the array type is never stepped over (there
1830             // is a leading zero) we can fold the cast into this GEP.
1831             if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
1832               GEP.setOperand(0, StrippedPtr);
1833               GEP.setSourceElementType(XATy);
1834               return &GEP;
1835             }
1836             // Cannot replace the base pointer directly because StrippedPtr's
1837             // address space is different. Instead, create a new GEP followed by
1838             // an addrspacecast.
1839             // e.g.,
1840             // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
1841             //   i32 0, ...
1842             // ->
1843             // %0 = GEP [10 x i8] addrspace(1)* X, ...
1844             // addrspacecast i8 addrspace(1)* %0 to i8*
1845             SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
1846             Value *NewGEP = GEP.isInBounds()
1847                                 ? Builder.CreateInBoundsGEP(
1848                                       nullptr, StrippedPtr, Idx, GEP.getName())
1849                                 : Builder.CreateGEP(nullptr, StrippedPtr, Idx,
1850                                                     GEP.getName());
1851             return new AddrSpaceCastInst(NewGEP, GEP.getType());
1852           }
1853         }
1854       }
1855     } else if (GEP.getNumOperands() == 2) {
1856       // Transform things like:
1857       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1858       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
1859       Type *SrcElTy = StrippedPtrTy->getElementType();
1860       Type *ResElTy = GEP.getSourceElementType();
1861       if (SrcElTy->isArrayTy() &&
1862           DL.getTypeAllocSize(SrcElTy->getArrayElementType()) ==
1863               DL.getTypeAllocSize(ResElTy)) {
1864         Type *IdxType = DL.getIndexType(GEP.getType());
1865         Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
1866         Value *NewGEP =
1867             GEP.isInBounds()
1868                 ? Builder.CreateInBoundsGEP(nullptr, StrippedPtr, Idx,
1869                                             GEP.getName())
1870                 : Builder.CreateGEP(nullptr, StrippedPtr, Idx, GEP.getName());
1871 
1872         // V and GEP are both pointer types --> BitCast
1873         return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1874                                                              GEP.getType());
1875       }
1876 
1877       // Transform things like:
1878       // %V = mul i64 %N, 4
1879       // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1880       // into:  %t1 = getelementptr i32* %arr, i32 %N; bitcast
1881       if (ResElTy->isSized() && SrcElTy->isSized()) {
1882         // Check that changing the type amounts to dividing the index by a scale
1883         // factor.
1884         uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1885         uint64_t SrcSize = DL.getTypeAllocSize(SrcElTy);
1886         if (ResSize && SrcSize % ResSize == 0) {
1887           Value *Idx = GEP.getOperand(1);
1888           unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1889           uint64_t Scale = SrcSize / ResSize;
1890 
1891           // Earlier transforms ensure that the index has the right type
1892           // according to Data Layout, which considerably simplifies the
1893           // logic by eliminating implicit casts.
1894           assert(Idx->getType() == DL.getIndexType(GEP.getType()) &&
1895                  "Index type does not match the Data Layout preferences");
1896 
1897           bool NSW;
1898           if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1899             // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1900             // If the multiplication NewIdx * Scale may overflow then the new
1901             // GEP may not be "inbounds".
1902             Value *NewGEP =
1903                 GEP.isInBounds() && NSW
1904                     ? Builder.CreateInBoundsGEP(nullptr, StrippedPtr, NewIdx,
1905                                                 GEP.getName())
1906                     : Builder.CreateGEP(nullptr, StrippedPtr, NewIdx,
1907                                         GEP.getName());
1908 
1909             // The NewGEP must be pointer typed, so must the old one -> BitCast
1910             return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1911                                                                  GEP.getType());
1912           }
1913         }
1914       }
1915 
1916       // Similarly, transform things like:
1917       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
1918       //   (where tmp = 8*tmp2) into:
1919       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
1920       if (ResElTy->isSized() && SrcElTy->isSized() && SrcElTy->isArrayTy()) {
1921         // Check that changing to the array element type amounts to dividing the
1922         // index by a scale factor.
1923         uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1924         uint64_t ArrayEltSize =
1925             DL.getTypeAllocSize(SrcElTy->getArrayElementType());
1926         if (ResSize && ArrayEltSize % ResSize == 0) {
1927           Value *Idx = GEP.getOperand(1);
1928           unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1929           uint64_t Scale = ArrayEltSize / ResSize;
1930 
1931           // Earlier transforms ensure that the index has the right type
1932           // according to the Data Layout, which considerably simplifies
1933           // the logic by eliminating implicit casts.
1934           assert(Idx->getType() == DL.getIndexType(GEP.getType()) &&
1935                  "Index type does not match the Data Layout preferences");
1936 
1937           bool NSW;
1938           if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1939             // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1940             // If the multiplication NewIdx * Scale may overflow then the new
1941             // GEP may not be "inbounds".
1942             Type *IndTy = DL.getIndexType(GEP.getType());
1943             Value *Off[2] = {Constant::getNullValue(IndTy), NewIdx};
1944 
1945             Value *NewGEP = GEP.isInBounds() && NSW
1946                                 ? Builder.CreateInBoundsGEP(
1947                                       SrcElTy, StrippedPtr, Off, GEP.getName())
1948                                 : Builder.CreateGEP(SrcElTy, StrippedPtr, Off,
1949                                                     GEP.getName());
1950             // The NewGEP must be pointer typed, so must the old one -> BitCast
1951             return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1952                                                                  GEP.getType());
1953           }
1954         }
1955       }
1956     }
1957   }
1958 
1959   // addrspacecast between types is canonicalized as a bitcast, then an
1960   // addrspacecast. To take advantage of the below bitcast + struct GEP, look
1961   // through the addrspacecast.
1962   if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
1963     //   X = bitcast A addrspace(1)* to B addrspace(1)*
1964     //   Y = addrspacecast A addrspace(1)* to B addrspace(2)*
1965     //   Z = gep Y, <...constant indices...>
1966     // Into an addrspacecasted GEP of the struct.
1967     if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1968       PtrOp = BC;
1969   }
1970 
1971   /// See if we can simplify:
1972   ///   X = bitcast A* to B*
1973   ///   Y = gep X, <...constant indices...>
1974   /// into a gep of the original struct.  This is important for SROA and alias
1975   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
1976   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1977     Value *Operand = BCI->getOperand(0);
1978     PointerType *OpType = cast<PointerType>(Operand->getType());
1979     unsigned OffsetBits = DL.getIndexTypeSizeInBits(GEP.getType());
1980     APInt Offset(OffsetBits, 0);
1981     if (!isa<BitCastInst>(Operand) &&
1982         GEP.accumulateConstantOffset(DL, Offset)) {
1983 
1984       // If this GEP instruction doesn't move the pointer, just replace the GEP
1985       // with a bitcast of the real input to the dest type.
1986       if (!Offset) {
1987         // If the bitcast is of an allocation, and the allocation will be
1988         // converted to match the type of the cast, don't touch this.
1989         if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, &TLI)) {
1990           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1991           if (Instruction *I = visitBitCast(*BCI)) {
1992             if (I != BCI) {
1993               I->takeName(BCI);
1994               BCI->getParent()->getInstList().insert(BCI->getIterator(), I);
1995               replaceInstUsesWith(*BCI, I);
1996             }
1997             return &GEP;
1998           }
1999         }
2000 
2001         if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
2002           return new AddrSpaceCastInst(Operand, GEP.getType());
2003         return new BitCastInst(Operand, GEP.getType());
2004       }
2005 
2006       // Otherwise, if the offset is non-zero, we need to find out if there is a
2007       // field at Offset in 'A's type.  If so, we can pull the cast through the
2008       // GEP.
2009       SmallVector<Value*, 8> NewIndices;
2010       if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
2011         Value *NGEP =
2012             GEP.isInBounds()
2013                 ? Builder.CreateInBoundsGEP(nullptr, Operand, NewIndices)
2014                 : Builder.CreateGEP(nullptr, Operand, NewIndices);
2015 
2016         if (NGEP->getType() == GEP.getType())
2017           return replaceInstUsesWith(GEP, NGEP);
2018         NGEP->takeName(&GEP);
2019 
2020         if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
2021           return new AddrSpaceCastInst(NGEP, GEP.getType());
2022         return new BitCastInst(NGEP, GEP.getType());
2023       }
2024     }
2025   }
2026 
2027   if (!GEP.isInBounds()) {
2028     unsigned IdxWidth =
2029         DL.getIndexSizeInBits(PtrOp->getType()->getPointerAddressSpace());
2030     APInt BasePtrOffset(IdxWidth, 0);
2031     Value *UnderlyingPtrOp =
2032             PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL,
2033                                                              BasePtrOffset);
2034     if (auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) {
2035       if (GEP.accumulateConstantOffset(DL, BasePtrOffset) &&
2036           BasePtrOffset.isNonNegative()) {
2037         APInt AllocSize(IdxWidth, DL.getTypeAllocSize(AI->getAllocatedType()));
2038         if (BasePtrOffset.ule(AllocSize)) {
2039           return GetElementPtrInst::CreateInBounds(
2040               PtrOp, makeArrayRef(Ops).slice(1), GEP.getName());
2041         }
2042       }
2043     }
2044   }
2045 
2046   return nullptr;
2047 }
2048 
2049 static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI,
2050                                          Instruction *AI) {
2051   if (isa<ConstantPointerNull>(V))
2052     return true;
2053   if (auto *LI = dyn_cast<LoadInst>(V))
2054     return isa<GlobalVariable>(LI->getPointerOperand());
2055   // Two distinct allocations will never be equal.
2056   // We rely on LookThroughBitCast in isAllocLikeFn being false, since looking
2057   // through bitcasts of V can cause
2058   // the result statement below to be true, even when AI and V (ex:
2059   // i8* ->i32* ->i8* of AI) are the same allocations.
2060   return isAllocLikeFn(V, TLI) && V != AI;
2061 }
2062 
2063 static bool isAllocSiteRemovable(Instruction *AI,
2064                                  SmallVectorImpl<WeakTrackingVH> &Users,
2065                                  const TargetLibraryInfo *TLI) {
2066   SmallVector<Instruction*, 4> Worklist;
2067   Worklist.push_back(AI);
2068 
2069   do {
2070     Instruction *PI = Worklist.pop_back_val();
2071     for (User *U : PI->users()) {
2072       Instruction *I = cast<Instruction>(U);
2073       switch (I->getOpcode()) {
2074       default:
2075         // Give up the moment we see something we can't handle.
2076         return false;
2077 
2078       case Instruction::AddrSpaceCast:
2079       case Instruction::BitCast:
2080       case Instruction::GetElementPtr:
2081         Users.emplace_back(I);
2082         Worklist.push_back(I);
2083         continue;
2084 
2085       case Instruction::ICmp: {
2086         ICmpInst *ICI = cast<ICmpInst>(I);
2087         // We can fold eq/ne comparisons with null to false/true, respectively.
2088         // We also fold comparisons in some conditions provided the alloc has
2089         // not escaped (see isNeverEqualToUnescapedAlloc).
2090         if (!ICI->isEquality())
2091           return false;
2092         unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0;
2093         if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI))
2094           return false;
2095         Users.emplace_back(I);
2096         continue;
2097       }
2098 
2099       case Instruction::Call:
2100         // Ignore no-op and store intrinsics.
2101         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2102           switch (II->getIntrinsicID()) {
2103           default:
2104             return false;
2105 
2106           case Intrinsic::memmove:
2107           case Intrinsic::memcpy:
2108           case Intrinsic::memset: {
2109             MemIntrinsic *MI = cast<MemIntrinsic>(II);
2110             if (MI->isVolatile() || MI->getRawDest() != PI)
2111               return false;
2112             LLVM_FALLTHROUGH;
2113           }
2114           case Intrinsic::invariant_start:
2115           case Intrinsic::invariant_end:
2116           case Intrinsic::lifetime_start:
2117           case Intrinsic::lifetime_end:
2118           case Intrinsic::objectsize:
2119             Users.emplace_back(I);
2120             continue;
2121           }
2122         }
2123 
2124         if (isFreeCall(I, TLI)) {
2125           Users.emplace_back(I);
2126           continue;
2127         }
2128         return false;
2129 
2130       case Instruction::Store: {
2131         StoreInst *SI = cast<StoreInst>(I);
2132         if (SI->isVolatile() || SI->getPointerOperand() != PI)
2133           return false;
2134         Users.emplace_back(I);
2135         continue;
2136       }
2137       }
2138       llvm_unreachable("missing a return?");
2139     }
2140   } while (!Worklist.empty());
2141   return true;
2142 }
2143 
2144 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
2145   // If we have a malloc call which is only used in any amount of comparisons
2146   // to null and free calls, delete the calls and replace the comparisons with
2147   // true or false as appropriate.
2148   SmallVector<WeakTrackingVH, 64> Users;
2149 
2150   // If we are removing an alloca with a dbg.declare, insert dbg.value calls
2151   // before each store.
2152   TinyPtrVector<DbgInfoIntrinsic *> DIIs;
2153   std::unique_ptr<DIBuilder> DIB;
2154   if (isa<AllocaInst>(MI)) {
2155     DIIs = FindDbgAddrUses(&MI);
2156     DIB.reset(new DIBuilder(*MI.getModule(), /*AllowUnresolved=*/false));
2157   }
2158 
2159   if (isAllocSiteRemovable(&MI, Users, &TLI)) {
2160     for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2161       // Lowering all @llvm.objectsize calls first because they may
2162       // use a bitcast/GEP of the alloca we are removing.
2163       if (!Users[i])
2164        continue;
2165 
2166       Instruction *I = cast<Instruction>(&*Users[i]);
2167 
2168       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2169         if (II->getIntrinsicID() == Intrinsic::objectsize) {
2170           ConstantInt *Result = lowerObjectSizeCall(II, DL, &TLI,
2171                                                     /*MustSucceed=*/true);
2172           replaceInstUsesWith(*I, Result);
2173           eraseInstFromFunction(*I);
2174           Users[i] = nullptr; // Skip examining in the next loop.
2175         }
2176       }
2177     }
2178     for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2179       if (!Users[i])
2180         continue;
2181 
2182       Instruction *I = cast<Instruction>(&*Users[i]);
2183 
2184       if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
2185         replaceInstUsesWith(*C,
2186                             ConstantInt::get(Type::getInt1Ty(C->getContext()),
2187                                              C->isFalseWhenEqual()));
2188       } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I) ||
2189                  isa<AddrSpaceCastInst>(I)) {
2190         replaceInstUsesWith(*I, UndefValue::get(I->getType()));
2191       } else if (auto *SI = dyn_cast<StoreInst>(I)) {
2192         for (auto *DII : DIIs)
2193           ConvertDebugDeclareToDebugValue(DII, SI, *DIB);
2194       }
2195       eraseInstFromFunction(*I);
2196     }
2197 
2198     if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
2199       // Replace invoke with a NOP intrinsic to maintain the original CFG
2200       Module *M = II->getModule();
2201       Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
2202       InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
2203                          None, "", II->getParent());
2204     }
2205 
2206     for (auto *DII : DIIs)
2207       eraseInstFromFunction(*DII);
2208 
2209     return eraseInstFromFunction(MI);
2210   }
2211   return nullptr;
2212 }
2213 
2214 /// \brief Move the call to free before a NULL test.
2215 ///
2216 /// Check if this free is accessed after its argument has been test
2217 /// against NULL (property 0).
2218 /// If yes, it is legal to move this call in its predecessor block.
2219 ///
2220 /// The move is performed only if the block containing the call to free
2221 /// will be removed, i.e.:
2222 /// 1. it has only one predecessor P, and P has two successors
2223 /// 2. it contains the call and an unconditional branch
2224 /// 3. its successor is the same as its predecessor's successor
2225 ///
2226 /// The profitability is out-of concern here and this function should
2227 /// be called only if the caller knows this transformation would be
2228 /// profitable (e.g., for code size).
2229 static Instruction *
2230 tryToMoveFreeBeforeNullTest(CallInst &FI) {
2231   Value *Op = FI.getArgOperand(0);
2232   BasicBlock *FreeInstrBB = FI.getParent();
2233   BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
2234 
2235   // Validate part of constraint #1: Only one predecessor
2236   // FIXME: We can extend the number of predecessor, but in that case, we
2237   //        would duplicate the call to free in each predecessor and it may
2238   //        not be profitable even for code size.
2239   if (!PredBB)
2240     return nullptr;
2241 
2242   // Validate constraint #2: Does this block contains only the call to
2243   //                         free and an unconditional branch?
2244   // FIXME: We could check if we can speculate everything in the
2245   //        predecessor block
2246   if (FreeInstrBB->size() != 2)
2247     return nullptr;
2248   BasicBlock *SuccBB;
2249   if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
2250     return nullptr;
2251 
2252   // Validate the rest of constraint #1 by matching on the pred branch.
2253   TerminatorInst *TI = PredBB->getTerminator();
2254   BasicBlock *TrueBB, *FalseBB;
2255   ICmpInst::Predicate Pred;
2256   if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
2257     return nullptr;
2258   if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2259     return nullptr;
2260 
2261   // Validate constraint #3: Ensure the null case just falls through.
2262   if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
2263     return nullptr;
2264   assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
2265          "Broken CFG: missing edge from predecessor to successor");
2266 
2267   FI.moveBefore(TI);
2268   return &FI;
2269 }
2270 
2271 Instruction *InstCombiner::visitFree(CallInst &FI) {
2272   Value *Op = FI.getArgOperand(0);
2273 
2274   // free undef -> unreachable.
2275   if (isa<UndefValue>(Op)) {
2276     // Insert a new store to null because we cannot modify the CFG here.
2277     Builder.CreateStore(ConstantInt::getTrue(FI.getContext()),
2278                         UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
2279     return eraseInstFromFunction(FI);
2280   }
2281 
2282   // If we have 'free null' delete the instruction.  This can happen in stl code
2283   // when lots of inlining happens.
2284   if (isa<ConstantPointerNull>(Op))
2285     return eraseInstFromFunction(FI);
2286 
2287   // If we optimize for code size, try to move the call to free before the null
2288   // test so that simplify cfg can remove the empty block and dead code
2289   // elimination the branch. I.e., helps to turn something like:
2290   // if (foo) free(foo);
2291   // into
2292   // free(foo);
2293   if (MinimizeSize)
2294     if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
2295       return I;
2296 
2297   return nullptr;
2298 }
2299 
2300 Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
2301   if (RI.getNumOperands() == 0) // ret void
2302     return nullptr;
2303 
2304   Value *ResultOp = RI.getOperand(0);
2305   Type *VTy = ResultOp->getType();
2306   if (!VTy->isIntegerTy())
2307     return nullptr;
2308 
2309   // There might be assume intrinsics dominating this return that completely
2310   // determine the value. If so, constant fold it.
2311   KnownBits Known = computeKnownBits(ResultOp, 0, &RI);
2312   if (Known.isConstant())
2313     RI.setOperand(0, Constant::getIntegerValue(VTy, Known.getConstant()));
2314 
2315   return nullptr;
2316 }
2317 
2318 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2319   // Change br (not X), label True, label False to: br X, label False, True
2320   Value *X = nullptr;
2321   BasicBlock *TrueDest;
2322   BasicBlock *FalseDest;
2323   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
2324       !isa<Constant>(X)) {
2325     // Swap Destinations and condition...
2326     BI.setCondition(X);
2327     BI.swapSuccessors();
2328     return &BI;
2329   }
2330 
2331   // If the condition is irrelevant, remove the use so that other
2332   // transforms on the condition become more effective.
2333   if (BI.isConditional() && !isa<ConstantInt>(BI.getCondition()) &&
2334       BI.getSuccessor(0) == BI.getSuccessor(1)) {
2335     BI.setCondition(ConstantInt::getFalse(BI.getCondition()->getType()));
2336     return &BI;
2337   }
2338 
2339   // Canonicalize, for example, icmp_ne -> icmp_eq or fcmp_one -> fcmp_oeq.
2340   CmpInst::Predicate Pred;
2341   if (match(&BI, m_Br(m_OneUse(m_Cmp(Pred, m_Value(), m_Value())), TrueDest,
2342                       FalseDest)) &&
2343       !isCanonicalPredicate(Pred)) {
2344     // Swap destinations and condition.
2345     CmpInst *Cond = cast<CmpInst>(BI.getCondition());
2346     Cond->setPredicate(CmpInst::getInversePredicate(Pred));
2347     BI.swapSuccessors();
2348     Worklist.Add(Cond);
2349     return &BI;
2350   }
2351 
2352   return nullptr;
2353 }
2354 
2355 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2356   Value *Cond = SI.getCondition();
2357   Value *Op0;
2358   ConstantInt *AddRHS;
2359   if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) {
2360     // Change 'switch (X+4) case 1:' into 'switch (X) case -3'.
2361     for (auto Case : SI.cases()) {
2362       Constant *NewCase = ConstantExpr::getSub(Case.getCaseValue(), AddRHS);
2363       assert(isa<ConstantInt>(NewCase) &&
2364              "Result of expression should be constant");
2365       Case.setValue(cast<ConstantInt>(NewCase));
2366     }
2367     SI.setCondition(Op0);
2368     return &SI;
2369   }
2370 
2371   KnownBits Known = computeKnownBits(Cond, 0, &SI);
2372   unsigned LeadingKnownZeros = Known.countMinLeadingZeros();
2373   unsigned LeadingKnownOnes = Known.countMinLeadingOnes();
2374 
2375   // Compute the number of leading bits we can ignore.
2376   // TODO: A better way to determine this would use ComputeNumSignBits().
2377   for (auto &C : SI.cases()) {
2378     LeadingKnownZeros = std::min(
2379         LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2380     LeadingKnownOnes = std::min(
2381         LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2382   }
2383 
2384   unsigned NewWidth = Known.getBitWidth() - std::max(LeadingKnownZeros, LeadingKnownOnes);
2385 
2386   // Shrink the condition operand if the new type is smaller than the old type.
2387   // This may produce a non-standard type for the switch, but that's ok because
2388   // the backend should extend back to a legal type for the target.
2389   if (NewWidth > 0 && NewWidth < Known.getBitWidth()) {
2390     IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2391     Builder.SetInsertPoint(&SI);
2392     Value *NewCond = Builder.CreateTrunc(Cond, Ty, "trunc");
2393     SI.setCondition(NewCond);
2394 
2395     for (auto Case : SI.cases()) {
2396       APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth);
2397       Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));
2398     }
2399     return &SI;
2400   }
2401 
2402   return nullptr;
2403 }
2404 
2405 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
2406   Value *Agg = EV.getAggregateOperand();
2407 
2408   if (!EV.hasIndices())
2409     return replaceInstUsesWith(EV, Agg);
2410 
2411   if (Value *V = SimplifyExtractValueInst(Agg, EV.getIndices(),
2412                                           SQ.getWithInstruction(&EV)))
2413     return replaceInstUsesWith(EV, V);
2414 
2415   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2416     // We're extracting from an insertvalue instruction, compare the indices
2417     const unsigned *exti, *exte, *insi, *inse;
2418     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2419          exte = EV.idx_end(), inse = IV->idx_end();
2420          exti != exte && insi != inse;
2421          ++exti, ++insi) {
2422       if (*insi != *exti)
2423         // The insert and extract both reference distinctly different elements.
2424         // This means the extract is not influenced by the insert, and we can
2425         // replace the aggregate operand of the extract with the aggregate
2426         // operand of the insert. i.e., replace
2427         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2428         // %E = extractvalue { i32, { i32 } } %I, 0
2429         // with
2430         // %E = extractvalue { i32, { i32 } } %A, 0
2431         return ExtractValueInst::Create(IV->getAggregateOperand(),
2432                                         EV.getIndices());
2433     }
2434     if (exti == exte && insi == inse)
2435       // Both iterators are at the end: Index lists are identical. Replace
2436       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2437       // %C = extractvalue { i32, { i32 } } %B, 1, 0
2438       // with "i32 42"
2439       return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
2440     if (exti == exte) {
2441       // The extract list is a prefix of the insert list. i.e. replace
2442       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2443       // %E = extractvalue { i32, { i32 } } %I, 1
2444       // with
2445       // %X = extractvalue { i32, { i32 } } %A, 1
2446       // %E = insertvalue { i32 } %X, i32 42, 0
2447       // by switching the order of the insert and extract (though the
2448       // insertvalue should be left in, since it may have other uses).
2449       Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(),
2450                                                 EV.getIndices());
2451       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
2452                                      makeArrayRef(insi, inse));
2453     }
2454     if (insi == inse)
2455       // The insert list is a prefix of the extract list
2456       // We can simply remove the common indices from the extract and make it
2457       // operate on the inserted value instead of the insertvalue result.
2458       // i.e., replace
2459       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2460       // %E = extractvalue { i32, { i32 } } %I, 1, 0
2461       // with
2462       // %E extractvalue { i32 } { i32 42 }, 0
2463       return ExtractValueInst::Create(IV->getInsertedValueOperand(),
2464                                       makeArrayRef(exti, exte));
2465   }
2466   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2467     // We're extracting from an intrinsic, see if we're the only user, which
2468     // allows us to simplify multiple result intrinsics to simpler things that
2469     // just get one value.
2470     if (II->hasOneUse()) {
2471       // Check if we're grabbing the overflow bit or the result of a 'with
2472       // overflow' intrinsic.  If it's the latter we can remove the intrinsic
2473       // and replace it with a traditional binary instruction.
2474       switch (II->getIntrinsicID()) {
2475       case Intrinsic::uadd_with_overflow:
2476       case Intrinsic::sadd_with_overflow:
2477         if (*EV.idx_begin() == 0) {  // Normal result.
2478           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2479           replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2480           eraseInstFromFunction(*II);
2481           return BinaryOperator::CreateAdd(LHS, RHS);
2482         }
2483 
2484         // If the normal result of the add is dead, and the RHS is a constant,
2485         // we can transform this into a range comparison.
2486         // overflow = uadd a, -4  -->  overflow = icmp ugt a, 3
2487         if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2488           if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2489             return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2490                                 ConstantExpr::getNot(CI));
2491         break;
2492       case Intrinsic::usub_with_overflow:
2493       case Intrinsic::ssub_with_overflow:
2494         if (*EV.idx_begin() == 0) {  // Normal result.
2495           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2496           replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2497           eraseInstFromFunction(*II);
2498           return BinaryOperator::CreateSub(LHS, RHS);
2499         }
2500         break;
2501       case Intrinsic::umul_with_overflow:
2502       case Intrinsic::smul_with_overflow:
2503         if (*EV.idx_begin() == 0) {  // Normal result.
2504           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2505           replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2506           eraseInstFromFunction(*II);
2507           return BinaryOperator::CreateMul(LHS, RHS);
2508         }
2509         break;
2510       default:
2511         break;
2512       }
2513     }
2514   }
2515   if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2516     // If the (non-volatile) load only has one use, we can rewrite this to a
2517     // load from a GEP. This reduces the size of the load. If a load is used
2518     // only by extractvalue instructions then this either must have been
2519     // optimized before, or it is a struct with padding, in which case we
2520     // don't want to do the transformation as it loses padding knowledge.
2521     if (L->isSimple() && L->hasOneUse()) {
2522       // extractvalue has integer indices, getelementptr has Value*s. Convert.
2523       SmallVector<Value*, 4> Indices;
2524       // Prefix an i32 0 since we need the first element.
2525       Indices.push_back(Builder.getInt32(0));
2526       for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2527             I != E; ++I)
2528         Indices.push_back(Builder.getInt32(*I));
2529 
2530       // We need to insert these at the location of the old load, not at that of
2531       // the extractvalue.
2532       Builder.SetInsertPoint(L);
2533       Value *GEP = Builder.CreateInBoundsGEP(L->getType(),
2534                                              L->getPointerOperand(), Indices);
2535       Instruction *NL = Builder.CreateLoad(GEP);
2536       // Whatever aliasing information we had for the orignal load must also
2537       // hold for the smaller load, so propagate the annotations.
2538       AAMDNodes Nodes;
2539       L->getAAMetadata(Nodes);
2540       NL->setAAMetadata(Nodes);
2541       // Returning the load directly will cause the main loop to insert it in
2542       // the wrong spot, so use replaceInstUsesWith().
2543       return replaceInstUsesWith(EV, NL);
2544     }
2545   // We could simplify extracts from other values. Note that nested extracts may
2546   // already be simplified implicitly by the above: extract (extract (insert) )
2547   // will be translated into extract ( insert ( extract ) ) first and then just
2548   // the value inserted, if appropriate. Similarly for extracts from single-use
2549   // loads: extract (extract (load)) will be translated to extract (load (gep))
2550   // and if again single-use then via load (gep (gep)) to load (gep).
2551   // However, double extracts from e.g. function arguments or return values
2552   // aren't handled yet.
2553   return nullptr;
2554 }
2555 
2556 /// Return 'true' if the given typeinfo will match anything.
2557 static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
2558   switch (Personality) {
2559   case EHPersonality::GNU_C:
2560   case EHPersonality::GNU_C_SjLj:
2561   case EHPersonality::Rust:
2562     // The GCC C EH and Rust personality only exists to support cleanups, so
2563     // it's not clear what the semantics of catch clauses are.
2564     return false;
2565   case EHPersonality::Unknown:
2566     return false;
2567   case EHPersonality::GNU_Ada:
2568     // While __gnat_all_others_value will match any Ada exception, it doesn't
2569     // match foreign exceptions (or didn't, before gcc-4.7).
2570     return false;
2571   case EHPersonality::GNU_CXX:
2572   case EHPersonality::GNU_CXX_SjLj:
2573   case EHPersonality::GNU_ObjC:
2574   case EHPersonality::MSVC_X86SEH:
2575   case EHPersonality::MSVC_Win64SEH:
2576   case EHPersonality::MSVC_CXX:
2577   case EHPersonality::CoreCLR:
2578     return TypeInfo->isNullValue();
2579   }
2580   llvm_unreachable("invalid enum");
2581 }
2582 
2583 static bool shorter_filter(const Value *LHS, const Value *RHS) {
2584   return
2585     cast<ArrayType>(LHS->getType())->getNumElements()
2586   <
2587     cast<ArrayType>(RHS->getType())->getNumElements();
2588 }
2589 
2590 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2591   // The logic here should be correct for any real-world personality function.
2592   // However if that turns out not to be true, the offending logic can always
2593   // be conditioned on the personality function, like the catch-all logic is.
2594   EHPersonality Personality =
2595       classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
2596 
2597   // Simplify the list of clauses, eg by removing repeated catch clauses
2598   // (these are often created by inlining).
2599   bool MakeNewInstruction = false; // If true, recreate using the following:
2600   SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
2601   bool CleanupFlag = LI.isCleanup();   // - The new instruction is a cleanup.
2602 
2603   SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2604   for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2605     bool isLastClause = i + 1 == e;
2606     if (LI.isCatch(i)) {
2607       // A catch clause.
2608       Constant *CatchClause = LI.getClause(i);
2609       Constant *TypeInfo = CatchClause->stripPointerCasts();
2610 
2611       // If we already saw this clause, there is no point in having a second
2612       // copy of it.
2613       if (AlreadyCaught.insert(TypeInfo).second) {
2614         // This catch clause was not already seen.
2615         NewClauses.push_back(CatchClause);
2616       } else {
2617         // Repeated catch clause - drop the redundant copy.
2618         MakeNewInstruction = true;
2619       }
2620 
2621       // If this is a catch-all then there is no point in keeping any following
2622       // clauses or marking the landingpad as having a cleanup.
2623       if (isCatchAll(Personality, TypeInfo)) {
2624         if (!isLastClause)
2625           MakeNewInstruction = true;
2626         CleanupFlag = false;
2627         break;
2628       }
2629     } else {
2630       // A filter clause.  If any of the filter elements were already caught
2631       // then they can be dropped from the filter.  It is tempting to try to
2632       // exploit the filter further by saying that any typeinfo that does not
2633       // occur in the filter can't be caught later (and thus can be dropped).
2634       // However this would be wrong, since typeinfos can match without being
2635       // equal (for example if one represents a C++ class, and the other some
2636       // class derived from it).
2637       assert(LI.isFilter(i) && "Unsupported landingpad clause!");
2638       Constant *FilterClause = LI.getClause(i);
2639       ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2640       unsigned NumTypeInfos = FilterType->getNumElements();
2641 
2642       // An empty filter catches everything, so there is no point in keeping any
2643       // following clauses or marking the landingpad as having a cleanup.  By
2644       // dealing with this case here the following code is made a bit simpler.
2645       if (!NumTypeInfos) {
2646         NewClauses.push_back(FilterClause);
2647         if (!isLastClause)
2648           MakeNewInstruction = true;
2649         CleanupFlag = false;
2650         break;
2651       }
2652 
2653       bool MakeNewFilter = false; // If true, make a new filter.
2654       SmallVector<Constant *, 16> NewFilterElts; // New elements.
2655       if (isa<ConstantAggregateZero>(FilterClause)) {
2656         // Not an empty filter - it contains at least one null typeinfo.
2657         assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2658         Constant *TypeInfo =
2659           Constant::getNullValue(FilterType->getElementType());
2660         // If this typeinfo is a catch-all then the filter can never match.
2661         if (isCatchAll(Personality, TypeInfo)) {
2662           // Throw the filter away.
2663           MakeNewInstruction = true;
2664           continue;
2665         }
2666 
2667         // There is no point in having multiple copies of this typeinfo, so
2668         // discard all but the first copy if there is more than one.
2669         NewFilterElts.push_back(TypeInfo);
2670         if (NumTypeInfos > 1)
2671           MakeNewFilter = true;
2672       } else {
2673         ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2674         SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2675         NewFilterElts.reserve(NumTypeInfos);
2676 
2677         // Remove any filter elements that were already caught or that already
2678         // occurred in the filter.  While there, see if any of the elements are
2679         // catch-alls.  If so, the filter can be discarded.
2680         bool SawCatchAll = false;
2681         for (unsigned j = 0; j != NumTypeInfos; ++j) {
2682           Constant *Elt = Filter->getOperand(j);
2683           Constant *TypeInfo = Elt->stripPointerCasts();
2684           if (isCatchAll(Personality, TypeInfo)) {
2685             // This element is a catch-all.  Bail out, noting this fact.
2686             SawCatchAll = true;
2687             break;
2688           }
2689 
2690           // Even if we've seen a type in a catch clause, we don't want to
2691           // remove it from the filter.  An unexpected type handler may be
2692           // set up for a call site which throws an exception of the same
2693           // type caught.  In order for the exception thrown by the unexpected
2694           // handler to propagate correctly, the filter must be correctly
2695           // described for the call site.
2696           //
2697           // Example:
2698           //
2699           // void unexpected() { throw 1;}
2700           // void foo() throw (int) {
2701           //   std::set_unexpected(unexpected);
2702           //   try {
2703           //     throw 2.0;
2704           //   } catch (int i) {}
2705           // }
2706 
2707           // There is no point in having multiple copies of the same typeinfo in
2708           // a filter, so only add it if we didn't already.
2709           if (SeenInFilter.insert(TypeInfo).second)
2710             NewFilterElts.push_back(cast<Constant>(Elt));
2711         }
2712         // A filter containing a catch-all cannot match anything by definition.
2713         if (SawCatchAll) {
2714           // Throw the filter away.
2715           MakeNewInstruction = true;
2716           continue;
2717         }
2718 
2719         // If we dropped something from the filter, make a new one.
2720         if (NewFilterElts.size() < NumTypeInfos)
2721           MakeNewFilter = true;
2722       }
2723       if (MakeNewFilter) {
2724         FilterType = ArrayType::get(FilterType->getElementType(),
2725                                     NewFilterElts.size());
2726         FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2727         MakeNewInstruction = true;
2728       }
2729 
2730       NewClauses.push_back(FilterClause);
2731 
2732       // If the new filter is empty then it will catch everything so there is
2733       // no point in keeping any following clauses or marking the landingpad
2734       // as having a cleanup.  The case of the original filter being empty was
2735       // already handled above.
2736       if (MakeNewFilter && !NewFilterElts.size()) {
2737         assert(MakeNewInstruction && "New filter but not a new instruction!");
2738         CleanupFlag = false;
2739         break;
2740       }
2741     }
2742   }
2743 
2744   // If several filters occur in a row then reorder them so that the shortest
2745   // filters come first (those with the smallest number of elements).  This is
2746   // advantageous because shorter filters are more likely to match, speeding up
2747   // unwinding, but mostly because it increases the effectiveness of the other
2748   // filter optimizations below.
2749   for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2750     unsigned j;
2751     // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2752     for (j = i; j != e; ++j)
2753       if (!isa<ArrayType>(NewClauses[j]->getType()))
2754         break;
2755 
2756     // Check whether the filters are already sorted by length.  We need to know
2757     // if sorting them is actually going to do anything so that we only make a
2758     // new landingpad instruction if it does.
2759     for (unsigned k = i; k + 1 < j; ++k)
2760       if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2761         // Not sorted, so sort the filters now.  Doing an unstable sort would be
2762         // correct too but reordering filters pointlessly might confuse users.
2763         std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2764                          shorter_filter);
2765         MakeNewInstruction = true;
2766         break;
2767       }
2768 
2769     // Look for the next batch of filters.
2770     i = j + 1;
2771   }
2772 
2773   // If typeinfos matched if and only if equal, then the elements of a filter L
2774   // that occurs later than a filter F could be replaced by the intersection of
2775   // the elements of F and L.  In reality two typeinfos can match without being
2776   // equal (for example if one represents a C++ class, and the other some class
2777   // derived from it) so it would be wrong to perform this transform in general.
2778   // However the transform is correct and useful if F is a subset of L.  In that
2779   // case L can be replaced by F, and thus removed altogether since repeating a
2780   // filter is pointless.  So here we look at all pairs of filters F and L where
2781   // L follows F in the list of clauses, and remove L if every element of F is
2782   // an element of L.  This can occur when inlining C++ functions with exception
2783   // specifications.
2784   for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2785     // Examine each filter in turn.
2786     Value *Filter = NewClauses[i];
2787     ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2788     if (!FTy)
2789       // Not a filter - skip it.
2790       continue;
2791     unsigned FElts = FTy->getNumElements();
2792     // Examine each filter following this one.  Doing this backwards means that
2793     // we don't have to worry about filters disappearing under us when removed.
2794     for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2795       Value *LFilter = NewClauses[j];
2796       ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2797       if (!LTy)
2798         // Not a filter - skip it.
2799         continue;
2800       // If Filter is a subset of LFilter, i.e. every element of Filter is also
2801       // an element of LFilter, then discard LFilter.
2802       SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
2803       // If Filter is empty then it is a subset of LFilter.
2804       if (!FElts) {
2805         // Discard LFilter.
2806         NewClauses.erase(J);
2807         MakeNewInstruction = true;
2808         // Move on to the next filter.
2809         continue;
2810       }
2811       unsigned LElts = LTy->getNumElements();
2812       // If Filter is longer than LFilter then it cannot be a subset of it.
2813       if (FElts > LElts)
2814         // Move on to the next filter.
2815         continue;
2816       // At this point we know that LFilter has at least one element.
2817       if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
2818         // Filter is a subset of LFilter iff Filter contains only zeros (as we
2819         // already know that Filter is not longer than LFilter).
2820         if (isa<ConstantAggregateZero>(Filter)) {
2821           assert(FElts <= LElts && "Should have handled this case earlier!");
2822           // Discard LFilter.
2823           NewClauses.erase(J);
2824           MakeNewInstruction = true;
2825         }
2826         // Move on to the next filter.
2827         continue;
2828       }
2829       ConstantArray *LArray = cast<ConstantArray>(LFilter);
2830       if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2831         // Since Filter is non-empty and contains only zeros, it is a subset of
2832         // LFilter iff LFilter contains a zero.
2833         assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2834         for (unsigned l = 0; l != LElts; ++l)
2835           if (LArray->getOperand(l)->isNullValue()) {
2836             // LFilter contains a zero - discard it.
2837             NewClauses.erase(J);
2838             MakeNewInstruction = true;
2839             break;
2840           }
2841         // Move on to the next filter.
2842         continue;
2843       }
2844       // At this point we know that both filters are ConstantArrays.  Loop over
2845       // operands to see whether every element of Filter is also an element of
2846       // LFilter.  Since filters tend to be short this is probably faster than
2847       // using a method that scales nicely.
2848       ConstantArray *FArray = cast<ConstantArray>(Filter);
2849       bool AllFound = true;
2850       for (unsigned f = 0; f != FElts; ++f) {
2851         Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2852         AllFound = false;
2853         for (unsigned l = 0; l != LElts; ++l) {
2854           Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2855           if (LTypeInfo == FTypeInfo) {
2856             AllFound = true;
2857             break;
2858           }
2859         }
2860         if (!AllFound)
2861           break;
2862       }
2863       if (AllFound) {
2864         // Discard LFilter.
2865         NewClauses.erase(J);
2866         MakeNewInstruction = true;
2867       }
2868       // Move on to the next filter.
2869     }
2870   }
2871 
2872   // If we changed any of the clauses, replace the old landingpad instruction
2873   // with a new one.
2874   if (MakeNewInstruction) {
2875     LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
2876                                                  NewClauses.size());
2877     for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2878       NLI->addClause(NewClauses[i]);
2879     // A landing pad with no clauses must have the cleanup flag set.  It is
2880     // theoretically possible, though highly unlikely, that we eliminated all
2881     // clauses.  If so, force the cleanup flag to true.
2882     if (NewClauses.empty())
2883       CleanupFlag = true;
2884     NLI->setCleanup(CleanupFlag);
2885     return NLI;
2886   }
2887 
2888   // Even if none of the clauses changed, we may nonetheless have understood
2889   // that the cleanup flag is pointless.  Clear it if so.
2890   if (LI.isCleanup() != CleanupFlag) {
2891     assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2892     LI.setCleanup(CleanupFlag);
2893     return &LI;
2894   }
2895 
2896   return nullptr;
2897 }
2898 
2899 /// Try to move the specified instruction from its current block into the
2900 /// beginning of DestBlock, which can only happen if it's safe to move the
2901 /// instruction past all of the instructions between it and the end of its
2902 /// block.
2903 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2904   assert(I->hasOneUse() && "Invariants didn't hold!");
2905 
2906   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
2907   if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() ||
2908       isa<TerminatorInst>(I))
2909     return false;
2910 
2911   // Do not sink alloca instructions out of the entry block.
2912   if (isa<AllocaInst>(I) && I->getParent() ==
2913         &DestBlock->getParent()->getEntryBlock())
2914     return false;
2915 
2916   // Do not sink into catchswitch blocks.
2917   if (isa<CatchSwitchInst>(DestBlock->getTerminator()))
2918     return false;
2919 
2920   // Do not sink convergent call instructions.
2921   if (auto *CI = dyn_cast<CallInst>(I)) {
2922     if (CI->isConvergent())
2923       return false;
2924   }
2925   // We can only sink load instructions if there is nothing between the load and
2926   // the end of block that could change the value.
2927   if (I->mayReadFromMemory()) {
2928     for (BasicBlock::iterator Scan = I->getIterator(),
2929                               E = I->getParent()->end();
2930          Scan != E; ++Scan)
2931       if (Scan->mayWriteToMemory())
2932         return false;
2933   }
2934 
2935   BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
2936   I->moveBefore(&*InsertPos);
2937   ++NumSunkInst;
2938   return true;
2939 }
2940 
2941 bool InstCombiner::run() {
2942   while (!Worklist.isEmpty()) {
2943     Instruction *I = Worklist.RemoveOne();
2944     if (I == nullptr) continue;  // skip null values.
2945 
2946     // Check to see if we can DCE the instruction.
2947     if (isInstructionTriviallyDead(I, &TLI)) {
2948       DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
2949       eraseInstFromFunction(*I);
2950       ++NumDeadInst;
2951       MadeIRChange = true;
2952       continue;
2953     }
2954 
2955     if (!DebugCounter::shouldExecute(VisitCounter))
2956       continue;
2957 
2958     // Instruction isn't dead, see if we can constant propagate it.
2959     if (!I->use_empty() &&
2960         (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) {
2961       if (Constant *C = ConstantFoldInstruction(I, DL, &TLI)) {
2962         DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
2963 
2964         // Add operands to the worklist.
2965         replaceInstUsesWith(*I, C);
2966         ++NumConstProp;
2967         if (isInstructionTriviallyDead(I, &TLI))
2968           eraseInstFromFunction(*I);
2969         MadeIRChange = true;
2970         continue;
2971       }
2972     }
2973 
2974     // In general, it is possible for computeKnownBits to determine all bits in
2975     // a value even when the operands are not all constants.
2976     Type *Ty = I->getType();
2977     if (ExpensiveCombines && !I->use_empty() && Ty->isIntOrIntVectorTy()) {
2978       KnownBits Known = computeKnownBits(I, /*Depth*/0, I);
2979       if (Known.isConstant()) {
2980         Constant *C = ConstantInt::get(Ty, Known.getConstant());
2981         DEBUG(dbgs() << "IC: ConstFold (all bits known) to: " << *C <<
2982                         " from: " << *I << '\n');
2983 
2984         // Add operands to the worklist.
2985         replaceInstUsesWith(*I, C);
2986         ++NumConstProp;
2987         if (isInstructionTriviallyDead(I, &TLI))
2988           eraseInstFromFunction(*I);
2989         MadeIRChange = true;
2990         continue;
2991       }
2992     }
2993 
2994     // See if we can trivially sink this instruction to a successor basic block.
2995     if (I->hasOneUse()) {
2996       BasicBlock *BB = I->getParent();
2997       Instruction *UserInst = cast<Instruction>(*I->user_begin());
2998       BasicBlock *UserParent;
2999 
3000       // Get the block the use occurs in.
3001       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
3002         UserParent = PN->getIncomingBlock(*I->use_begin());
3003       else
3004         UserParent = UserInst->getParent();
3005 
3006       if (UserParent != BB) {
3007         bool UserIsSuccessor = false;
3008         // See if the user is one of our successors.
3009         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
3010           if (*SI == UserParent) {
3011             UserIsSuccessor = true;
3012             break;
3013           }
3014 
3015         // If the user is one of our immediate successors, and if that successor
3016         // only has us as a predecessors (we'd have to split the critical edge
3017         // otherwise), we can keep going.
3018         if (UserIsSuccessor && UserParent->getUniquePredecessor()) {
3019           // Okay, the CFG is simple enough, try to sink this instruction.
3020           if (TryToSinkInstruction(I, UserParent)) {
3021             DEBUG(dbgs() << "IC: Sink: " << *I << '\n');
3022             MadeIRChange = true;
3023             // We'll add uses of the sunk instruction below, but since sinking
3024             // can expose opportunities for it's *operands* add them to the
3025             // worklist
3026             for (Use &U : I->operands())
3027               if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
3028                 Worklist.Add(OpI);
3029           }
3030         }
3031       }
3032     }
3033 
3034     // Now that we have an instruction, try combining it to simplify it.
3035     Builder.SetInsertPoint(I);
3036     Builder.SetCurrentDebugLocation(I->getDebugLoc());
3037 
3038 #ifndef NDEBUG
3039     std::string OrigI;
3040 #endif
3041     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
3042     DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
3043 
3044     if (Instruction *Result = visit(*I)) {
3045       ++NumCombined;
3046       // Should we replace the old instruction with a new one?
3047       if (Result != I) {
3048         DEBUG(dbgs() << "IC: Old = " << *I << '\n'
3049                      << "    New = " << *Result << '\n');
3050 
3051         if (I->getDebugLoc())
3052           Result->setDebugLoc(I->getDebugLoc());
3053         // Everything uses the new instruction now.
3054         I->replaceAllUsesWith(Result);
3055 
3056         // Move the name to the new instruction first.
3057         Result->takeName(I);
3058 
3059         // Push the new instruction and any users onto the worklist.
3060         Worklist.AddUsersToWorkList(*Result);
3061         Worklist.Add(Result);
3062 
3063         // Insert the new instruction into the basic block...
3064         BasicBlock *InstParent = I->getParent();
3065         BasicBlock::iterator InsertPos = I->getIterator();
3066 
3067         // If we replace a PHI with something that isn't a PHI, fix up the
3068         // insertion point.
3069         if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
3070           InsertPos = InstParent->getFirstInsertionPt();
3071 
3072         InstParent->getInstList().insert(InsertPos, Result);
3073 
3074         eraseInstFromFunction(*I);
3075       } else {
3076         DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
3077                      << "    New = " << *I << '\n');
3078 
3079         // If the instruction was modified, it's possible that it is now dead.
3080         // if so, remove it.
3081         if (isInstructionTriviallyDead(I, &TLI)) {
3082           eraseInstFromFunction(*I);
3083         } else {
3084           Worklist.AddUsersToWorkList(*I);
3085           Worklist.Add(I);
3086         }
3087       }
3088       MadeIRChange = true;
3089     }
3090   }
3091 
3092   Worklist.Zap();
3093   return MadeIRChange;
3094 }
3095 
3096 /// Walk the function in depth-first order, adding all reachable code to the
3097 /// worklist.
3098 ///
3099 /// This has a couple of tricks to make the code faster and more powerful.  In
3100 /// particular, we constant fold and DCE instructions as we go, to avoid adding
3101 /// them to the worklist (this significantly speeds up instcombine on code where
3102 /// many instructions are dead or constant).  Additionally, if we find a branch
3103 /// whose condition is a known constant, we only visit the reachable successors.
3104 static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL,
3105                                        SmallPtrSetImpl<BasicBlock *> &Visited,
3106                                        InstCombineWorklist &ICWorklist,
3107                                        const TargetLibraryInfo *TLI) {
3108   bool MadeIRChange = false;
3109   SmallVector<BasicBlock*, 256> Worklist;
3110   Worklist.push_back(BB);
3111 
3112   SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
3113   DenseMap<Constant *, Constant *> FoldedConstants;
3114 
3115   do {
3116     BB = Worklist.pop_back_val();
3117 
3118     // We have now visited this block!  If we've already been here, ignore it.
3119     if (!Visited.insert(BB).second)
3120       continue;
3121 
3122     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
3123       Instruction *Inst = &*BBI++;
3124 
3125       // DCE instruction if trivially dead.
3126       if (isInstructionTriviallyDead(Inst, TLI)) {
3127         ++NumDeadInst;
3128         DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
3129         salvageDebugInfo(*Inst);
3130         Inst->eraseFromParent();
3131         MadeIRChange = true;
3132         continue;
3133       }
3134 
3135       // ConstantProp instruction if trivially constant.
3136       if (!Inst->use_empty() &&
3137           (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0))))
3138         if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
3139           DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
3140                        << *Inst << '\n');
3141           Inst->replaceAllUsesWith(C);
3142           ++NumConstProp;
3143           if (isInstructionTriviallyDead(Inst, TLI))
3144             Inst->eraseFromParent();
3145           MadeIRChange = true;
3146           continue;
3147         }
3148 
3149       // See if we can constant fold its operands.
3150       for (Use &U : Inst->operands()) {
3151         if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U))
3152           continue;
3153 
3154         auto *C = cast<Constant>(U);
3155         Constant *&FoldRes = FoldedConstants[C];
3156         if (!FoldRes)
3157           FoldRes = ConstantFoldConstant(C, DL, TLI);
3158         if (!FoldRes)
3159           FoldRes = C;
3160 
3161         if (FoldRes != C) {
3162           DEBUG(dbgs() << "IC: ConstFold operand of: " << *Inst
3163                        << "\n    Old = " << *C
3164                        << "\n    New = " << *FoldRes << '\n');
3165           U = FoldRes;
3166           MadeIRChange = true;
3167         }
3168       }
3169 
3170       // Skip processing debug intrinsics in InstCombine. Processing these call instructions
3171       // consumes non-trivial amount of time and provides no value for the optimization.
3172       if (!isa<DbgInfoIntrinsic>(Inst))
3173         InstrsForInstCombineWorklist.push_back(Inst);
3174     }
3175 
3176     // Recursively visit successors.  If this is a branch or switch on a
3177     // constant, only visit the reachable successor.
3178     TerminatorInst *TI = BB->getTerminator();
3179     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3180       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
3181         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
3182         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
3183         Worklist.push_back(ReachableBB);
3184         continue;
3185       }
3186     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3187       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
3188         Worklist.push_back(SI->findCaseValue(Cond)->getCaseSuccessor());
3189         continue;
3190       }
3191     }
3192 
3193     for (BasicBlock *SuccBB : TI->successors())
3194       Worklist.push_back(SuccBB);
3195   } while (!Worklist.empty());
3196 
3197   // Once we've found all of the instructions to add to instcombine's worklist,
3198   // add them in reverse order.  This way instcombine will visit from the top
3199   // of the function down.  This jives well with the way that it adds all uses
3200   // of instructions to the worklist after doing a transformation, thus avoiding
3201   // some N^2 behavior in pathological cases.
3202   ICWorklist.AddInitialGroup(InstrsForInstCombineWorklist);
3203 
3204   return MadeIRChange;
3205 }
3206 
3207 /// \brief Populate the IC worklist from a function, and prune any dead basic
3208 /// blocks discovered in the process.
3209 ///
3210 /// This also does basic constant propagation and other forward fixing to make
3211 /// the combiner itself run much faster.
3212 static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
3213                                           TargetLibraryInfo *TLI,
3214                                           InstCombineWorklist &ICWorklist) {
3215   bool MadeIRChange = false;
3216 
3217   // Do a depth-first traversal of the function, populate the worklist with
3218   // the reachable instructions.  Ignore blocks that are not reachable.  Keep
3219   // track of which blocks we visit.
3220   SmallPtrSet<BasicBlock *, 32> Visited;
3221   MadeIRChange |=
3222       AddReachableCodeToWorklist(&F.front(), DL, Visited, ICWorklist, TLI);
3223 
3224   // Do a quick scan over the function.  If we find any blocks that are
3225   // unreachable, remove any instructions inside of them.  This prevents
3226   // the instcombine code from having to deal with some bad special cases.
3227   for (BasicBlock &BB : F) {
3228     if (Visited.count(&BB))
3229       continue;
3230 
3231     unsigned NumDeadInstInBB = removeAllNonTerminatorAndEHPadInstructions(&BB);
3232     MadeIRChange |= NumDeadInstInBB > 0;
3233     NumDeadInst += NumDeadInstInBB;
3234   }
3235 
3236   return MadeIRChange;
3237 }
3238 
3239 static bool combineInstructionsOverFunction(
3240     Function &F, InstCombineWorklist &Worklist, AliasAnalysis *AA,
3241     AssumptionCache &AC, TargetLibraryInfo &TLI, DominatorTree &DT,
3242     OptimizationRemarkEmitter &ORE, bool ExpensiveCombines = true,
3243     LoopInfo *LI = nullptr) {
3244   auto &DL = F.getParent()->getDataLayout();
3245   ExpensiveCombines |= EnableExpensiveCombines;
3246 
3247   /// Builder - This is an IRBuilder that automatically inserts new
3248   /// instructions into the worklist when they are created.
3249   IRBuilder<TargetFolder, IRBuilderCallbackInserter> Builder(
3250       F.getContext(), TargetFolder(DL),
3251       IRBuilderCallbackInserter([&Worklist, &AC](Instruction *I) {
3252         Worklist.Add(I);
3253         if (match(I, m_Intrinsic<Intrinsic::assume>()))
3254           AC.registerAssumption(cast<CallInst>(I));
3255       }));
3256 
3257   // Lower dbg.declare intrinsics otherwise their value may be clobbered
3258   // by instcombiner.
3259   bool MadeIRChange = false;
3260   if (ShouldLowerDbgDeclare)
3261     MadeIRChange = LowerDbgDeclare(F);
3262 
3263   // Iterate while there is work to do.
3264   int Iteration = 0;
3265   while (true) {
3266     ++Iteration;
3267     DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
3268                  << F.getName() << "\n");
3269 
3270     MadeIRChange |= prepareICWorklistFromFunction(F, DL, &TLI, Worklist);
3271 
3272     InstCombiner IC(Worklist, Builder, F.optForMinSize(), ExpensiveCombines, AA,
3273                     AC, TLI, DT, ORE, DL, LI);
3274     IC.MaxArraySizeForCombine = MaxArraySize;
3275 
3276     if (!IC.run())
3277       break;
3278   }
3279 
3280   return MadeIRChange || Iteration > 1;
3281 }
3282 
3283 PreservedAnalyses InstCombinePass::run(Function &F,
3284                                        FunctionAnalysisManager &AM) {
3285   auto &AC = AM.getResult<AssumptionAnalysis>(F);
3286   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3287   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
3288   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
3289 
3290   auto *LI = AM.getCachedResult<LoopAnalysis>(F);
3291 
3292   auto *AA = &AM.getResult<AAManager>(F);
3293   if (!combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, ORE,
3294                                        ExpensiveCombines, LI))
3295     // No changes, all analyses are preserved.
3296     return PreservedAnalyses::all();
3297 
3298   // Mark all the analyses that instcombine updates as preserved.
3299   PreservedAnalyses PA;
3300   PA.preserveSet<CFGAnalyses>();
3301   PA.preserve<AAManager>();
3302   PA.preserve<BasicAA>();
3303   PA.preserve<GlobalsAA>();
3304   return PA;
3305 }
3306 
3307 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
3308   AU.setPreservesCFG();
3309   AU.addRequired<AAResultsWrapperPass>();
3310   AU.addRequired<AssumptionCacheTracker>();
3311   AU.addRequired<TargetLibraryInfoWrapperPass>();
3312   AU.addRequired<DominatorTreeWrapperPass>();
3313   AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
3314   AU.addPreserved<DominatorTreeWrapperPass>();
3315   AU.addPreserved<AAResultsWrapperPass>();
3316   AU.addPreserved<BasicAAWrapperPass>();
3317   AU.addPreserved<GlobalsAAWrapperPass>();
3318 }
3319 
3320 bool InstructionCombiningPass::runOnFunction(Function &F) {
3321   if (skipFunction(F))
3322     return false;
3323 
3324   // Required analyses.
3325   auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3326   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3327   auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3328   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3329   auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
3330 
3331   // Optional analyses.
3332   auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3333   auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
3334 
3335   return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, ORE,
3336                                          ExpensiveCombines, LI);
3337 }
3338 
3339 char InstructionCombiningPass::ID = 0;
3340 
3341 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
3342                       "Combine redundant instructions", false, false)
3343 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3344 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3345 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3346 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3347 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3348 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
3349 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
3350                     "Combine redundant instructions", false, false)
3351 
3352 // Initialization Routines
3353 void llvm::initializeInstCombine(PassRegistry &Registry) {
3354   initializeInstructionCombiningPassPass(Registry);
3355 }
3356 
3357 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
3358   initializeInstructionCombiningPassPass(*unwrap(R));
3359 }
3360 
3361 FunctionPass *llvm::createInstructionCombiningPass(bool ExpensiveCombines) {
3362   return new InstructionCombiningPass(ExpensiveCombines);
3363 }
3364