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