LLVM 19.0.0git
LowerConstantIntrinsics.cpp
Go to the documentation of this file.
1//===- LowerConstantIntrinsics.cpp - Lower constant intrinsic calls -------===//
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// This pass lowers all remaining 'objectsize' 'is.constant' intrinsic calls
10// and provides constant propagation and basic CFG cleanup on the result.
11//
12//===----------------------------------------------------------------------===//
13
16#include "llvm/ADT/SetVector.h"
17#include "llvm/ADT/Statistic.h"
23#include "llvm/IR/BasicBlock.h"
24#include "llvm/IR/Constants.h"
25#include "llvm/IR/Dominators.h"
26#include "llvm/IR/Function.h"
31#include "llvm/Pass.h"
32#include "llvm/Support/Debug.h"
35#include <optional>
36
37using namespace llvm;
38using namespace llvm::PatternMatch;
39
40#define DEBUG_TYPE "lower-is-constant-intrinsic"
41
42STATISTIC(IsConstantIntrinsicsHandled,
43 "Number of 'is.constant' intrinsic calls handled");
44STATISTIC(ObjectSizeIntrinsicsHandled,
45 "Number of 'objectsize' intrinsic calls handled");
46
48 if (auto *C = dyn_cast<Constant>(II->getOperand(0)))
49 if (C->isManifestConstant())
50 return ConstantInt::getTrue(II->getType());
51 return ConstantInt::getFalse(II->getType());
52}
53
55 Value *NewValue,
56 DomTreeUpdater *DTU) {
57 bool HasDeadBlocks = false;
58 SmallSetVector<Instruction *, 8> UnsimplifiedUsers;
59 replaceAndRecursivelySimplify(II, NewValue, nullptr, nullptr, nullptr,
60 &UnsimplifiedUsers);
61 // UnsimplifiedUsers can contain PHI nodes that may be removed when
62 // replacing the branch instructions, so use a value handle worklist
63 // to handle those possibly removed instructions.
64 SmallVector<WeakVH, 8> Worklist(UnsimplifiedUsers.begin(),
65 UnsimplifiedUsers.end());
66
67 for (auto &VH : Worklist) {
68 BranchInst *BI = dyn_cast_or_null<BranchInst>(VH);
69 if (!BI)
70 continue;
71 if (BI->isUnconditional())
72 continue;
73
75 if (match(BI->getOperand(0), m_Zero())) {
76 Target = BI->getSuccessor(1);
77 Other = BI->getSuccessor(0);
78 } else if (match(BI->getOperand(0), m_One())) {
79 Target = BI->getSuccessor(0);
80 Other = BI->getSuccessor(1);
81 } else {
82 Target = nullptr;
83 Other = nullptr;
84 }
85 if (Target && Target != Other) {
86 BasicBlock *Source = BI->getParent();
87 Other->removePredecessor(Source);
88
89 Instruction *NewBI = BranchInst::Create(Target, Source);
90 NewBI->setDebugLoc(BI->getDebugLoc());
91 BI->eraseFromParent();
92
93 if (DTU)
94 DTU->applyUpdates({{DominatorTree::Delete, Source, Other}});
95 if (pred_empty(Other))
96 HasDeadBlocks = true;
97 }
98 }
99 return HasDeadBlocks;
100}
101
103 DominatorTree *DT) {
104 std::optional<DomTreeUpdater> DTU;
105 if (DT)
106 DTU.emplace(DT, DomTreeUpdater::UpdateStrategy::Lazy);
107
108 bool HasDeadBlocks = false;
109 const auto &DL = F.getDataLayout();
111
113 for (BasicBlock *BB : RPOT) {
114 for (Instruction &I: *BB) {
115 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
116 if (!II)
117 continue;
118 switch (II->getIntrinsicID()) {
119 default:
120 break;
121 case Intrinsic::is_constant:
122 case Intrinsic::objectsize:
123 Worklist.push_back(WeakTrackingVH(&I));
124 break;
125 }
126 }
127 }
128 for (WeakTrackingVH &VH: Worklist) {
129 // Items on the worklist can be mutated by earlier recursive replaces.
130 // This can remove the intrinsic as dead (VH == null), but also replace
131 // the intrinsic in place.
132 if (!VH)
133 continue;
134 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&*VH);
135 if (!II)
136 continue;
137 Value *NewValue;
138 switch (II->getIntrinsicID()) {
139 default:
140 continue;
141 case Intrinsic::is_constant:
142 NewValue = lowerIsConstantIntrinsic(II);
143 LLVM_DEBUG(dbgs() << "Folding " << *II << " to " << *NewValue << "\n");
144 IsConstantIntrinsicsHandled++;
145 break;
146 case Intrinsic::objectsize:
147 NewValue = lowerObjectSizeCall(II, DL, &TLI, true);
148 LLVM_DEBUG(dbgs() << "Folding " << *II << " to " << *NewValue << "\n");
149 ObjectSizeIntrinsicsHandled++;
150 break;
151 }
153 II, NewValue, DTU ? &*DTU : nullptr);
154 }
155 if (HasDeadBlocks)
156 removeUnreachableBlocks(F, DTU ? &*DTU : nullptr);
157 return !Worklist.empty();
158}
159
166 return PA;
167 }
168
169 return PreservedAnalyses::all();
170}
171
172namespace {
173/// Legacy pass for lowering is.constant intrinsics out of the IR.
174///
175/// When this pass is run over a function it converts is.constant intrinsics
176/// into 'true' or 'false'. This complements the normal constant folding
177/// to 'true' as part of Instruction Simplify passes.
178class LowerConstantIntrinsics : public FunctionPass {
179public:
180 static char ID;
181 LowerConstantIntrinsics() : FunctionPass(ID) {
183 }
184
185 bool runOnFunction(Function &F) override {
186 const TargetLibraryInfo &TLI =
187 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
188 DominatorTree *DT = nullptr;
189 if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
190 DT = &DTWP->getDomTree();
191 return lowerConstantIntrinsics(F, TLI, DT);
192 }
193
194 void getAnalysisUsage(AnalysisUsage &AU) const override {
198 }
199};
200} // namespace
201
202char LowerConstantIntrinsics::ID = 0;
203INITIALIZE_PASS_BEGIN(LowerConstantIntrinsics, "lower-constant-intrinsics",
204 "Lower constant intrinsics", false, false)
207INITIALIZE_PASS_END(LowerConstantIntrinsics, "lower-constant-intrinsics",
209
211 return new LowerConstantIntrinsics();
212}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define LLVM_DEBUG(X)
Definition: Debug.h:101
std::optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1294
static bool runOnFunction(Function &F, bool PostInlining)
expand Expand reduction intrinsics
This is the interface for a simple mod/ref and alias analysis over globals.
static bool lowerConstantIntrinsics(Function &F, const TargetLibraryInfo &TLI, DominatorTree *DT)
static bool replaceConditionalBranchesOnConstant(Instruction *II, Value *NewValue, DomTreeUpdater *DTU)
static Value * lowerIsConstantIntrinsic(IntrinsicInst *II)
The header file for the LowerConstantIntrinsics pass as used by the new pass manager.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:55
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:59
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:52
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
This file implements a set that has insertion order iteration characteristics.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Definition: PassManager.h:424
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:405
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
Conditional or Unconditional Branch instruction.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:850
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:857
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:317
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:311
void applyUpdates(ArrayRef< typename DomTreeT::UpdateType > Updates)
Submit updates to all available trees.
Legacy wrapper pass to provide the GlobalsAAResult object.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:466
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:92
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:463
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:48
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
void preserve()
Mark an analysis as preserved.
Definition: Analysis.h:131
iterator end()
Get an iterator to the end of the SetVector.
Definition: SetVector.h:113
iterator begin()
Get an iterator to the beginning of the SetVector.
Definition: SetVector.h:103
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:370
bool empty() const
Definition: SmallVector.h:94
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
Target - Wrapper for Target specific information.
Value * getOperand(unsigned i) const
Definition: User.h:169
LLVM Value Representation.
Definition: Value.h:74
Value handle that is nullable, but tries to track the Value.
Definition: ValueHandle.h:204
const ParentTy * getParent() const
Definition: ilist_node.h:32
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
Definition: PatternMatch.h:592
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
Definition: PatternMatch.h:612
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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.
void initializeLowerConstantIntrinsicsPass(PassRegistry &)
bool replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI=nullptr, const DominatorTree *DT=nullptr, AssumptionCache *AC=nullptr, SmallSetVector< Instruction *, 8 > *UnsimplifiedUsers=nullptr)
Replace all uses of 'I' with 'SimpleV' and simplify the uses recursively.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
FunctionPass * createLowerConstantIntrinsicsPass()
bool pred_empty(const BasicBlock *BB)
Definition: CFG.h:118
bool removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Remove all blocks that can not be reached from the function's entry.
Definition: Local.cpp:3202
PreservedAnalyses run(Function &F, FunctionAnalysisManager &)
Run the pass over the function.