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) {
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   Cast->setOperand(0, BinOp2->getOperand(0));
301   BinOp1->setOperand(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)) {
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       GEP.getParent()->getInstList().insert(
1979           GEP.getParent()->getFirstInsertionPt(), NewGEP);
1980     } else {
1981       // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1982       // into the current block so it can be merged, and create a new PHI to
1983       // set that index.
1984       PHINode *NewPN;
1985       {
1986         IRBuilderBase::InsertPointGuard Guard(Builder);
1987         Builder.SetInsertPoint(PN);
1988         NewPN = Builder.CreatePHI(Op1->getOperand(DI)->getType(),
1989                                   PN->getNumOperands());
1990       }
1991 
1992       for (auto &I : PN->operands())
1993         NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1994                            PN->getIncomingBlock(I));
1995 
1996       NewGEP->setOperand(DI, NewPN);
1997       GEP.getParent()->getInstList().insert(
1998           GEP.getParent()->getFirstInsertionPt(), NewGEP);
1999       NewGEP->setOperand(DI, NewPN);
2000     }
2001 
2002     GEP.setOperand(0, NewGEP);
2003     PtrOp = NewGEP;
2004   }
2005 
2006   // Combine Indices - If the source pointer to this getelementptr instruction
2007   // is a getelementptr instruction, combine the indices of the two
2008   // getelementptr instructions into a single instruction.
2009   if (auto *Src = dyn_cast<GEPOperator>(PtrOp)) {
2010     if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
2011       return nullptr;
2012 
2013     // Try to reassociate loop invariant GEP chains to enable LICM.
2014     if (LI && Src->getNumOperands() == 2 && GEP.getNumOperands() == 2 &&
2015         Src->hasOneUse()) {
2016       if (Loop *L = LI->getLoopFor(GEP.getParent())) {
2017         Value *GO1 = GEP.getOperand(1);
2018         Value *SO1 = Src->getOperand(1);
2019         // Reassociate the two GEPs if SO1 is variant in the loop and GO1 is
2020         // invariant: this breaks the dependence between GEPs and allows LICM
2021         // to hoist the invariant part out of the loop.
2022         if (L->isLoopInvariant(GO1) && !L->isLoopInvariant(SO1)) {
2023           // We have to be careful here.
2024           // We have something like:
2025           //  %src = getelementptr <ty>, <ty>* %base, <ty> %idx
2026           //  %gep = getelementptr <ty>, <ty>* %src, <ty> %idx2
2027           // If we just swap idx & idx2 then we could inadvertantly
2028           // change %src from a vector to a scalar, or vice versa.
2029           // Cases:
2030           //  1) %base a scalar & idx a scalar & idx2 a vector
2031           //      => Swapping idx & idx2 turns %src into a vector type.
2032           //  2) %base a scalar & idx a vector & idx2 a scalar
2033           //      => Swapping idx & idx2 turns %src in a scalar type
2034           //  3) %base, %idx, and %idx2 are scalars
2035           //      => %src & %gep are scalars
2036           //      => swapping idx & idx2 is safe
2037           //  4) %base a vector
2038           //      => %src is a vector
2039           //      => swapping idx & idx2 is safe.
2040           auto *SO0 = Src->getOperand(0);
2041           auto *SO0Ty = SO0->getType();
2042           if (!isa<VectorType>(GEPType) || // case 3
2043               isa<VectorType>(SO0Ty)) {    // case 4
2044             Src->setOperand(1, GO1);
2045             GEP.setOperand(1, SO1);
2046             return &GEP;
2047           } else {
2048             // Case 1 or 2
2049             // -- have to recreate %src & %gep
2050             // put NewSrc at same location as %src
2051             Builder.SetInsertPoint(cast<Instruction>(PtrOp));
2052             auto *NewSrc = cast<GetElementPtrInst>(
2053                 Builder.CreateGEP(GEPEltType, SO0, GO1, Src->getName()));
2054             NewSrc->setIsInBounds(Src->isInBounds());
2055             auto *NewGEP = GetElementPtrInst::Create(GEPEltType, NewSrc, {SO1});
2056             NewGEP->setIsInBounds(GEP.isInBounds());
2057             return NewGEP;
2058           }
2059         }
2060       }
2061     }
2062 
2063     // Note that if our source is a gep chain itself then we wait for that
2064     // chain to be resolved before we perform this transformation.  This
2065     // avoids us creating a TON of code in some cases.
2066     if (auto *SrcGEP = dyn_cast<GEPOperator>(Src->getOperand(0)))
2067       if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
2068         return nullptr;   // Wait until our source is folded to completion.
2069 
2070     SmallVector<Value*, 8> Indices;
2071 
2072     // Find out whether the last index in the source GEP is a sequential idx.
2073     bool EndsWithSequential = false;
2074     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
2075          I != E; ++I)
2076       EndsWithSequential = I.isSequential();
2077 
2078     // Can we combine the two pointer arithmetics offsets?
2079     if (EndsWithSequential) {
2080       // Replace: gep (gep %P, long B), long A, ...
2081       // With:    T = long A+B; gep %P, T, ...
2082       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
2083       Value *GO1 = GEP.getOperand(1);
2084 
2085       // If they aren't the same type, then the input hasn't been processed
2086       // by the loop above yet (which canonicalizes sequential index types to
2087       // intptr_t).  Just avoid transforming this until the input has been
2088       // normalized.
2089       if (SO1->getType() != GO1->getType())
2090         return nullptr;
2091 
2092       Value *Sum =
2093           SimplifyAddInst(GO1, SO1, false, false, SQ.getWithInstruction(&GEP));
2094       // Only do the combine when we are sure the cost after the
2095       // merge is never more than that before the merge.
2096       if (Sum == nullptr)
2097         return nullptr;
2098 
2099       // Update the GEP in place if possible.
2100       if (Src->getNumOperands() == 2) {
2101         GEP.setIsInBounds(isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP)));
2102         GEP.setOperand(0, Src->getOperand(0));
2103         GEP.setOperand(1, Sum);
2104         return &GEP;
2105       }
2106       Indices.append(Src->op_begin()+1, Src->op_end()-1);
2107       Indices.push_back(Sum);
2108       Indices.append(GEP.op_begin()+2, GEP.op_end());
2109     } else if (isa<Constant>(*GEP.idx_begin()) &&
2110                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
2111                Src->getNumOperands() != 1) {
2112       // Otherwise we can do the fold if the first index of the GEP is a zero
2113       Indices.append(Src->op_begin()+1, Src->op_end());
2114       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
2115     }
2116 
2117     if (!Indices.empty())
2118       return isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP))
2119                  ? GetElementPtrInst::CreateInBounds(
2120                        Src->getSourceElementType(), Src->getOperand(0), Indices,
2121                        GEP.getName())
2122                  : GetElementPtrInst::Create(Src->getSourceElementType(),
2123                                              Src->getOperand(0), Indices,
2124                                              GEP.getName());
2125   }
2126 
2127   if (GEP.getNumIndices() == 1) {
2128     unsigned AS = GEP.getPointerAddressSpace();
2129     if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
2130         DL.getIndexSizeInBits(AS)) {
2131       uint64_t TyAllocSize = DL.getTypeAllocSize(GEPEltType);
2132 
2133       bool Matched = false;
2134       uint64_t C;
2135       Value *V = nullptr;
2136       if (TyAllocSize == 1) {
2137         V = GEP.getOperand(1);
2138         Matched = true;
2139       } else if (match(GEP.getOperand(1),
2140                        m_AShr(m_Value(V), m_ConstantInt(C)))) {
2141         if (TyAllocSize == 1ULL << C)
2142           Matched = true;
2143       } else if (match(GEP.getOperand(1),
2144                        m_SDiv(m_Value(V), m_ConstantInt(C)))) {
2145         if (TyAllocSize == C)
2146           Matched = true;
2147       }
2148 
2149       if (Matched) {
2150         // Canonicalize (gep i8* X, -(ptrtoint Y))
2151         // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
2152         // The GEP pattern is emitted by the SCEV expander for certain kinds of
2153         // pointer arithmetic.
2154         if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
2155           Operator *Index = cast<Operator>(V);
2156           Value *PtrToInt = Builder.CreatePtrToInt(PtrOp, Index->getType());
2157           Value *NewSub = Builder.CreateSub(PtrToInt, Index->getOperand(1));
2158           return CastInst::Create(Instruction::IntToPtr, NewSub, GEPType);
2159         }
2160         // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
2161         // to (bitcast Y)
2162         Value *Y;
2163         if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
2164                            m_PtrToInt(m_Specific(GEP.getOperand(0))))))
2165           return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y, GEPType);
2166       }
2167     }
2168   }
2169 
2170   // We do not handle pointer-vector geps here.
2171   if (GEPType->isVectorTy())
2172     return nullptr;
2173 
2174   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
2175   Value *StrippedPtr = PtrOp->stripPointerCasts();
2176   PointerType *StrippedPtrTy = cast<PointerType>(StrippedPtr->getType());
2177 
2178   if (StrippedPtr != PtrOp) {
2179     bool HasZeroPointerIndex = false;
2180     Type *StrippedPtrEltTy = StrippedPtrTy->getElementType();
2181 
2182     if (auto *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
2183       HasZeroPointerIndex = C->isZero();
2184 
2185     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
2186     // into     : GEP [10 x i8]* X, i32 0, ...
2187     //
2188     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
2189     //           into     : GEP i8* X, ...
2190     //
2191     // This occurs when the program declares an array extern like "int X[];"
2192     if (HasZeroPointerIndex) {
2193       if (auto *CATy = dyn_cast<ArrayType>(GEPEltType)) {
2194         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
2195         if (CATy->getElementType() == StrippedPtrEltTy) {
2196           // -> GEP i8* X, ...
2197           SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
2198           GetElementPtrInst *Res = GetElementPtrInst::Create(
2199               StrippedPtrEltTy, StrippedPtr, Idx, GEP.getName());
2200           Res->setIsInBounds(GEP.isInBounds());
2201           if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
2202             return Res;
2203           // Insert Res, and create an addrspacecast.
2204           // e.g.,
2205           // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
2206           // ->
2207           // %0 = GEP i8 addrspace(1)* X, ...
2208           // addrspacecast i8 addrspace(1)* %0 to i8*
2209           return new AddrSpaceCastInst(Builder.Insert(Res), GEPType);
2210         }
2211 
2212         if (auto *XATy = dyn_cast<ArrayType>(StrippedPtrEltTy)) {
2213           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
2214           if (CATy->getElementType() == XATy->getElementType()) {
2215             // -> GEP [10 x i8]* X, i32 0, ...
2216             // At this point, we know that the cast source type is a pointer
2217             // to an array of the same type as the destination pointer
2218             // array.  Because the array type is never stepped over (there
2219             // is a leading zero) we can fold the cast into this GEP.
2220             if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
2221               GEP.setOperand(0, StrippedPtr);
2222               GEP.setSourceElementType(XATy);
2223               return &GEP;
2224             }
2225             // Cannot replace the base pointer directly because StrippedPtr's
2226             // address space is different. Instead, create a new GEP followed by
2227             // an addrspacecast.
2228             // e.g.,
2229             // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
2230             //   i32 0, ...
2231             // ->
2232             // %0 = GEP [10 x i8] addrspace(1)* X, ...
2233             // addrspacecast i8 addrspace(1)* %0 to i8*
2234             SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
2235             Value *NewGEP =
2236                 GEP.isInBounds()
2237                     ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr,
2238                                                 Idx, GEP.getName())
2239                     : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Idx,
2240                                         GEP.getName());
2241             return new AddrSpaceCastInst(NewGEP, GEPType);
2242           }
2243         }
2244       }
2245     } else if (GEP.getNumOperands() == 2) {
2246       // Transform things like:
2247       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
2248       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
2249       if (StrippedPtrEltTy->isArrayTy() &&
2250           DL.getTypeAllocSize(StrippedPtrEltTy->getArrayElementType()) ==
2251               DL.getTypeAllocSize(GEPEltType)) {
2252         Type *IdxType = DL.getIndexType(GEPType);
2253         Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
2254         Value *NewGEP =
2255             GEP.isInBounds()
2256                 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, Idx,
2257                                             GEP.getName())
2258                 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Idx,
2259                                     GEP.getName());
2260 
2261         // V and GEP are both pointer types --> BitCast
2262         return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, GEPType);
2263       }
2264 
2265       // Transform things like:
2266       // %V = mul i64 %N, 4
2267       // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
2268       // into:  %t1 = getelementptr i32* %arr, i32 %N; bitcast
2269       if (GEPEltType->isSized() && StrippedPtrEltTy->isSized()) {
2270         // Check that changing the type amounts to dividing the index by a scale
2271         // factor.
2272         uint64_t ResSize = DL.getTypeAllocSize(GEPEltType);
2273         uint64_t SrcSize = DL.getTypeAllocSize(StrippedPtrEltTy);
2274         if (ResSize && SrcSize % ResSize == 0) {
2275           Value *Idx = GEP.getOperand(1);
2276           unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
2277           uint64_t Scale = SrcSize / ResSize;
2278 
2279           // Earlier transforms ensure that the index has the right type
2280           // according to Data Layout, which considerably simplifies the
2281           // logic by eliminating implicit casts.
2282           assert(Idx->getType() == DL.getIndexType(GEPType) &&
2283                  "Index type does not match the Data Layout preferences");
2284 
2285           bool NSW;
2286           if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
2287             // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
2288             // If the multiplication NewIdx * Scale may overflow then the new
2289             // GEP may not be "inbounds".
2290             Value *NewGEP =
2291                 GEP.isInBounds() && NSW
2292                     ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr,
2293                                                 NewIdx, GEP.getName())
2294                     : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, NewIdx,
2295                                         GEP.getName());
2296 
2297             // The NewGEP must be pointer typed, so must the old one -> BitCast
2298             return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
2299                                                                  GEPType);
2300           }
2301         }
2302       }
2303 
2304       // Similarly, transform things like:
2305       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
2306       //   (where tmp = 8*tmp2) into:
2307       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
2308       if (GEPEltType->isSized() && StrippedPtrEltTy->isSized() &&
2309           StrippedPtrEltTy->isArrayTy()) {
2310         // Check that changing to the array element type amounts to dividing the
2311         // index by a scale factor.
2312         uint64_t ResSize = DL.getTypeAllocSize(GEPEltType);
2313         uint64_t ArrayEltSize =
2314             DL.getTypeAllocSize(StrippedPtrEltTy->getArrayElementType());
2315         if (ResSize && ArrayEltSize % ResSize == 0) {
2316           Value *Idx = GEP.getOperand(1);
2317           unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
2318           uint64_t Scale = ArrayEltSize / ResSize;
2319 
2320           // Earlier transforms ensure that the index has the right type
2321           // according to the Data Layout, which considerably simplifies
2322           // the logic by eliminating implicit casts.
2323           assert(Idx->getType() == DL.getIndexType(GEPType) &&
2324                  "Index type does not match the Data Layout preferences");
2325 
2326           bool NSW;
2327           if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
2328             // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
2329             // If the multiplication NewIdx * Scale may overflow then the new
2330             // GEP may not be "inbounds".
2331             Type *IndTy = DL.getIndexType(GEPType);
2332             Value *Off[2] = {Constant::getNullValue(IndTy), NewIdx};
2333 
2334             Value *NewGEP =
2335                 GEP.isInBounds() && NSW
2336                     ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr,
2337                                                 Off, GEP.getName())
2338                     : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Off,
2339                                         GEP.getName());
2340             // The NewGEP must be pointer typed, so must the old one -> BitCast
2341             return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
2342                                                                  GEPType);
2343           }
2344         }
2345       }
2346     }
2347   }
2348 
2349   // addrspacecast between types is canonicalized as a bitcast, then an
2350   // addrspacecast. To take advantage of the below bitcast + struct GEP, look
2351   // through the addrspacecast.
2352   Value *ASCStrippedPtrOp = PtrOp;
2353   if (auto *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
2354     //   X = bitcast A addrspace(1)* to B addrspace(1)*
2355     //   Y = addrspacecast A addrspace(1)* to B addrspace(2)*
2356     //   Z = gep Y, <...constant indices...>
2357     // Into an addrspacecasted GEP of the struct.
2358     if (auto *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
2359       ASCStrippedPtrOp = BC;
2360   }
2361 
2362   if (auto *BCI = dyn_cast<BitCastInst>(ASCStrippedPtrOp)) {
2363     Value *SrcOp = BCI->getOperand(0);
2364     PointerType *SrcType = cast<PointerType>(BCI->getSrcTy());
2365     Type *SrcEltType = SrcType->getElementType();
2366 
2367     // GEP directly using the source operand if this GEP is accessing an element
2368     // of a bitcasted pointer to vector or array of the same dimensions:
2369     // gep (bitcast <c x ty>* X to [c x ty]*), Y, Z --> gep X, Y, Z
2370     // gep (bitcast [c x ty]* X to <c x ty>*), Y, Z --> gep X, Y, Z
2371     auto areMatchingArrayAndVecTypes = [](Type *ArrTy, Type *VecTy,
2372                                           const DataLayout &DL) {
2373       return ArrTy->getArrayElementType() == VecTy->getVectorElementType() &&
2374              ArrTy->getArrayNumElements() == VecTy->getVectorNumElements() &&
2375              DL.getTypeAllocSize(ArrTy) == DL.getTypeAllocSize(VecTy);
2376     };
2377     if (GEP.getNumOperands() == 3 &&
2378         ((GEPEltType->isArrayTy() && SrcEltType->isVectorTy() &&
2379           areMatchingArrayAndVecTypes(GEPEltType, SrcEltType, DL)) ||
2380          (GEPEltType->isVectorTy() && SrcEltType->isArrayTy() &&
2381           areMatchingArrayAndVecTypes(SrcEltType, GEPEltType, DL)))) {
2382 
2383       // Create a new GEP here, as using `setOperand()` followed by
2384       // `setSourceElementType()` won't actually update the type of the
2385       // existing GEP Value. Causing issues if this Value is accessed when
2386       // constructing an AddrSpaceCastInst
2387       Value *NGEP =
2388           GEP.isInBounds()
2389               ? Builder.CreateInBoundsGEP(SrcEltType, SrcOp, {Ops[1], Ops[2]})
2390               : Builder.CreateGEP(SrcEltType, SrcOp, {Ops[1], Ops[2]});
2391       NGEP->takeName(&GEP);
2392 
2393       // Preserve GEP address space to satisfy users
2394       if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
2395         return new AddrSpaceCastInst(NGEP, GEPType);
2396 
2397       return replaceInstUsesWith(GEP, NGEP);
2398     }
2399 
2400     // See if we can simplify:
2401     //   X = bitcast A* to B*
2402     //   Y = gep X, <...constant indices...>
2403     // into a gep of the original struct. This is important for SROA and alias
2404     // analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
2405     unsigned OffsetBits = DL.getIndexTypeSizeInBits(GEPType);
2406     APInt Offset(OffsetBits, 0);
2407     if (!isa<BitCastInst>(SrcOp) && GEP.accumulateConstantOffset(DL, Offset)) {
2408       // If this GEP instruction doesn't move the pointer, just replace the GEP
2409       // with a bitcast of the real input to the dest type.
2410       if (!Offset) {
2411         // If the bitcast is of an allocation, and the allocation will be
2412         // converted to match the type of the cast, don't touch this.
2413         if (isa<AllocaInst>(SrcOp) || isAllocationFn(SrcOp, &TLI)) {
2414           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
2415           if (Instruction *I = visitBitCast(*BCI)) {
2416             if (I != BCI) {
2417               I->takeName(BCI);
2418               BCI->getParent()->getInstList().insert(BCI->getIterator(), I);
2419               replaceInstUsesWith(*BCI, I);
2420             }
2421             return &GEP;
2422           }
2423         }
2424 
2425         if (SrcType->getPointerAddressSpace() != GEP.getAddressSpace())
2426           return new AddrSpaceCastInst(SrcOp, GEPType);
2427         return new BitCastInst(SrcOp, GEPType);
2428       }
2429 
2430       // Otherwise, if the offset is non-zero, we need to find out if there is a
2431       // field at Offset in 'A's type.  If so, we can pull the cast through the
2432       // GEP.
2433       SmallVector<Value*, 8> NewIndices;
2434       if (FindElementAtOffset(SrcType, Offset.getSExtValue(), NewIndices)) {
2435         Value *NGEP =
2436             GEP.isInBounds()
2437                 ? Builder.CreateInBoundsGEP(SrcEltType, SrcOp, NewIndices)
2438                 : Builder.CreateGEP(SrcEltType, SrcOp, NewIndices);
2439 
2440         if (NGEP->getType() == GEPType)
2441           return replaceInstUsesWith(GEP, NGEP);
2442         NGEP->takeName(&GEP);
2443 
2444         if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
2445           return new AddrSpaceCastInst(NGEP, GEPType);
2446         return new BitCastInst(NGEP, GEPType);
2447       }
2448     }
2449   }
2450 
2451   if (!GEP.isInBounds()) {
2452     unsigned IdxWidth =
2453         DL.getIndexSizeInBits(PtrOp->getType()->getPointerAddressSpace());
2454     APInt BasePtrOffset(IdxWidth, 0);
2455     Value *UnderlyingPtrOp =
2456             PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL,
2457                                                              BasePtrOffset);
2458     if (auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) {
2459       if (GEP.accumulateConstantOffset(DL, BasePtrOffset) &&
2460           BasePtrOffset.isNonNegative()) {
2461         APInt AllocSize(IdxWidth, DL.getTypeAllocSize(AI->getAllocatedType()));
2462         if (BasePtrOffset.ule(AllocSize)) {
2463           return GetElementPtrInst::CreateInBounds(
2464               GEP.getSourceElementType(), PtrOp, makeArrayRef(Ops).slice(1),
2465               GEP.getName());
2466         }
2467       }
2468     }
2469   }
2470 
2471   if (Instruction *R = foldSelectGEP(GEP, Builder))
2472     return R;
2473 
2474   return nullptr;
2475 }
2476 
2477 static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI,
2478                                          Instruction *AI) {
2479   if (isa<ConstantPointerNull>(V))
2480     return true;
2481   if (auto *LI = dyn_cast<LoadInst>(V))
2482     return isa<GlobalVariable>(LI->getPointerOperand());
2483   // Two distinct allocations will never be equal.
2484   // We rely on LookThroughBitCast in isAllocLikeFn being false, since looking
2485   // through bitcasts of V can cause
2486   // the result statement below to be true, even when AI and V (ex:
2487   // i8* ->i32* ->i8* of AI) are the same allocations.
2488   return isAllocLikeFn(V, TLI) && V != AI;
2489 }
2490 
2491 static bool isAllocSiteRemovable(Instruction *AI,
2492                                  SmallVectorImpl<WeakTrackingVH> &Users,
2493                                  const TargetLibraryInfo *TLI) {
2494   SmallVector<Instruction*, 4> Worklist;
2495   Worklist.push_back(AI);
2496 
2497   do {
2498     Instruction *PI = Worklist.pop_back_val();
2499     for (User *U : PI->users()) {
2500       Instruction *I = cast<Instruction>(U);
2501       switch (I->getOpcode()) {
2502       default:
2503         // Give up the moment we see something we can't handle.
2504         return false;
2505 
2506       case Instruction::AddrSpaceCast:
2507       case Instruction::BitCast:
2508       case Instruction::GetElementPtr:
2509         Users.emplace_back(I);
2510         Worklist.push_back(I);
2511         continue;
2512 
2513       case Instruction::ICmp: {
2514         ICmpInst *ICI = cast<ICmpInst>(I);
2515         // We can fold eq/ne comparisons with null to false/true, respectively.
2516         // We also fold comparisons in some conditions provided the alloc has
2517         // not escaped (see isNeverEqualToUnescapedAlloc).
2518         if (!ICI->isEquality())
2519           return false;
2520         unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0;
2521         if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI))
2522           return false;
2523         Users.emplace_back(I);
2524         continue;
2525       }
2526 
2527       case Instruction::Call:
2528         // Ignore no-op and store intrinsics.
2529         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2530           switch (II->getIntrinsicID()) {
2531           default:
2532             return false;
2533 
2534           case Intrinsic::memmove:
2535           case Intrinsic::memcpy:
2536           case Intrinsic::memset: {
2537             MemIntrinsic *MI = cast<MemIntrinsic>(II);
2538             if (MI->isVolatile() || MI->getRawDest() != PI)
2539               return false;
2540             LLVM_FALLTHROUGH;
2541           }
2542           case Intrinsic::invariant_start:
2543           case Intrinsic::invariant_end:
2544           case Intrinsic::lifetime_start:
2545           case Intrinsic::lifetime_end:
2546           case Intrinsic::objectsize:
2547             Users.emplace_back(I);
2548             continue;
2549           }
2550         }
2551 
2552         if (isFreeCall(I, TLI)) {
2553           Users.emplace_back(I);
2554           continue;
2555         }
2556         return false;
2557 
2558       case Instruction::Store: {
2559         StoreInst *SI = cast<StoreInst>(I);
2560         if (SI->isVolatile() || SI->getPointerOperand() != PI)
2561           return false;
2562         Users.emplace_back(I);
2563         continue;
2564       }
2565       }
2566       llvm_unreachable("missing a return?");
2567     }
2568   } while (!Worklist.empty());
2569   return true;
2570 }
2571 
2572 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
2573   // If we have a malloc call which is only used in any amount of comparisons to
2574   // null and free calls, delete the calls and replace the comparisons with true
2575   // or false as appropriate.
2576 
2577   // This is based on the principle that we can substitute our own allocation
2578   // function (which will never return null) rather than knowledge of the
2579   // specific function being called. In some sense this can change the permitted
2580   // outputs of a program (when we convert a malloc to an alloca, the fact that
2581   // the allocation is now on the stack is potentially visible, for example),
2582   // but we believe in a permissible manner.
2583   SmallVector<WeakTrackingVH, 64> Users;
2584 
2585   // If we are removing an alloca with a dbg.declare, insert dbg.value calls
2586   // before each store.
2587   TinyPtrVector<DbgVariableIntrinsic *> DIIs;
2588   std::unique_ptr<DIBuilder> DIB;
2589   if (isa<AllocaInst>(MI)) {
2590     DIIs = FindDbgAddrUses(&MI);
2591     DIB.reset(new DIBuilder(*MI.getModule(), /*AllowUnresolved=*/false));
2592   }
2593 
2594   if (isAllocSiteRemovable(&MI, Users, &TLI)) {
2595     for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2596       // Lowering all @llvm.objectsize calls first because they may
2597       // use a bitcast/GEP of the alloca we are removing.
2598       if (!Users[i])
2599        continue;
2600 
2601       Instruction *I = cast<Instruction>(&*Users[i]);
2602 
2603       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2604         if (II->getIntrinsicID() == Intrinsic::objectsize) {
2605           Value *Result =
2606               lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/true);
2607           replaceInstUsesWith(*I, Result);
2608           eraseInstFromFunction(*I);
2609           Users[i] = nullptr; // Skip examining in the next loop.
2610         }
2611       }
2612     }
2613     for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2614       if (!Users[i])
2615         continue;
2616 
2617       Instruction *I = cast<Instruction>(&*Users[i]);
2618 
2619       if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
2620         replaceInstUsesWith(*C,
2621                             ConstantInt::get(Type::getInt1Ty(C->getContext()),
2622                                              C->isFalseWhenEqual()));
2623       } else if (auto *SI = dyn_cast<StoreInst>(I)) {
2624         for (auto *DII : DIIs)
2625           ConvertDebugDeclareToDebugValue(DII, SI, *DIB);
2626       } else {
2627         // Casts, GEP, or anything else: we're about to delete this instruction,
2628         // so it can not have any valid uses.
2629         replaceInstUsesWith(*I, UndefValue::get(I->getType()));
2630       }
2631       eraseInstFromFunction(*I);
2632     }
2633 
2634     if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
2635       // Replace invoke with a NOP intrinsic to maintain the original CFG
2636       Module *M = II->getModule();
2637       Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
2638       InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
2639                          None, "", II->getParent());
2640     }
2641 
2642     for (auto *DII : DIIs)
2643       eraseInstFromFunction(*DII);
2644 
2645     return eraseInstFromFunction(MI);
2646   }
2647   return nullptr;
2648 }
2649 
2650 /// Move the call to free before a NULL test.
2651 ///
2652 /// Check if this free is accessed after its argument has been test
2653 /// against NULL (property 0).
2654 /// If yes, it is legal to move this call in its predecessor block.
2655 ///
2656 /// The move is performed only if the block containing the call to free
2657 /// will be removed, i.e.:
2658 /// 1. it has only one predecessor P, and P has two successors
2659 /// 2. it contains the call, noops, and an unconditional branch
2660 /// 3. its successor is the same as its predecessor's successor
2661 ///
2662 /// The profitability is out-of concern here and this function should
2663 /// be called only if the caller knows this transformation would be
2664 /// profitable (e.g., for code size).
2665 static Instruction *tryToMoveFreeBeforeNullTest(CallInst &FI,
2666                                                 const DataLayout &DL) {
2667   Value *Op = FI.getArgOperand(0);
2668   BasicBlock *FreeInstrBB = FI.getParent();
2669   BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
2670 
2671   // Validate part of constraint #1: Only one predecessor
2672   // FIXME: We can extend the number of predecessor, but in that case, we
2673   //        would duplicate the call to free in each predecessor and it may
2674   //        not be profitable even for code size.
2675   if (!PredBB)
2676     return nullptr;
2677 
2678   // Validate constraint #2: Does this block contains only the call to
2679   //                         free, noops, and an unconditional branch?
2680   BasicBlock *SuccBB;
2681   Instruction *FreeInstrBBTerminator = FreeInstrBB->getTerminator();
2682   if (!match(FreeInstrBBTerminator, m_UnconditionalBr(SuccBB)))
2683     return nullptr;
2684 
2685   // If there are only 2 instructions in the block, at this point,
2686   // this is the call to free and unconditional.
2687   // If there are more than 2 instructions, check that they are noops
2688   // i.e., they won't hurt the performance of the generated code.
2689   if (FreeInstrBB->size() != 2) {
2690     for (const Instruction &Inst : *FreeInstrBB) {
2691       if (&Inst == &FI || &Inst == FreeInstrBBTerminator)
2692         continue;
2693       auto *Cast = dyn_cast<CastInst>(&Inst);
2694       if (!Cast || !Cast->isNoopCast(DL))
2695         return nullptr;
2696     }
2697   }
2698   // Validate the rest of constraint #1 by matching on the pred branch.
2699   Instruction *TI = PredBB->getTerminator();
2700   BasicBlock *TrueBB, *FalseBB;
2701   ICmpInst::Predicate Pred;
2702   if (!match(TI, m_Br(m_ICmp(Pred,
2703                              m_CombineOr(m_Specific(Op),
2704                                          m_Specific(Op->stripPointerCasts())),
2705                              m_Zero()),
2706                       TrueBB, FalseBB)))
2707     return nullptr;
2708   if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2709     return nullptr;
2710 
2711   // Validate constraint #3: Ensure the null case just falls through.
2712   if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
2713     return nullptr;
2714   assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
2715          "Broken CFG: missing edge from predecessor to successor");
2716 
2717   // At this point, we know that everything in FreeInstrBB can be moved
2718   // before TI.
2719   for (BasicBlock::iterator It = FreeInstrBB->begin(), End = FreeInstrBB->end();
2720        It != End;) {
2721     Instruction &Instr = *It++;
2722     if (&Instr == FreeInstrBBTerminator)
2723       break;
2724     Instr.moveBefore(TI);
2725   }
2726   assert(FreeInstrBB->size() == 1 &&
2727          "Only the branch instruction should remain");
2728   return &FI;
2729 }
2730 
2731 Instruction *InstCombiner::visitFree(CallInst &FI) {
2732   Value *Op = FI.getArgOperand(0);
2733 
2734   // free undef -> unreachable.
2735   if (isa<UndefValue>(Op)) {
2736     // Leave a marker since we can't modify the CFG here.
2737     CreateNonTerminatorUnreachable(&FI);
2738     return eraseInstFromFunction(FI);
2739   }
2740 
2741   // If we have 'free null' delete the instruction.  This can happen in stl code
2742   // when lots of inlining happens.
2743   if (isa<ConstantPointerNull>(Op))
2744     return eraseInstFromFunction(FI);
2745 
2746   // If we optimize for code size, try to move the call to free before the null
2747   // test so that simplify cfg can remove the empty block and dead code
2748   // elimination the branch. I.e., helps to turn something like:
2749   // if (foo) free(foo);
2750   // into
2751   // free(foo);
2752   if (MinimizeSize)
2753     if (Instruction *I = tryToMoveFreeBeforeNullTest(FI, DL))
2754       return I;
2755 
2756   return nullptr;
2757 }
2758 
2759 static bool isMustTailCall(Value *V) {
2760   if (auto *CI = dyn_cast<CallInst>(V))
2761     return CI->isMustTailCall();
2762   return false;
2763 }
2764 
2765 Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
2766   if (RI.getNumOperands() == 0) // ret void
2767     return nullptr;
2768 
2769   Value *ResultOp = RI.getOperand(0);
2770   Type *VTy = ResultOp->getType();
2771   if (!VTy->isIntegerTy() || isa<Constant>(ResultOp))
2772     return nullptr;
2773 
2774   // Don't replace result of musttail calls.
2775   if (isMustTailCall(ResultOp))
2776     return nullptr;
2777 
2778   // There might be assume intrinsics dominating this return that completely
2779   // determine the value. If so, constant fold it.
2780   KnownBits Known = computeKnownBits(ResultOp, 0, &RI);
2781   if (Known.isConstant())
2782     return replaceOperand(RI, 0,
2783         Constant::getIntegerValue(VTy, Known.getConstant()));
2784 
2785   return nullptr;
2786 }
2787 
2788 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2789   // Change br (not X), label True, label False to: br X, label False, True
2790   Value *X = nullptr;
2791   if (match(&BI, m_Br(m_Not(m_Value(X)), m_BasicBlock(), m_BasicBlock())) &&
2792       !isa<Constant>(X)) {
2793     // Swap Destinations and condition...
2794     BI.swapSuccessors();
2795     return replaceOperand(BI, 0, X);
2796   }
2797 
2798   // If the condition is irrelevant, remove the use so that other
2799   // transforms on the condition become more effective.
2800   if (BI.isConditional() && !isa<ConstantInt>(BI.getCondition()) &&
2801       BI.getSuccessor(0) == BI.getSuccessor(1))
2802     return replaceOperand(
2803         BI, 0, ConstantInt::getFalse(BI.getCondition()->getType()));
2804 
2805   // Canonicalize, for example, icmp_ne -> icmp_eq or fcmp_one -> fcmp_oeq.
2806   CmpInst::Predicate Pred;
2807   if (match(&BI, m_Br(m_OneUse(m_Cmp(Pred, m_Value(), m_Value())),
2808                       m_BasicBlock(), m_BasicBlock())) &&
2809       !isCanonicalPredicate(Pred)) {
2810     // Swap destinations and condition.
2811     CmpInst *Cond = cast<CmpInst>(BI.getCondition());
2812     Cond->setPredicate(CmpInst::getInversePredicate(Pred));
2813     BI.swapSuccessors();
2814     Worklist.push(Cond);
2815     return &BI;
2816   }
2817 
2818   return nullptr;
2819 }
2820 
2821 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2822   Value *Cond = SI.getCondition();
2823   Value *Op0;
2824   ConstantInt *AddRHS;
2825   if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) {
2826     // Change 'switch (X+4) case 1:' into 'switch (X) case -3'.
2827     for (auto Case : SI.cases()) {
2828       Constant *NewCase = ConstantExpr::getSub(Case.getCaseValue(), AddRHS);
2829       assert(isa<ConstantInt>(NewCase) &&
2830              "Result of expression should be constant");
2831       Case.setValue(cast<ConstantInt>(NewCase));
2832     }
2833     return replaceOperand(SI, 0, Op0);
2834   }
2835 
2836   KnownBits Known = computeKnownBits(Cond, 0, &SI);
2837   unsigned LeadingKnownZeros = Known.countMinLeadingZeros();
2838   unsigned LeadingKnownOnes = Known.countMinLeadingOnes();
2839 
2840   // Compute the number of leading bits we can ignore.
2841   // TODO: A better way to determine this would use ComputeNumSignBits().
2842   for (auto &C : SI.cases()) {
2843     LeadingKnownZeros = std::min(
2844         LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2845     LeadingKnownOnes = std::min(
2846         LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2847   }
2848 
2849   unsigned NewWidth = Known.getBitWidth() - std::max(LeadingKnownZeros, LeadingKnownOnes);
2850 
2851   // Shrink the condition operand if the new type is smaller than the old type.
2852   // But do not shrink to a non-standard type, because backend can't generate
2853   // good code for that yet.
2854   // TODO: We can make it aggressive again after fixing PR39569.
2855   if (NewWidth > 0 && NewWidth < Known.getBitWidth() &&
2856       shouldChangeType(Known.getBitWidth(), NewWidth)) {
2857     IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2858     Builder.SetInsertPoint(&SI);
2859     Value *NewCond = Builder.CreateTrunc(Cond, Ty, "trunc");
2860 
2861     for (auto Case : SI.cases()) {
2862       APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth);
2863       Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));
2864     }
2865     return replaceOperand(SI, 0, NewCond);
2866   }
2867 
2868   return nullptr;
2869 }
2870 
2871 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
2872   Value *Agg = EV.getAggregateOperand();
2873 
2874   if (!EV.hasIndices())
2875     return replaceInstUsesWith(EV, Agg);
2876 
2877   if (Value *V = SimplifyExtractValueInst(Agg, EV.getIndices(),
2878                                           SQ.getWithInstruction(&EV)))
2879     return replaceInstUsesWith(EV, V);
2880 
2881   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2882     // We're extracting from an insertvalue instruction, compare the indices
2883     const unsigned *exti, *exte, *insi, *inse;
2884     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2885          exte = EV.idx_end(), inse = IV->idx_end();
2886          exti != exte && insi != inse;
2887          ++exti, ++insi) {
2888       if (*insi != *exti)
2889         // The insert and extract both reference distinctly different elements.
2890         // This means the extract is not influenced by the insert, and we can
2891         // replace the aggregate operand of the extract with the aggregate
2892         // operand of the insert. i.e., replace
2893         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2894         // %E = extractvalue { i32, { i32 } } %I, 0
2895         // with
2896         // %E = extractvalue { i32, { i32 } } %A, 0
2897         return ExtractValueInst::Create(IV->getAggregateOperand(),
2898                                         EV.getIndices());
2899     }
2900     if (exti == exte && insi == inse)
2901       // Both iterators are at the end: Index lists are identical. Replace
2902       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2903       // %C = extractvalue { i32, { i32 } } %B, 1, 0
2904       // with "i32 42"
2905       return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
2906     if (exti == exte) {
2907       // The extract list is a prefix of the insert list. i.e. replace
2908       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2909       // %E = extractvalue { i32, { i32 } } %I, 1
2910       // with
2911       // %X = extractvalue { i32, { i32 } } %A, 1
2912       // %E = insertvalue { i32 } %X, i32 42, 0
2913       // by switching the order of the insert and extract (though the
2914       // insertvalue should be left in, since it may have other uses).
2915       Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(),
2916                                                 EV.getIndices());
2917       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
2918                                      makeArrayRef(insi, inse));
2919     }
2920     if (insi == inse)
2921       // The insert list is a prefix of the extract list
2922       // We can simply remove the common indices from the extract and make it
2923       // operate on the inserted value instead of the insertvalue result.
2924       // i.e., replace
2925       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2926       // %E = extractvalue { i32, { i32 } } %I, 1, 0
2927       // with
2928       // %E extractvalue { i32 } { i32 42 }, 0
2929       return ExtractValueInst::Create(IV->getInsertedValueOperand(),
2930                                       makeArrayRef(exti, exte));
2931   }
2932   if (WithOverflowInst *WO = dyn_cast<WithOverflowInst>(Agg)) {
2933     // We're extracting from an overflow intrinsic, see if we're the only user,
2934     // which allows us to simplify multiple result intrinsics to simpler
2935     // things that just get one value.
2936     if (WO->hasOneUse()) {
2937       // Check if we're grabbing only the result of a 'with overflow' intrinsic
2938       // and replace it with a traditional binary instruction.
2939       if (*EV.idx_begin() == 0) {
2940         Instruction::BinaryOps BinOp = WO->getBinaryOp();
2941         Value *LHS = WO->getLHS(), *RHS = WO->getRHS();
2942         replaceInstUsesWith(*WO, UndefValue::get(WO->getType()));
2943         eraseInstFromFunction(*WO);
2944         return BinaryOperator::Create(BinOp, LHS, RHS);
2945       }
2946 
2947       // If the normal result of the add is dead, and the RHS is a constant,
2948       // we can transform this into a range comparison.
2949       // overflow = uadd a, -4  -->  overflow = icmp ugt a, 3
2950       if (WO->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2951         if (ConstantInt *CI = dyn_cast<ConstantInt>(WO->getRHS()))
2952           return new ICmpInst(ICmpInst::ICMP_UGT, WO->getLHS(),
2953                               ConstantExpr::getNot(CI));
2954     }
2955   }
2956   if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2957     // If the (non-volatile) load only has one use, we can rewrite this to a
2958     // load from a GEP. This reduces the size of the load. If a load is used
2959     // only by extractvalue instructions then this either must have been
2960     // optimized before, or it is a struct with padding, in which case we
2961     // don't want to do the transformation as it loses padding knowledge.
2962     if (L->isSimple() && L->hasOneUse()) {
2963       // extractvalue has integer indices, getelementptr has Value*s. Convert.
2964       SmallVector<Value*, 4> Indices;
2965       // Prefix an i32 0 since we need the first element.
2966       Indices.push_back(Builder.getInt32(0));
2967       for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2968             I != E; ++I)
2969         Indices.push_back(Builder.getInt32(*I));
2970 
2971       // We need to insert these at the location of the old load, not at that of
2972       // the extractvalue.
2973       Builder.SetInsertPoint(L);
2974       Value *GEP = Builder.CreateInBoundsGEP(L->getType(),
2975                                              L->getPointerOperand(), Indices);
2976       Instruction *NL = Builder.CreateLoad(EV.getType(), GEP);
2977       // Whatever aliasing information we had for the orignal load must also
2978       // hold for the smaller load, so propagate the annotations.
2979       AAMDNodes Nodes;
2980       L->getAAMetadata(Nodes);
2981       NL->setAAMetadata(Nodes);
2982       // Returning the load directly will cause the main loop to insert it in
2983       // the wrong spot, so use replaceInstUsesWith().
2984       return replaceInstUsesWith(EV, NL);
2985     }
2986   // We could simplify extracts from other values. Note that nested extracts may
2987   // already be simplified implicitly by the above: extract (extract (insert) )
2988   // will be translated into extract ( insert ( extract ) ) first and then just
2989   // the value inserted, if appropriate. Similarly for extracts from single-use
2990   // loads: extract (extract (load)) will be translated to extract (load (gep))
2991   // and if again single-use then via load (gep (gep)) to load (gep).
2992   // However, double extracts from e.g. function arguments or return values
2993   // aren't handled yet.
2994   return nullptr;
2995 }
2996 
2997 /// Return 'true' if the given typeinfo will match anything.
2998 static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
2999   switch (Personality) {
3000   case EHPersonality::GNU_C:
3001   case EHPersonality::GNU_C_SjLj:
3002   case EHPersonality::Rust:
3003     // The GCC C EH and Rust personality only exists to support cleanups, so
3004     // it's not clear what the semantics of catch clauses are.
3005     return false;
3006   case EHPersonality::Unknown:
3007     return false;
3008   case EHPersonality::GNU_Ada:
3009     // While __gnat_all_others_value will match any Ada exception, it doesn't
3010     // match foreign exceptions (or didn't, before gcc-4.7).
3011     return false;
3012   case EHPersonality::GNU_CXX:
3013   case EHPersonality::GNU_CXX_SjLj:
3014   case EHPersonality::GNU_ObjC:
3015   case EHPersonality::MSVC_X86SEH:
3016   case EHPersonality::MSVC_Win64SEH:
3017   case EHPersonality::MSVC_CXX:
3018   case EHPersonality::CoreCLR:
3019   case EHPersonality::Wasm_CXX:
3020     return TypeInfo->isNullValue();
3021   }
3022   llvm_unreachable("invalid enum");
3023 }
3024 
3025 static bool shorter_filter(const Value *LHS, const Value *RHS) {
3026   return
3027     cast<ArrayType>(LHS->getType())->getNumElements()
3028   <
3029     cast<ArrayType>(RHS->getType())->getNumElements();
3030 }
3031 
3032 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
3033   // The logic here should be correct for any real-world personality function.
3034   // However if that turns out not to be true, the offending logic can always
3035   // be conditioned on the personality function, like the catch-all logic is.
3036   EHPersonality Personality =
3037       classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
3038 
3039   // Simplify the list of clauses, eg by removing repeated catch clauses
3040   // (these are often created by inlining).
3041   bool MakeNewInstruction = false; // If true, recreate using the following:
3042   SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
3043   bool CleanupFlag = LI.isCleanup();   // - The new instruction is a cleanup.
3044 
3045   SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
3046   for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
3047     bool isLastClause = i + 1 == e;
3048     if (LI.isCatch(i)) {
3049       // A catch clause.
3050       Constant *CatchClause = LI.getClause(i);
3051       Constant *TypeInfo = CatchClause->stripPointerCasts();
3052 
3053       // If we already saw this clause, there is no point in having a second
3054       // copy of it.
3055       if (AlreadyCaught.insert(TypeInfo).second) {
3056         // This catch clause was not already seen.
3057         NewClauses.push_back(CatchClause);
3058       } else {
3059         // Repeated catch clause - drop the redundant copy.
3060         MakeNewInstruction = true;
3061       }
3062 
3063       // If this is a catch-all then there is no point in keeping any following
3064       // clauses or marking the landingpad as having a cleanup.
3065       if (isCatchAll(Personality, TypeInfo)) {
3066         if (!isLastClause)
3067           MakeNewInstruction = true;
3068         CleanupFlag = false;
3069         break;
3070       }
3071     } else {
3072       // A filter clause.  If any of the filter elements were already caught
3073       // then they can be dropped from the filter.  It is tempting to try to
3074       // exploit the filter further by saying that any typeinfo that does not
3075       // occur in the filter can't be caught later (and thus can be dropped).
3076       // However this would be wrong, since typeinfos can match without being
3077       // equal (for example if one represents a C++ class, and the other some
3078       // class derived from it).
3079       assert(LI.isFilter(i) && "Unsupported landingpad clause!");
3080       Constant *FilterClause = LI.getClause(i);
3081       ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
3082       unsigned NumTypeInfos = FilterType->getNumElements();
3083 
3084       // An empty filter catches everything, so there is no point in keeping any
3085       // following clauses or marking the landingpad as having a cleanup.  By
3086       // dealing with this case here the following code is made a bit simpler.
3087       if (!NumTypeInfos) {
3088         NewClauses.push_back(FilterClause);
3089         if (!isLastClause)
3090           MakeNewInstruction = true;
3091         CleanupFlag = false;
3092         break;
3093       }
3094 
3095       bool MakeNewFilter = false; // If true, make a new filter.
3096       SmallVector<Constant *, 16> NewFilterElts; // New elements.
3097       if (isa<ConstantAggregateZero>(FilterClause)) {
3098         // Not an empty filter - it contains at least one null typeinfo.
3099         assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
3100         Constant *TypeInfo =
3101           Constant::getNullValue(FilterType->getElementType());
3102         // If this typeinfo is a catch-all then the filter can never match.
3103         if (isCatchAll(Personality, TypeInfo)) {
3104           // Throw the filter away.
3105           MakeNewInstruction = true;
3106           continue;
3107         }
3108 
3109         // There is no point in having multiple copies of this typeinfo, so
3110         // discard all but the first copy if there is more than one.
3111         NewFilterElts.push_back(TypeInfo);
3112         if (NumTypeInfos > 1)
3113           MakeNewFilter = true;
3114       } else {
3115         ConstantArray *Filter = cast<ConstantArray>(FilterClause);
3116         SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
3117         NewFilterElts.reserve(NumTypeInfos);
3118 
3119         // Remove any filter elements that were already caught or that already
3120         // occurred in the filter.  While there, see if any of the elements are
3121         // catch-alls.  If so, the filter can be discarded.
3122         bool SawCatchAll = false;
3123         for (unsigned j = 0; j != NumTypeInfos; ++j) {
3124           Constant *Elt = Filter->getOperand(j);
3125           Constant *TypeInfo = Elt->stripPointerCasts();
3126           if (isCatchAll(Personality, TypeInfo)) {
3127             // This element is a catch-all.  Bail out, noting this fact.
3128             SawCatchAll = true;
3129             break;
3130           }
3131 
3132           // Even if we've seen a type in a catch clause, we don't want to
3133           // remove it from the filter.  An unexpected type handler may be
3134           // set up for a call site which throws an exception of the same
3135           // type caught.  In order for the exception thrown by the unexpected
3136           // handler to propagate correctly, the filter must be correctly
3137           // described for the call site.
3138           //
3139           // Example:
3140           //
3141           // void unexpected() { throw 1;}
3142           // void foo() throw (int) {
3143           //   std::set_unexpected(unexpected);
3144           //   try {
3145           //     throw 2.0;
3146           //   } catch (int i) {}
3147           // }
3148 
3149           // There is no point in having multiple copies of the same typeinfo in
3150           // a filter, so only add it if we didn't already.
3151           if (SeenInFilter.insert(TypeInfo).second)
3152             NewFilterElts.push_back(cast<Constant>(Elt));
3153         }
3154         // A filter containing a catch-all cannot match anything by definition.
3155         if (SawCatchAll) {
3156           // Throw the filter away.
3157           MakeNewInstruction = true;
3158           continue;
3159         }
3160 
3161         // If we dropped something from the filter, make a new one.
3162         if (NewFilterElts.size() < NumTypeInfos)
3163           MakeNewFilter = true;
3164       }
3165       if (MakeNewFilter) {
3166         FilterType = ArrayType::get(FilterType->getElementType(),
3167                                     NewFilterElts.size());
3168         FilterClause = ConstantArray::get(FilterType, NewFilterElts);
3169         MakeNewInstruction = true;
3170       }
3171 
3172       NewClauses.push_back(FilterClause);
3173 
3174       // If the new filter is empty then it will catch everything so there is
3175       // no point in keeping any following clauses or marking the landingpad
3176       // as having a cleanup.  The case of the original filter being empty was
3177       // already handled above.
3178       if (MakeNewFilter && !NewFilterElts.size()) {
3179         assert(MakeNewInstruction && "New filter but not a new instruction!");
3180         CleanupFlag = false;
3181         break;
3182       }
3183     }
3184   }
3185 
3186   // If several filters occur in a row then reorder them so that the shortest
3187   // filters come first (those with the smallest number of elements).  This is
3188   // advantageous because shorter filters are more likely to match, speeding up
3189   // unwinding, but mostly because it increases the effectiveness of the other
3190   // filter optimizations below.
3191   for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
3192     unsigned j;
3193     // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
3194     for (j = i; j != e; ++j)
3195       if (!isa<ArrayType>(NewClauses[j]->getType()))
3196         break;
3197 
3198     // Check whether the filters are already sorted by length.  We need to know
3199     // if sorting them is actually going to do anything so that we only make a
3200     // new landingpad instruction if it does.
3201     for (unsigned k = i; k + 1 < j; ++k)
3202       if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
3203         // Not sorted, so sort the filters now.  Doing an unstable sort would be
3204         // correct too but reordering filters pointlessly might confuse users.
3205         std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
3206                          shorter_filter);
3207         MakeNewInstruction = true;
3208         break;
3209       }
3210 
3211     // Look for the next batch of filters.
3212     i = j + 1;
3213   }
3214 
3215   // If typeinfos matched if and only if equal, then the elements of a filter L
3216   // that occurs later than a filter F could be replaced by the intersection of
3217   // the elements of F and L.  In reality two typeinfos can match without being
3218   // equal (for example if one represents a C++ class, and the other some class
3219   // derived from it) so it would be wrong to perform this transform in general.
3220   // However the transform is correct and useful if F is a subset of L.  In that
3221   // case L can be replaced by F, and thus removed altogether since repeating a
3222   // filter is pointless.  So here we look at all pairs of filters F and L where
3223   // L follows F in the list of clauses, and remove L if every element of F is
3224   // an element of L.  This can occur when inlining C++ functions with exception
3225   // specifications.
3226   for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
3227     // Examine each filter in turn.
3228     Value *Filter = NewClauses[i];
3229     ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
3230     if (!FTy)
3231       // Not a filter - skip it.
3232       continue;
3233     unsigned FElts = FTy->getNumElements();
3234     // Examine each filter following this one.  Doing this backwards means that
3235     // we don't have to worry about filters disappearing under us when removed.
3236     for (unsigned j = NewClauses.size() - 1; j != i; --j) {
3237       Value *LFilter = NewClauses[j];
3238       ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
3239       if (!LTy)
3240         // Not a filter - skip it.
3241         continue;
3242       // If Filter is a subset of LFilter, i.e. every element of Filter is also
3243       // an element of LFilter, then discard LFilter.
3244       SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
3245       // If Filter is empty then it is a subset of LFilter.
3246       if (!FElts) {
3247         // Discard LFilter.
3248         NewClauses.erase(J);
3249         MakeNewInstruction = true;
3250         // Move on to the next filter.
3251         continue;
3252       }
3253       unsigned LElts = LTy->getNumElements();
3254       // If Filter is longer than LFilter then it cannot be a subset of it.
3255       if (FElts > LElts)
3256         // Move on to the next filter.
3257         continue;
3258       // At this point we know that LFilter has at least one element.
3259       if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
3260         // Filter is a subset of LFilter iff Filter contains only zeros (as we
3261         // already know that Filter is not longer than LFilter).
3262         if (isa<ConstantAggregateZero>(Filter)) {
3263           assert(FElts <= LElts && "Should have handled this case earlier!");
3264           // Discard LFilter.
3265           NewClauses.erase(J);
3266           MakeNewInstruction = true;
3267         }
3268         // Move on to the next filter.
3269         continue;
3270       }
3271       ConstantArray *LArray = cast<ConstantArray>(LFilter);
3272       if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
3273         // Since Filter is non-empty and contains only zeros, it is a subset of
3274         // LFilter iff LFilter contains a zero.
3275         assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
3276         for (unsigned l = 0; l != LElts; ++l)
3277           if (LArray->getOperand(l)->isNullValue()) {
3278             // LFilter contains a zero - discard it.
3279             NewClauses.erase(J);
3280             MakeNewInstruction = true;
3281             break;
3282           }
3283         // Move on to the next filter.
3284         continue;
3285       }
3286       // At this point we know that both filters are ConstantArrays.  Loop over
3287       // operands to see whether every element of Filter is also an element of
3288       // LFilter.  Since filters tend to be short this is probably faster than
3289       // using a method that scales nicely.
3290       ConstantArray *FArray = cast<ConstantArray>(Filter);
3291       bool AllFound = true;
3292       for (unsigned f = 0; f != FElts; ++f) {
3293         Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
3294         AllFound = false;
3295         for (unsigned l = 0; l != LElts; ++l) {
3296           Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
3297           if (LTypeInfo == FTypeInfo) {
3298             AllFound = true;
3299             break;
3300           }
3301         }
3302         if (!AllFound)
3303           break;
3304       }
3305       if (AllFound) {
3306         // Discard LFilter.
3307         NewClauses.erase(J);
3308         MakeNewInstruction = true;
3309       }
3310       // Move on to the next filter.
3311     }
3312   }
3313 
3314   // If we changed any of the clauses, replace the old landingpad instruction
3315   // with a new one.
3316   if (MakeNewInstruction) {
3317     LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
3318                                                  NewClauses.size());
3319     for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
3320       NLI->addClause(NewClauses[i]);
3321     // A landing pad with no clauses must have the cleanup flag set.  It is
3322     // theoretically possible, though highly unlikely, that we eliminated all
3323     // clauses.  If so, force the cleanup flag to true.
3324     if (NewClauses.empty())
3325       CleanupFlag = true;
3326     NLI->setCleanup(CleanupFlag);
3327     return NLI;
3328   }
3329 
3330   // Even if none of the clauses changed, we may nonetheless have understood
3331   // that the cleanup flag is pointless.  Clear it if so.
3332   if (LI.isCleanup() != CleanupFlag) {
3333     assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
3334     LI.setCleanup(CleanupFlag);
3335     return &LI;
3336   }
3337 
3338   return nullptr;
3339 }
3340 
3341 Instruction *InstCombiner::visitFreeze(FreezeInst &I) {
3342   Value *Op0 = I.getOperand(0);
3343 
3344   if (Value *V = SimplifyFreezeInst(Op0, SQ.getWithInstruction(&I)))
3345     return replaceInstUsesWith(I, V);
3346 
3347   return nullptr;
3348 }
3349 
3350 /// Try to move the specified instruction from its current block into the
3351 /// beginning of DestBlock, which can only happen if it's safe to move the
3352 /// instruction past all of the instructions between it and the end of its
3353 /// block.
3354 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
3355   assert(I->getSingleUndroppableUse() && "Invariants didn't hold!");
3356   BasicBlock *SrcBlock = I->getParent();
3357 
3358   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
3359   if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() ||
3360       I->isTerminator())
3361     return false;
3362 
3363   // Do not sink static or dynamic alloca instructions. Static allocas must
3364   // remain in the entry block, and dynamic allocas must not be sunk in between
3365   // a stacksave / stackrestore pair, which would incorrectly shorten its
3366   // lifetime.
3367   if (isa<AllocaInst>(I))
3368     return false;
3369 
3370   // Do not sink into catchswitch blocks.
3371   if (isa<CatchSwitchInst>(DestBlock->getTerminator()))
3372     return false;
3373 
3374   // Do not sink convergent call instructions.
3375   if (auto *CI = dyn_cast<CallInst>(I)) {
3376     if (CI->isConvergent())
3377       return false;
3378   }
3379   // We can only sink load instructions if there is nothing between the load and
3380   // the end of block that could change the value.
3381   if (I->mayReadFromMemory()) {
3382     for (BasicBlock::iterator Scan = I->getIterator(),
3383                               E = I->getParent()->end();
3384          Scan != E; ++Scan)
3385       if (Scan->mayWriteToMemory())
3386         return false;
3387   }
3388 
3389   I->dropDroppableUses([DestBlock](const Use *U) {
3390     if (auto *I = dyn_cast<Instruction>(U->getUser()))
3391       return I->getParent() != DestBlock;
3392     return true;
3393   });
3394   /// FIXME: We could remove droppable uses that are not dominated by
3395   /// the new position.
3396 
3397   BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
3398   I->moveBefore(&*InsertPos);
3399   ++NumSunkInst;
3400 
3401   // Also sink all related debug uses from the source basic block. Otherwise we
3402   // get debug use before the def. Attempt to salvage debug uses first, to
3403   // maximise the range variables have location for. If we cannot salvage, then
3404   // mark the location undef: we know it was supposed to receive a new location
3405   // here, but that computation has been sunk.
3406   SmallVector<DbgVariableIntrinsic *, 2> DbgUsers;
3407   findDbgUsers(DbgUsers, I);
3408   for (auto *DII : reverse(DbgUsers)) {
3409     if (DII->getParent() == SrcBlock) {
3410       if (isa<DbgDeclareInst>(DII)) {
3411         // A dbg.declare instruction should not be cloned, since there can only be
3412         // one per variable fragment. It should be left in the original place since
3413         // sunk instruction is not an alloca(otherwise we could not be here).
3414         // But we need to update arguments of dbg.declare instruction, so that it
3415         // would not point into sunk instruction.
3416         if (!isa<CastInst>(I))
3417           continue; // dbg.declare points at something it shouldn't
3418 
3419         DII->setOperand(
3420             0, MetadataAsValue::get(I->getContext(),
3421                                     ValueAsMetadata::get(I->getOperand(0))));
3422         continue;
3423       }
3424 
3425       // dbg.value is in the same basic block as the sunk inst, see if we can
3426       // salvage it. Clone a new copy of the instruction: on success we need
3427       // both salvaged and unsalvaged copies.
3428       SmallVector<DbgVariableIntrinsic *, 1> TmpUser{
3429           cast<DbgVariableIntrinsic>(DII->clone())};
3430 
3431       if (!salvageDebugInfoForDbgValues(*I, TmpUser)) {
3432         // We are unable to salvage: sink the cloned dbg.value, and mark the
3433         // original as undef, terminating any earlier variable location.
3434         LLVM_DEBUG(dbgs() << "SINK: " << *DII << '\n');
3435         TmpUser[0]->insertBefore(&*InsertPos);
3436         Value *Undef = UndefValue::get(I->getType());
3437         DII->setOperand(0, MetadataAsValue::get(DII->getContext(),
3438                                                 ValueAsMetadata::get(Undef)));
3439       } else {
3440         // We successfully salvaged: place the salvaged dbg.value in the
3441         // original location, and move the unmodified dbg.value to sink with
3442         // the sunk inst.
3443         TmpUser[0]->insertBefore(DII);
3444         DII->moveBefore(&*InsertPos);
3445       }
3446     }
3447   }
3448   return true;
3449 }
3450 
3451 bool InstCombiner::run() {
3452   while (!Worklist.isEmpty()) {
3453     // Walk deferred instructions in reverse order, and push them to the
3454     // worklist, which means they'll end up popped from the worklist in-order.
3455     while (Instruction *I = Worklist.popDeferred()) {
3456       // Check to see if we can DCE the instruction. We do this already here to
3457       // reduce the number of uses and thus allow other folds to trigger.
3458       // Note that eraseInstFromFunction() may push additional instructions on
3459       // the deferred worklist, so this will DCE whole instruction chains.
3460       if (isInstructionTriviallyDead(I, &TLI)) {
3461         eraseInstFromFunction(*I);
3462         ++NumDeadInst;
3463         continue;
3464       }
3465 
3466       Worklist.push(I);
3467     }
3468 
3469     Instruction *I = Worklist.removeOne();
3470     if (I == nullptr) continue;  // skip null values.
3471 
3472     // Check to see if we can DCE the instruction.
3473     if (isInstructionTriviallyDead(I, &TLI)) {
3474       eraseInstFromFunction(*I);
3475       ++NumDeadInst;
3476       continue;
3477     }
3478 
3479     if (!DebugCounter::shouldExecute(VisitCounter))
3480       continue;
3481 
3482     // Instruction isn't dead, see if we can constant propagate it.
3483     if (!I->use_empty() &&
3484         (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) {
3485       if (Constant *C = ConstantFoldInstruction(I, DL, &TLI)) {
3486         LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I
3487                           << '\n');
3488 
3489         // Add operands to the worklist.
3490         replaceInstUsesWith(*I, C);
3491         ++NumConstProp;
3492         if (isInstructionTriviallyDead(I, &TLI))
3493           eraseInstFromFunction(*I);
3494         MadeIRChange = true;
3495         continue;
3496       }
3497     }
3498 
3499     // See if we can trivially sink this instruction to a successor basic block.
3500     if (EnableCodeSinking)
3501       if (Use *SingleUse = I->getSingleUndroppableUse()) {
3502         BasicBlock *BB = I->getParent();
3503         Instruction *UserInst = cast<Instruction>(SingleUse->getUser());
3504         BasicBlock *UserParent;
3505 
3506         // Get the block the use occurs in.
3507         if (PHINode *PN = dyn_cast<PHINode>(UserInst))
3508           UserParent = PN->getIncomingBlock(*I->use_begin());
3509         else
3510           UserParent = UserInst->getParent();
3511 
3512         if (UserParent != BB) {
3513           bool UserIsSuccessor = false;
3514           // See if the user is one of our successors.
3515           for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E;
3516                ++SI)
3517             if (*SI == UserParent) {
3518               UserIsSuccessor = true;
3519               break;
3520             }
3521 
3522           // If the user is one of our immediate successors, and if that
3523           // successor only has us as a predecessors (we'd have to split the
3524           // critical edge otherwise), we can keep going.
3525           if (UserIsSuccessor && UserParent->getUniquePredecessor()) {
3526             // Okay, the CFG is simple enough, try to sink this instruction.
3527             if (TryToSinkInstruction(I, UserParent)) {
3528               LLVM_DEBUG(dbgs() << "IC: Sink: " << *I << '\n');
3529               MadeIRChange = true;
3530               // We'll add uses of the sunk instruction below, but since sinking
3531               // can expose opportunities for it's *operands* add them to the
3532               // worklist
3533               for (Use &U : I->operands())
3534                 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
3535                   Worklist.push(OpI);
3536             }
3537           }
3538         }
3539       }
3540 
3541     // Now that we have an instruction, try combining it to simplify it.
3542     Builder.SetInsertPoint(I);
3543     Builder.SetCurrentDebugLocation(I->getDebugLoc());
3544 
3545 #ifndef NDEBUG
3546     std::string OrigI;
3547 #endif
3548     LLVM_DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
3549     LLVM_DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
3550 
3551     if (Instruction *Result = visit(*I)) {
3552       ++NumCombined;
3553       // Should we replace the old instruction with a new one?
3554       if (Result != I) {
3555         LLVM_DEBUG(dbgs() << "IC: Old = " << *I << '\n'
3556                           << "    New = " << *Result << '\n');
3557 
3558         if (I->getDebugLoc())
3559           Result->setDebugLoc(I->getDebugLoc());
3560         // Everything uses the new instruction now.
3561         I->replaceAllUsesWith(Result);
3562 
3563         // Move the name to the new instruction first.
3564         Result->takeName(I);
3565 
3566         // Insert the new instruction into the basic block...
3567         BasicBlock *InstParent = I->getParent();
3568         BasicBlock::iterator InsertPos = I->getIterator();
3569 
3570         // If we replace a PHI with something that isn't a PHI, fix up the
3571         // insertion point.
3572         if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
3573           InsertPos = InstParent->getFirstInsertionPt();
3574 
3575         InstParent->getInstList().insert(InsertPos, Result);
3576 
3577         // Push the new instruction and any users onto the worklist.
3578         Worklist.pushUsersToWorkList(*Result);
3579         Worklist.push(Result);
3580 
3581         eraseInstFromFunction(*I);
3582       } else {
3583         LLVM_DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
3584                           << "    New = " << *I << '\n');
3585 
3586         // If the instruction was modified, it's possible that it is now dead.
3587         // if so, remove it.
3588         if (isInstructionTriviallyDead(I, &TLI)) {
3589           eraseInstFromFunction(*I);
3590         } else {
3591           Worklist.pushUsersToWorkList(*I);
3592           Worklist.push(I);
3593         }
3594       }
3595       MadeIRChange = true;
3596     }
3597   }
3598 
3599   Worklist.zap();
3600   return MadeIRChange;
3601 }
3602 
3603 /// Walk the function in depth-first order, adding all reachable code to the
3604 /// worklist.
3605 ///
3606 /// This has a couple of tricks to make the code faster and more powerful.  In
3607 /// particular, we constant fold and DCE instructions as we go, to avoid adding
3608 /// them to the worklist (this significantly speeds up instcombine on code where
3609 /// many instructions are dead or constant).  Additionally, if we find a branch
3610 /// whose condition is a known constant, we only visit the reachable successors.
3611 static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL,
3612                                        SmallPtrSetImpl<BasicBlock *> &Visited,
3613                                        InstCombineWorklist &ICWorklist,
3614                                        const TargetLibraryInfo *TLI) {
3615   bool MadeIRChange = false;
3616   SmallVector<BasicBlock*, 256> Worklist;
3617   Worklist.push_back(BB);
3618 
3619   SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
3620   DenseMap<Constant *, Constant *> FoldedConstants;
3621 
3622   do {
3623     BB = Worklist.pop_back_val();
3624 
3625     // We have now visited this block!  If we've already been here, ignore it.
3626     if (!Visited.insert(BB).second)
3627       continue;
3628 
3629     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
3630       Instruction *Inst = &*BBI++;
3631 
3632       // ConstantProp instruction if trivially constant.
3633       if (!Inst->use_empty() &&
3634           (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0))))
3635         if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
3636           LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *Inst
3637                             << '\n');
3638           Inst->replaceAllUsesWith(C);
3639           ++NumConstProp;
3640           if (isInstructionTriviallyDead(Inst, TLI))
3641             Inst->eraseFromParent();
3642           MadeIRChange = true;
3643           continue;
3644         }
3645 
3646       // See if we can constant fold its operands.
3647       for (Use &U : Inst->operands()) {
3648         if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U))
3649           continue;
3650 
3651         auto *C = cast<Constant>(U);
3652         Constant *&FoldRes = FoldedConstants[C];
3653         if (!FoldRes)
3654           FoldRes = ConstantFoldConstant(C, DL, TLI);
3655 
3656         if (FoldRes != C) {
3657           LLVM_DEBUG(dbgs() << "IC: ConstFold operand of: " << *Inst
3658                             << "\n    Old = " << *C
3659                             << "\n    New = " << *FoldRes << '\n');
3660           U = FoldRes;
3661           MadeIRChange = true;
3662         }
3663       }
3664 
3665       // Skip processing debug intrinsics in InstCombine. Processing these call instructions
3666       // consumes non-trivial amount of time and provides no value for the optimization.
3667       if (!isa<DbgInfoIntrinsic>(Inst))
3668         InstrsForInstCombineWorklist.push_back(Inst);
3669     }
3670 
3671     // Recursively visit successors.  If this is a branch or switch on a
3672     // constant, only visit the reachable successor.
3673     Instruction *TI = BB->getTerminator();
3674     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3675       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
3676         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
3677         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
3678         Worklist.push_back(ReachableBB);
3679         continue;
3680       }
3681     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3682       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
3683         Worklist.push_back(SI->findCaseValue(Cond)->getCaseSuccessor());
3684         continue;
3685       }
3686     }
3687 
3688     for (BasicBlock *SuccBB : successors(TI))
3689       Worklist.push_back(SuccBB);
3690   } while (!Worklist.empty());
3691 
3692   // Once we've found all of the instructions to add to instcombine's worklist,
3693   // add them in reverse order.  This way instcombine will visit from the top
3694   // of the function down.  This jives well with the way that it adds all uses
3695   // of instructions to the worklist after doing a transformation, thus avoiding
3696   // some N^2 behavior in pathological cases.
3697   ICWorklist.reserve(InstrsForInstCombineWorklist.size());
3698   for (Instruction *Inst : reverse(InstrsForInstCombineWorklist)) {
3699     // DCE instruction if trivially dead. As we iterate in reverse program
3700     // order here, we will clean up whole chains of dead instructions.
3701     if (isInstructionTriviallyDead(Inst, TLI)) {
3702       ++NumDeadInst;
3703       LLVM_DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
3704       salvageDebugInfoOrMarkUndef(*Inst);
3705       Inst->eraseFromParent();
3706       MadeIRChange = true;
3707       continue;
3708     }
3709 
3710     ICWorklist.push(Inst);
3711   }
3712 
3713   return MadeIRChange;
3714 }
3715 
3716 /// Populate the IC worklist from a function, and prune any dead basic
3717 /// blocks discovered in the process.
3718 ///
3719 /// This also does basic constant propagation and other forward fixing to make
3720 /// the combiner itself run much faster.
3721 static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
3722                                           TargetLibraryInfo *TLI,
3723                                           InstCombineWorklist &ICWorklist) {
3724   bool MadeIRChange = false;
3725 
3726   // Do a depth-first traversal of the function, populate the worklist with
3727   // the reachable instructions.  Ignore blocks that are not reachable.  Keep
3728   // track of which blocks we visit.
3729   SmallPtrSet<BasicBlock *, 32> Visited;
3730   MadeIRChange |=
3731       AddReachableCodeToWorklist(&F.front(), DL, Visited, ICWorklist, TLI);
3732 
3733   // Do a quick scan over the function.  If we find any blocks that are
3734   // unreachable, remove any instructions inside of them.  This prevents
3735   // the instcombine code from having to deal with some bad special cases.
3736   for (BasicBlock &BB : F) {
3737     if (Visited.count(&BB))
3738       continue;
3739 
3740     unsigned NumDeadInstInBB = removeAllNonTerminatorAndEHPadInstructions(&BB);
3741     MadeIRChange |= NumDeadInstInBB > 0;
3742     NumDeadInst += NumDeadInstInBB;
3743   }
3744 
3745   return MadeIRChange;
3746 }
3747 
3748 static bool combineInstructionsOverFunction(
3749     Function &F, InstCombineWorklist &Worklist, AliasAnalysis *AA,
3750     AssumptionCache &AC, TargetLibraryInfo &TLI, DominatorTree &DT,
3751     OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI,
3752     ProfileSummaryInfo *PSI, unsigned MaxIterations, LoopInfo *LI) {
3753   auto &DL = F.getParent()->getDataLayout();
3754   MaxIterations = std::min(MaxIterations, LimitMaxIterations.getValue());
3755 
3756   /// Builder - This is an IRBuilder that automatically inserts new
3757   /// instructions into the worklist when they are created.
3758   IRBuilder<TargetFolder, IRBuilderCallbackInserter> Builder(
3759       F.getContext(), TargetFolder(DL),
3760       IRBuilderCallbackInserter([&Worklist, &AC](Instruction *I) {
3761         Worklist.add(I);
3762         if (match(I, m_Intrinsic<Intrinsic::assume>()))
3763           AC.registerAssumption(cast<CallInst>(I));
3764       }));
3765 
3766   // Lower dbg.declare intrinsics otherwise their value may be clobbered
3767   // by instcombiner.
3768   bool MadeIRChange = false;
3769   if (ShouldLowerDbgDeclare)
3770     MadeIRChange = LowerDbgDeclare(F);
3771 
3772   // Iterate while there is work to do.
3773   unsigned Iteration = 0;
3774   while (true) {
3775     ++Iteration;
3776 
3777     if (Iteration > InfiniteLoopDetectionThreshold) {
3778       report_fatal_error(
3779           "Instruction Combining seems stuck in an infinite loop after " +
3780           Twine(InfiniteLoopDetectionThreshold) + " iterations.");
3781     }
3782 
3783     if (Iteration > MaxIterations) {
3784       LLVM_DEBUG(dbgs() << "\n\n[IC] Iteration limit #" << MaxIterations
3785                         << " on " << F.getName()
3786                         << " reached; stopping before reaching a fixpoint\n");
3787       break;
3788     }
3789 
3790     LLVM_DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
3791                       << F.getName() << "\n");
3792 
3793     MadeIRChange |= prepareICWorklistFromFunction(F, DL, &TLI, Worklist);
3794 
3795     InstCombiner IC(Worklist, Builder, F.hasMinSize(), AA,
3796                     AC, TLI, DT, ORE, BFI, PSI, DL, LI);
3797     IC.MaxArraySizeForCombine = MaxArraySize;
3798 
3799     if (!IC.run())
3800       break;
3801 
3802     MadeIRChange = true;
3803   }
3804 
3805   return MadeIRChange;
3806 }
3807 
3808 InstCombinePass::InstCombinePass() : MaxIterations(LimitMaxIterations) {}
3809 
3810 InstCombinePass::InstCombinePass(unsigned MaxIterations)
3811     : MaxIterations(MaxIterations) {}
3812 
3813 PreservedAnalyses InstCombinePass::run(Function &F,
3814                                        FunctionAnalysisManager &AM) {
3815   auto &AC = AM.getResult<AssumptionAnalysis>(F);
3816   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3817   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
3818   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
3819 
3820   auto *LI = AM.getCachedResult<LoopAnalysis>(F);
3821 
3822   auto *AA = &AM.getResult<AAManager>(F);
3823   const ModuleAnalysisManager &MAM =
3824       AM.getResult<ModuleAnalysisManagerFunctionProxy>(F).getManager();
3825   ProfileSummaryInfo *PSI =
3826       MAM.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
3827   auto *BFI = (PSI && PSI->hasProfileSummary()) ?
3828       &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr;
3829 
3830   if (!combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, ORE, BFI,
3831                                        PSI, MaxIterations, LI))
3832     // No changes, all analyses are preserved.
3833     return PreservedAnalyses::all();
3834 
3835   // Mark all the analyses that instcombine updates as preserved.
3836   PreservedAnalyses PA;
3837   PA.preserveSet<CFGAnalyses>();
3838   PA.preserve<AAManager>();
3839   PA.preserve<BasicAA>();
3840   PA.preserve<GlobalsAA>();
3841   return PA;
3842 }
3843 
3844 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
3845   AU.setPreservesCFG();
3846   AU.addRequired<AAResultsWrapperPass>();
3847   AU.addRequired<AssumptionCacheTracker>();
3848   AU.addRequired<TargetLibraryInfoWrapperPass>();
3849   AU.addRequired<DominatorTreeWrapperPass>();
3850   AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
3851   AU.addPreserved<DominatorTreeWrapperPass>();
3852   AU.addPreserved<AAResultsWrapperPass>();
3853   AU.addPreserved<BasicAAWrapperPass>();
3854   AU.addPreserved<GlobalsAAWrapperPass>();
3855   AU.addRequired<ProfileSummaryInfoWrapperPass>();
3856   LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);
3857 }
3858 
3859 bool InstructionCombiningPass::runOnFunction(Function &F) {
3860   if (skipFunction(F))
3861     return false;
3862 
3863   // Required analyses.
3864   auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3865   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3866   auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
3867   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3868   auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
3869 
3870   // Optional analyses.
3871   auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3872   auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
3873   ProfileSummaryInfo *PSI =
3874       &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
3875   BlockFrequencyInfo *BFI =
3876       (PSI && PSI->hasProfileSummary()) ?
3877       &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI() :
3878       nullptr;
3879 
3880   return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, ORE, BFI,
3881                                          PSI, MaxIterations, LI);
3882 }
3883 
3884 char InstructionCombiningPass::ID = 0;
3885 
3886 InstructionCombiningPass::InstructionCombiningPass()
3887     : FunctionPass(ID), MaxIterations(InstCombineDefaultMaxIterations) {
3888   initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry());
3889 }
3890 
3891 InstructionCombiningPass::InstructionCombiningPass(unsigned MaxIterations)
3892     : FunctionPass(ID), MaxIterations(MaxIterations) {
3893   initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry());
3894 }
3895 
3896 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
3897                       "Combine redundant instructions", false, false)
3898 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3899 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3900 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3901 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3902 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3903 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
3904 INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass)
3905 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
3906 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
3907                     "Combine redundant instructions", false, false)
3908 
3909 // Initialization Routines
3910 void llvm::initializeInstCombine(PassRegistry &Registry) {
3911   initializeInstructionCombiningPassPass(Registry);
3912 }
3913 
3914 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
3915   initializeInstructionCombiningPassPass(*unwrap(R));
3916 }
3917 
3918 FunctionPass *llvm::createInstructionCombiningPass() {
3919   return new InstructionCombiningPass();
3920 }
3921 
3922 FunctionPass *llvm::createInstructionCombiningPass(unsigned MaxIterations) {
3923   return new InstructionCombiningPass(MaxIterations);
3924 }
3925 
3926 void LLVMAddInstructionCombiningPass(LLVMPassManagerRef PM) {
3927   unwrap(PM)->add(createInstructionCombiningPass());
3928 }
3929