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