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