LLVM 23.0.0git
InstCombiner.h
Go to the documentation of this file.
1//===- InstCombiner.h - InstCombine implementation --------------*- C++ -*-===//
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/// \file
9///
10/// This file provides the interface for the instcombine pass implementation.
11/// The interface is used for generic transformations in this folder and
12/// target specific combinations in the targets.
13/// The visitor implementation is in \c InstCombinerImpl in
14/// \c InstCombineInternal.h.
15///
16//===----------------------------------------------------------------------===//
17
18#ifndef LLVM_TRANSFORMS_INSTCOMBINE_INSTCOMBINER_H
19#define LLVM_TRANSFORMS_INSTCOMBINE_INSTCOMBINER_H
20
26#include "llvm/IR/IRBuilder.h"
29#include "llvm/Support/Debug.h"
31#include <cassert>
32
33#define DEBUG_TYPE "instcombine"
35
36namespace llvm {
37
38class AAResults;
39class AssumptionCache;
40class OptimizationRemarkEmitter;
41class ProfileSummaryInfo;
42class TargetLibraryInfo;
43class TargetTransformInfo;
44
45/// The core instruction combiner logic.
46///
47/// This class provides both the logic to recursively visit instructions and
48/// combine them.
50 /// IRBuilder inserter that adds new instructions to the worklist and new
51 /// assumptions to the AssumptionCache.
52 class LLVM_ABI IRBuilderInstCombineInserter final
54 InstCombiner &IC;
55
56 public:
57 ~IRBuilderInstCombineInserter() override;
58 IRBuilderInstCombineInserter(InstCombiner &IC) : IC(IC) {}
59
60 void InsertHelper(Instruction *I, const Twine &Name,
61 BasicBlock::iterator InsertPt) const override;
62 };
63
64 /// Only used to call target specific intrinsic combining.
65 /// It must **NOT** be used for any other purpose, as InstCombine is a
66 /// target-independent canonicalization transform.
67 TargetTransformInfo &TTIForTargetIntrinsicsOnly;
68
69public:
70 /// Maximum size of array considered when transforming.
72
73 /// An IRBuilder that automatically inserts new instructions into the
74 /// worklist.
77
78protected:
79 /// A worklist of the instructions that need to be simplified.
81
83
84 // Mode in which we are running the combiner.
85 const bool MinimizeSize;
86
88
89 // Required analyses.
93 const DataLayout &DL;
100
102
103 bool MadeIRChange = false;
104
105 /// Edges that are known to never be taken.
107
108 /// Order of predecessors to canonicalize phi nodes towards.
110
111 /// Backedges, used to avoid pushing instructions across backedges in cases
112 /// where this may result in infinite combine loops. For irreducible loops
113 /// this picks an arbitrary backedge.
115 bool ComputedBackEdges = false;
116
117 /// Source for annotation metadata, used by the IRBuilder inserter.
119
120public:
126 const DataLayout &DL,
128 : TTIForTargetIntrinsicsOnly(TTI),
129 Builder(F.getContext(), TargetFolder(DL),
130 IRBuilderInstCombineInserter(*this)),
131 Worklist(Worklist), F(F), MinimizeSize(F.hasMinSize()), AA(AA), AC(AC),
132 TLI(TLI), DT(DT), DL(DL),
133 SQ(DL, &TLI, &DT, &AC, nullptr, /*UseInstrInfo*/ true,
134 /*CanUseUndef*/ true, &DC),
135 ORE(ORE), BFI(BFI), BPI(BPI), PSI(PSI), RPOT(RPOT) {}
136
137 virtual ~InstCombiner() = default;
138
139 /// Return the source operand of a potentially bitcasted value while
140 /// optionally checking if it has one use. If there is no bitcast or the one
141 /// use check is not met, return the input value itself.
142 static Value *peekThroughBitcast(Value *V, bool OneUseOnly = false) {
143 if (auto *BitCast = dyn_cast<BitCastInst>(V))
144 if (!OneUseOnly || BitCast->hasOneUse())
145 return BitCast->getOperand(0);
146
147 // V is not a bitcast or V has more than one use and OneUseOnly is true.
148 return V;
149 }
150
151 /// Assign a complexity or rank value to LLVM Values. This is used to reduce
152 /// the amount of pattern matching needed for compares and commutative
153 /// instructions. For example, if we have:
154 /// icmp ugt X, Constant
155 /// or
156 /// xor (add X, Constant), cast Z
157 ///
158 /// We do not have to consider the commuted variants of these patterns because
159 /// canonicalization based on complexity guarantees the above ordering.
160 ///
161 /// This routine maps IR values to various complexity ranks:
162 /// 0 -> undef
163 /// 1 -> Constants
164 /// 2 -> Cast and (f)neg/not instructions
165 /// 3 -> Other instructions and arguments
166 static unsigned getComplexity(Value *V) {
167 if (isa<Constant>(V))
168 return isa<UndefValue>(V) ? 0 : 1;
169
170 using namespace llvm::PatternMatch;
171 if (isa<CastInst>(V) || match(V, m_Neg(m_Value())) ||
172 match(V, m_Not(m_Value())) || match(V, m_FNeg(m_Value())))
173 return 2;
174
175 return 3;
176 }
177
178 /// Predicate canonicalization reduces the number of patterns that need to be
179 /// matched by other transforms. For example, we may swap the operands of a
180 /// conditional branch or select to create a compare with a canonical
181 /// (inverted) predicate which is then more likely to be matched with other
182 /// values.
184 switch (Pred) {
185 case CmpInst::ICMP_NE:
190 // TODO: There are 16 FCMP predicates. Should others be (not) canonical?
194 return false;
195 default:
196 return true;
197 }
198 }
199
200 /// Add one to a Constant
202 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
203 }
204
205 /// Subtract one from a Constant
207 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
208 }
209
211 // a ? b : false and a ? true : b are the canonical form of logical and/or.
212 // This includes !a ? b : false and !a ? true : b. Absorbing the not into
213 // the select by swapping operands would break recognition of this pattern
214 // in other analyses, so don't do that.
219 }
220
221 /// Return nonnull value if V is free to invert under the condition of
222 /// WillInvertAllUses.
223 /// If Builder is nonnull, it will return a simplified ~V.
224 /// If Builder is null, it will return an arbitrary nonnull value (not
225 /// dereferenceable).
226 /// If the inversion will consume instructions, `DoesConsume` will be set to
227 /// true. Otherwise it will be false.
228 LLVM_ABI Value *getFreelyInvertedImpl(Value *V, bool WillInvertAllUses,
229 BuilderTy *Builder, bool &DoesConsume,
230 unsigned Depth);
231
232 Value *getFreelyInverted(Value *V, bool WillInvertAllUses,
233 BuilderTy *Builder, bool &DoesConsume) {
234 DoesConsume = false;
235 return getFreelyInvertedImpl(V, WillInvertAllUses, Builder, DoesConsume,
236 /*Depth*/ 0);
237 }
238
239 Value *getFreelyInverted(Value *V, bool WillInvertAllUses,
241 bool Unused;
242 return getFreelyInverted(V, WillInvertAllUses, Builder, Unused);
243 }
244
245 /// Return true if the specified value is free to invert (apply ~ to).
246 /// This happens in cases where the ~ can be eliminated. If WillInvertAllUses
247 /// is true, work under the assumption that the caller intends to remove all
248 /// uses of V and only keep uses of ~V.
249 ///
250 /// See also: canFreelyInvertAllUsersOf()
251 bool isFreeToInvert(Value *V, bool WillInvertAllUses,
252 bool &DoesConsume) {
253 return getFreelyInverted(V, WillInvertAllUses, /*Builder*/ nullptr,
254 DoesConsume) != nullptr;
255 }
256
257 bool isFreeToInvert(Value *V, bool WillInvertAllUses) {
258 bool Unused;
259 return isFreeToInvert(V, WillInvertAllUses, Unused);
260 }
261
262 /// Given i1 V, can every user of V be freely adapted if V is changed to !V ?
263 /// InstCombine's freelyInvertAllUsersOf() must be kept in sync with this fn.
264 /// NOTE: for Instructions only!
265 ///
266 /// See also: isFreeToInvert()
268 // Look at every user of V.
269 for (Use &U : V->uses()) {
270 if (U.getUser() == IgnoredUser)
271 continue; // Don't consider this user.
272
273 auto *I = cast<Instruction>(U.getUser());
274 switch (I->getOpcode()) {
275 case Instruction::Select:
276 if (U.getOperandNo() != 0) // Only if the value is used as select cond.
277 return false;
279 return false;
280 break;
281 case Instruction::CondBr:
282 assert(U.getOperandNo() == 0 && "Must be branching on that value.");
283 break; // Free to invert by swapping true/false values/destinations.
284 case Instruction::Xor: // Can invert 'xor' if it's a 'not', by ignoring
285 // it.
287 return false; // Not a 'not'.
288 break;
289 default:
290 return false; // Don't know, likely not freely invertible.
291 }
292 // So far all users were free to invert...
293 }
294 return true; // Can freely invert all users!
295 }
296
297 /// Some binary operators require special handling to avoid poison and
298 /// undefined behavior. If a constant vector has undef elements, replace those
299 /// undefs with identity constants if possible because those are always safe
300 /// to execute. If no identity constant exists, replace undef with some other
301 /// safe constant.
302 static Constant *
304 bool IsRHSConstant) {
305 auto *InVTy = cast<FixedVectorType>(In->getType());
306
307 Type *EltTy = InVTy->getElementType();
308 auto *SafeC = ConstantExpr::getBinOpIdentity(Opcode, EltTy, IsRHSConstant);
309 if (!SafeC) {
310 // TODO: Should this be available as a constant utility function? It is
311 // similar to getBinOpAbsorber().
312 if (IsRHSConstant) {
313 switch (Opcode) {
314 case Instruction::SRem: // X % 1 = 0
315 case Instruction::URem: // X %u 1 = 0
316 SafeC = ConstantInt::get(EltTy, 1);
317 break;
318 case Instruction::FRem: // X % 1.0 (doesn't simplify, but it is safe)
319 SafeC = ConstantFP::get(EltTy, 1.0);
320 break;
321 default:
323 "Only rem opcodes have no identity constant for RHS");
324 }
325 } else {
326 switch (Opcode) {
327 case Instruction::Shl: // 0 << X = 0
328 case Instruction::LShr: // 0 >>u X = 0
329 case Instruction::AShr: // 0 >> X = 0
330 case Instruction::SDiv: // 0 / X = 0
331 case Instruction::UDiv: // 0 /u X = 0
332 case Instruction::SRem: // 0 % X = 0
333 case Instruction::URem: // 0 %u X = 0
334 case Instruction::Sub: // 0 - X (doesn't simplify, but it is safe)
335 case Instruction::FSub: // 0.0 - X (doesn't simplify, but it is safe)
336 case Instruction::FDiv: // 0.0 / X (doesn't simplify, but it is safe)
337 case Instruction::FRem: // 0.0 % X = 0
338 SafeC = Constant::getNullValue(EltTy);
339 break;
340 default:
341 llvm_unreachable("Expected to find identity constant for opcode");
342 }
343 }
344 }
345 assert(SafeC && "Must have safe constant for binop");
346 unsigned NumElts = InVTy->getNumElements();
347 SmallVector<Constant *, 16> Out(NumElts);
348 for (unsigned i = 0; i != NumElts; ++i) {
349 Constant *C = In->getAggregateElement(i);
350 Out[i] = isa<UndefValue>(C) ? SafeC : C;
351 }
352 return ConstantVector::get(Out);
353 }
354
355 /// Ignore all operations which only change the sign of a value, returning the
356 /// underlying magnitude value.
358 using namespace llvm::PatternMatch;
359
360 match(Val, m_FNeg(m_Value(Val)));
361 match(Val, m_FAbs(m_Value(Val)));
362 match(Val, m_CopySign(m_Value(Val), m_Value()));
363 return Val;
364 }
365
367
370 DominatorTree &getDominatorTree() const { return DT; }
371 const DataLayout &getDataLayout() const { return DL; }
372 const SimplifyQuery &getSimplifyQuery() const { return SQ; }
378
379 // Call target specific combiners
380 LLVM_ABI std::optional<Instruction *>
381 targetInstCombineIntrinsic(IntrinsicInst &II);
382 LLVM_ABI std::optional<Value *>
383 targetSimplifyDemandedUseBitsIntrinsic(IntrinsicInst &II, APInt DemandedMask,
384 KnownBits &Known,
385 bool &KnownBitsComputed);
386 LLVM_ABI std::optional<Value *> targetSimplifyDemandedVectorEltsIntrinsic(
387 IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts,
388 APInt &UndefElts2, APInt &UndefElts3,
389 std::function<void(Instruction *, unsigned, APInt, APInt &)>
390 SimplifyAndSetOp);
391
392 LLVM_ABI void computeBackEdges();
393 bool isBackEdge(const BasicBlock *From, const BasicBlock *To) {
396 return BackEdges.contains({From, To});
397 }
398
399 /// Inserts an instruction \p New before instruction \p Old
400 ///
401 /// Also adds the new instruction to the worklist and returns \p New so that
402 /// it is suitable for use as the return from the visitation patterns.
404 assert(New && !New->getParent() &&
405 "New instruction already inserted into a basic block!");
406 New->insertBefore(Old); // Insert inst
407 Worklist.add(New);
408 return New;
409 }
410
411 /// Same as InsertNewInstBefore, but also sets the debug loc.
413 New->setDebugLoc(Old->getDebugLoc());
414 return InsertNewInstBefore(New, Old);
415 }
416
417 /// A combiner-aware RAUW-like routine.
418 ///
419 /// This method is to be used when an instruction is found to be dead,
420 /// replaceable with another preexisting expression. Here we add all uses of
421 /// I to the worklist, replace all uses of I with the new value, then return
422 /// I, so that the inst combiner will know that I was modified.
424 // If there are no uses to replace, then we return nullptr to indicate that
425 // no changes were made to the program.
426 if (I.use_empty()) return nullptr;
427
428 Worklist.pushUsersToWorkList(I); // Add all modified instrs to worklist.
429
430 // If we are replacing the instruction with itself, this must be in a
431 // segment of unreachable code, so just clobber the instruction.
432 if (&I == V)
433 V = PoisonValue::get(I.getType());
434
435 LLVM_DEBUG(dbgs() << "IC: Replacing " << I << "\n"
436 << " with " << *V << '\n');
437
438 // If V is a new unnamed instruction, take the name from the old one.
439 if (V->use_empty() && isa<Instruction>(V) && !V->hasName() && I.hasName())
440 V->takeName(&I);
441
442 I.replaceAllUsesWith(V);
443 return &I;
444 }
445
446 /// Replace operand of instruction and add old operand to the worklist.
448 Value *OldOp = I.getOperand(OpNum);
449 I.setOperand(OpNum, V);
450 Worklist.handleUseCountDecrement(OldOp);
451 return &I;
452 }
453
454 /// Replace use and add the previously used value to the worklist.
455 void replaceUse(Use &U, Value *NewValue) {
456 Value *OldOp = U;
457 U = NewValue;
458 Worklist.handleUseCountDecrement(OldOp);
459 }
460
461 /// Combiner aware instruction erasure.
462 ///
463 /// When dealing with an instruction that has side effects or produces a void
464 /// value, we can't rely on DCE to delete the instruction. Instead, visit
465 /// methods should return the value returned by this function.
467
468 void computeKnownBits(const Value *V, KnownBits &Known,
469 const Instruction *CxtI, unsigned Depth = 0) const {
470 llvm::computeKnownBits(V, Known, SQ.getWithInstruction(CxtI), Depth);
471 }
472
474 unsigned Depth = 0) const {
475 return llvm::computeKnownBits(V, SQ.getWithInstruction(CxtI), Depth);
476 }
477
478 bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero = false,
479 const Instruction *CxtI = nullptr,
480 unsigned Depth = 0) {
481 return llvm::isKnownToBeAPowerOfTwo(V, OrZero, SQ.getWithInstruction(CxtI),
482 Depth);
483 }
484
485 bool MaskedValueIsZero(const Value *V, const APInt &Mask,
486 const Instruction *CxtI = nullptr,
487 unsigned Depth = 0) const {
488 return llvm::MaskedValueIsZero(V, Mask, SQ.getWithInstruction(CxtI), Depth);
489 }
490
491 unsigned ComputeNumSignBits(const Value *Op,
492 const Instruction *CxtI = nullptr,
493 unsigned Depth = 0) const {
494 return llvm::ComputeNumSignBits(Op, DL, &AC, CxtI, &DT, Depth);
495 }
496
498 const Instruction *CxtI = nullptr,
499 unsigned Depth = 0) const {
500 return llvm::ComputeMaxSignificantBits(Op, DL, &AC, CxtI, &DT, Depth);
501 }
502
503 /// Return true if the cast from integer to FP can be proven to be exact
504 /// for all possible inputs (the conversion does not lose any precision).
505 LLVM_ABI bool isKnownExactCastIntToFP(CastInst &I) const;
506 LLVM_ABI bool
507 canBeCastedExactlyIntToFP(Value *V, Type *FPTy, bool IsSigned,
508 const Instruction *CxtI = nullptr) const;
509
511 const Value *RHS,
512 const Instruction *CxtI,
513 bool IsNSW = false) const {
515 LHS, RHS, SQ.getWithInstruction(CxtI), IsNSW);
516 }
517
519 const Instruction *CxtI) const {
520 return llvm::computeOverflowForSignedMul(LHS, RHS,
521 SQ.getWithInstruction(CxtI));
522 }
523
526 const WithCache<const Value *> &RHS,
527 const Instruction *CxtI) const {
529 SQ.getWithInstruction(CxtI));
530 }
531
534 const WithCache<const Value *> &RHS,
535 const Instruction *CxtI) const {
536 return llvm::computeOverflowForSignedAdd(LHS, RHS,
537 SQ.getWithInstruction(CxtI));
538 }
539
541 const Value *RHS,
542 const Instruction *CxtI) const {
544 SQ.getWithInstruction(CxtI));
545 }
546
548 const Instruction *CxtI) const {
549 return llvm::computeOverflowForSignedSub(LHS, RHS,
550 SQ.getWithInstruction(CxtI));
551 }
552
553 virtual bool SimplifyDemandedBits(Instruction *I, unsigned OpNo,
554 const APInt &DemandedMask, KnownBits &Known,
555 const SimplifyQuery &Q,
556 unsigned Depth = 0) = 0;
557
558 bool SimplifyDemandedBits(Instruction *I, unsigned OpNo,
559 const APInt &DemandedMask, KnownBits &Known) {
560 return SimplifyDemandedBits(I, OpNo, DemandedMask, Known,
561 SQ.getWithInstruction(I));
562 }
563
564 virtual Value *
565 SimplifyDemandedVectorElts(Value *V, APInt DemandedElts, APInt &UndefElts,
566 unsigned Depth = 0,
567 bool AllowMultipleUsers = false) = 0;
568
569 LLVM_ABI bool isValidAddrSpaceCast(unsigned FromAS, unsigned ToAS) const;
570};
571
572} // namespace llvm
573
574#undef DEBUG_TYPE
575
576#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition Compiler.h:213
#define LLVM_LIBRARY_VISIBILITY
Definition Compiler.h:137
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Class for arbitrary precision integers.
Definition APInt.h:78
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Analysis providing branch probability information.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:748
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary opcode.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:151
This provides the default implementation of the IRBuilder 'InsertHelper' method that is called whenev...
Definition IRBuilder.h:61
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2868
OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const Instruction *CxtI) const
SimplifyQuery SQ
const DataLayout & getDataLayout() const
unsigned ComputeMaxSignificantBits(const Value *Op, const Instruction *CxtI=nullptr, unsigned Depth=0) const
bool isFreeToInvert(Value *V, bool WillInvertAllUses)
virtual Instruction * eraseInstFromFunction(Instruction &I)=0
Combiner aware instruction erasure.
bool isFreeToInvert(Value *V, bool WillInvertAllUses, bool &DoesConsume)
Return true if the specified value is free to invert (apply ~ to).
DominatorTree & getDominatorTree() const
OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const Instruction *CxtI, bool IsNSW=false) const
virtual ~InstCombiner()=default
BlockFrequencyInfo * BFI
static unsigned getComplexity(Value *V)
Assign a complexity or rank value to LLVM Values.
SmallDenseMap< BasicBlock *, SmallVector< BasicBlock * >, 8 > PredOrder
Order of predecessors to canonicalize phi nodes towards.
TargetLibraryInfo & TLI
TargetLibraryInfo & getTargetLibraryInfo() const
unsigned ComputeNumSignBits(const Value *Op, const Instruction *CxtI=nullptr, unsigned Depth=0) const
BlockFrequencyInfo * getBlockFrequencyInfo() const
Instruction * InsertNewInstBefore(Instruction *New, BasicBlock::iterator Old)
Inserts an instruction New before instruction Old.
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
uint64_t MaxArraySizeForCombine
Maximum size of array considered when transforming.
static bool shouldAvoidAbsorbingNotIntoSelect(const SelectInst &SI)
OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const Instruction *CxtI) const
static Constant * SubOne(Constant *C)
Subtract one from a Constant.
void replaceUse(Use &U, Value *NewValue)
Replace use and add the previously used value to the worklist.
OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const Instruction *CxtI) const
static bool isCanonicalPredicate(CmpPredicate Pred)
Predicate canonicalization reduces the number of patterns that need to be matched by other transforms...
Instruction * AnnotationMetadataSource
Source for annotation metadata, used by the IRBuilder inserter.
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
Instruction * InsertNewInstWith(Instruction *New, BasicBlock::iterator Old)
Same as InsertNewInstBefore, but also sets the debug loc.
BranchProbabilityInfo * BPI
bool SimplifyDemandedBits(Instruction *I, unsigned OpNo, const APInt &DemandedMask, KnownBits &Known)
InstCombiner(InstructionWorklist &Worklist, Function &F, AAResults *AA, AssumptionCache &AC, TargetLibraryInfo &TLI, TargetTransformInfo &TTI, DominatorTree &DT, OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI, BranchProbabilityInfo *BPI, ProfileSummaryInfo *PSI, const DataLayout &DL, ReversePostOrderTraversal< BasicBlock * > &RPOT)
virtual bool SimplifyDemandedBits(Instruction *I, unsigned OpNo, const APInt &DemandedMask, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)=0
ReversePostOrderTraversal< BasicBlock * > & RPOT
const DataLayout & DL
DomConditionCache DC
const bool MinimizeSize
void computeKnownBits(const Value *V, KnownBits &Known, const Instruction *CxtI, unsigned Depth=0) const
virtual Value * SimplifyDemandedVectorElts(Value *V, APInt DemandedElts, APInt &UndefElts, unsigned Depth=0, bool AllowMultipleUsers=false)=0
static Value * peekThroughBitcast(Value *V, bool OneUseOnly=false)
Return the source operand of a potentially bitcasted value while optionally checking if it has one us...
KnownBits computeKnownBits(const Value *V, const Instruction *CxtI, unsigned Depth=0) const
IRBuilder< TargetFolder, IRBuilderInstCombineInserter > BuilderTy
An IRBuilder that automatically inserts new instructions into the worklist.
bool canFreelyInvertAllUsersOf(Instruction *V, Value *IgnoredUser)
Given i1 V, can every user of V be freely adapted if V is changed to !V ?
Value * getFreelyInverted(Value *V, bool WillInvertAllUses, BuilderTy *Builder)
AssumptionCache & AC
void addToWorklist(Instruction *I)
LLVM_ABI Value * getFreelyInvertedImpl(Value *V, bool WillInvertAllUses, BuilderTy *Builder, bool &DoesConsume, unsigned Depth)
Return nonnull value if V is free to invert under the condition of WillInvertAllUses.
static Value * stripSignOnlyFPOps(Value *Val)
Ignore all operations which only change the sign of a value, returning the underlying magnitude value...
SmallDenseSet< std::pair< const BasicBlock *, const BasicBlock * >, 8 > BackEdges
Backedges, used to avoid pushing instructions across backedges in cases where this may result in infi...
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
bool MaskedValueIsZero(const Value *V, const APInt &Mask, const Instruction *CxtI=nullptr, unsigned Depth=0) const
DominatorTree & DT
static Constant * getSafeVectorConstantForBinop(BinaryOperator::BinaryOps Opcode, Constant *In, bool IsRHSConstant)
Some binary operators require special handling to avoid poison and undefined behavior.
OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const Instruction *CxtI) const
ProfileSummaryInfo * getProfileSummaryInfo() const
OptimizationRemarkEmitter & getOptimizationRemarkEmitter() const
ProfileSummaryInfo * PSI
SmallDenseSet< std::pair< BasicBlock *, BasicBlock * >, 8 > DeadEdges
Edges that are known to never be taken.
AssumptionCache & getAssumptionCache() const
OptimizationRemarkEmitter & ORE
LLVM_ABI bool isValidAddrSpaceCast(unsigned FromAS, unsigned ToAS) const
OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const Instruction *CxtI) const
Value * getFreelyInverted(Value *V, bool WillInvertAllUses, BuilderTy *Builder, bool &DoesConsume)
const SimplifyQuery & getSimplifyQuery() const
bool isBackEdge(const BasicBlock *From, const BasicBlock *To)
static Constant * AddOne(Constant *C)
Add one to a Constant.
bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero=false, const Instruction *CxtI=nullptr, unsigned Depth=0)
InstructionWorklist - This is the worklist management logic for InstCombine and other simplification ...
A wrapper class for inspecting calls to intrinsic functions.
The optimization diagnostic interface.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Analysis providing profile information.
This class represents the LLVM 'select' instruction.
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:301
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetFolder - Create constants with target dependent folding.
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
iterator_range< use_iterator > uses()
Definition Value.h:380
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
LogicalOp_match< LHS, RHS, Instruction::And > m_LogicalAnd(const LHS &L, const RHS &R)
Matches L && R either in the form of L & R or L ?
bool match(Val *V, const Pattern &P)
auto m_Value()
Match an arbitrary value and ignore it.
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
LogicalOp_match< LHS, RHS, Instruction::Or > m_LogicalOr(const LHS &L, const RHS &R)
Matches L || R either in the form of L | R or L ?
BinaryOp_match< cst_pred_ty< is_all_ones >, ValTy, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
m_Intrinsic_Ty< Opnd0 >::Ty m_FAbs(const Opnd0 &Op0)
m_Intrinsic_Ty< Opnd0, Opnd1 >::Ty m_CopySign(const Opnd0 &Op0, const Opnd1 &Op1)
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
LLVM_ABI OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ, bool IsNSW=false)
LLVM_ABI OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
TargetTransformInfo TTI
LLVM_ABI OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
DWARFExpression::Operation Op
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
LLVM_ABI OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Get the upper bound on bit size for this Value Op as a signed integer.
LLVM_ABI OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.