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