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