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