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