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