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 = isa<Constant>(LHS) ? C2 : Shuffle->getOperand(0);
1329       Value *NewRHS = isa<Constant>(LHS) ? Shuffle->getOperand(0) : C2;
1330       Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
1331       return Builder->CreateShuffleVector(NewBO,
1332           UndefValue::get(Inst.getType()), Shuffle->getMask());
1333     }
1334   }
1335 
1336   return nullptr;
1337 }
1338 
1339 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1340   SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1341 
1342   if (Value *V = SimplifyGEPInst(Ops, DL, TLI, DT, AC))
1343     return ReplaceInstUsesWith(GEP, V);
1344 
1345   Value *PtrOp = GEP.getOperand(0);
1346 
1347   // Eliminate unneeded casts for indices, and replace indices which displace
1348   // by multiples of a zero size type with zero.
1349   bool MadeChange = false;
1350   Type *IntPtrTy =
1351     DL.getIntPtrType(GEP.getPointerOperandType()->getScalarType());
1352 
1353   gep_type_iterator GTI = gep_type_begin(GEP);
1354   for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
1355        ++I, ++GTI) {
1356     // Skip indices into struct types.
1357     SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
1358     if (!SeqTy)
1359       continue;
1360 
1361     // Index type should have the same width as IntPtr
1362     Type *IndexTy = (*I)->getType();
1363     Type *NewIndexType = IndexTy->isVectorTy() ?
1364       VectorType::get(IntPtrTy, IndexTy->getVectorNumElements()) : IntPtrTy;
1365 
1366     // If the element type has zero size then any index over it is equivalent
1367     // to an index of zero, so replace it with zero if it is not zero already.
1368     if (SeqTy->getElementType()->isSized() &&
1369         DL.getTypeAllocSize(SeqTy->getElementType()) == 0)
1370       if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1371         *I = Constant::getNullValue(NewIndexType);
1372         MadeChange = true;
1373       }
1374 
1375     if (IndexTy != NewIndexType) {
1376       // If we are using a wider index than needed for this platform, shrink
1377       // it to what we need.  If narrower, sign-extend it to what we need.
1378       // This explicit cast can make subsequent optimizations more obvious.
1379       *I = Builder->CreateIntCast(*I, NewIndexType, true);
1380       MadeChange = true;
1381     }
1382   }
1383   if (MadeChange)
1384     return &GEP;
1385 
1386   // Check to see if the inputs to the PHI node are getelementptr instructions.
1387   if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1388     GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1389     if (!Op1)
1390       return nullptr;
1391 
1392     // Don't fold a GEP into itself through a PHI node. This can only happen
1393     // through the back-edge of a loop. Folding a GEP into itself means that
1394     // the value of the previous iteration needs to be stored in the meantime,
1395     // thus requiring an additional register variable to be live, but not
1396     // actually achieving anything (the GEP still needs to be executed once per
1397     // loop iteration).
1398     if (Op1 == &GEP)
1399       return nullptr;
1400 
1401     signed DI = -1;
1402 
1403     for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1404       GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
1405       if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1406         return nullptr;
1407 
1408       // As for Op1 above, don't try to fold a GEP into itself.
1409       if (Op2 == &GEP)
1410         return nullptr;
1411 
1412       // Keep track of the type as we walk the GEP.
1413       Type *CurTy = Op1->getOperand(0)->getType()->getScalarType();
1414 
1415       for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1416         if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1417           return nullptr;
1418 
1419         if (Op1->getOperand(J) != Op2->getOperand(J)) {
1420           if (DI == -1) {
1421             // We have not seen any differences yet in the GEPs feeding the
1422             // PHI yet, so we record this one if it is allowed to be a
1423             // variable.
1424 
1425             // The first two arguments can vary for any GEP, the rest have to be
1426             // static for struct slots
1427             if (J > 1 && CurTy->isStructTy())
1428               return nullptr;
1429 
1430             DI = J;
1431           } else {
1432             // The GEP is different by more than one input. While this could be
1433             // extended to support GEPs that vary by more than one variable it
1434             // doesn't make sense since it greatly increases the complexity and
1435             // would result in an R+R+R addressing mode which no backend
1436             // directly supports and would need to be broken into several
1437             // simpler instructions anyway.
1438             return nullptr;
1439           }
1440         }
1441 
1442         // Sink down a layer of the type for the next iteration.
1443         if (J > 0) {
1444           if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
1445             CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1446           } else {
1447             CurTy = nullptr;
1448           }
1449         }
1450       }
1451     }
1452 
1453     // If not all GEPs are identical we'll have to create a new PHI node.
1454     // Check that the old PHI node has only one use so that it will get
1455     // removed.
1456     if (DI != -1 && !PN->hasOneUse())
1457       return nullptr;
1458 
1459     GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
1460     if (DI == -1) {
1461       // All the GEPs feeding the PHI are identical. Clone one down into our
1462       // BB so that it can be merged with the current GEP.
1463       GEP.getParent()->getInstList().insert(
1464           GEP.getParent()->getFirstInsertionPt(), NewGEP);
1465     } else {
1466       // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1467       // into the current block so it can be merged, and create a new PHI to
1468       // set that index.
1469       PHINode *NewPN;
1470       {
1471         IRBuilderBase::InsertPointGuard Guard(*Builder);
1472         Builder->SetInsertPoint(PN);
1473         NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
1474                                    PN->getNumOperands());
1475       }
1476 
1477       for (auto &I : PN->operands())
1478         NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1479                            PN->getIncomingBlock(I));
1480 
1481       NewGEP->setOperand(DI, NewPN);
1482       GEP.getParent()->getInstList().insert(
1483           GEP.getParent()->getFirstInsertionPt(), NewGEP);
1484       NewGEP->setOperand(DI, NewPN);
1485     }
1486 
1487     GEP.setOperand(0, NewGEP);
1488     PtrOp = NewGEP;
1489   }
1490 
1491   // Combine Indices - If the source pointer to this getelementptr instruction
1492   // is a getelementptr instruction, combine the indices of the two
1493   // getelementptr instructions into a single instruction.
1494   //
1495   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
1496     if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
1497       return nullptr;
1498 
1499     // Note that if our source is a gep chain itself then we wait for that
1500     // chain to be resolved before we perform this transformation.  This
1501     // avoids us creating a TON of code in some cases.
1502     if (GEPOperator *SrcGEP =
1503           dyn_cast<GEPOperator>(Src->getOperand(0)))
1504       if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
1505         return nullptr;   // Wait until our source is folded to completion.
1506 
1507     SmallVector<Value*, 8> Indices;
1508 
1509     // Find out whether the last index in the source GEP is a sequential idx.
1510     bool EndsWithSequential = false;
1511     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1512          I != E; ++I)
1513       EndsWithSequential = !(*I)->isStructTy();
1514 
1515     // Can we combine the two pointer arithmetics offsets?
1516     if (EndsWithSequential) {
1517       // Replace: gep (gep %P, long B), long A, ...
1518       // With:    T = long A+B; gep %P, T, ...
1519       //
1520       Value *Sum;
1521       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1522       Value *GO1 = GEP.getOperand(1);
1523       if (SO1 == Constant::getNullValue(SO1->getType())) {
1524         Sum = GO1;
1525       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
1526         Sum = SO1;
1527       } else {
1528         // If they aren't the same type, then the input hasn't been processed
1529         // by the loop above yet (which canonicalizes sequential index types to
1530         // intptr_t).  Just avoid transforming this until the input has been
1531         // normalized.
1532         if (SO1->getType() != GO1->getType())
1533           return nullptr;
1534         // Only do the combine when GO1 and SO1 are both constants. Only in
1535         // this case, we are sure the cost after the merge is never more than
1536         // that before the merge.
1537         if (!isa<Constant>(GO1) || !isa<Constant>(SO1))
1538           return nullptr;
1539         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
1540       }
1541 
1542       // Update the GEP in place if possible.
1543       if (Src->getNumOperands() == 2) {
1544         GEP.setOperand(0, Src->getOperand(0));
1545         GEP.setOperand(1, Sum);
1546         return &GEP;
1547       }
1548       Indices.append(Src->op_begin()+1, Src->op_end()-1);
1549       Indices.push_back(Sum);
1550       Indices.append(GEP.op_begin()+2, GEP.op_end());
1551     } else if (isa<Constant>(*GEP.idx_begin()) &&
1552                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
1553                Src->getNumOperands() != 1) {
1554       // Otherwise we can do the fold if the first index of the GEP is a zero
1555       Indices.append(Src->op_begin()+1, Src->op_end());
1556       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
1557     }
1558 
1559     if (!Indices.empty())
1560       return GEP.isInBounds() && Src->isInBounds()
1561                  ? GetElementPtrInst::CreateInBounds(
1562                        Src->getSourceElementType(), Src->getOperand(0), Indices,
1563                        GEP.getName())
1564                  : GetElementPtrInst::Create(Src->getSourceElementType(),
1565                                              Src->getOperand(0), Indices,
1566                                              GEP.getName());
1567   }
1568 
1569   if (GEP.getNumIndices() == 1) {
1570     unsigned AS = GEP.getPointerAddressSpace();
1571     if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
1572         DL.getPointerSizeInBits(AS)) {
1573       Type *PtrTy = GEP.getPointerOperandType();
1574       Type *Ty = PtrTy->getPointerElementType();
1575       uint64_t TyAllocSize = DL.getTypeAllocSize(Ty);
1576 
1577       bool Matched = false;
1578       uint64_t C;
1579       Value *V = nullptr;
1580       if (TyAllocSize == 1) {
1581         V = GEP.getOperand(1);
1582         Matched = true;
1583       } else if (match(GEP.getOperand(1),
1584                        m_AShr(m_Value(V), m_ConstantInt(C)))) {
1585         if (TyAllocSize == 1ULL << C)
1586           Matched = true;
1587       } else if (match(GEP.getOperand(1),
1588                        m_SDiv(m_Value(V), m_ConstantInt(C)))) {
1589         if (TyAllocSize == C)
1590           Matched = true;
1591       }
1592 
1593       if (Matched) {
1594         // Canonicalize (gep i8* X, -(ptrtoint Y))
1595         // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
1596         // The GEP pattern is emitted by the SCEV expander for certain kinds of
1597         // pointer arithmetic.
1598         if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
1599           Operator *Index = cast<Operator>(V);
1600           Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
1601           Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
1602           return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
1603         }
1604         // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
1605         // to (bitcast Y)
1606         Value *Y;
1607         if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
1608                            m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
1609           return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
1610                                                                GEP.getType());
1611         }
1612       }
1613     }
1614   }
1615 
1616   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
1617   Value *StrippedPtr = PtrOp->stripPointerCasts();
1618   PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
1619 
1620   // We do not handle pointer-vector geps here.
1621   if (!StrippedPtrTy)
1622     return nullptr;
1623 
1624   if (StrippedPtr != PtrOp) {
1625     bool HasZeroPointerIndex = false;
1626     if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1627       HasZeroPointerIndex = C->isZero();
1628 
1629     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1630     // into     : GEP [10 x i8]* X, i32 0, ...
1631     //
1632     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1633     //           into     : GEP i8* X, ...
1634     //
1635     // This occurs when the program declares an array extern like "int X[];"
1636     if (HasZeroPointerIndex) {
1637       PointerType *CPTy = cast<PointerType>(PtrOp->getType());
1638       if (ArrayType *CATy =
1639           dyn_cast<ArrayType>(CPTy->getElementType())) {
1640         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
1641         if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
1642           // -> GEP i8* X, ...
1643           SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
1644           GetElementPtrInst *Res = GetElementPtrInst::Create(
1645               StrippedPtrTy->getElementType(), StrippedPtr, Idx, GEP.getName());
1646           Res->setIsInBounds(GEP.isInBounds());
1647           if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1648             return Res;
1649           // Insert Res, and create an addrspacecast.
1650           // e.g.,
1651           // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1652           // ->
1653           // %0 = GEP i8 addrspace(1)* X, ...
1654           // addrspacecast i8 addrspace(1)* %0 to i8*
1655           return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
1656         }
1657 
1658         if (ArrayType *XATy =
1659               dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
1660           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
1661           if (CATy->getElementType() == XATy->getElementType()) {
1662             // -> GEP [10 x i8]* X, i32 0, ...
1663             // At this point, we know that the cast source type is a pointer
1664             // to an array of the same type as the destination pointer
1665             // array.  Because the array type is never stepped over (there
1666             // is a leading zero) we can fold the cast into this GEP.
1667             if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
1668               GEP.setOperand(0, StrippedPtr);
1669               GEP.setSourceElementType(XATy);
1670               return &GEP;
1671             }
1672             // Cannot replace the base pointer directly because StrippedPtr's
1673             // address space is different. Instead, create a new GEP followed by
1674             // an addrspacecast.
1675             // e.g.,
1676             // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
1677             //   i32 0, ...
1678             // ->
1679             // %0 = GEP [10 x i8] addrspace(1)* X, ...
1680             // addrspacecast i8 addrspace(1)* %0 to i8*
1681             SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
1682             Value *NewGEP = GEP.isInBounds()
1683                                 ? Builder->CreateInBoundsGEP(
1684                                       nullptr, StrippedPtr, Idx, GEP.getName())
1685                                 : Builder->CreateGEP(nullptr, StrippedPtr, Idx,
1686                                                      GEP.getName());
1687             return new AddrSpaceCastInst(NewGEP, GEP.getType());
1688           }
1689         }
1690       }
1691     } else if (GEP.getNumOperands() == 2) {
1692       // Transform things like:
1693       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1694       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
1695       Type *SrcElTy = StrippedPtrTy->getElementType();
1696       Type *ResElTy = PtrOp->getType()->getPointerElementType();
1697       if (SrcElTy->isArrayTy() &&
1698           DL.getTypeAllocSize(SrcElTy->getArrayElementType()) ==
1699               DL.getTypeAllocSize(ResElTy)) {
1700         Type *IdxType = DL.getIntPtrType(GEP.getType());
1701         Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
1702         Value *NewGEP =
1703             GEP.isInBounds()
1704                 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, Idx,
1705                                              GEP.getName())
1706                 : Builder->CreateGEP(nullptr, StrippedPtr, Idx, GEP.getName());
1707 
1708         // V and GEP are both pointer types --> BitCast
1709         return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1710                                                              GEP.getType());
1711       }
1712 
1713       // Transform things like:
1714       // %V = mul i64 %N, 4
1715       // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1716       // into:  %t1 = getelementptr i32* %arr, i32 %N; bitcast
1717       if (ResElTy->isSized() && SrcElTy->isSized()) {
1718         // Check that changing the type amounts to dividing the index by a scale
1719         // factor.
1720         uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1721         uint64_t SrcSize = DL.getTypeAllocSize(SrcElTy);
1722         if (ResSize && SrcSize % ResSize == 0) {
1723           Value *Idx = GEP.getOperand(1);
1724           unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1725           uint64_t Scale = SrcSize / ResSize;
1726 
1727           // Earlier transforms ensure that the index has type IntPtrType, which
1728           // considerably simplifies the logic by eliminating implicit casts.
1729           assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
1730                  "Index not cast to pointer width?");
1731 
1732           bool NSW;
1733           if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1734             // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1735             // If the multiplication NewIdx * Scale may overflow then the new
1736             // GEP may not be "inbounds".
1737             Value *NewGEP =
1738                 GEP.isInBounds() && NSW
1739                     ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, NewIdx,
1740                                                  GEP.getName())
1741                     : Builder->CreateGEP(nullptr, StrippedPtr, NewIdx,
1742                                          GEP.getName());
1743 
1744             // The NewGEP must be pointer typed, so must the old one -> BitCast
1745             return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1746                                                                  GEP.getType());
1747           }
1748         }
1749       }
1750 
1751       // Similarly, transform things like:
1752       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
1753       //   (where tmp = 8*tmp2) into:
1754       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
1755       if (ResElTy->isSized() && SrcElTy->isSized() && SrcElTy->isArrayTy()) {
1756         // Check that changing to the array element type amounts to dividing the
1757         // index by a scale factor.
1758         uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1759         uint64_t ArrayEltSize =
1760             DL.getTypeAllocSize(SrcElTy->getArrayElementType());
1761         if (ResSize && ArrayEltSize % ResSize == 0) {
1762           Value *Idx = GEP.getOperand(1);
1763           unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1764           uint64_t Scale = ArrayEltSize / ResSize;
1765 
1766           // Earlier transforms ensure that the index has type IntPtrType, which
1767           // considerably simplifies the logic by eliminating implicit casts.
1768           assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
1769                  "Index not cast to pointer width?");
1770 
1771           bool NSW;
1772           if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1773             // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1774             // If the multiplication NewIdx * Scale may overflow then the new
1775             // GEP may not be "inbounds".
1776             Value *Off[2] = {
1777                 Constant::getNullValue(DL.getIntPtrType(GEP.getType())),
1778                 NewIdx};
1779 
1780             Value *NewGEP = GEP.isInBounds() && NSW
1781                                 ? Builder->CreateInBoundsGEP(
1782                                       SrcElTy, StrippedPtr, Off, GEP.getName())
1783                                 : Builder->CreateGEP(SrcElTy, StrippedPtr, Off,
1784                                                      GEP.getName());
1785             // The NewGEP must be pointer typed, so must the old one -> BitCast
1786             return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1787                                                                  GEP.getType());
1788           }
1789         }
1790       }
1791     }
1792   }
1793 
1794   // addrspacecast between types is canonicalized as a bitcast, then an
1795   // addrspacecast. To take advantage of the below bitcast + struct GEP, look
1796   // through the addrspacecast.
1797   if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
1798     //   X = bitcast A addrspace(1)* to B addrspace(1)*
1799     //   Y = addrspacecast A addrspace(1)* to B addrspace(2)*
1800     //   Z = gep Y, <...constant indices...>
1801     // Into an addrspacecasted GEP of the struct.
1802     if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1803       PtrOp = BC;
1804   }
1805 
1806   /// See if we can simplify:
1807   ///   X = bitcast A* to B*
1808   ///   Y = gep X, <...constant indices...>
1809   /// into a gep of the original struct.  This is important for SROA and alias
1810   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
1811   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1812     Value *Operand = BCI->getOperand(0);
1813     PointerType *OpType = cast<PointerType>(Operand->getType());
1814     unsigned OffsetBits = DL.getPointerTypeSizeInBits(GEP.getType());
1815     APInt Offset(OffsetBits, 0);
1816     if (!isa<BitCastInst>(Operand) &&
1817         GEP.accumulateConstantOffset(DL, Offset)) {
1818 
1819       // If this GEP instruction doesn't move the pointer, just replace the GEP
1820       // with a bitcast of the real input to the dest type.
1821       if (!Offset) {
1822         // If the bitcast is of an allocation, and the allocation will be
1823         // converted to match the type of the cast, don't touch this.
1824         if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, TLI)) {
1825           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1826           if (Instruction *I = visitBitCast(*BCI)) {
1827             if (I != BCI) {
1828               I->takeName(BCI);
1829               BCI->getParent()->getInstList().insert(BCI->getIterator(), I);
1830               ReplaceInstUsesWith(*BCI, I);
1831             }
1832             return &GEP;
1833           }
1834         }
1835 
1836         if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1837           return new AddrSpaceCastInst(Operand, GEP.getType());
1838         return new BitCastInst(Operand, GEP.getType());
1839       }
1840 
1841       // Otherwise, if the offset is non-zero, we need to find out if there is a
1842       // field at Offset in 'A's type.  If so, we can pull the cast through the
1843       // GEP.
1844       SmallVector<Value*, 8> NewIndices;
1845       if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
1846         Value *NGEP =
1847             GEP.isInBounds()
1848                 ? Builder->CreateInBoundsGEP(nullptr, Operand, NewIndices)
1849                 : Builder->CreateGEP(nullptr, Operand, NewIndices);
1850 
1851         if (NGEP->getType() == GEP.getType())
1852           return ReplaceInstUsesWith(GEP, NGEP);
1853         NGEP->takeName(&GEP);
1854 
1855         if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1856           return new AddrSpaceCastInst(NGEP, GEP.getType());
1857         return new BitCastInst(NGEP, GEP.getType());
1858       }
1859     }
1860   }
1861 
1862   return nullptr;
1863 }
1864 
1865 static bool
1866 isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
1867                      const TargetLibraryInfo *TLI) {
1868   SmallVector<Instruction*, 4> Worklist;
1869   Worklist.push_back(AI);
1870 
1871   do {
1872     Instruction *PI = Worklist.pop_back_val();
1873     for (User *U : PI->users()) {
1874       Instruction *I = cast<Instruction>(U);
1875       switch (I->getOpcode()) {
1876       default:
1877         // Give up the moment we see something we can't handle.
1878         return false;
1879 
1880       case Instruction::BitCast:
1881       case Instruction::GetElementPtr:
1882         Users.emplace_back(I);
1883         Worklist.push_back(I);
1884         continue;
1885 
1886       case Instruction::ICmp: {
1887         ICmpInst *ICI = cast<ICmpInst>(I);
1888         // We can fold eq/ne comparisons with null to false/true, respectively.
1889         if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1)))
1890           return false;
1891         Users.emplace_back(I);
1892         continue;
1893       }
1894 
1895       case Instruction::Call:
1896         // Ignore no-op and store intrinsics.
1897         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1898           switch (II->getIntrinsicID()) {
1899           default:
1900             return false;
1901 
1902           case Intrinsic::memmove:
1903           case Intrinsic::memcpy:
1904           case Intrinsic::memset: {
1905             MemIntrinsic *MI = cast<MemIntrinsic>(II);
1906             if (MI->isVolatile() || MI->getRawDest() != PI)
1907               return false;
1908           }
1909           // fall through
1910           case Intrinsic::dbg_declare:
1911           case Intrinsic::dbg_value:
1912           case Intrinsic::invariant_start:
1913           case Intrinsic::invariant_end:
1914           case Intrinsic::lifetime_start:
1915           case Intrinsic::lifetime_end:
1916           case Intrinsic::objectsize:
1917             Users.emplace_back(I);
1918             continue;
1919           }
1920         }
1921 
1922         if (isFreeCall(I, TLI)) {
1923           Users.emplace_back(I);
1924           continue;
1925         }
1926         return false;
1927 
1928       case Instruction::Store: {
1929         StoreInst *SI = cast<StoreInst>(I);
1930         if (SI->isVolatile() || SI->getPointerOperand() != PI)
1931           return false;
1932         Users.emplace_back(I);
1933         continue;
1934       }
1935       }
1936       llvm_unreachable("missing a return?");
1937     }
1938   } while (!Worklist.empty());
1939   return true;
1940 }
1941 
1942 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
1943   // If we have a malloc call which is only used in any amount of comparisons
1944   // to null and free calls, delete the calls and replace the comparisons with
1945   // true or false as appropriate.
1946   SmallVector<WeakVH, 64> Users;
1947   if (isAllocSiteRemovable(&MI, Users, TLI)) {
1948     for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1949       Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1950       if (!I) continue;
1951 
1952       if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
1953         ReplaceInstUsesWith(*C,
1954                             ConstantInt::get(Type::getInt1Ty(C->getContext()),
1955                                              C->isFalseWhenEqual()));
1956       } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
1957         ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
1958       } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1959         if (II->getIntrinsicID() == Intrinsic::objectsize) {
1960           ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
1961           uint64_t DontKnow = CI->isZero() ? -1ULL : 0;
1962           ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow));
1963         }
1964       }
1965       EraseInstFromFunction(*I);
1966     }
1967 
1968     if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
1969       // Replace invoke with a NOP intrinsic to maintain the original CFG
1970       Module *M = II->getParent()->getParent()->getParent();
1971       Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
1972       InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
1973                          None, "", II->getParent());
1974     }
1975     return EraseInstFromFunction(MI);
1976   }
1977   return nullptr;
1978 }
1979 
1980 /// \brief Move the call to free before a NULL test.
1981 ///
1982 /// Check if this free is accessed after its argument has been test
1983 /// against NULL (property 0).
1984 /// If yes, it is legal to move this call in its predecessor block.
1985 ///
1986 /// The move is performed only if the block containing the call to free
1987 /// will be removed, i.e.:
1988 /// 1. it has only one predecessor P, and P has two successors
1989 /// 2. it contains the call and an unconditional branch
1990 /// 3. its successor is the same as its predecessor's successor
1991 ///
1992 /// The profitability is out-of concern here and this function should
1993 /// be called only if the caller knows this transformation would be
1994 /// profitable (e.g., for code size).
1995 static Instruction *
1996 tryToMoveFreeBeforeNullTest(CallInst &FI) {
1997   Value *Op = FI.getArgOperand(0);
1998   BasicBlock *FreeInstrBB = FI.getParent();
1999   BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
2000 
2001   // Validate part of constraint #1: Only one predecessor
2002   // FIXME: We can extend the number of predecessor, but in that case, we
2003   //        would duplicate the call to free in each predecessor and it may
2004   //        not be profitable even for code size.
2005   if (!PredBB)
2006     return nullptr;
2007 
2008   // Validate constraint #2: Does this block contains only the call to
2009   //                         free and an unconditional branch?
2010   // FIXME: We could check if we can speculate everything in the
2011   //        predecessor block
2012   if (FreeInstrBB->size() != 2)
2013     return nullptr;
2014   BasicBlock *SuccBB;
2015   if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
2016     return nullptr;
2017 
2018   // Validate the rest of constraint #1 by matching on the pred branch.
2019   TerminatorInst *TI = PredBB->getTerminator();
2020   BasicBlock *TrueBB, *FalseBB;
2021   ICmpInst::Predicate Pred;
2022   if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
2023     return nullptr;
2024   if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2025     return nullptr;
2026 
2027   // Validate constraint #3: Ensure the null case just falls through.
2028   if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
2029     return nullptr;
2030   assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
2031          "Broken CFG: missing edge from predecessor to successor");
2032 
2033   FI.moveBefore(TI);
2034   return &FI;
2035 }
2036 
2037 
2038 Instruction *InstCombiner::visitFree(CallInst &FI) {
2039   Value *Op = FI.getArgOperand(0);
2040 
2041   // free undef -> unreachable.
2042   if (isa<UndefValue>(Op)) {
2043     // Insert a new store to null because we cannot modify the CFG here.
2044     Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
2045                          UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
2046     return EraseInstFromFunction(FI);
2047   }
2048 
2049   // If we have 'free null' delete the instruction.  This can happen in stl code
2050   // when lots of inlining happens.
2051   if (isa<ConstantPointerNull>(Op))
2052     return EraseInstFromFunction(FI);
2053 
2054   // If we optimize for code size, try to move the call to free before the null
2055   // test so that simplify cfg can remove the empty block and dead code
2056   // elimination the branch. I.e., helps to turn something like:
2057   // if (foo) free(foo);
2058   // into
2059   // free(foo);
2060   if (MinimizeSize)
2061     if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
2062       return I;
2063 
2064   return nullptr;
2065 }
2066 
2067 Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
2068   if (RI.getNumOperands() == 0) // ret void
2069     return nullptr;
2070 
2071   Value *ResultOp = RI.getOperand(0);
2072   Type *VTy = ResultOp->getType();
2073   if (!VTy->isIntegerTy())
2074     return nullptr;
2075 
2076   // There might be assume intrinsics dominating this return that completely
2077   // determine the value. If so, constant fold it.
2078   unsigned BitWidth = VTy->getPrimitiveSizeInBits();
2079   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2080   computeKnownBits(ResultOp, KnownZero, KnownOne, 0, &RI);
2081   if ((KnownZero|KnownOne).isAllOnesValue())
2082     RI.setOperand(0, Constant::getIntegerValue(VTy, KnownOne));
2083 
2084   return nullptr;
2085 }
2086 
2087 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2088   // Change br (not X), label True, label False to: br X, label False, True
2089   Value *X = nullptr;
2090   BasicBlock *TrueDest;
2091   BasicBlock *FalseDest;
2092   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
2093       !isa<Constant>(X)) {
2094     // Swap Destinations and condition...
2095     BI.setCondition(X);
2096     BI.swapSuccessors();
2097     return &BI;
2098   }
2099 
2100   // If the condition is irrelevant, remove the use so that other
2101   // transforms on the condition become more effective.
2102   if (BI.isConditional() &&
2103       BI.getSuccessor(0) == BI.getSuccessor(1) &&
2104       !isa<UndefValue>(BI.getCondition())) {
2105     BI.setCondition(UndefValue::get(BI.getCondition()->getType()));
2106     return &BI;
2107   }
2108 
2109   // Canonicalize fcmp_one -> fcmp_oeq
2110   FCmpInst::Predicate FPred; Value *Y;
2111   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
2112                              TrueDest, FalseDest)) &&
2113       BI.getCondition()->hasOneUse())
2114     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
2115         FPred == FCmpInst::FCMP_OGE) {
2116       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
2117       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
2118 
2119       // Swap Destinations and condition.
2120       BI.swapSuccessors();
2121       Worklist.Add(Cond);
2122       return &BI;
2123     }
2124 
2125   // Canonicalize icmp_ne -> icmp_eq
2126   ICmpInst::Predicate IPred;
2127   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
2128                       TrueDest, FalseDest)) &&
2129       BI.getCondition()->hasOneUse())
2130     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
2131         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
2132         IPred == ICmpInst::ICMP_SGE) {
2133       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
2134       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
2135       // Swap Destinations and condition.
2136       BI.swapSuccessors();
2137       Worklist.Add(Cond);
2138       return &BI;
2139     }
2140 
2141   return nullptr;
2142 }
2143 
2144 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2145   Value *Cond = SI.getCondition();
2146   unsigned BitWidth = cast<IntegerType>(Cond->getType())->getBitWidth();
2147   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2148   computeKnownBits(Cond, KnownZero, KnownOne, 0, &SI);
2149   unsigned LeadingKnownZeros = KnownZero.countLeadingOnes();
2150   unsigned LeadingKnownOnes = KnownOne.countLeadingOnes();
2151 
2152   // Compute the number of leading bits we can ignore.
2153   for (auto &C : SI.cases()) {
2154     LeadingKnownZeros = std::min(
2155         LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2156     LeadingKnownOnes = std::min(
2157         LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2158   }
2159 
2160   unsigned NewWidth = BitWidth - std::max(LeadingKnownZeros, LeadingKnownOnes);
2161 
2162   // Truncate the condition operand if the new type is equal to or larger than
2163   // the largest legal integer type. We need to be conservative here since
2164   // x86 generates redundant zero-extension instructions if the operand is
2165   // truncated to i8 or i16.
2166   bool TruncCond = false;
2167   if (NewWidth > 0 && BitWidth > NewWidth &&
2168       NewWidth >= DL.getLargestLegalIntTypeSize()) {
2169     TruncCond = true;
2170     IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2171     Builder->SetInsertPoint(&SI);
2172     Value *NewCond = Builder->CreateTrunc(SI.getCondition(), Ty, "trunc");
2173     SI.setCondition(NewCond);
2174 
2175     for (auto &C : SI.cases())
2176       static_cast<SwitchInst::CaseIt *>(&C)->setValue(ConstantInt::get(
2177           SI.getContext(), C.getCaseValue()->getValue().trunc(NewWidth)));
2178   }
2179 
2180   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
2181     if (I->getOpcode() == Instruction::Add)
2182       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2183         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
2184         // Skip the first item since that's the default case.
2185         for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
2186              i != e; ++i) {
2187           ConstantInt* CaseVal = i.getCaseValue();
2188           Constant *LHS = CaseVal;
2189           if (TruncCond)
2190             LHS = LeadingKnownZeros
2191                       ? ConstantExpr::getZExt(CaseVal, Cond->getType())
2192                       : ConstantExpr::getSExt(CaseVal, Cond->getType());
2193           Constant* NewCaseVal = ConstantExpr::getSub(LHS, AddRHS);
2194           assert(isa<ConstantInt>(NewCaseVal) &&
2195                  "Result of expression should be constant");
2196           i.setValue(cast<ConstantInt>(NewCaseVal));
2197         }
2198         SI.setCondition(I->getOperand(0));
2199         Worklist.Add(I);
2200         return &SI;
2201       }
2202   }
2203 
2204   return TruncCond ? &SI : nullptr;
2205 }
2206 
2207 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
2208   Value *Agg = EV.getAggregateOperand();
2209 
2210   if (!EV.hasIndices())
2211     return ReplaceInstUsesWith(EV, Agg);
2212 
2213   if (Value *V =
2214           SimplifyExtractValueInst(Agg, EV.getIndices(), DL, TLI, DT, AC))
2215     return ReplaceInstUsesWith(EV, V);
2216 
2217   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2218     // We're extracting from an insertvalue instruction, compare the indices
2219     const unsigned *exti, *exte, *insi, *inse;
2220     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2221          exte = EV.idx_end(), inse = IV->idx_end();
2222          exti != exte && insi != inse;
2223          ++exti, ++insi) {
2224       if (*insi != *exti)
2225         // The insert and extract both reference distinctly different elements.
2226         // This means the extract is not influenced by the insert, and we can
2227         // replace the aggregate operand of the extract with the aggregate
2228         // operand of the insert. i.e., replace
2229         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2230         // %E = extractvalue { i32, { i32 } } %I, 0
2231         // with
2232         // %E = extractvalue { i32, { i32 } } %A, 0
2233         return ExtractValueInst::Create(IV->getAggregateOperand(),
2234                                         EV.getIndices());
2235     }
2236     if (exti == exte && insi == inse)
2237       // Both iterators are at the end: Index lists are identical. Replace
2238       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2239       // %C = extractvalue { i32, { i32 } } %B, 1, 0
2240       // with "i32 42"
2241       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
2242     if (exti == exte) {
2243       // The extract list is a prefix of the insert list. i.e. replace
2244       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2245       // %E = extractvalue { i32, { i32 } } %I, 1
2246       // with
2247       // %X = extractvalue { i32, { i32 } } %A, 1
2248       // %E = insertvalue { i32 } %X, i32 42, 0
2249       // by switching the order of the insert and extract (though the
2250       // insertvalue should be left in, since it may have other uses).
2251       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
2252                                                  EV.getIndices());
2253       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
2254                                      makeArrayRef(insi, inse));
2255     }
2256     if (insi == inse)
2257       // The insert list is a prefix of the extract list
2258       // We can simply remove the common indices from the extract and make it
2259       // operate on the inserted value instead of the insertvalue result.
2260       // i.e., replace
2261       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2262       // %E = extractvalue { i32, { i32 } } %I, 1, 0
2263       // with
2264       // %E extractvalue { i32 } { i32 42 }, 0
2265       return ExtractValueInst::Create(IV->getInsertedValueOperand(),
2266                                       makeArrayRef(exti, exte));
2267   }
2268   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2269     // We're extracting from an intrinsic, see if we're the only user, which
2270     // allows us to simplify multiple result intrinsics to simpler things that
2271     // just get one value.
2272     if (II->hasOneUse()) {
2273       // Check if we're grabbing the overflow bit or the result of a 'with
2274       // overflow' intrinsic.  If it's the latter we can remove the intrinsic
2275       // and replace it with a traditional binary instruction.
2276       switch (II->getIntrinsicID()) {
2277       case Intrinsic::uadd_with_overflow:
2278       case Intrinsic::sadd_with_overflow:
2279         if (*EV.idx_begin() == 0) {  // Normal result.
2280           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2281           ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2282           EraseInstFromFunction(*II);
2283           return BinaryOperator::CreateAdd(LHS, RHS);
2284         }
2285 
2286         // If the normal result of the add is dead, and the RHS is a constant,
2287         // we can transform this into a range comparison.
2288         // overflow = uadd a, -4  -->  overflow = icmp ugt a, 3
2289         if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2290           if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2291             return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2292                                 ConstantExpr::getNot(CI));
2293         break;
2294       case Intrinsic::usub_with_overflow:
2295       case Intrinsic::ssub_with_overflow:
2296         if (*EV.idx_begin() == 0) {  // Normal result.
2297           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2298           ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2299           EraseInstFromFunction(*II);
2300           return BinaryOperator::CreateSub(LHS, RHS);
2301         }
2302         break;
2303       case Intrinsic::umul_with_overflow:
2304       case Intrinsic::smul_with_overflow:
2305         if (*EV.idx_begin() == 0) {  // Normal result.
2306           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2307           ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2308           EraseInstFromFunction(*II);
2309           return BinaryOperator::CreateMul(LHS, RHS);
2310         }
2311         break;
2312       default:
2313         break;
2314       }
2315     }
2316   }
2317   if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2318     // If the (non-volatile) load only has one use, we can rewrite this to a
2319     // load from a GEP. This reduces the size of the load.
2320     // FIXME: If a load is used only by extractvalue instructions then this
2321     //        could be done regardless of having multiple uses.
2322     if (L->isSimple() && L->hasOneUse()) {
2323       // extractvalue has integer indices, getelementptr has Value*s. Convert.
2324       SmallVector<Value*, 4> Indices;
2325       // Prefix an i32 0 since we need the first element.
2326       Indices.push_back(Builder->getInt32(0));
2327       for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2328             I != E; ++I)
2329         Indices.push_back(Builder->getInt32(*I));
2330 
2331       // We need to insert these at the location of the old load, not at that of
2332       // the extractvalue.
2333       Builder->SetInsertPoint(L);
2334       Value *GEP = Builder->CreateInBoundsGEP(L->getType(),
2335                                               L->getPointerOperand(), Indices);
2336       // Returning the load directly will cause the main loop to insert it in
2337       // the wrong spot, so use ReplaceInstUsesWith().
2338       return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
2339     }
2340   // We could simplify extracts from other values. Note that nested extracts may
2341   // already be simplified implicitly by the above: extract (extract (insert) )
2342   // will be translated into extract ( insert ( extract ) ) first and then just
2343   // the value inserted, if appropriate. Similarly for extracts from single-use
2344   // loads: extract (extract (load)) will be translated to extract (load (gep))
2345   // and if again single-use then via load (gep (gep)) to load (gep).
2346   // However, double extracts from e.g. function arguments or return values
2347   // aren't handled yet.
2348   return nullptr;
2349 }
2350 
2351 /// Return 'true' if the given typeinfo will match anything.
2352 static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
2353   switch (Personality) {
2354   case EHPersonality::GNU_C:
2355     // The GCC C EH personality only exists to support cleanups, so it's not
2356     // clear what the semantics of catch clauses are.
2357     return false;
2358   case EHPersonality::Unknown:
2359     return false;
2360   case EHPersonality::GNU_Ada:
2361     // While __gnat_all_others_value will match any Ada exception, it doesn't
2362     // match foreign exceptions (or didn't, before gcc-4.7).
2363     return false;
2364   case EHPersonality::GNU_CXX:
2365   case EHPersonality::GNU_ObjC:
2366   case EHPersonality::MSVC_X86SEH:
2367   case EHPersonality::MSVC_Win64SEH:
2368   case EHPersonality::MSVC_CXX:
2369   case EHPersonality::CoreCLR:
2370     return TypeInfo->isNullValue();
2371   }
2372   llvm_unreachable("invalid enum");
2373 }
2374 
2375 static bool shorter_filter(const Value *LHS, const Value *RHS) {
2376   return
2377     cast<ArrayType>(LHS->getType())->getNumElements()
2378   <
2379     cast<ArrayType>(RHS->getType())->getNumElements();
2380 }
2381 
2382 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2383   // The logic here should be correct for any real-world personality function.
2384   // However if that turns out not to be true, the offending logic can always
2385   // be conditioned on the personality function, like the catch-all logic is.
2386   EHPersonality Personality =
2387       classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
2388 
2389   // Simplify the list of clauses, eg by removing repeated catch clauses
2390   // (these are often created by inlining).
2391   bool MakeNewInstruction = false; // If true, recreate using the following:
2392   SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
2393   bool CleanupFlag = LI.isCleanup();   // - The new instruction is a cleanup.
2394 
2395   SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2396   for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2397     bool isLastClause = i + 1 == e;
2398     if (LI.isCatch(i)) {
2399       // A catch clause.
2400       Constant *CatchClause = LI.getClause(i);
2401       Constant *TypeInfo = CatchClause->stripPointerCasts();
2402 
2403       // If we already saw this clause, there is no point in having a second
2404       // copy of it.
2405       if (AlreadyCaught.insert(TypeInfo).second) {
2406         // This catch clause was not already seen.
2407         NewClauses.push_back(CatchClause);
2408       } else {
2409         // Repeated catch clause - drop the redundant copy.
2410         MakeNewInstruction = true;
2411       }
2412 
2413       // If this is a catch-all then there is no point in keeping any following
2414       // clauses or marking the landingpad as having a cleanup.
2415       if (isCatchAll(Personality, TypeInfo)) {
2416         if (!isLastClause)
2417           MakeNewInstruction = true;
2418         CleanupFlag = false;
2419         break;
2420       }
2421     } else {
2422       // A filter clause.  If any of the filter elements were already caught
2423       // then they can be dropped from the filter.  It is tempting to try to
2424       // exploit the filter further by saying that any typeinfo that does not
2425       // occur in the filter can't be caught later (and thus can be dropped).
2426       // However this would be wrong, since typeinfos can match without being
2427       // equal (for example if one represents a C++ class, and the other some
2428       // class derived from it).
2429       assert(LI.isFilter(i) && "Unsupported landingpad clause!");
2430       Constant *FilterClause = LI.getClause(i);
2431       ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2432       unsigned NumTypeInfos = FilterType->getNumElements();
2433 
2434       // An empty filter catches everything, so there is no point in keeping any
2435       // following clauses or marking the landingpad as having a cleanup.  By
2436       // dealing with this case here the following code is made a bit simpler.
2437       if (!NumTypeInfos) {
2438         NewClauses.push_back(FilterClause);
2439         if (!isLastClause)
2440           MakeNewInstruction = true;
2441         CleanupFlag = false;
2442         break;
2443       }
2444 
2445       bool MakeNewFilter = false; // If true, make a new filter.
2446       SmallVector<Constant *, 16> NewFilterElts; // New elements.
2447       if (isa<ConstantAggregateZero>(FilterClause)) {
2448         // Not an empty filter - it contains at least one null typeinfo.
2449         assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2450         Constant *TypeInfo =
2451           Constant::getNullValue(FilterType->getElementType());
2452         // If this typeinfo is a catch-all then the filter can never match.
2453         if (isCatchAll(Personality, TypeInfo)) {
2454           // Throw the filter away.
2455           MakeNewInstruction = true;
2456           continue;
2457         }
2458 
2459         // There is no point in having multiple copies of this typeinfo, so
2460         // discard all but the first copy if there is more than one.
2461         NewFilterElts.push_back(TypeInfo);
2462         if (NumTypeInfos > 1)
2463           MakeNewFilter = true;
2464       } else {
2465         ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2466         SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2467         NewFilterElts.reserve(NumTypeInfos);
2468 
2469         // Remove any filter elements that were already caught or that already
2470         // occurred in the filter.  While there, see if any of the elements are
2471         // catch-alls.  If so, the filter can be discarded.
2472         bool SawCatchAll = false;
2473         for (unsigned j = 0; j != NumTypeInfos; ++j) {
2474           Constant *Elt = Filter->getOperand(j);
2475           Constant *TypeInfo = Elt->stripPointerCasts();
2476           if (isCatchAll(Personality, TypeInfo)) {
2477             // This element is a catch-all.  Bail out, noting this fact.
2478             SawCatchAll = true;
2479             break;
2480           }
2481 
2482           // Even if we've seen a type in a catch clause, we don't want to
2483           // remove it from the filter.  An unexpected type handler may be
2484           // set up for a call site which throws an exception of the same
2485           // type caught.  In order for the exception thrown by the unexpected
2486           // handler to propogate correctly, the filter must be correctly
2487           // described for the call site.
2488           //
2489           // Example:
2490           //
2491           // void unexpected() { throw 1;}
2492           // void foo() throw (int) {
2493           //   std::set_unexpected(unexpected);
2494           //   try {
2495           //     throw 2.0;
2496           //   } catch (int i) {}
2497           // }
2498 
2499           // There is no point in having multiple copies of the same typeinfo in
2500           // a filter, so only add it if we didn't already.
2501           if (SeenInFilter.insert(TypeInfo).second)
2502             NewFilterElts.push_back(cast<Constant>(Elt));
2503         }
2504         // A filter containing a catch-all cannot match anything by definition.
2505         if (SawCatchAll) {
2506           // Throw the filter away.
2507           MakeNewInstruction = true;
2508           continue;
2509         }
2510 
2511         // If we dropped something from the filter, make a new one.
2512         if (NewFilterElts.size() < NumTypeInfos)
2513           MakeNewFilter = true;
2514       }
2515       if (MakeNewFilter) {
2516         FilterType = ArrayType::get(FilterType->getElementType(),
2517                                     NewFilterElts.size());
2518         FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2519         MakeNewInstruction = true;
2520       }
2521 
2522       NewClauses.push_back(FilterClause);
2523 
2524       // If the new filter is empty then it will catch everything so there is
2525       // no point in keeping any following clauses or marking the landingpad
2526       // as having a cleanup.  The case of the original filter being empty was
2527       // already handled above.
2528       if (MakeNewFilter && !NewFilterElts.size()) {
2529         assert(MakeNewInstruction && "New filter but not a new instruction!");
2530         CleanupFlag = false;
2531         break;
2532       }
2533     }
2534   }
2535 
2536   // If several filters occur in a row then reorder them so that the shortest
2537   // filters come first (those with the smallest number of elements).  This is
2538   // advantageous because shorter filters are more likely to match, speeding up
2539   // unwinding, but mostly because it increases the effectiveness of the other
2540   // filter optimizations below.
2541   for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2542     unsigned j;
2543     // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2544     for (j = i; j != e; ++j)
2545       if (!isa<ArrayType>(NewClauses[j]->getType()))
2546         break;
2547 
2548     // Check whether the filters are already sorted by length.  We need to know
2549     // if sorting them is actually going to do anything so that we only make a
2550     // new landingpad instruction if it does.
2551     for (unsigned k = i; k + 1 < j; ++k)
2552       if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2553         // Not sorted, so sort the filters now.  Doing an unstable sort would be
2554         // correct too but reordering filters pointlessly might confuse users.
2555         std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2556                          shorter_filter);
2557         MakeNewInstruction = true;
2558         break;
2559       }
2560 
2561     // Look for the next batch of filters.
2562     i = j + 1;
2563   }
2564 
2565   // If typeinfos matched if and only if equal, then the elements of a filter L
2566   // that occurs later than a filter F could be replaced by the intersection of
2567   // the elements of F and L.  In reality two typeinfos can match without being
2568   // equal (for example if one represents a C++ class, and the other some class
2569   // derived from it) so it would be wrong to perform this transform in general.
2570   // However the transform is correct and useful if F is a subset of L.  In that
2571   // case L can be replaced by F, and thus removed altogether since repeating a
2572   // filter is pointless.  So here we look at all pairs of filters F and L where
2573   // L follows F in the list of clauses, and remove L if every element of F is
2574   // an element of L.  This can occur when inlining C++ functions with exception
2575   // specifications.
2576   for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2577     // Examine each filter in turn.
2578     Value *Filter = NewClauses[i];
2579     ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2580     if (!FTy)
2581       // Not a filter - skip it.
2582       continue;
2583     unsigned FElts = FTy->getNumElements();
2584     // Examine each filter following this one.  Doing this backwards means that
2585     // we don't have to worry about filters disappearing under us when removed.
2586     for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2587       Value *LFilter = NewClauses[j];
2588       ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2589       if (!LTy)
2590         // Not a filter - skip it.
2591         continue;
2592       // If Filter is a subset of LFilter, i.e. every element of Filter is also
2593       // an element of LFilter, then discard LFilter.
2594       SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
2595       // If Filter is empty then it is a subset of LFilter.
2596       if (!FElts) {
2597         // Discard LFilter.
2598         NewClauses.erase(J);
2599         MakeNewInstruction = true;
2600         // Move on to the next filter.
2601         continue;
2602       }
2603       unsigned LElts = LTy->getNumElements();
2604       // If Filter is longer than LFilter then it cannot be a subset of it.
2605       if (FElts > LElts)
2606         // Move on to the next filter.
2607         continue;
2608       // At this point we know that LFilter has at least one element.
2609       if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
2610         // Filter is a subset of LFilter iff Filter contains only zeros (as we
2611         // already know that Filter is not longer than LFilter).
2612         if (isa<ConstantAggregateZero>(Filter)) {
2613           assert(FElts <= LElts && "Should have handled this case earlier!");
2614           // Discard LFilter.
2615           NewClauses.erase(J);
2616           MakeNewInstruction = true;
2617         }
2618         // Move on to the next filter.
2619         continue;
2620       }
2621       ConstantArray *LArray = cast<ConstantArray>(LFilter);
2622       if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2623         // Since Filter is non-empty and contains only zeros, it is a subset of
2624         // LFilter iff LFilter contains a zero.
2625         assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2626         for (unsigned l = 0; l != LElts; ++l)
2627           if (LArray->getOperand(l)->isNullValue()) {
2628             // LFilter contains a zero - discard it.
2629             NewClauses.erase(J);
2630             MakeNewInstruction = true;
2631             break;
2632           }
2633         // Move on to the next filter.
2634         continue;
2635       }
2636       // At this point we know that both filters are ConstantArrays.  Loop over
2637       // operands to see whether every element of Filter is also an element of
2638       // LFilter.  Since filters tend to be short this is probably faster than
2639       // using a method that scales nicely.
2640       ConstantArray *FArray = cast<ConstantArray>(Filter);
2641       bool AllFound = true;
2642       for (unsigned f = 0; f != FElts; ++f) {
2643         Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2644         AllFound = false;
2645         for (unsigned l = 0; l != LElts; ++l) {
2646           Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2647           if (LTypeInfo == FTypeInfo) {
2648             AllFound = true;
2649             break;
2650           }
2651         }
2652         if (!AllFound)
2653           break;
2654       }
2655       if (AllFound) {
2656         // Discard LFilter.
2657         NewClauses.erase(J);
2658         MakeNewInstruction = true;
2659       }
2660       // Move on to the next filter.
2661     }
2662   }
2663 
2664   // If we changed any of the clauses, replace the old landingpad instruction
2665   // with a new one.
2666   if (MakeNewInstruction) {
2667     LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
2668                                                  NewClauses.size());
2669     for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2670       NLI->addClause(NewClauses[i]);
2671     // A landing pad with no clauses must have the cleanup flag set.  It is
2672     // theoretically possible, though highly unlikely, that we eliminated all
2673     // clauses.  If so, force the cleanup flag to true.
2674     if (NewClauses.empty())
2675       CleanupFlag = true;
2676     NLI->setCleanup(CleanupFlag);
2677     return NLI;
2678   }
2679 
2680   // Even if none of the clauses changed, we may nonetheless have understood
2681   // that the cleanup flag is pointless.  Clear it if so.
2682   if (LI.isCleanup() != CleanupFlag) {
2683     assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2684     LI.setCleanup(CleanupFlag);
2685     return &LI;
2686   }
2687 
2688   return nullptr;
2689 }
2690 
2691 /// Try to move the specified instruction from its current block into the
2692 /// beginning of DestBlock, which can only happen if it's safe to move the
2693 /// instruction past all of the instructions between it and the end of its
2694 /// block.
2695 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2696   assert(I->hasOneUse() && "Invariants didn't hold!");
2697 
2698   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
2699   if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() ||
2700       isa<TerminatorInst>(I))
2701     return false;
2702 
2703   // Do not sink alloca instructions out of the entry block.
2704   if (isa<AllocaInst>(I) && I->getParent() ==
2705         &DestBlock->getParent()->getEntryBlock())
2706     return false;
2707 
2708   // Do not sink convergent call instructions.
2709   if (auto *CI = dyn_cast<CallInst>(I)) {
2710     if (CI->isConvergent())
2711       return false;
2712   }
2713 
2714   // We can only sink load instructions if there is nothing between the load and
2715   // the end of block that could change the value.
2716   if (I->mayReadFromMemory()) {
2717     for (BasicBlock::iterator Scan = I->getIterator(),
2718                               E = I->getParent()->end();
2719          Scan != E; ++Scan)
2720       if (Scan->mayWriteToMemory())
2721         return false;
2722   }
2723 
2724   BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
2725   I->moveBefore(&*InsertPos);
2726   ++NumSunkInst;
2727   return true;
2728 }
2729 
2730 bool InstCombiner::run() {
2731   while (!Worklist.isEmpty()) {
2732     Instruction *I = Worklist.RemoveOne();
2733     if (I == nullptr) continue;  // skip null values.
2734 
2735     // Check to see if we can DCE the instruction.
2736     if (isInstructionTriviallyDead(I, TLI)) {
2737       DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
2738       EraseInstFromFunction(*I);
2739       ++NumDeadInst;
2740       MadeIRChange = true;
2741       continue;
2742     }
2743 
2744     // Instruction isn't dead, see if we can constant propagate it.
2745     if (!I->use_empty() &&
2746         (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) {
2747       if (Constant *C = ConstantFoldInstruction(I, DL, TLI)) {
2748         DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
2749 
2750         // Add operands to the worklist.
2751         ReplaceInstUsesWith(*I, C);
2752         ++NumConstProp;
2753         EraseInstFromFunction(*I);
2754         MadeIRChange = true;
2755         continue;
2756       }
2757     }
2758 
2759     // In general, it is possible for computeKnownBits to determine all bits in a
2760     // value even when the operands are not all constants.
2761     if (!I->use_empty() && I->getType()->isIntegerTy()) {
2762       unsigned BitWidth = I->getType()->getScalarSizeInBits();
2763       APInt KnownZero(BitWidth, 0);
2764       APInt KnownOne(BitWidth, 0);
2765       computeKnownBits(I, KnownZero, KnownOne, /*Depth*/0, I);
2766       if ((KnownZero | KnownOne).isAllOnesValue()) {
2767         Constant *C = ConstantInt::get(I->getContext(), KnownOne);
2768         DEBUG(dbgs() << "IC: ConstFold (all bits known) to: " << *C <<
2769                         " from: " << *I << '\n');
2770 
2771         // Add operands to the worklist.
2772         ReplaceInstUsesWith(*I, C);
2773         ++NumConstProp;
2774         EraseInstFromFunction(*I);
2775         MadeIRChange = true;
2776         continue;
2777       }
2778     }
2779 
2780     // See if we can trivially sink this instruction to a successor basic block.
2781     if (I->hasOneUse()) {
2782       BasicBlock *BB = I->getParent();
2783       Instruction *UserInst = cast<Instruction>(*I->user_begin());
2784       BasicBlock *UserParent;
2785 
2786       // Get the block the use occurs in.
2787       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
2788         UserParent = PN->getIncomingBlock(*I->use_begin());
2789       else
2790         UserParent = UserInst->getParent();
2791 
2792       if (UserParent != BB) {
2793         bool UserIsSuccessor = false;
2794         // See if the user is one of our successors.
2795         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2796           if (*SI == UserParent) {
2797             UserIsSuccessor = true;
2798             break;
2799           }
2800 
2801         // If the user is one of our immediate successors, and if that successor
2802         // only has us as a predecessors (we'd have to split the critical edge
2803         // otherwise), we can keep going.
2804         if (UserIsSuccessor && UserParent->getSinglePredecessor()) {
2805           // Okay, the CFG is simple enough, try to sink this instruction.
2806           if (TryToSinkInstruction(I, UserParent)) {
2807             MadeIRChange = true;
2808             // We'll add uses of the sunk instruction below, but since sinking
2809             // can expose opportunities for it's *operands* add them to the
2810             // worklist
2811             for (Use &U : I->operands())
2812               if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
2813                 Worklist.Add(OpI);
2814           }
2815         }
2816       }
2817     }
2818 
2819     // Now that we have an instruction, try combining it to simplify it.
2820     Builder->SetInsertPoint(I);
2821     Builder->SetCurrentDebugLocation(I->getDebugLoc());
2822 
2823 #ifndef NDEBUG
2824     std::string OrigI;
2825 #endif
2826     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
2827     DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
2828 
2829     if (Instruction *Result = visit(*I)) {
2830       ++NumCombined;
2831       // Should we replace the old instruction with a new one?
2832       if (Result != I) {
2833         DEBUG(dbgs() << "IC: Old = " << *I << '\n'
2834                      << "    New = " << *Result << '\n');
2835 
2836         if (I->getDebugLoc())
2837           Result->setDebugLoc(I->getDebugLoc());
2838         // Everything uses the new instruction now.
2839         I->replaceAllUsesWith(Result);
2840 
2841         // Move the name to the new instruction first.
2842         Result->takeName(I);
2843 
2844         // Push the new instruction and any users onto the worklist.
2845         Worklist.Add(Result);
2846         Worklist.AddUsersToWorkList(*Result);
2847 
2848         // Insert the new instruction into the basic block...
2849         BasicBlock *InstParent = I->getParent();
2850         BasicBlock::iterator InsertPos = I->getIterator();
2851 
2852         // If we replace a PHI with something that isn't a PHI, fix up the
2853         // insertion point.
2854         if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2855           InsertPos = InstParent->getFirstInsertionPt();
2856 
2857         InstParent->getInstList().insert(InsertPos, Result);
2858 
2859         EraseInstFromFunction(*I);
2860       } else {
2861 #ifndef NDEBUG
2862         DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
2863                      << "    New = " << *I << '\n');
2864 #endif
2865 
2866         // If the instruction was modified, it's possible that it is now dead.
2867         // if so, remove it.
2868         if (isInstructionTriviallyDead(I, TLI)) {
2869           EraseInstFromFunction(*I);
2870         } else {
2871           Worklist.Add(I);
2872           Worklist.AddUsersToWorkList(*I);
2873         }
2874       }
2875       MadeIRChange = true;
2876     }
2877   }
2878 
2879   Worklist.Zap();
2880   return MadeIRChange;
2881 }
2882 
2883 /// Walk the function in depth-first order, adding all reachable code to the
2884 /// worklist.
2885 ///
2886 /// This has a couple of tricks to make the code faster and more powerful.  In
2887 /// particular, we constant fold and DCE instructions as we go, to avoid adding
2888 /// them to the worklist (this significantly speeds up instcombine on code where
2889 /// many instructions are dead or constant).  Additionally, if we find a branch
2890 /// whose condition is a known constant, we only visit the reachable successors.
2891 ///
2892 static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL,
2893                                        SmallPtrSetImpl<BasicBlock *> &Visited,
2894                                        InstCombineWorklist &ICWorklist,
2895                                        const TargetLibraryInfo *TLI) {
2896   bool MadeIRChange = false;
2897   SmallVector<BasicBlock*, 256> Worklist;
2898   Worklist.push_back(BB);
2899 
2900   SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
2901   DenseMap<ConstantExpr*, Constant*> FoldedConstants;
2902 
2903   do {
2904     BB = Worklist.pop_back_val();
2905 
2906     // We have now visited this block!  If we've already been here, ignore it.
2907     if (!Visited.insert(BB).second)
2908       continue;
2909 
2910     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
2911       Instruction *Inst = &*BBI++;
2912 
2913       // DCE instruction if trivially dead.
2914       if (isInstructionTriviallyDead(Inst, TLI)) {
2915         ++NumDeadInst;
2916         DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
2917         Inst->eraseFromParent();
2918         continue;
2919       }
2920 
2921       // ConstantProp instruction if trivially constant.
2922       if (!Inst->use_empty() &&
2923           (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0))))
2924         if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
2925           DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
2926                        << *Inst << '\n');
2927           Inst->replaceAllUsesWith(C);
2928           ++NumConstProp;
2929           Inst->eraseFromParent();
2930           continue;
2931         }
2932 
2933       // See if we can constant fold its operands.
2934       for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end(); i != e;
2935            ++i) {
2936         ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
2937         if (CE == nullptr)
2938           continue;
2939 
2940         Constant *&FoldRes = FoldedConstants[CE];
2941         if (!FoldRes)
2942           FoldRes = ConstantFoldConstantExpression(CE, DL, TLI);
2943         if (!FoldRes)
2944           FoldRes = CE;
2945 
2946         if (FoldRes != CE) {
2947           *i = FoldRes;
2948           MadeIRChange = true;
2949         }
2950       }
2951 
2952       InstrsForInstCombineWorklist.push_back(Inst);
2953     }
2954 
2955     // Recursively visit successors.  If this is a branch or switch on a
2956     // constant, only visit the reachable successor.
2957     TerminatorInst *TI = BB->getTerminator();
2958     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2959       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
2960         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
2961         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
2962         Worklist.push_back(ReachableBB);
2963         continue;
2964       }
2965     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2966       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
2967         // See if this is an explicit destination.
2968         for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
2969              i != e; ++i)
2970           if (i.getCaseValue() == Cond) {
2971             BasicBlock *ReachableBB = i.getCaseSuccessor();
2972             Worklist.push_back(ReachableBB);
2973             continue;
2974           }
2975 
2976         // Otherwise it is the default destination.
2977         Worklist.push_back(SI->getDefaultDest());
2978         continue;
2979       }
2980     }
2981 
2982     for (BasicBlock *SuccBB : TI->successors())
2983       Worklist.push_back(SuccBB);
2984   } while (!Worklist.empty());
2985 
2986   // Once we've found all of the instructions to add to instcombine's worklist,
2987   // add them in reverse order.  This way instcombine will visit from the top
2988   // of the function down.  This jives well with the way that it adds all uses
2989   // of instructions to the worklist after doing a transformation, thus avoiding
2990   // some N^2 behavior in pathological cases.
2991   ICWorklist.AddInitialGroup(InstrsForInstCombineWorklist);
2992 
2993   return MadeIRChange;
2994 }
2995 
2996 /// \brief Populate the IC worklist from a function, and prune any dead basic
2997 /// blocks discovered in the process.
2998 ///
2999 /// This also does basic constant propagation and other forward fixing to make
3000 /// the combiner itself run much faster.
3001 static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
3002                                           TargetLibraryInfo *TLI,
3003                                           InstCombineWorklist &ICWorklist) {
3004   bool MadeIRChange = false;
3005 
3006   // Do a depth-first traversal of the function, populate the worklist with
3007   // the reachable instructions.  Ignore blocks that are not reachable.  Keep
3008   // track of which blocks we visit.
3009   SmallPtrSet<BasicBlock *, 64> Visited;
3010   MadeIRChange |=
3011       AddReachableCodeToWorklist(&F.front(), DL, Visited, ICWorklist, TLI);
3012 
3013   // Do a quick scan over the function.  If we find any blocks that are
3014   // unreachable, remove any instructions inside of them.  This prevents
3015   // the instcombine code from having to deal with some bad special cases.
3016   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
3017     if (Visited.count(&*BB))
3018       continue;
3019 
3020     // Delete the instructions backwards, as it has a reduced likelihood of
3021     // having to update as many def-use and use-def chains.
3022     Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
3023     while (EndInst != BB->begin()) {
3024       // Delete the next to last instruction.
3025       Instruction *Inst = &*--EndInst->getIterator();
3026       if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
3027         Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
3028       if (Inst->isEHPad()) {
3029         EndInst = Inst;
3030         continue;
3031       }
3032       if (!isa<DbgInfoIntrinsic>(Inst)) {
3033         ++NumDeadInst;
3034         MadeIRChange = true;
3035       }
3036       if (!Inst->getType()->isTokenTy())
3037         Inst->eraseFromParent();
3038     }
3039   }
3040 
3041   return MadeIRChange;
3042 }
3043 
3044 static bool
3045 combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist,
3046                                 AliasAnalysis *AA, AssumptionCache &AC,
3047                                 TargetLibraryInfo &TLI, DominatorTree &DT,
3048                                 LoopInfo *LI = nullptr) {
3049   auto &DL = F.getParent()->getDataLayout();
3050 
3051   /// Builder - This is an IRBuilder that automatically inserts new
3052   /// instructions into the worklist when they are created.
3053   IRBuilder<true, TargetFolder, InstCombineIRInserter> Builder(
3054       F.getContext(), TargetFolder(DL), InstCombineIRInserter(Worklist, &AC));
3055 
3056   // Lower dbg.declare intrinsics otherwise their value may be clobbered
3057   // by instcombiner.
3058   bool DbgDeclaresChanged = LowerDbgDeclare(F);
3059 
3060   // Iterate while there is work to do.
3061   int Iteration = 0;
3062   for (;;) {
3063     ++Iteration;
3064     DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
3065                  << F.getName() << "\n");
3066 
3067     bool Changed = false;
3068     if (prepareICWorklistFromFunction(F, DL, &TLI, Worklist))
3069       Changed = true;
3070 
3071     InstCombiner IC(Worklist, &Builder, F.optForMinSize(),
3072                     AA, &AC, &TLI, &DT, DL, LI);
3073     if (IC.run())
3074       Changed = true;
3075 
3076     if (!Changed)
3077       break;
3078   }
3079 
3080   return DbgDeclaresChanged || Iteration > 1;
3081 }
3082 
3083 PreservedAnalyses InstCombinePass::run(Function &F,
3084                                        AnalysisManager<Function> *AM) {
3085   auto &AC = AM->getResult<AssumptionAnalysis>(F);
3086   auto &DT = AM->getResult<DominatorTreeAnalysis>(F);
3087   auto &TLI = AM->getResult<TargetLibraryAnalysis>(F);
3088 
3089   auto *LI = AM->getCachedResult<LoopAnalysis>(F);
3090 
3091   // FIXME: The AliasAnalysis is not yet supported in the new pass manager
3092   if (!combineInstructionsOverFunction(F, Worklist, nullptr, AC, TLI, DT, LI))
3093     // No changes, all analyses are preserved.
3094     return PreservedAnalyses::all();
3095 
3096   // Mark all the analyses that instcombine updates as preserved.
3097   // FIXME: Need a way to preserve CFG analyses here!
3098   PreservedAnalyses PA;
3099   PA.preserve<DominatorTreeAnalysis>();
3100   return PA;
3101 }
3102 
3103 namespace {
3104 /// \brief The legacy pass manager's instcombine pass.
3105 ///
3106 /// This is a basic whole-function wrapper around the instcombine utility. It
3107 /// will try to combine all instructions in the function.
3108 class InstructionCombiningPass : public FunctionPass {
3109   InstCombineWorklist Worklist;
3110 
3111 public:
3112   static char ID; // Pass identification, replacement for typeid
3113 
3114   InstructionCombiningPass() : FunctionPass(ID) {
3115     initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry());
3116   }
3117 
3118   void getAnalysisUsage(AnalysisUsage &AU) const override;
3119   bool runOnFunction(Function &F) override;
3120 };
3121 }
3122 
3123 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
3124   AU.setPreservesCFG();
3125   AU.addRequired<AAResultsWrapperPass>();
3126   AU.addRequired<AssumptionCacheTracker>();
3127   AU.addRequired<TargetLibraryInfoWrapperPass>();
3128   AU.addRequired<DominatorTreeWrapperPass>();
3129   AU.addPreserved<DominatorTreeWrapperPass>();
3130   AU.addPreserved<GlobalsAAWrapperPass>();
3131 }
3132 
3133 bool InstructionCombiningPass::runOnFunction(Function &F) {
3134   if (skipOptnoneFunction(F))
3135     return false;
3136 
3137   // Required analyses.
3138   auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3139   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3140   auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3141   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3142 
3143   // Optional analyses.
3144   auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3145   auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
3146 
3147   return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, LI);
3148 }
3149 
3150 char InstructionCombiningPass::ID = 0;
3151 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
3152                       "Combine redundant instructions", false, false)
3153 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3154 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3155 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3156 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3157 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3158 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
3159                     "Combine redundant instructions", false, false)
3160 
3161 // Initialization Routines
3162 void llvm::initializeInstCombine(PassRegistry &Registry) {
3163   initializeInstructionCombiningPassPass(Registry);
3164 }
3165 
3166 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
3167   initializeInstructionCombiningPassPass(*unwrap(R));
3168 }
3169 
3170 FunctionPass *llvm::createInstructionCombiningPass() {
3171   return new InstructionCombiningPass();
3172 }
3173