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