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