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