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