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