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