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