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