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