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