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