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     UndefValue *Undef = UndefValue::get(Inst.getType());
1716     SmallVector<int, 8> NewMask(MaskC.size(), SplatIndex);
1717     Value *NewSplat = Builder.CreateShuffleVector(NewBO, Undef, NewMask);
1718     Instruction *R = BinaryOperator::Create(Opcode, NewSplat, OtherOp);
1719 
1720     // Intersect FMF on both new binops. Other (poison-generating) flags are
1721     // dropped to be safe.
1722     if (isa<FPMathOperator>(R)) {
1723       R->copyFastMathFlags(&Inst);
1724       R->andIRFlags(BO);
1725     }
1726     if (auto *NewInstBO = dyn_cast<BinaryOperator>(NewBO))
1727       NewInstBO->copyIRFlags(R);
1728     return R;
1729   }
1730 
1731   return nullptr;
1732 }
1733 
1734 /// Try to narrow the width of a binop if at least 1 operand is an extend of
1735 /// of a value. This requires a potentially expensive known bits check to make
1736 /// sure the narrow op does not overflow.
1737 Instruction *InstCombinerImpl::narrowMathIfNoOverflow(BinaryOperator &BO) {
1738   // We need at least one extended operand.
1739   Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1);
1740 
1741   // If this is a sub, we swap the operands since we always want an extension
1742   // on the RHS. The LHS can be an extension or a constant.
1743   if (BO.getOpcode() == Instruction::Sub)
1744     std::swap(Op0, Op1);
1745 
1746   Value *X;
1747   bool IsSext = match(Op0, m_SExt(m_Value(X)));
1748   if (!IsSext && !match(Op0, m_ZExt(m_Value(X))))
1749     return nullptr;
1750 
1751   // If both operands are the same extension from the same source type and we
1752   // can eliminate at least one (hasOneUse), this might work.
1753   CastInst::CastOps CastOpc = IsSext ? Instruction::SExt : Instruction::ZExt;
1754   Value *Y;
1755   if (!(match(Op1, m_ZExtOrSExt(m_Value(Y))) && X->getType() == Y->getType() &&
1756         cast<Operator>(Op1)->getOpcode() == CastOpc &&
1757         (Op0->hasOneUse() || Op1->hasOneUse()))) {
1758     // If that did not match, see if we have a suitable constant operand.
1759     // Truncating and extending must produce the same constant.
1760     Constant *WideC;
1761     if (!Op0->hasOneUse() || !match(Op1, m_Constant(WideC)))
1762       return nullptr;
1763     Constant *NarrowC = ConstantExpr::getTrunc(WideC, X->getType());
1764     if (ConstantExpr::getCast(CastOpc, NarrowC, BO.getType()) != WideC)
1765       return nullptr;
1766     Y = NarrowC;
1767   }
1768 
1769   // Swap back now that we found our operands.
1770   if (BO.getOpcode() == Instruction::Sub)
1771     std::swap(X, Y);
1772 
1773   // Both operands have narrow versions. Last step: the math must not overflow
1774   // in the narrow width.
1775   if (!willNotOverflow(BO.getOpcode(), X, Y, BO, IsSext))
1776     return nullptr;
1777 
1778   // bo (ext X), (ext Y) --> ext (bo X, Y)
1779   // bo (ext X), C       --> ext (bo X, C')
1780   Value *NarrowBO = Builder.CreateBinOp(BO.getOpcode(), X, Y, "narrow");
1781   if (auto *NewBinOp = dyn_cast<BinaryOperator>(NarrowBO)) {
1782     if (IsSext)
1783       NewBinOp->setHasNoSignedWrap();
1784     else
1785       NewBinOp->setHasNoUnsignedWrap();
1786   }
1787   return CastInst::Create(CastOpc, NarrowBO, BO.getType());
1788 }
1789 
1790 static bool isMergedGEPInBounds(GEPOperator &GEP1, GEPOperator &GEP2) {
1791   // At least one GEP must be inbounds.
1792   if (!GEP1.isInBounds() && !GEP2.isInBounds())
1793     return false;
1794 
1795   return (GEP1.isInBounds() || GEP1.hasAllZeroIndices()) &&
1796          (GEP2.isInBounds() || GEP2.hasAllZeroIndices());
1797 }
1798 
1799 /// Thread a GEP operation with constant indices through the constant true/false
1800 /// arms of a select.
1801 static Instruction *foldSelectGEP(GetElementPtrInst &GEP,
1802                                   InstCombiner::BuilderTy &Builder) {
1803   if (!GEP.hasAllConstantIndices())
1804     return nullptr;
1805 
1806   Instruction *Sel;
1807   Value *Cond;
1808   Constant *TrueC, *FalseC;
1809   if (!match(GEP.getPointerOperand(), m_Instruction(Sel)) ||
1810       !match(Sel,
1811              m_Select(m_Value(Cond), m_Constant(TrueC), m_Constant(FalseC))))
1812     return nullptr;
1813 
1814   // gep (select Cond, TrueC, FalseC), IndexC --> select Cond, TrueC', FalseC'
1815   // Propagate 'inbounds' and metadata from existing instructions.
1816   // Note: using IRBuilder to create the constants for efficiency.
1817   SmallVector<Value *, 4> IndexC(GEP.idx_begin(), GEP.idx_end());
1818   bool IsInBounds = GEP.isInBounds();
1819   Value *NewTrueC = IsInBounds ? Builder.CreateInBoundsGEP(TrueC, IndexC)
1820                                : Builder.CreateGEP(TrueC, IndexC);
1821   Value *NewFalseC = IsInBounds ? Builder.CreateInBoundsGEP(FalseC, IndexC)
1822                                 : Builder.CreateGEP(FalseC, IndexC);
1823   return SelectInst::Create(Cond, NewTrueC, NewFalseC, "", nullptr, Sel);
1824 }
1825 
1826 Instruction *InstCombinerImpl::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1827   SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1828   Type *GEPType = GEP.getType();
1829   Type *GEPEltType = GEP.getSourceElementType();
1830   bool IsGEPSrcEleScalable = isa<ScalableVectorType>(GEPEltType);
1831   if (Value *V = SimplifyGEPInst(GEPEltType, Ops, SQ.getWithInstruction(&GEP)))
1832     return replaceInstUsesWith(GEP, V);
1833 
1834   // For vector geps, use the generic demanded vector support.
1835   // Skip if GEP return type is scalable. The number of elements is unknown at
1836   // compile-time.
1837   if (auto *GEPFVTy = dyn_cast<FixedVectorType>(GEPType)) {
1838     auto VWidth = GEPFVTy->getNumElements();
1839     APInt UndefElts(VWidth, 0);
1840     APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1841     if (Value *V = SimplifyDemandedVectorElts(&GEP, AllOnesEltMask,
1842                                               UndefElts)) {
1843       if (V != &GEP)
1844         return replaceInstUsesWith(GEP, V);
1845       return &GEP;
1846     }
1847 
1848     // TODO: 1) Scalarize splat operands, 2) scalarize entire instruction if
1849     // possible (decide on canonical form for pointer broadcast), 3) exploit
1850     // undef elements to decrease demanded bits
1851   }
1852 
1853   Value *PtrOp = GEP.getOperand(0);
1854 
1855   // Eliminate unneeded casts for indices, and replace indices which displace
1856   // by multiples of a zero size type with zero.
1857   bool MadeChange = false;
1858 
1859   // Index width may not be the same width as pointer width.
1860   // Data layout chooses the right type based on supported integer types.
1861   Type *NewScalarIndexTy =
1862       DL.getIndexType(GEP.getPointerOperandType()->getScalarType());
1863 
1864   gep_type_iterator GTI = gep_type_begin(GEP);
1865   for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
1866        ++I, ++GTI) {
1867     // Skip indices into struct types.
1868     if (GTI.isStruct())
1869       continue;
1870 
1871     Type *IndexTy = (*I)->getType();
1872     Type *NewIndexType =
1873         IndexTy->isVectorTy()
1874             ? VectorType::get(NewScalarIndexTy,
1875                               cast<VectorType>(IndexTy)->getElementCount())
1876             : NewScalarIndexTy;
1877 
1878     // If the element type has zero size then any index over it is equivalent
1879     // to an index of zero, so replace it with zero if it is not zero already.
1880     Type *EltTy = GTI.getIndexedType();
1881     if (EltTy->isSized() && DL.getTypeAllocSize(EltTy).isZero())
1882       if (!isa<Constant>(*I) || !match(I->get(), m_Zero())) {
1883         *I = Constant::getNullValue(NewIndexType);
1884         MadeChange = true;
1885       }
1886 
1887     if (IndexTy != NewIndexType) {
1888       // If we are using a wider index than needed for this platform, shrink
1889       // it to what we need.  If narrower, sign-extend it to what we need.
1890       // This explicit cast can make subsequent optimizations more obvious.
1891       *I = Builder.CreateIntCast(*I, NewIndexType, true);
1892       MadeChange = true;
1893     }
1894   }
1895   if (MadeChange)
1896     return &GEP;
1897 
1898   // Check to see if the inputs to the PHI node are getelementptr instructions.
1899   if (auto *PN = dyn_cast<PHINode>(PtrOp)) {
1900     auto *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1901     if (!Op1)
1902       return nullptr;
1903 
1904     // Don't fold a GEP into itself through a PHI node. This can only happen
1905     // through the back-edge of a loop. Folding a GEP into itself means that
1906     // the value of the previous iteration needs to be stored in the meantime,
1907     // thus requiring an additional register variable to be live, but not
1908     // actually achieving anything (the GEP still needs to be executed once per
1909     // loop iteration).
1910     if (Op1 == &GEP)
1911       return nullptr;
1912 
1913     int DI = -1;
1914 
1915     for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1916       auto *Op2 = dyn_cast<GetElementPtrInst>(*I);
1917       if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1918         return nullptr;
1919 
1920       // As for Op1 above, don't try to fold a GEP into itself.
1921       if (Op2 == &GEP)
1922         return nullptr;
1923 
1924       // Keep track of the type as we walk the GEP.
1925       Type *CurTy = nullptr;
1926 
1927       for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1928         if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1929           return nullptr;
1930 
1931         if (Op1->getOperand(J) != Op2->getOperand(J)) {
1932           if (DI == -1) {
1933             // We have not seen any differences yet in the GEPs feeding the
1934             // PHI yet, so we record this one if it is allowed to be a
1935             // variable.
1936 
1937             // The first two arguments can vary for any GEP, the rest have to be
1938             // static for struct slots
1939             if (J > 1) {
1940               assert(CurTy && "No current type?");
1941               if (CurTy->isStructTy())
1942                 return nullptr;
1943             }
1944 
1945             DI = J;
1946           } else {
1947             // The GEP is different by more than one input. While this could be
1948             // extended to support GEPs that vary by more than one variable it
1949             // doesn't make sense since it greatly increases the complexity and
1950             // would result in an R+R+R addressing mode which no backend
1951             // directly supports and would need to be broken into several
1952             // simpler instructions anyway.
1953             return nullptr;
1954           }
1955         }
1956 
1957         // Sink down a layer of the type for the next iteration.
1958         if (J > 0) {
1959           if (J == 1) {
1960             CurTy = Op1->getSourceElementType();
1961           } else {
1962             CurTy =
1963                 GetElementPtrInst::getTypeAtIndex(CurTy, Op1->getOperand(J));
1964           }
1965         }
1966       }
1967     }
1968 
1969     // If not all GEPs are identical we'll have to create a new PHI node.
1970     // Check that the old PHI node has only one use so that it will get
1971     // removed.
1972     if (DI != -1 && !PN->hasOneUse())
1973       return nullptr;
1974 
1975     auto *NewGEP = cast<GetElementPtrInst>(Op1->clone());
1976     if (DI == -1) {
1977       // All the GEPs feeding the PHI are identical. Clone one down into our
1978       // BB so that it can be merged with the current GEP.
1979     } else {
1980       // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1981       // into the current block so it can be merged, and create a new PHI to
1982       // set that index.
1983       PHINode *NewPN;
1984       {
1985         IRBuilderBase::InsertPointGuard Guard(Builder);
1986         Builder.SetInsertPoint(PN);
1987         NewPN = Builder.CreatePHI(Op1->getOperand(DI)->getType(),
1988                                   PN->getNumOperands());
1989       }
1990 
1991       for (auto &I : PN->operands())
1992         NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1993                            PN->getIncomingBlock(I));
1994 
1995       NewGEP->setOperand(DI, NewPN);
1996     }
1997 
1998     GEP.getParent()->getInstList().insert(
1999         GEP.getParent()->getFirstInsertionPt(), NewGEP);
2000     replaceOperand(GEP, 0, NewGEP);
2001     PtrOp = NewGEP;
2002   }
2003 
2004   // Combine Indices - If the source pointer to this getelementptr instruction
2005   // is a getelementptr instruction, combine the indices of the two
2006   // getelementptr instructions into a single instruction.
2007   if (auto *Src = dyn_cast<GEPOperator>(PtrOp)) {
2008     if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
2009       return nullptr;
2010 
2011     // Try to reassociate loop invariant GEP chains to enable LICM.
2012     if (LI && Src->getNumOperands() == 2 && GEP.getNumOperands() == 2 &&
2013         Src->hasOneUse()) {
2014       if (Loop *L = LI->getLoopFor(GEP.getParent())) {
2015         Value *GO1 = GEP.getOperand(1);
2016         Value *SO1 = Src->getOperand(1);
2017         // Reassociate the two GEPs if SO1 is variant in the loop and GO1 is
2018         // invariant: this breaks the dependence between GEPs and allows LICM
2019         // to hoist the invariant part out of the loop.
2020         if (L->isLoopInvariant(GO1) && !L->isLoopInvariant(SO1)) {
2021           // We have to be careful here.
2022           // We have something like:
2023           //  %src = getelementptr <ty>, <ty>* %base, <ty> %idx
2024           //  %gep = getelementptr <ty>, <ty>* %src, <ty> %idx2
2025           // If we just swap idx & idx2 then we could inadvertantly
2026           // change %src from a vector to a scalar, or vice versa.
2027           // Cases:
2028           //  1) %base a scalar & idx a scalar & idx2 a vector
2029           //      => Swapping idx & idx2 turns %src into a vector type.
2030           //  2) %base a scalar & idx a vector & idx2 a scalar
2031           //      => Swapping idx & idx2 turns %src in a scalar type
2032           //  3) %base, %idx, and %idx2 are scalars
2033           //      => %src & %gep are scalars
2034           //      => swapping idx & idx2 is safe
2035           //  4) %base a vector
2036           //      => %src is a vector
2037           //      => swapping idx & idx2 is safe.
2038           auto *SO0 = Src->getOperand(0);
2039           auto *SO0Ty = SO0->getType();
2040           if (!isa<VectorType>(GEPType) || // case 3
2041               isa<VectorType>(SO0Ty)) {    // case 4
2042             Src->setOperand(1, GO1);
2043             GEP.setOperand(1, SO1);
2044             return &GEP;
2045           } else {
2046             // Case 1 or 2
2047             // -- have to recreate %src & %gep
2048             // put NewSrc at same location as %src
2049             Builder.SetInsertPoint(cast<Instruction>(PtrOp));
2050             auto *NewSrc = cast<GetElementPtrInst>(
2051                 Builder.CreateGEP(GEPEltType, SO0, GO1, Src->getName()));
2052             NewSrc->setIsInBounds(Src->isInBounds());
2053             auto *NewGEP = GetElementPtrInst::Create(GEPEltType, NewSrc, {SO1});
2054             NewGEP->setIsInBounds(GEP.isInBounds());
2055             return NewGEP;
2056           }
2057         }
2058       }
2059     }
2060 
2061     // Note that if our source is a gep chain itself then we wait for that
2062     // chain to be resolved before we perform this transformation.  This
2063     // avoids us creating a TON of code in some cases.
2064     if (auto *SrcGEP = dyn_cast<GEPOperator>(Src->getOperand(0)))
2065       if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
2066         return nullptr;   // Wait until our source is folded to completion.
2067 
2068     SmallVector<Value*, 8> Indices;
2069 
2070     // Find out whether the last index in the source GEP is a sequential idx.
2071     bool EndsWithSequential = false;
2072     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
2073          I != E; ++I)
2074       EndsWithSequential = I.isSequential();
2075 
2076     // Can we combine the two pointer arithmetics offsets?
2077     if (EndsWithSequential) {
2078       // Replace: gep (gep %P, long B), long A, ...
2079       // With:    T = long A+B; gep %P, T, ...
2080       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
2081       Value *GO1 = GEP.getOperand(1);
2082 
2083       // If they aren't the same type, then the input hasn't been processed
2084       // by the loop above yet (which canonicalizes sequential index types to
2085       // intptr_t).  Just avoid transforming this until the input has been
2086       // normalized.
2087       if (SO1->getType() != GO1->getType())
2088         return nullptr;
2089 
2090       Value *Sum =
2091           SimplifyAddInst(GO1, SO1, false, false, SQ.getWithInstruction(&GEP));
2092       // Only do the combine when we are sure the cost after the
2093       // merge is never more than that before the merge.
2094       if (Sum == nullptr)
2095         return nullptr;
2096 
2097       // Update the GEP in place if possible.
2098       if (Src->getNumOperands() == 2) {
2099         GEP.setIsInBounds(isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP)));
2100         replaceOperand(GEP, 0, Src->getOperand(0));
2101         replaceOperand(GEP, 1, Sum);
2102         return &GEP;
2103       }
2104       Indices.append(Src->op_begin()+1, Src->op_end()-1);
2105       Indices.push_back(Sum);
2106       Indices.append(GEP.op_begin()+2, GEP.op_end());
2107     } else if (isa<Constant>(*GEP.idx_begin()) &&
2108                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
2109                Src->getNumOperands() != 1) {
2110       // Otherwise we can do the fold if the first index of the GEP is a zero
2111       Indices.append(Src->op_begin()+1, Src->op_end());
2112       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
2113     }
2114 
2115     if (!Indices.empty())
2116       return isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP))
2117                  ? GetElementPtrInst::CreateInBounds(
2118                        Src->getSourceElementType(), Src->getOperand(0), Indices,
2119                        GEP.getName())
2120                  : GetElementPtrInst::Create(Src->getSourceElementType(),
2121                                              Src->getOperand(0), Indices,
2122                                              GEP.getName());
2123   }
2124 
2125   // Skip if GEP source element type is scalable. The type alloc size is unknown
2126   // at compile-time.
2127   if (GEP.getNumIndices() == 1 && !IsGEPSrcEleScalable) {
2128     unsigned AS = GEP.getPointerAddressSpace();
2129     if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
2130         DL.getIndexSizeInBits(AS)) {
2131       uint64_t TyAllocSize = DL.getTypeAllocSize(GEPEltType).getFixedSize();
2132 
2133       bool Matched = false;
2134       uint64_t C;
2135       Value *V = nullptr;
2136       if (TyAllocSize == 1) {
2137         V = GEP.getOperand(1);
2138         Matched = true;
2139       } else if (match(GEP.getOperand(1),
2140                        m_AShr(m_Value(V), m_ConstantInt(C)))) {
2141         if (TyAllocSize == 1ULL << C)
2142           Matched = true;
2143       } else if (match(GEP.getOperand(1),
2144                        m_SDiv(m_Value(V), m_ConstantInt(C)))) {
2145         if (TyAllocSize == C)
2146           Matched = true;
2147       }
2148 
2149       if (Matched) {
2150         // Canonicalize (gep i8* X, -(ptrtoint Y))
2151         // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
2152         // The GEP pattern is emitted by the SCEV expander for certain kinds of
2153         // pointer arithmetic.
2154         if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
2155           Operator *Index = cast<Operator>(V);
2156           Value *PtrToInt = Builder.CreatePtrToInt(PtrOp, Index->getType());
2157           Value *NewSub = Builder.CreateSub(PtrToInt, Index->getOperand(1));
2158           return CastInst::Create(Instruction::IntToPtr, NewSub, GEPType);
2159         }
2160         // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
2161         // to (bitcast Y)
2162         Value *Y;
2163         if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
2164                            m_PtrToInt(m_Specific(GEP.getOperand(0))))))
2165           return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y, GEPType);
2166       }
2167     }
2168   }
2169 
2170   // We do not handle pointer-vector geps here.
2171   if (GEPType->isVectorTy())
2172     return nullptr;
2173 
2174   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
2175   Value *StrippedPtr = PtrOp->stripPointerCasts();
2176   PointerType *StrippedPtrTy = cast<PointerType>(StrippedPtr->getType());
2177 
2178   if (StrippedPtr != PtrOp) {
2179     bool HasZeroPointerIndex = false;
2180     Type *StrippedPtrEltTy = StrippedPtrTy->getElementType();
2181 
2182     if (auto *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
2183       HasZeroPointerIndex = C->isZero();
2184 
2185     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
2186     // into     : GEP [10 x i8]* X, i32 0, ...
2187     //
2188     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
2189     //           into     : GEP i8* X, ...
2190     //
2191     // This occurs when the program declares an array extern like "int X[];"
2192     if (HasZeroPointerIndex) {
2193       if (auto *CATy = dyn_cast<ArrayType>(GEPEltType)) {
2194         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
2195         if (CATy->getElementType() == StrippedPtrEltTy) {
2196           // -> GEP i8* X, ...
2197           SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
2198           GetElementPtrInst *Res = GetElementPtrInst::Create(
2199               StrippedPtrEltTy, StrippedPtr, Idx, GEP.getName());
2200           Res->setIsInBounds(GEP.isInBounds());
2201           if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
2202             return Res;
2203           // Insert Res, and create an addrspacecast.
2204           // e.g.,
2205           // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
2206           // ->
2207           // %0 = GEP i8 addrspace(1)* X, ...
2208           // addrspacecast i8 addrspace(1)* %0 to i8*
2209           return new AddrSpaceCastInst(Builder.Insert(Res), GEPType);
2210         }
2211 
2212         if (auto *XATy = dyn_cast<ArrayType>(StrippedPtrEltTy)) {
2213           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
2214           if (CATy->getElementType() == XATy->getElementType()) {
2215             // -> GEP [10 x i8]* X, i32 0, ...
2216             // At this point, we know that the cast source type is a pointer
2217             // to an array of the same type as the destination pointer
2218             // array.  Because the array type is never stepped over (there
2219             // is a leading zero) we can fold the cast into this GEP.
2220             if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
2221               GEP.setSourceElementType(XATy);
2222               return replaceOperand(GEP, 0, StrippedPtr);
2223             }
2224             // Cannot replace the base pointer directly because StrippedPtr's
2225             // address space is different. Instead, create a new GEP followed by
2226             // an addrspacecast.
2227             // e.g.,
2228             // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
2229             //   i32 0, ...
2230             // ->
2231             // %0 = GEP [10 x i8] addrspace(1)* X, ...
2232             // addrspacecast i8 addrspace(1)* %0 to i8*
2233             SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
2234             Value *NewGEP =
2235                 GEP.isInBounds()
2236                     ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr,
2237                                                 Idx, GEP.getName())
2238                     : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Idx,
2239                                         GEP.getName());
2240             return new AddrSpaceCastInst(NewGEP, GEPType);
2241           }
2242         }
2243       }
2244     } else if (GEP.getNumOperands() == 2 && !IsGEPSrcEleScalable) {
2245       // Skip if GEP source element type is scalable. The type alloc size is
2246       // unknown at compile-time.
2247       // Transform things like: %t = getelementptr i32*
2248       // bitcast ([2 x i32]* %str to i32*), i32 %V into:  %t1 = getelementptr [2
2249       // x i32]* %str, i32 0, i32 %V; bitcast
2250       if (StrippedPtrEltTy->isArrayTy() &&
2251           DL.getTypeAllocSize(StrippedPtrEltTy->getArrayElementType()) ==
2252               DL.getTypeAllocSize(GEPEltType)) {
2253         Type *IdxType = DL.getIndexType(GEPType);
2254         Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
2255         Value *NewGEP =
2256             GEP.isInBounds()
2257                 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, Idx,
2258                                             GEP.getName())
2259                 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Idx,
2260                                     GEP.getName());
2261 
2262         // V and GEP are both pointer types --> BitCast
2263         return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, GEPType);
2264       }
2265 
2266       // Transform things like:
2267       // %V = mul i64 %N, 4
2268       // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
2269       // into:  %t1 = getelementptr i32* %arr, i32 %N; bitcast
2270       if (GEPEltType->isSized() && StrippedPtrEltTy->isSized()) {
2271         // Check that changing the type amounts to dividing the index by a scale
2272         // factor.
2273         uint64_t ResSize = DL.getTypeAllocSize(GEPEltType).getFixedSize();
2274         uint64_t SrcSize = DL.getTypeAllocSize(StrippedPtrEltTy).getFixedSize();
2275         if (ResSize && SrcSize % ResSize == 0) {
2276           Value *Idx = GEP.getOperand(1);
2277           unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
2278           uint64_t Scale = SrcSize / ResSize;
2279 
2280           // Earlier transforms ensure that the index has the right type
2281           // according to Data Layout, which considerably simplifies the
2282           // logic by eliminating implicit casts.
2283           assert(Idx->getType() == DL.getIndexType(GEPType) &&
2284                  "Index type does not match the Data Layout preferences");
2285 
2286           bool NSW;
2287           if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
2288             // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
2289             // If the multiplication NewIdx * Scale may overflow then the new
2290             // GEP may not be "inbounds".
2291             Value *NewGEP =
2292                 GEP.isInBounds() && NSW
2293                     ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr,
2294                                                 NewIdx, GEP.getName())
2295                     : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, NewIdx,
2296                                         GEP.getName());
2297 
2298             // The NewGEP must be pointer typed, so must the old one -> BitCast
2299             return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
2300                                                                  GEPType);
2301           }
2302         }
2303       }
2304 
2305       // Similarly, transform things like:
2306       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
2307       //   (where tmp = 8*tmp2) into:
2308       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
2309       if (GEPEltType->isSized() && StrippedPtrEltTy->isSized() &&
2310           StrippedPtrEltTy->isArrayTy()) {
2311         // Check that changing to the array element type amounts to dividing the
2312         // index by a scale factor.
2313         uint64_t ResSize = DL.getTypeAllocSize(GEPEltType).getFixedSize();
2314         uint64_t ArrayEltSize =
2315             DL.getTypeAllocSize(StrippedPtrEltTy->getArrayElementType())
2316                 .getFixedSize();
2317         if (ResSize && ArrayEltSize % ResSize == 0) {
2318           Value *Idx = GEP.getOperand(1);
2319           unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
2320           uint64_t Scale = ArrayEltSize / ResSize;
2321 
2322           // Earlier transforms ensure that the index has the right type
2323           // according to the Data Layout, which considerably simplifies
2324           // the logic by eliminating implicit casts.
2325           assert(Idx->getType() == DL.getIndexType(GEPType) &&
2326                  "Index type does not match the Data Layout preferences");
2327 
2328           bool NSW;
2329           if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
2330             // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
2331             // If the multiplication NewIdx * Scale may overflow then the new
2332             // GEP may not be "inbounds".
2333             Type *IndTy = DL.getIndexType(GEPType);
2334             Value *Off[2] = {Constant::getNullValue(IndTy), NewIdx};
2335 
2336             Value *NewGEP =
2337                 GEP.isInBounds() && NSW
2338                     ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr,
2339                                                 Off, GEP.getName())
2340                     : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Off,
2341                                         GEP.getName());
2342             // The NewGEP must be pointer typed, so must the old one -> BitCast
2343             return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
2344                                                                  GEPType);
2345           }
2346         }
2347       }
2348     }
2349   }
2350 
2351   // addrspacecast between types is canonicalized as a bitcast, then an
2352   // addrspacecast. To take advantage of the below bitcast + struct GEP, look
2353   // through the addrspacecast.
2354   Value *ASCStrippedPtrOp = PtrOp;
2355   if (auto *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
2356     //   X = bitcast A addrspace(1)* to B addrspace(1)*
2357     //   Y = addrspacecast A addrspace(1)* to B addrspace(2)*
2358     //   Z = gep Y, <...constant indices...>
2359     // Into an addrspacecasted GEP of the struct.
2360     if (auto *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
2361       ASCStrippedPtrOp = BC;
2362   }
2363 
2364   if (auto *BCI = dyn_cast<BitCastInst>(ASCStrippedPtrOp)) {
2365     Value *SrcOp = BCI->getOperand(0);
2366     PointerType *SrcType = cast<PointerType>(BCI->getSrcTy());
2367     Type *SrcEltType = SrcType->getElementType();
2368 
2369     // GEP directly using the source operand if this GEP is accessing an element
2370     // of a bitcasted pointer to vector or array of the same dimensions:
2371     // gep (bitcast <c x ty>* X to [c x ty]*), Y, Z --> gep X, Y, Z
2372     // gep (bitcast [c x ty]* X to <c x ty>*), Y, Z --> gep X, Y, Z
2373     auto areMatchingArrayAndVecTypes = [](Type *ArrTy, Type *VecTy,
2374                                           const DataLayout &DL) {
2375       auto *VecVTy = cast<FixedVectorType>(VecTy);
2376       return ArrTy->getArrayElementType() == VecVTy->getElementType() &&
2377              ArrTy->getArrayNumElements() == VecVTy->getNumElements() &&
2378              DL.getTypeAllocSize(ArrTy) == DL.getTypeAllocSize(VecTy);
2379     };
2380     if (GEP.getNumOperands() == 3 &&
2381         ((GEPEltType->isArrayTy() && SrcEltType->isVectorTy() &&
2382           areMatchingArrayAndVecTypes(GEPEltType, SrcEltType, DL)) ||
2383          (GEPEltType->isVectorTy() && SrcEltType->isArrayTy() &&
2384           areMatchingArrayAndVecTypes(SrcEltType, GEPEltType, DL)))) {
2385 
2386       // Create a new GEP here, as using `setOperand()` followed by
2387       // `setSourceElementType()` won't actually update the type of the
2388       // existing GEP Value. Causing issues if this Value is accessed when
2389       // constructing an AddrSpaceCastInst
2390       Value *NGEP =
2391           GEP.isInBounds()
2392               ? Builder.CreateInBoundsGEP(SrcEltType, SrcOp, {Ops[1], Ops[2]})
2393               : Builder.CreateGEP(SrcEltType, SrcOp, {Ops[1], Ops[2]});
2394       NGEP->takeName(&GEP);
2395 
2396       // Preserve GEP address space to satisfy users
2397       if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
2398         return new AddrSpaceCastInst(NGEP, GEPType);
2399 
2400       return replaceInstUsesWith(GEP, NGEP);
2401     }
2402 
2403     // See if we can simplify:
2404     //   X = bitcast A* to B*
2405     //   Y = gep X, <...constant indices...>
2406     // into a gep of the original struct. This is important for SROA and alias
2407     // analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
2408     unsigned OffsetBits = DL.getIndexTypeSizeInBits(GEPType);
2409     APInt Offset(OffsetBits, 0);
2410     if (!isa<BitCastInst>(SrcOp) && GEP.accumulateConstantOffset(DL, Offset)) {
2411       // If this GEP instruction doesn't move the pointer, just replace the GEP
2412       // with a bitcast of the real input to the dest type.
2413       if (!Offset) {
2414         // If the bitcast is of an allocation, and the allocation will be
2415         // converted to match the type of the cast, don't touch this.
2416         if (isa<AllocaInst>(SrcOp) || isAllocationFn(SrcOp, &TLI)) {
2417           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
2418           if (Instruction *I = visitBitCast(*BCI)) {
2419             if (I != BCI) {
2420               I->takeName(BCI);
2421               BCI->getParent()->getInstList().insert(BCI->getIterator(), I);
2422               replaceInstUsesWith(*BCI, I);
2423             }
2424             return &GEP;
2425           }
2426         }
2427 
2428         if (SrcType->getPointerAddressSpace() != GEP.getAddressSpace())
2429           return new AddrSpaceCastInst(SrcOp, GEPType);
2430         return new BitCastInst(SrcOp, GEPType);
2431       }
2432 
2433       // Otherwise, if the offset is non-zero, we need to find out if there is a
2434       // field at Offset in 'A's type.  If so, we can pull the cast through the
2435       // GEP.
2436       SmallVector<Value*, 8> NewIndices;
2437       if (FindElementAtOffset(SrcType, Offset.getSExtValue(), NewIndices)) {
2438         Value *NGEP =
2439             GEP.isInBounds()
2440                 ? Builder.CreateInBoundsGEP(SrcEltType, SrcOp, NewIndices)
2441                 : Builder.CreateGEP(SrcEltType, SrcOp, NewIndices);
2442 
2443         if (NGEP->getType() == GEPType)
2444           return replaceInstUsesWith(GEP, NGEP);
2445         NGEP->takeName(&GEP);
2446 
2447         if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
2448           return new AddrSpaceCastInst(NGEP, GEPType);
2449         return new BitCastInst(NGEP, GEPType);
2450       }
2451     }
2452   }
2453 
2454   if (!GEP.isInBounds()) {
2455     unsigned IdxWidth =
2456         DL.getIndexSizeInBits(PtrOp->getType()->getPointerAddressSpace());
2457     APInt BasePtrOffset(IdxWidth, 0);
2458     Value *UnderlyingPtrOp =
2459             PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL,
2460                                                              BasePtrOffset);
2461     if (auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) {
2462       if (GEP.accumulateConstantOffset(DL, BasePtrOffset) &&
2463           BasePtrOffset.isNonNegative()) {
2464         APInt AllocSize(
2465             IdxWidth,
2466             DL.getTypeAllocSize(AI->getAllocatedType()).getKnownMinSize());
2467         if (BasePtrOffset.ule(AllocSize)) {
2468           return GetElementPtrInst::CreateInBounds(
2469               GEP.getSourceElementType(), PtrOp, makeArrayRef(Ops).slice(1),
2470               GEP.getName());
2471         }
2472       }
2473     }
2474   }
2475 
2476   if (Instruction *R = foldSelectGEP(GEP, Builder))
2477     return R;
2478 
2479   return nullptr;
2480 }
2481 
2482 static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI,
2483                                          Instruction *AI) {
2484   if (isa<ConstantPointerNull>(V))
2485     return true;
2486   if (auto *LI = dyn_cast<LoadInst>(V))
2487     return isa<GlobalVariable>(LI->getPointerOperand());
2488   // Two distinct allocations will never be equal.
2489   // We rely on LookThroughBitCast in isAllocLikeFn being false, since looking
2490   // through bitcasts of V can cause
2491   // the result statement below to be true, even when AI and V (ex:
2492   // i8* ->i32* ->i8* of AI) are the same allocations.
2493   return isAllocLikeFn(V, TLI) && V != AI;
2494 }
2495 
2496 static bool isAllocSiteRemovable(Instruction *AI,
2497                                  SmallVectorImpl<WeakTrackingVH> &Users,
2498                                  const TargetLibraryInfo *TLI) {
2499   SmallVector<Instruction*, 4> Worklist;
2500   Worklist.push_back(AI);
2501 
2502   do {
2503     Instruction *PI = Worklist.pop_back_val();
2504     for (User *U : PI->users()) {
2505       Instruction *I = cast<Instruction>(U);
2506       switch (I->getOpcode()) {
2507       default:
2508         // Give up the moment we see something we can't handle.
2509         return false;
2510 
2511       case Instruction::AddrSpaceCast:
2512       case Instruction::BitCast:
2513       case Instruction::GetElementPtr:
2514         Users.emplace_back(I);
2515         Worklist.push_back(I);
2516         continue;
2517 
2518       case Instruction::ICmp: {
2519         ICmpInst *ICI = cast<ICmpInst>(I);
2520         // We can fold eq/ne comparisons with null to false/true, respectively.
2521         // We also fold comparisons in some conditions provided the alloc has
2522         // not escaped (see isNeverEqualToUnescapedAlloc).
2523         if (!ICI->isEquality())
2524           return false;
2525         unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0;
2526         if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI))
2527           return false;
2528         Users.emplace_back(I);
2529         continue;
2530       }
2531 
2532       case Instruction::Call:
2533         // Ignore no-op and store intrinsics.
2534         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2535           switch (II->getIntrinsicID()) {
2536           default:
2537             return false;
2538 
2539           case Intrinsic::memmove:
2540           case Intrinsic::memcpy:
2541           case Intrinsic::memset: {
2542             MemIntrinsic *MI = cast<MemIntrinsic>(II);
2543             if (MI->isVolatile() || MI->getRawDest() != PI)
2544               return false;
2545             LLVM_FALLTHROUGH;
2546           }
2547           case Intrinsic::assume:
2548           case Intrinsic::invariant_start:
2549           case Intrinsic::invariant_end:
2550           case Intrinsic::lifetime_start:
2551           case Intrinsic::lifetime_end:
2552           case Intrinsic::objectsize:
2553             Users.emplace_back(I);
2554             continue;
2555           }
2556         }
2557 
2558         if (isFreeCall(I, TLI)) {
2559           Users.emplace_back(I);
2560           continue;
2561         }
2562         return false;
2563 
2564       case Instruction::Store: {
2565         StoreInst *SI = cast<StoreInst>(I);
2566         if (SI->isVolatile() || SI->getPointerOperand() != PI)
2567           return false;
2568         Users.emplace_back(I);
2569         continue;
2570       }
2571       }
2572       llvm_unreachable("missing a return?");
2573     }
2574   } while (!Worklist.empty());
2575   return true;
2576 }
2577 
2578 Instruction *InstCombinerImpl::visitAllocSite(Instruction &MI) {
2579   // If we have a malloc call which is only used in any amount of comparisons to
2580   // null and free calls, delete the calls and replace the comparisons with true
2581   // or false as appropriate.
2582 
2583   // This is based on the principle that we can substitute our own allocation
2584   // function (which will never return null) rather than knowledge of the
2585   // specific function being called. In some sense this can change the permitted
2586   // outputs of a program (when we convert a malloc to an alloca, the fact that
2587   // the allocation is now on the stack is potentially visible, for example),
2588   // but we believe in a permissible manner.
2589   SmallVector<WeakTrackingVH, 64> Users;
2590 
2591   // If we are removing an alloca with a dbg.declare, insert dbg.value calls
2592   // before each store.
2593   TinyPtrVector<DbgVariableIntrinsic *> DIIs;
2594   std::unique_ptr<DIBuilder> DIB;
2595   if (isa<AllocaInst>(MI)) {
2596     DIIs = FindDbgAddrUses(&MI);
2597     DIB.reset(new DIBuilder(*MI.getModule(), /*AllowUnresolved=*/false));
2598   }
2599 
2600   if (isAllocSiteRemovable(&MI, Users, &TLI)) {
2601     for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2602       // Lowering all @llvm.objectsize calls first because they may
2603       // use a bitcast/GEP of the alloca we are removing.
2604       if (!Users[i])
2605        continue;
2606 
2607       Instruction *I = cast<Instruction>(&*Users[i]);
2608 
2609       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2610         if (II->getIntrinsicID() == Intrinsic::objectsize) {
2611           Value *Result =
2612               lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/true);
2613           replaceInstUsesWith(*I, Result);
2614           eraseInstFromFunction(*I);
2615           Users[i] = nullptr; // Skip examining in the next loop.
2616         }
2617       }
2618     }
2619     for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2620       if (!Users[i])
2621         continue;
2622 
2623       Instruction *I = cast<Instruction>(&*Users[i]);
2624 
2625       if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
2626         replaceInstUsesWith(*C,
2627                             ConstantInt::get(Type::getInt1Ty(C->getContext()),
2628                                              C->isFalseWhenEqual()));
2629       } else if (auto *SI = dyn_cast<StoreInst>(I)) {
2630         for (auto *DII : DIIs)
2631           ConvertDebugDeclareToDebugValue(DII, SI, *DIB);
2632       } else {
2633         // Casts, GEP, or anything else: we're about to delete this instruction,
2634         // so it can not have any valid uses.
2635         replaceInstUsesWith(*I, UndefValue::get(I->getType()));
2636       }
2637       eraseInstFromFunction(*I);
2638     }
2639 
2640     if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
2641       // Replace invoke with a NOP intrinsic to maintain the original CFG
2642       Module *M = II->getModule();
2643       Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
2644       InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
2645                          None, "", II->getParent());
2646     }
2647 
2648     for (auto *DII : DIIs)
2649       eraseInstFromFunction(*DII);
2650 
2651     return eraseInstFromFunction(MI);
2652   }
2653   return nullptr;
2654 }
2655 
2656 /// Move the call to free before a NULL test.
2657 ///
2658 /// Check if this free is accessed after its argument has been test
2659 /// against NULL (property 0).
2660 /// If yes, it is legal to move this call in its predecessor block.
2661 ///
2662 /// The move is performed only if the block containing the call to free
2663 /// will be removed, i.e.:
2664 /// 1. it has only one predecessor P, and P has two successors
2665 /// 2. it contains the call, noops, and an unconditional branch
2666 /// 3. its successor is the same as its predecessor's successor
2667 ///
2668 /// The profitability is out-of concern here and this function should
2669 /// be called only if the caller knows this transformation would be
2670 /// profitable (e.g., for code size).
2671 static Instruction *tryToMoveFreeBeforeNullTest(CallInst &FI,
2672                                                 const DataLayout &DL) {
2673   Value *Op = FI.getArgOperand(0);
2674   BasicBlock *FreeInstrBB = FI.getParent();
2675   BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
2676 
2677   // Validate part of constraint #1: Only one predecessor
2678   // FIXME: We can extend the number of predecessor, but in that case, we
2679   //        would duplicate the call to free in each predecessor and it may
2680   //        not be profitable even for code size.
2681   if (!PredBB)
2682     return nullptr;
2683 
2684   // Validate constraint #2: Does this block contains only the call to
2685   //                         free, noops, and an unconditional branch?
2686   BasicBlock *SuccBB;
2687   Instruction *FreeInstrBBTerminator = FreeInstrBB->getTerminator();
2688   if (!match(FreeInstrBBTerminator, m_UnconditionalBr(SuccBB)))
2689     return nullptr;
2690 
2691   // If there are only 2 instructions in the block, at this point,
2692   // this is the call to free and unconditional.
2693   // If there are more than 2 instructions, check that they are noops
2694   // i.e., they won't hurt the performance of the generated code.
2695   if (FreeInstrBB->size() != 2) {
2696     for (const Instruction &Inst : FreeInstrBB->instructionsWithoutDebug()) {
2697       if (&Inst == &FI || &Inst == FreeInstrBBTerminator)
2698         continue;
2699       auto *Cast = dyn_cast<CastInst>(&Inst);
2700       if (!Cast || !Cast->isNoopCast(DL))
2701         return nullptr;
2702     }
2703   }
2704   // Validate the rest of constraint #1 by matching on the pred branch.
2705   Instruction *TI = PredBB->getTerminator();
2706   BasicBlock *TrueBB, *FalseBB;
2707   ICmpInst::Predicate Pred;
2708   if (!match(TI, m_Br(m_ICmp(Pred,
2709                              m_CombineOr(m_Specific(Op),
2710                                          m_Specific(Op->stripPointerCasts())),
2711                              m_Zero()),
2712                       TrueBB, FalseBB)))
2713     return nullptr;
2714   if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2715     return nullptr;
2716 
2717   // Validate constraint #3: Ensure the null case just falls through.
2718   if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
2719     return nullptr;
2720   assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
2721          "Broken CFG: missing edge from predecessor to successor");
2722 
2723   // At this point, we know that everything in FreeInstrBB can be moved
2724   // before TI.
2725   for (BasicBlock::iterator It = FreeInstrBB->begin(), End = FreeInstrBB->end();
2726        It != End;) {
2727     Instruction &Instr = *It++;
2728     if (&Instr == FreeInstrBBTerminator)
2729       break;
2730     Instr.moveBefore(TI);
2731   }
2732   assert(FreeInstrBB->size() == 1 &&
2733          "Only the branch instruction should remain");
2734   return &FI;
2735 }
2736 
2737 Instruction *InstCombinerImpl::visitFree(CallInst &FI) {
2738   Value *Op = FI.getArgOperand(0);
2739 
2740   // free undef -> unreachable.
2741   if (isa<UndefValue>(Op)) {
2742     // Leave a marker since we can't modify the CFG here.
2743     CreateNonTerminatorUnreachable(&FI);
2744     return eraseInstFromFunction(FI);
2745   }
2746 
2747   // If we have 'free null' delete the instruction.  This can happen in stl code
2748   // when lots of inlining happens.
2749   if (isa<ConstantPointerNull>(Op))
2750     return eraseInstFromFunction(FI);
2751 
2752   // If we optimize for code size, try to move the call to free before the null
2753   // test so that simplify cfg can remove the empty block and dead code
2754   // elimination the branch. I.e., helps to turn something like:
2755   // if (foo) free(foo);
2756   // into
2757   // free(foo);
2758   //
2759   // Note that we can only do this for 'free' and not for any flavor of
2760   // 'operator delete'; there is no 'operator delete' symbol for which we are
2761   // permitted to invent a call, even if we're passing in a null pointer.
2762   if (MinimizeSize) {
2763     LibFunc Func;
2764     if (TLI.getLibFunc(FI, Func) && TLI.has(Func) && Func == LibFunc_free)
2765       if (Instruction *I = tryToMoveFreeBeforeNullTest(FI, DL))
2766         return I;
2767   }
2768 
2769   return nullptr;
2770 }
2771 
2772 static bool isMustTailCall(Value *V) {
2773   if (auto *CI = dyn_cast<CallInst>(V))
2774     return CI->isMustTailCall();
2775   return false;
2776 }
2777 
2778 Instruction *InstCombinerImpl::visitReturnInst(ReturnInst &RI) {
2779   if (RI.getNumOperands() == 0) // ret void
2780     return nullptr;
2781 
2782   Value *ResultOp = RI.getOperand(0);
2783   Type *VTy = ResultOp->getType();
2784   if (!VTy->isIntegerTy() || isa<Constant>(ResultOp))
2785     return nullptr;
2786 
2787   // Don't replace result of musttail calls.
2788   if (isMustTailCall(ResultOp))
2789     return nullptr;
2790 
2791   // There might be assume intrinsics dominating this return that completely
2792   // determine the value. If so, constant fold it.
2793   KnownBits Known = computeKnownBits(ResultOp, 0, &RI);
2794   if (Known.isConstant())
2795     return replaceOperand(RI, 0,
2796         Constant::getIntegerValue(VTy, Known.getConstant()));
2797 
2798   return nullptr;
2799 }
2800 
2801 Instruction *InstCombinerImpl::visitUnreachableInst(UnreachableInst &I) {
2802   // Try to remove the previous instruction if it must lead to unreachable.
2803   // This includes instructions like stores and "llvm.assume" that may not get
2804   // removed by simple dead code elimination.
2805   Instruction *Prev = I.getPrevNonDebugInstruction();
2806   if (Prev && !Prev->isEHPad() &&
2807       isGuaranteedToTransferExecutionToSuccessor(Prev)) {
2808     eraseInstFromFunction(*Prev);
2809     return &I;
2810   }
2811   return nullptr;
2812 }
2813 
2814 Instruction *InstCombinerImpl::visitUnconditionalBranchInst(BranchInst &BI) {
2815   assert(BI.isUnconditional() && "Only for unconditional branches.");
2816 
2817   // If this store is the second-to-last instruction in the basic block
2818   // (excluding debug info and bitcasts of pointers) and if the block ends with
2819   // an unconditional branch, try to move the store to the successor block.
2820 
2821   auto GetLastSinkableStore = [](BasicBlock::iterator BBI) {
2822     auto IsNoopInstrForStoreMerging = [](BasicBlock::iterator BBI) {
2823       return isa<DbgInfoIntrinsic>(BBI) ||
2824              (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy());
2825     };
2826 
2827     BasicBlock::iterator FirstInstr = BBI->getParent()->begin();
2828     do {
2829       if (BBI != FirstInstr)
2830         --BBI;
2831     } while (BBI != FirstInstr && IsNoopInstrForStoreMerging(BBI));
2832 
2833     return dyn_cast<StoreInst>(BBI);
2834   };
2835 
2836   if (StoreInst *SI = GetLastSinkableStore(BasicBlock::iterator(BI)))
2837     if (mergeStoreIntoSuccessor(*SI))
2838       return &BI;
2839 
2840   return nullptr;
2841 }
2842 
2843 Instruction *InstCombinerImpl::visitBranchInst(BranchInst &BI) {
2844   if (BI.isUnconditional())
2845     return visitUnconditionalBranchInst(BI);
2846 
2847   // Change br (not X), label True, label False to: br X, label False, True
2848   Value *X = nullptr;
2849   if (match(&BI, m_Br(m_Not(m_Value(X)), m_BasicBlock(), m_BasicBlock())) &&
2850       !isa<Constant>(X)) {
2851     // Swap Destinations and condition...
2852     BI.swapSuccessors();
2853     return replaceOperand(BI, 0, X);
2854   }
2855 
2856   // If the condition is irrelevant, remove the use so that other
2857   // transforms on the condition become more effective.
2858   if (!isa<ConstantInt>(BI.getCondition()) &&
2859       BI.getSuccessor(0) == BI.getSuccessor(1))
2860     return replaceOperand(
2861         BI, 0, ConstantInt::getFalse(BI.getCondition()->getType()));
2862 
2863   // Canonicalize, for example, fcmp_one -> fcmp_oeq.
2864   CmpInst::Predicate Pred;
2865   if (match(&BI, m_Br(m_OneUse(m_FCmp(Pred, m_Value(), m_Value())),
2866                       m_BasicBlock(), m_BasicBlock())) &&
2867       !isCanonicalPredicate(Pred)) {
2868     // Swap destinations and condition.
2869     CmpInst *Cond = cast<CmpInst>(BI.getCondition());
2870     Cond->setPredicate(CmpInst::getInversePredicate(Pred));
2871     BI.swapSuccessors();
2872     Worklist.push(Cond);
2873     return &BI;
2874   }
2875 
2876   return nullptr;
2877 }
2878 
2879 Instruction *InstCombinerImpl::visitSwitchInst(SwitchInst &SI) {
2880   Value *Cond = SI.getCondition();
2881   Value *Op0;
2882   ConstantInt *AddRHS;
2883   if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) {
2884     // Change 'switch (X+4) case 1:' into 'switch (X) case -3'.
2885     for (auto Case : SI.cases()) {
2886       Constant *NewCase = ConstantExpr::getSub(Case.getCaseValue(), AddRHS);
2887       assert(isa<ConstantInt>(NewCase) &&
2888              "Result of expression should be constant");
2889       Case.setValue(cast<ConstantInt>(NewCase));
2890     }
2891     return replaceOperand(SI, 0, Op0);
2892   }
2893 
2894   KnownBits Known = computeKnownBits(Cond, 0, &SI);
2895   unsigned LeadingKnownZeros = Known.countMinLeadingZeros();
2896   unsigned LeadingKnownOnes = Known.countMinLeadingOnes();
2897 
2898   // Compute the number of leading bits we can ignore.
2899   // TODO: A better way to determine this would use ComputeNumSignBits().
2900   for (auto &C : SI.cases()) {
2901     LeadingKnownZeros = std::min(
2902         LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2903     LeadingKnownOnes = std::min(
2904         LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2905   }
2906 
2907   unsigned NewWidth = Known.getBitWidth() - std::max(LeadingKnownZeros, LeadingKnownOnes);
2908 
2909   // Shrink the condition operand if the new type is smaller than the old type.
2910   // But do not shrink to a non-standard type, because backend can't generate
2911   // good code for that yet.
2912   // TODO: We can make it aggressive again after fixing PR39569.
2913   if (NewWidth > 0 && NewWidth < Known.getBitWidth() &&
2914       shouldChangeType(Known.getBitWidth(), NewWidth)) {
2915     IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2916     Builder.SetInsertPoint(&SI);
2917     Value *NewCond = Builder.CreateTrunc(Cond, Ty, "trunc");
2918 
2919     for (auto Case : SI.cases()) {
2920       APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth);
2921       Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));
2922     }
2923     return replaceOperand(SI, 0, NewCond);
2924   }
2925 
2926   return nullptr;
2927 }
2928 
2929 Instruction *InstCombinerImpl::visitExtractValueInst(ExtractValueInst &EV) {
2930   Value *Agg = EV.getAggregateOperand();
2931 
2932   if (!EV.hasIndices())
2933     return replaceInstUsesWith(EV, Agg);
2934 
2935   if (Value *V = SimplifyExtractValueInst(Agg, EV.getIndices(),
2936                                           SQ.getWithInstruction(&EV)))
2937     return replaceInstUsesWith(EV, V);
2938 
2939   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2940     // We're extracting from an insertvalue instruction, compare the indices
2941     const unsigned *exti, *exte, *insi, *inse;
2942     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2943          exte = EV.idx_end(), inse = IV->idx_end();
2944          exti != exte && insi != inse;
2945          ++exti, ++insi) {
2946       if (*insi != *exti)
2947         // The insert and extract both reference distinctly different elements.
2948         // This means the extract is not influenced by the insert, and we can
2949         // replace the aggregate operand of the extract with the aggregate
2950         // operand of the insert. i.e., replace
2951         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2952         // %E = extractvalue { i32, { i32 } } %I, 0
2953         // with
2954         // %E = extractvalue { i32, { i32 } } %A, 0
2955         return ExtractValueInst::Create(IV->getAggregateOperand(),
2956                                         EV.getIndices());
2957     }
2958     if (exti == exte && insi == inse)
2959       // Both iterators are at the end: Index lists are identical. Replace
2960       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2961       // %C = extractvalue { i32, { i32 } } %B, 1, 0
2962       // with "i32 42"
2963       return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
2964     if (exti == exte) {
2965       // The extract list is a prefix of the insert list. i.e. replace
2966       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2967       // %E = extractvalue { i32, { i32 } } %I, 1
2968       // with
2969       // %X = extractvalue { i32, { i32 } } %A, 1
2970       // %E = insertvalue { i32 } %X, i32 42, 0
2971       // by switching the order of the insert and extract (though the
2972       // insertvalue should be left in, since it may have other uses).
2973       Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(),
2974                                                 EV.getIndices());
2975       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
2976                                      makeArrayRef(insi, inse));
2977     }
2978     if (insi == inse)
2979       // The insert list is a prefix of the extract list
2980       // We can simply remove the common indices from the extract and make it
2981       // operate on the inserted value instead of the insertvalue result.
2982       // i.e., replace
2983       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2984       // %E = extractvalue { i32, { i32 } } %I, 1, 0
2985       // with
2986       // %E extractvalue { i32 } { i32 42 }, 0
2987       return ExtractValueInst::Create(IV->getInsertedValueOperand(),
2988                                       makeArrayRef(exti, exte));
2989   }
2990   if (WithOverflowInst *WO = dyn_cast<WithOverflowInst>(Agg)) {
2991     // We're extracting from an overflow intrinsic, see if we're the only user,
2992     // which allows us to simplify multiple result intrinsics to simpler
2993     // things that just get one value.
2994     if (WO->hasOneUse()) {
2995       // Check if we're grabbing only the result of a 'with overflow' intrinsic
2996       // and replace it with a traditional binary instruction.
2997       if (*EV.idx_begin() == 0) {
2998         Instruction::BinaryOps BinOp = WO->getBinaryOp();
2999         Value *LHS = WO->getLHS(), *RHS = WO->getRHS();
3000         replaceInstUsesWith(*WO, UndefValue::get(WO->getType()));
3001         eraseInstFromFunction(*WO);
3002         return BinaryOperator::Create(BinOp, LHS, RHS);
3003       }
3004 
3005       // If the normal result of the add is dead, and the RHS is a constant,
3006       // we can transform this into a range comparison.
3007       // overflow = uadd a, -4  -->  overflow = icmp ugt a, 3
3008       if (WO->getIntrinsicID() == Intrinsic::uadd_with_overflow)
3009         if (ConstantInt *CI = dyn_cast<ConstantInt>(WO->getRHS()))
3010           return new ICmpInst(ICmpInst::ICMP_UGT, WO->getLHS(),
3011                               ConstantExpr::getNot(CI));
3012     }
3013   }
3014   if (LoadInst *L = dyn_cast<LoadInst>(Agg))
3015     // If the (non-volatile) load only has one use, we can rewrite this to a
3016     // load from a GEP. This reduces the size of the load. If a load is used
3017     // only by extractvalue instructions then this either must have been
3018     // optimized before, or it is a struct with padding, in which case we
3019     // don't want to do the transformation as it loses padding knowledge.
3020     if (L->isSimple() && L->hasOneUse()) {
3021       // extractvalue has integer indices, getelementptr has Value*s. Convert.
3022       SmallVector<Value*, 4> Indices;
3023       // Prefix an i32 0 since we need the first element.
3024       Indices.push_back(Builder.getInt32(0));
3025       for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
3026             I != E; ++I)
3027         Indices.push_back(Builder.getInt32(*I));
3028 
3029       // We need to insert these at the location of the old load, not at that of
3030       // the extractvalue.
3031       Builder.SetInsertPoint(L);
3032       Value *GEP = Builder.CreateInBoundsGEP(L->getType(),
3033                                              L->getPointerOperand(), Indices);
3034       Instruction *NL = Builder.CreateLoad(EV.getType(), GEP);
3035       // Whatever aliasing information we had for the orignal load must also
3036       // hold for the smaller load, so propagate the annotations.
3037       AAMDNodes Nodes;
3038       L->getAAMetadata(Nodes);
3039       NL->setAAMetadata(Nodes);
3040       // Returning the load directly will cause the main loop to insert it in
3041       // the wrong spot, so use replaceInstUsesWith().
3042       return replaceInstUsesWith(EV, NL);
3043     }
3044   // We could simplify extracts from other values. Note that nested extracts may
3045   // already be simplified implicitly by the above: extract (extract (insert) )
3046   // will be translated into extract ( insert ( extract ) ) first and then just
3047   // the value inserted, if appropriate. Similarly for extracts from single-use
3048   // loads: extract (extract (load)) will be translated to extract (load (gep))
3049   // and if again single-use then via load (gep (gep)) to load (gep).
3050   // However, double extracts from e.g. function arguments or return values
3051   // aren't handled yet.
3052   return nullptr;
3053 }
3054 
3055 /// Return 'true' if the given typeinfo will match anything.
3056 static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
3057   switch (Personality) {
3058   case EHPersonality::GNU_C:
3059   case EHPersonality::GNU_C_SjLj:
3060   case EHPersonality::Rust:
3061     // The GCC C EH and Rust personality only exists to support cleanups, so
3062     // it's not clear what the semantics of catch clauses are.
3063     return false;
3064   case EHPersonality::Unknown:
3065     return false;
3066   case EHPersonality::GNU_Ada:
3067     // While __gnat_all_others_value will match any Ada exception, it doesn't
3068     // match foreign exceptions (or didn't, before gcc-4.7).
3069     return false;
3070   case EHPersonality::GNU_CXX:
3071   case EHPersonality::GNU_CXX_SjLj:
3072   case EHPersonality::GNU_ObjC:
3073   case EHPersonality::MSVC_X86SEH:
3074   case EHPersonality::MSVC_Win64SEH:
3075   case EHPersonality::MSVC_CXX:
3076   case EHPersonality::CoreCLR:
3077   case EHPersonality::Wasm_CXX:
3078     return TypeInfo->isNullValue();
3079   }
3080   llvm_unreachable("invalid enum");
3081 }
3082 
3083 static bool shorter_filter(const Value *LHS, const Value *RHS) {
3084   return
3085     cast<ArrayType>(LHS->getType())->getNumElements()
3086   <
3087     cast<ArrayType>(RHS->getType())->getNumElements();
3088 }
3089 
3090 Instruction *InstCombinerImpl::visitLandingPadInst(LandingPadInst &LI) {
3091   // The logic here should be correct for any real-world personality function.
3092   // However if that turns out not to be true, the offending logic can always
3093   // be conditioned on the personality function, like the catch-all logic is.
3094   EHPersonality Personality =
3095       classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
3096 
3097   // Simplify the list of clauses, eg by removing repeated catch clauses
3098   // (these are often created by inlining).
3099   bool MakeNewInstruction = false; // If true, recreate using the following:
3100   SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
3101   bool CleanupFlag = LI.isCleanup();   // - The new instruction is a cleanup.
3102 
3103   SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
3104   for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
3105     bool isLastClause = i + 1 == e;
3106     if (LI.isCatch(i)) {
3107       // A catch clause.
3108       Constant *CatchClause = LI.getClause(i);
3109       Constant *TypeInfo = CatchClause->stripPointerCasts();
3110 
3111       // If we already saw this clause, there is no point in having a second
3112       // copy of it.
3113       if (AlreadyCaught.insert(TypeInfo).second) {
3114         // This catch clause was not already seen.
3115         NewClauses.push_back(CatchClause);
3116       } else {
3117         // Repeated catch clause - drop the redundant copy.
3118         MakeNewInstruction = true;
3119       }
3120 
3121       // If this is a catch-all then there is no point in keeping any following
3122       // clauses or marking the landingpad as having a cleanup.
3123       if (isCatchAll(Personality, TypeInfo)) {
3124         if (!isLastClause)
3125           MakeNewInstruction = true;
3126         CleanupFlag = false;
3127         break;
3128       }
3129     } else {
3130       // A filter clause.  If any of the filter elements were already caught
3131       // then they can be dropped from the filter.  It is tempting to try to
3132       // exploit the filter further by saying that any typeinfo that does not
3133       // occur in the filter can't be caught later (and thus can be dropped).
3134       // However this would be wrong, since typeinfos can match without being
3135       // equal (for example if one represents a C++ class, and the other some
3136       // class derived from it).
3137       assert(LI.isFilter(i) && "Unsupported landingpad clause!");
3138       Constant *FilterClause = LI.getClause(i);
3139       ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
3140       unsigned NumTypeInfos = FilterType->getNumElements();
3141 
3142       // An empty filter catches everything, so there is no point in keeping any
3143       // following clauses or marking the landingpad as having a cleanup.  By
3144       // dealing with this case here the following code is made a bit simpler.
3145       if (!NumTypeInfos) {
3146         NewClauses.push_back(FilterClause);
3147         if (!isLastClause)
3148           MakeNewInstruction = true;
3149         CleanupFlag = false;
3150         break;
3151       }
3152 
3153       bool MakeNewFilter = false; // If true, make a new filter.
3154       SmallVector<Constant *, 16> NewFilterElts; // New elements.
3155       if (isa<ConstantAggregateZero>(FilterClause)) {
3156         // Not an empty filter - it contains at least one null typeinfo.
3157         assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
3158         Constant *TypeInfo =
3159           Constant::getNullValue(FilterType->getElementType());
3160         // If this typeinfo is a catch-all then the filter can never match.
3161         if (isCatchAll(Personality, TypeInfo)) {
3162           // Throw the filter away.
3163           MakeNewInstruction = true;
3164           continue;
3165         }
3166 
3167         // There is no point in having multiple copies of this typeinfo, so
3168         // discard all but the first copy if there is more than one.
3169         NewFilterElts.push_back(TypeInfo);
3170         if (NumTypeInfos > 1)
3171           MakeNewFilter = true;
3172       } else {
3173         ConstantArray *Filter = cast<ConstantArray>(FilterClause);
3174         SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
3175         NewFilterElts.reserve(NumTypeInfos);
3176 
3177         // Remove any filter elements that were already caught or that already
3178         // occurred in the filter.  While there, see if any of the elements are
3179         // catch-alls.  If so, the filter can be discarded.
3180         bool SawCatchAll = false;
3181         for (unsigned j = 0; j != NumTypeInfos; ++j) {
3182           Constant *Elt = Filter->getOperand(j);
3183           Constant *TypeInfo = Elt->stripPointerCasts();
3184           if (isCatchAll(Personality, TypeInfo)) {
3185             // This element is a catch-all.  Bail out, noting this fact.
3186             SawCatchAll = true;
3187             break;
3188           }
3189 
3190           // Even if we've seen a type in a catch clause, we don't want to
3191           // remove it from the filter.  An unexpected type handler may be
3192           // set up for a call site which throws an exception of the same
3193           // type caught.  In order for the exception thrown by the unexpected
3194           // handler to propagate correctly, the filter must be correctly
3195           // described for the call site.
3196           //
3197           // Example:
3198           //
3199           // void unexpected() { throw 1;}
3200           // void foo() throw (int) {
3201           //   std::set_unexpected(unexpected);
3202           //   try {
3203           //     throw 2.0;
3204           //   } catch (int i) {}
3205           // }
3206 
3207           // There is no point in having multiple copies of the same typeinfo in
3208           // a filter, so only add it if we didn't already.
3209           if (SeenInFilter.insert(TypeInfo).second)
3210             NewFilterElts.push_back(cast<Constant>(Elt));
3211         }
3212         // A filter containing a catch-all cannot match anything by definition.
3213         if (SawCatchAll) {
3214           // Throw the filter away.
3215           MakeNewInstruction = true;
3216           continue;
3217         }
3218 
3219         // If we dropped something from the filter, make a new one.
3220         if (NewFilterElts.size() < NumTypeInfos)
3221           MakeNewFilter = true;
3222       }
3223       if (MakeNewFilter) {
3224         FilterType = ArrayType::get(FilterType->getElementType(),
3225                                     NewFilterElts.size());
3226         FilterClause = ConstantArray::get(FilterType, NewFilterElts);
3227         MakeNewInstruction = true;
3228       }
3229 
3230       NewClauses.push_back(FilterClause);
3231 
3232       // If the new filter is empty then it will catch everything so there is
3233       // no point in keeping any following clauses or marking the landingpad
3234       // as having a cleanup.  The case of the original filter being empty was
3235       // already handled above.
3236       if (MakeNewFilter && !NewFilterElts.size()) {
3237         assert(MakeNewInstruction && "New filter but not a new instruction!");
3238         CleanupFlag = false;
3239         break;
3240       }
3241     }
3242   }
3243 
3244   // If several filters occur in a row then reorder them so that the shortest
3245   // filters come first (those with the smallest number of elements).  This is
3246   // advantageous because shorter filters are more likely to match, speeding up
3247   // unwinding, but mostly because it increases the effectiveness of the other
3248   // filter optimizations below.
3249   for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
3250     unsigned j;
3251     // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
3252     for (j = i; j != e; ++j)
3253       if (!isa<ArrayType>(NewClauses[j]->getType()))
3254         break;
3255 
3256     // Check whether the filters are already sorted by length.  We need to know
3257     // if sorting them is actually going to do anything so that we only make a
3258     // new landingpad instruction if it does.
3259     for (unsigned k = i; k + 1 < j; ++k)
3260       if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
3261         // Not sorted, so sort the filters now.  Doing an unstable sort would be
3262         // correct too but reordering filters pointlessly might confuse users.
3263         std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
3264                          shorter_filter);
3265         MakeNewInstruction = true;
3266         break;
3267       }
3268 
3269     // Look for the next batch of filters.
3270     i = j + 1;
3271   }
3272 
3273   // If typeinfos matched if and only if equal, then the elements of a filter L
3274   // that occurs later than a filter F could be replaced by the intersection of
3275   // the elements of F and L.  In reality two typeinfos can match without being
3276   // equal (for example if one represents a C++ class, and the other some class
3277   // derived from it) so it would be wrong to perform this transform in general.
3278   // However the transform is correct and useful if F is a subset of L.  In that
3279   // case L can be replaced by F, and thus removed altogether since repeating a
3280   // filter is pointless.  So here we look at all pairs of filters F and L where
3281   // L follows F in the list of clauses, and remove L if every element of F is
3282   // an element of L.  This can occur when inlining C++ functions with exception
3283   // specifications.
3284   for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
3285     // Examine each filter in turn.
3286     Value *Filter = NewClauses[i];
3287     ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
3288     if (!FTy)
3289       // Not a filter - skip it.
3290       continue;
3291     unsigned FElts = FTy->getNumElements();
3292     // Examine each filter following this one.  Doing this backwards means that
3293     // we don't have to worry about filters disappearing under us when removed.
3294     for (unsigned j = NewClauses.size() - 1; j != i; --j) {
3295       Value *LFilter = NewClauses[j];
3296       ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
3297       if (!LTy)
3298         // Not a filter - skip it.
3299         continue;
3300       // If Filter is a subset of LFilter, i.e. every element of Filter is also
3301       // an element of LFilter, then discard LFilter.
3302       SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
3303       // If Filter is empty then it is a subset of LFilter.
3304       if (!FElts) {
3305         // Discard LFilter.
3306         NewClauses.erase(J);
3307         MakeNewInstruction = true;
3308         // Move on to the next filter.
3309         continue;
3310       }
3311       unsigned LElts = LTy->getNumElements();
3312       // If Filter is longer than LFilter then it cannot be a subset of it.
3313       if (FElts > LElts)
3314         // Move on to the next filter.
3315         continue;
3316       // At this point we know that LFilter has at least one element.
3317       if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
3318         // Filter is a subset of LFilter iff Filter contains only zeros (as we
3319         // already know that Filter is not longer than LFilter).
3320         if (isa<ConstantAggregateZero>(Filter)) {
3321           assert(FElts <= LElts && "Should have handled this case earlier!");
3322           // Discard LFilter.
3323           NewClauses.erase(J);
3324           MakeNewInstruction = true;
3325         }
3326         // Move on to the next filter.
3327         continue;
3328       }
3329       ConstantArray *LArray = cast<ConstantArray>(LFilter);
3330       if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
3331         // Since Filter is non-empty and contains only zeros, it is a subset of
3332         // LFilter iff LFilter contains a zero.
3333         assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
3334         for (unsigned l = 0; l != LElts; ++l)
3335           if (LArray->getOperand(l)->isNullValue()) {
3336             // LFilter contains a zero - discard it.
3337             NewClauses.erase(J);
3338             MakeNewInstruction = true;
3339             break;
3340           }
3341         // Move on to the next filter.
3342         continue;
3343       }
3344       // At this point we know that both filters are ConstantArrays.  Loop over
3345       // operands to see whether every element of Filter is also an element of
3346       // LFilter.  Since filters tend to be short this is probably faster than
3347       // using a method that scales nicely.
3348       ConstantArray *FArray = cast<ConstantArray>(Filter);
3349       bool AllFound = true;
3350       for (unsigned f = 0; f != FElts; ++f) {
3351         Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
3352         AllFound = false;
3353         for (unsigned l = 0; l != LElts; ++l) {
3354           Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
3355           if (LTypeInfo == FTypeInfo) {
3356             AllFound = true;
3357             break;
3358           }
3359         }
3360         if (!AllFound)
3361           break;
3362       }
3363       if (AllFound) {
3364         // Discard LFilter.
3365         NewClauses.erase(J);
3366         MakeNewInstruction = true;
3367       }
3368       // Move on to the next filter.
3369     }
3370   }
3371 
3372   // If we changed any of the clauses, replace the old landingpad instruction
3373   // with a new one.
3374   if (MakeNewInstruction) {
3375     LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
3376                                                  NewClauses.size());
3377     for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
3378       NLI->addClause(NewClauses[i]);
3379     // A landing pad with no clauses must have the cleanup flag set.  It is
3380     // theoretically possible, though highly unlikely, that we eliminated all
3381     // clauses.  If so, force the cleanup flag to true.
3382     if (NewClauses.empty())
3383       CleanupFlag = true;
3384     NLI->setCleanup(CleanupFlag);
3385     return NLI;
3386   }
3387 
3388   // Even if none of the clauses changed, we may nonetheless have understood
3389   // that the cleanup flag is pointless.  Clear it if so.
3390   if (LI.isCleanup() != CleanupFlag) {
3391     assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
3392     LI.setCleanup(CleanupFlag);
3393     return &LI;
3394   }
3395 
3396   return nullptr;
3397 }
3398 
3399 Instruction *InstCombinerImpl::visitFreeze(FreezeInst &I) {
3400   Value *Op0 = I.getOperand(0);
3401 
3402   if (Value *V = SimplifyFreezeInst(Op0, SQ.getWithInstruction(&I)))
3403     return replaceInstUsesWith(I, V);
3404 
3405   // freeze (phi const, x) --> phi const, (freeze x)
3406   if (auto *PN = dyn_cast<PHINode>(Op0)) {
3407     if (Instruction *NV = foldOpIntoPhi(I, PN))
3408       return NV;
3409   }
3410 
3411   if (match(Op0, m_Undef())) {
3412     // If I is freeze(undef), see its uses and fold it to the best constant.
3413     // - or: pick -1
3414     // - select's condition: pick the value that leads to choosing a constant
3415     // - other ops: pick 0
3416     Constant *BestValue = nullptr;
3417     Constant *NullValue = Constant::getNullValue(I.getType());
3418     for (const auto *U : I.users()) {
3419       Constant *C = NullValue;
3420 
3421       if (match(U, m_Or(m_Value(), m_Value())))
3422         C = Constant::getAllOnesValue(I.getType());
3423       else if (const auto *SI = dyn_cast<SelectInst>(U)) {
3424         if (SI->getCondition() == &I) {
3425           APInt CondVal(1, isa<Constant>(SI->getFalseValue()) ? 0 : 1);
3426           C = Constant::getIntegerValue(I.getType(), CondVal);
3427         }
3428       }
3429 
3430       if (!BestValue)
3431         BestValue = C;
3432       else if (BestValue != C)
3433         BestValue = NullValue;
3434     }
3435 
3436     return replaceInstUsesWith(I, BestValue);
3437   }
3438 
3439   return nullptr;
3440 }
3441 
3442 /// Try to move the specified instruction from its current block into the
3443 /// beginning of DestBlock, which can only happen if it's safe to move the
3444 /// instruction past all of the instructions between it and the end of its
3445 /// block.
3446 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
3447   assert(I->getSingleUndroppableUse() && "Invariants didn't hold!");
3448   BasicBlock *SrcBlock = I->getParent();
3449 
3450   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
3451   if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() ||
3452       I->isTerminator())
3453     return false;
3454 
3455   // Do not sink static or dynamic alloca instructions. Static allocas must
3456   // remain in the entry block, and dynamic allocas must not be sunk in between
3457   // a stacksave / stackrestore pair, which would incorrectly shorten its
3458   // lifetime.
3459   if (isa<AllocaInst>(I))
3460     return false;
3461 
3462   // Do not sink into catchswitch blocks.
3463   if (isa<CatchSwitchInst>(DestBlock->getTerminator()))
3464     return false;
3465 
3466   // Do not sink convergent call instructions.
3467   if (auto *CI = dyn_cast<CallInst>(I)) {
3468     if (CI->isConvergent())
3469       return false;
3470   }
3471   // We can only sink load instructions if there is nothing between the load and
3472   // the end of block that could change the value.
3473   if (I->mayReadFromMemory()) {
3474     // We don't want to do any sophisticated alias analysis, so we only check
3475     // the instructions after I in I's parent block if we try to sink to its
3476     // successor block.
3477     if (DestBlock->getUniquePredecessor() != I->getParent())
3478       return false;
3479     for (BasicBlock::iterator Scan = I->getIterator(),
3480                               E = I->getParent()->end();
3481          Scan != E; ++Scan)
3482       if (Scan->mayWriteToMemory())
3483         return false;
3484   }
3485 
3486   I->dropDroppableUses([DestBlock](const Use *U) {
3487     if (auto *I = dyn_cast<Instruction>(U->getUser()))
3488       return I->getParent() != DestBlock;
3489     return true;
3490   });
3491   /// FIXME: We could remove droppable uses that are not dominated by
3492   /// the new position.
3493 
3494   BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
3495   I->moveBefore(&*InsertPos);
3496   ++NumSunkInst;
3497 
3498   // Also sink all related debug uses from the source basic block. Otherwise we
3499   // get debug use before the def. Attempt to salvage debug uses first, to
3500   // maximise the range variables have location for. If we cannot salvage, then
3501   // mark the location undef: we know it was supposed to receive a new location
3502   // here, but that computation has been sunk.
3503   SmallVector<DbgVariableIntrinsic *, 2> DbgUsers;
3504   findDbgUsers(DbgUsers, I);
3505 
3506   // Update the arguments of a dbg.declare instruction, so that it
3507   // does not point into a sunk instruction.
3508   auto updateDbgDeclare = [&I](DbgVariableIntrinsic *DII) {
3509     if (!isa<DbgDeclareInst>(DII))
3510       return false;
3511 
3512     if (isa<CastInst>(I))
3513       DII->setOperand(
3514           0, MetadataAsValue::get(I->getContext(),
3515                                   ValueAsMetadata::get(I->getOperand(0))));
3516     return true;
3517   };
3518 
3519   SmallVector<DbgVariableIntrinsic *, 2> DIIClones;
3520   for (auto User : DbgUsers) {
3521     // A dbg.declare instruction should not be cloned, since there can only be
3522     // one per variable fragment. It should be left in the original place
3523     // because the sunk instruction is not an alloca (otherwise we could not be
3524     // here).
3525     if (User->getParent() != SrcBlock || updateDbgDeclare(User))
3526       continue;
3527 
3528     DIIClones.emplace_back(cast<DbgVariableIntrinsic>(User->clone()));
3529     LLVM_DEBUG(dbgs() << "CLONE: " << *DIIClones.back() << '\n');
3530   }
3531 
3532   // Perform salvaging without the clones, then sink the clones.
3533   if (!DIIClones.empty()) {
3534     salvageDebugInfoForDbgValues(*I, DbgUsers);
3535     for (auto &DIIClone : DIIClones) {
3536       DIIClone->insertBefore(&*InsertPos);
3537       LLVM_DEBUG(dbgs() << "SINK: " << *DIIClone << '\n');
3538     }
3539   }
3540 
3541   return true;
3542 }
3543 
3544 bool InstCombinerImpl::run() {
3545   while (!Worklist.isEmpty()) {
3546     // Walk deferred instructions in reverse order, and push them to the
3547     // worklist, which means they'll end up popped from the worklist in-order.
3548     while (Instruction *I = Worklist.popDeferred()) {
3549       // Check to see if we can DCE the instruction. We do this already here to
3550       // reduce the number of uses and thus allow other folds to trigger.
3551       // Note that eraseInstFromFunction() may push additional instructions on
3552       // the deferred worklist, so this will DCE whole instruction chains.
3553       if (isInstructionTriviallyDead(I, &TLI)) {
3554         eraseInstFromFunction(*I);
3555         ++NumDeadInst;
3556         continue;
3557       }
3558 
3559       Worklist.push(I);
3560     }
3561 
3562     Instruction *I = Worklist.removeOne();
3563     if (I == nullptr) continue;  // skip null values.
3564 
3565     // Check to see if we can DCE the instruction.
3566     if (isInstructionTriviallyDead(I, &TLI)) {
3567       eraseInstFromFunction(*I);
3568       ++NumDeadInst;
3569       continue;
3570     }
3571 
3572     if (!DebugCounter::shouldExecute(VisitCounter))
3573       continue;
3574 
3575     // Instruction isn't dead, see if we can constant propagate it.
3576     if (!I->use_empty() &&
3577         (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) {
3578       if (Constant *C = ConstantFoldInstruction(I, DL, &TLI)) {
3579         LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I
3580                           << '\n');
3581 
3582         // Add operands to the worklist.
3583         replaceInstUsesWith(*I, C);
3584         ++NumConstProp;
3585         if (isInstructionTriviallyDead(I, &TLI))
3586           eraseInstFromFunction(*I);
3587         MadeIRChange = true;
3588         continue;
3589       }
3590     }
3591 
3592     // See if we can trivially sink this instruction to its user if we can
3593     // prove that the successor is not executed more frequently than our block.
3594     if (EnableCodeSinking)
3595       if (Use *SingleUse = I->getSingleUndroppableUse()) {
3596         BasicBlock *BB = I->getParent();
3597         Instruction *UserInst = cast<Instruction>(SingleUse->getUser());
3598         BasicBlock *UserParent;
3599 
3600         // Get the block the use occurs in.
3601         if (PHINode *PN = dyn_cast<PHINode>(UserInst))
3602           UserParent = PN->getIncomingBlock(*SingleUse);
3603         else
3604           UserParent = UserInst->getParent();
3605 
3606         if (UserParent != BB) {
3607           // See if the user is one of our successors that has only one
3608           // predecessor, so that we don't have to split the critical edge.
3609           bool ShouldSink = UserParent->getUniquePredecessor() == BB;
3610           // Another option where we can sink is a block that ends with a
3611           // terminator that does not pass control to other block (such as
3612           // return or unreachable). In this case:
3613           //   - I dominates the User (by SSA form);
3614           //   - the User will be executed at most once.
3615           // So sinking I down to User is always profitable or neutral.
3616           if (!ShouldSink) {
3617             auto *Term = UserParent->getTerminator();
3618             ShouldSink = isa<ReturnInst>(Term) || isa<UnreachableInst>(Term);
3619           }
3620           if (ShouldSink) {
3621             assert(DT.dominates(BB, UserParent) &&
3622                    "Dominance relation broken?");
3623             // Okay, the CFG is simple enough, try to sink this instruction.
3624             if (TryToSinkInstruction(I, UserParent)) {
3625               LLVM_DEBUG(dbgs() << "IC: Sink: " << *I << '\n');
3626               MadeIRChange = true;
3627               // We'll add uses of the sunk instruction below, but since sinking
3628               // can expose opportunities for it's *operands* add them to the
3629               // worklist
3630               for (Use &U : I->operands())
3631                 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
3632                   Worklist.push(OpI);
3633             }
3634           }
3635         }
3636       }
3637 
3638     // Now that we have an instruction, try combining it to simplify it.
3639     Builder.SetInsertPoint(I);
3640     Builder.SetCurrentDebugLocation(I->getDebugLoc());
3641 
3642 #ifndef NDEBUG
3643     std::string OrigI;
3644 #endif
3645     LLVM_DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
3646     LLVM_DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
3647 
3648     if (Instruction *Result = visit(*I)) {
3649       ++NumCombined;
3650       // Should we replace the old instruction with a new one?
3651       if (Result != I) {
3652         LLVM_DEBUG(dbgs() << "IC: Old = " << *I << '\n'
3653                           << "    New = " << *Result << '\n');
3654 
3655         if (I->getDebugLoc())
3656           Result->setDebugLoc(I->getDebugLoc());
3657         // Everything uses the new instruction now.
3658         I->replaceAllUsesWith(Result);
3659 
3660         // Move the name to the new instruction first.
3661         Result->takeName(I);
3662 
3663         // Insert the new instruction into the basic block...
3664         BasicBlock *InstParent = I->getParent();
3665         BasicBlock::iterator InsertPos = I->getIterator();
3666 
3667         // Are we replace a PHI with something that isn't a PHI, or vice versa?
3668         if (isa<PHINode>(Result) != isa<PHINode>(I)) {
3669           // We need to fix up the insertion point.
3670           if (isa<PHINode>(I)) // PHI -> Non-PHI
3671             InsertPos = InstParent->getFirstInsertionPt();
3672           else // Non-PHI -> PHI
3673             InsertPos = InstParent->getFirstNonPHI()->getIterator();
3674         }
3675 
3676         InstParent->getInstList().insert(InsertPos, Result);
3677 
3678         // Push the new instruction and any users onto the worklist.
3679         Worklist.pushUsersToWorkList(*Result);
3680         Worklist.push(Result);
3681 
3682         eraseInstFromFunction(*I);
3683       } else {
3684         LLVM_DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
3685                           << "    New = " << *I << '\n');
3686 
3687         // If the instruction was modified, it's possible that it is now dead.
3688         // if so, remove it.
3689         if (isInstructionTriviallyDead(I, &TLI)) {
3690           eraseInstFromFunction(*I);
3691         } else {
3692           Worklist.pushUsersToWorkList(*I);
3693           Worklist.push(I);
3694         }
3695       }
3696       MadeIRChange = true;
3697     }
3698   }
3699 
3700   Worklist.zap();
3701   return MadeIRChange;
3702 }
3703 
3704 /// Populate the IC worklist from a function, by walking it in depth-first
3705 /// order and adding all reachable code to the worklist.
3706 ///
3707 /// This has a couple of tricks to make the code faster and more powerful.  In
3708 /// particular, we constant fold and DCE instructions as we go, to avoid adding
3709 /// them to the worklist (this significantly speeds up instcombine on code where
3710 /// many instructions are dead or constant).  Additionally, if we find a branch
3711 /// whose condition is a known constant, we only visit the reachable successors.
3712 static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
3713                                           const TargetLibraryInfo *TLI,
3714                                           InstCombineWorklist &ICWorklist) {
3715   bool MadeIRChange = false;
3716   SmallPtrSet<BasicBlock *, 32> Visited;
3717   SmallVector<BasicBlock*, 256> Worklist;
3718   Worklist.push_back(&F.front());
3719 
3720   SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
3721   DenseMap<Constant *, Constant *> FoldedConstants;
3722 
3723   do {
3724     BasicBlock *BB = Worklist.pop_back_val();
3725 
3726     // We have now visited this block!  If we've already been here, ignore it.
3727     if (!Visited.insert(BB).second)
3728       continue;
3729 
3730     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
3731       Instruction *Inst = &*BBI++;
3732 
3733       // ConstantProp instruction if trivially constant.
3734       if (!Inst->use_empty() &&
3735           (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0))))
3736         if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
3737           LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *Inst
3738                             << '\n');
3739           Inst->replaceAllUsesWith(C);
3740           ++NumConstProp;
3741           if (isInstructionTriviallyDead(Inst, TLI))
3742             Inst->eraseFromParent();
3743           MadeIRChange = true;
3744           continue;
3745         }
3746 
3747       // See if we can constant fold its operands.
3748       for (Use &U : Inst->operands()) {
3749         if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U))
3750           continue;
3751 
3752         auto *C = cast<Constant>(U);
3753         Constant *&FoldRes = FoldedConstants[C];
3754         if (!FoldRes)
3755           FoldRes = ConstantFoldConstant(C, DL, TLI);
3756 
3757         if (FoldRes != C) {
3758           LLVM_DEBUG(dbgs() << "IC: ConstFold operand of: " << *Inst
3759                             << "\n    Old = " << *C
3760                             << "\n    New = " << *FoldRes << '\n');
3761           U = FoldRes;
3762           MadeIRChange = true;
3763         }
3764       }
3765 
3766       // Skip processing debug intrinsics in InstCombine. Processing these call instructions
3767       // consumes non-trivial amount of time and provides no value for the optimization.
3768       if (!isa<DbgInfoIntrinsic>(Inst))
3769         InstrsForInstCombineWorklist.push_back(Inst);
3770     }
3771 
3772     // Recursively visit successors.  If this is a branch or switch on a
3773     // constant, only visit the reachable successor.
3774     Instruction *TI = BB->getTerminator();
3775     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3776       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
3777         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
3778         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
3779         Worklist.push_back(ReachableBB);
3780         continue;
3781       }
3782     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3783       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
3784         Worklist.push_back(SI->findCaseValue(Cond)->getCaseSuccessor());
3785         continue;
3786       }
3787     }
3788 
3789     for (BasicBlock *SuccBB : successors(TI))
3790       Worklist.push_back(SuccBB);
3791   } while (!Worklist.empty());
3792 
3793   // Remove instructions inside unreachable blocks. This prevents the
3794   // instcombine code from having to deal with some bad special cases, and
3795   // reduces use counts of instructions.
3796   for (BasicBlock &BB : F) {
3797     if (Visited.count(&BB))
3798       continue;
3799 
3800     unsigned NumDeadInstInBB;
3801     unsigned NumDeadDbgInstInBB;
3802     std::tie(NumDeadInstInBB, NumDeadDbgInstInBB) =
3803         removeAllNonTerminatorAndEHPadInstructions(&BB);
3804 
3805     MadeIRChange |= NumDeadInstInBB + NumDeadDbgInstInBB > 0;
3806     NumDeadInst += NumDeadInstInBB;
3807   }
3808 
3809   // Once we've found all of the instructions to add to instcombine's worklist,
3810   // add them in reverse order.  This way instcombine will visit from the top
3811   // of the function down.  This jives well with the way that it adds all uses
3812   // of instructions to the worklist after doing a transformation, thus avoiding
3813   // some N^2 behavior in pathological cases.
3814   ICWorklist.reserve(InstrsForInstCombineWorklist.size());
3815   for (Instruction *Inst : reverse(InstrsForInstCombineWorklist)) {
3816     // DCE instruction if trivially dead. As we iterate in reverse program
3817     // order here, we will clean up whole chains of dead instructions.
3818     if (isInstructionTriviallyDead(Inst, TLI)) {
3819       ++NumDeadInst;
3820       LLVM_DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
3821       salvageDebugInfo(*Inst);
3822       Inst->eraseFromParent();
3823       MadeIRChange = true;
3824       continue;
3825     }
3826 
3827     ICWorklist.push(Inst);
3828   }
3829 
3830   return MadeIRChange;
3831 }
3832 
3833 static bool combineInstructionsOverFunction(
3834     Function &F, InstCombineWorklist &Worklist, AliasAnalysis *AA,
3835     AssumptionCache &AC, TargetLibraryInfo &TLI, TargetTransformInfo &TTI,
3836     DominatorTree &DT, OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI,
3837     ProfileSummaryInfo *PSI, unsigned MaxIterations, LoopInfo *LI) {
3838   auto &DL = F.getParent()->getDataLayout();
3839   MaxIterations = std::min(MaxIterations, LimitMaxIterations.getValue());
3840 
3841   /// Builder - This is an IRBuilder that automatically inserts new
3842   /// instructions into the worklist when they are created.
3843   IRBuilder<TargetFolder, IRBuilderCallbackInserter> Builder(
3844       F.getContext(), TargetFolder(DL),
3845       IRBuilderCallbackInserter([&Worklist, &AC](Instruction *I) {
3846         Worklist.add(I);
3847         if (match(I, m_Intrinsic<Intrinsic::assume>()))
3848           AC.registerAssumption(cast<CallInst>(I));
3849       }));
3850 
3851   // Lower dbg.declare intrinsics otherwise their value may be clobbered
3852   // by instcombiner.
3853   bool MadeIRChange = false;
3854   if (ShouldLowerDbgDeclare)
3855     MadeIRChange = LowerDbgDeclare(F);
3856 
3857   // Iterate while there is work to do.
3858   unsigned Iteration = 0;
3859   while (true) {
3860     ++NumWorklistIterations;
3861     ++Iteration;
3862 
3863     if (Iteration > InfiniteLoopDetectionThreshold) {
3864       report_fatal_error(
3865           "Instruction Combining seems stuck in an infinite loop after " +
3866           Twine(InfiniteLoopDetectionThreshold) + " iterations.");
3867     }
3868 
3869     if (Iteration > MaxIterations) {
3870       LLVM_DEBUG(dbgs() << "\n\n[IC] Iteration limit #" << MaxIterations
3871                         << " on " << F.getName()
3872                         << " reached; stopping before reaching a fixpoint\n");
3873       break;
3874     }
3875 
3876     LLVM_DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
3877                       << F.getName() << "\n");
3878 
3879     MadeIRChange |= prepareICWorklistFromFunction(F, DL, &TLI, Worklist);
3880 
3881     InstCombinerImpl IC(Worklist, Builder, F.hasMinSize(), AA, AC, TLI, TTI, DT,
3882                         ORE, BFI, PSI, DL, LI);
3883     IC.MaxArraySizeForCombine = MaxArraySize;
3884 
3885     if (!IC.run())
3886       break;
3887 
3888     MadeIRChange = true;
3889   }
3890 
3891   return MadeIRChange;
3892 }
3893 
3894 InstCombinePass::InstCombinePass() : MaxIterations(LimitMaxIterations) {}
3895 
3896 InstCombinePass::InstCombinePass(unsigned MaxIterations)
3897     : MaxIterations(MaxIterations) {}
3898 
3899 PreservedAnalyses InstCombinePass::run(Function &F,
3900                                        FunctionAnalysisManager &AM) {
3901   auto &AC = AM.getResult<AssumptionAnalysis>(F);
3902   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3903   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
3904   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
3905   auto &TTI = AM.getResult<TargetIRAnalysis>(F);
3906 
3907   auto *LI = AM.getCachedResult<LoopAnalysis>(F);
3908 
3909   auto *AA = &AM.getResult<AAManager>(F);
3910   auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
3911   ProfileSummaryInfo *PSI =
3912       MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
3913   auto *BFI = (PSI && PSI->hasProfileSummary()) ?
3914       &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr;
3915 
3916   if (!combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, TTI, DT, ORE,
3917                                        BFI, PSI, MaxIterations, LI))
3918     // No changes, all analyses are preserved.
3919     return PreservedAnalyses::all();
3920 
3921   // Mark all the analyses that instcombine updates as preserved.
3922   PreservedAnalyses PA;
3923   PA.preserveSet<CFGAnalyses>();
3924   PA.preserve<AAManager>();
3925   PA.preserve<BasicAA>();
3926   PA.preserve<GlobalsAA>();
3927   return PA;
3928 }
3929 
3930 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
3931   AU.setPreservesCFG();
3932   AU.addRequired<AAResultsWrapperPass>();
3933   AU.addRequired<AssumptionCacheTracker>();
3934   AU.addRequired<TargetLibraryInfoWrapperPass>();
3935   AU.addRequired<TargetTransformInfoWrapperPass>();
3936   AU.addRequired<DominatorTreeWrapperPass>();
3937   AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
3938   AU.addPreserved<DominatorTreeWrapperPass>();
3939   AU.addPreserved<AAResultsWrapperPass>();
3940   AU.addPreserved<BasicAAWrapperPass>();
3941   AU.addPreserved<GlobalsAAWrapperPass>();
3942   AU.addRequired<ProfileSummaryInfoWrapperPass>();
3943   LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);
3944 }
3945 
3946 bool InstructionCombiningPass::runOnFunction(Function &F) {
3947   if (skipFunction(F))
3948     return false;
3949 
3950   // Required analyses.
3951   auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3952   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3953   auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
3954   auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
3955   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3956   auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
3957 
3958   // Optional analyses.
3959   auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3960   auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
3961   ProfileSummaryInfo *PSI =
3962       &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
3963   BlockFrequencyInfo *BFI =
3964       (PSI && PSI->hasProfileSummary()) ?
3965       &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI() :
3966       nullptr;
3967 
3968   return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, TTI, DT, ORE,
3969                                          BFI, PSI, MaxIterations, LI);
3970 }
3971 
3972 char InstructionCombiningPass::ID = 0;
3973 
3974 InstructionCombiningPass::InstructionCombiningPass()
3975     : FunctionPass(ID), MaxIterations(InstCombineDefaultMaxIterations) {
3976   initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry());
3977 }
3978 
3979 InstructionCombiningPass::InstructionCombiningPass(unsigned MaxIterations)
3980     : FunctionPass(ID), MaxIterations(MaxIterations) {
3981   initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry());
3982 }
3983 
3984 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
3985                       "Combine redundant instructions", false, false)
3986 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3987 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3988 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
3989 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3990 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3991 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3992 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
3993 INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass)
3994 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
3995 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
3996                     "Combine redundant instructions", false, false)
3997 
3998 // Initialization Routines
3999 void llvm::initializeInstCombine(PassRegistry &Registry) {
4000   initializeInstructionCombiningPassPass(Registry);
4001 }
4002 
4003 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
4004   initializeInstructionCombiningPassPass(*unwrap(R));
4005 }
4006 
4007 FunctionPass *llvm::createInstructionCombiningPass() {
4008   return new InstructionCombiningPass();
4009 }
4010 
4011 FunctionPass *llvm::createInstructionCombiningPass(unsigned MaxIterations) {
4012   return new InstructionCombiningPass(MaxIterations);
4013 }
4014 
4015 void LLVMAddInstructionCombiningPass(LLVMPassManagerRef PM) {
4016   unwrap(PM)->add(createInstructionCombiningPass());
4017 }
4018