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