LLVM 23.0.0git
InlineAsmPrepare.cpp
Go to the documentation of this file.
1//===-- InlineAsmPrepare - Prepare inline asm for code gen ----------------===//
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 callbrs in LLVM IR in order to to assist SelectionDAG's
10// codegen.
11//
12// In particular, this pass assists in inserting register copies for the output
13// values of a callbr along the edges leading to the indirect target blocks.
14// Though the output SSA value is defined by the callbr instruction itself in
15// the IR representation, the value cannot be copied to the appropriate virtual
16// registers prior to jumping to an indirect label, since the jump occurs
17// within the user-provided assembly blob.
18//
19// Instead, those copies must occur separately at the beginning of each
20// indirect target. That requires that we create a separate SSA definition in
21// each of them (via llvm.callbr.landingpad), and may require splitting
22// critical edges so we have a location to place the intrinsic. Finally, we
23// remap users of the original callbr output SSA value to instead point to the
24// appropriate llvm.callbr.landingpad value.
25//
26// Ideally, this could be done inside SelectionDAG, or in the
27// MachineInstruction representation, without the use of an IR-level intrinsic.
28// But, within the current framework, it’s simpler to implement as an IR pass.
29// (If support for callbr in GlobalISel is implemented, it’s worth considering
30// whether this is still required.)
31//
32//===----------------------------------------------------------------------===//
33
35#include "llvm/ADT/ArrayRef.h"
38#include "llvm/ADT/iterator.h"
39#include "llvm/Analysis/CFG.h"
40#include "llvm/CodeGen/Passes.h"
41#include "llvm/IR/BasicBlock.h"
42#include "llvm/IR/Dominators.h"
43#include "llvm/IR/Function.h"
44#include "llvm/IR/IRBuilder.h"
47#include "llvm/IR/Intrinsics.h"
49#include "llvm/Pass.h"
52
53using namespace llvm;
54
55#define DEBUG_TYPE "inline-asm-prepare"
56
59 DominatorTree &DT);
61 SSAUpdater &SSAUpdate);
63
64namespace {
65
66class InlineAsmPrepare : public FunctionPass {
67public:
68 InlineAsmPrepare() : FunctionPass(ID) {}
69 void getAnalysisUsage(AnalysisUsage &AU) const override;
70 bool runOnFunction(Function &F) override;
71 static char ID;
72};
73
74} // end anonymous namespace
75
78 bool Changed = false;
80
81 if (CBRs.empty())
83
84 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
85
86 Changed |= SplitCriticalEdges(CBRs, DT);
87 Changed |= InsertIntrinsicCalls(CBRs, DT);
88
89 if (!Changed)
93 return PA;
94}
95
96char InlineAsmPrepare::ID = 0;
97INITIALIZE_PASS_BEGIN(InlineAsmPrepare, "inline-asm-prepare",
98 "Prepare inline asm insts", false, false)
100INITIALIZE_PASS_END(InlineAsmPrepare, "inline-asm-prepare",
101 "Prepare inline asm insts", false, false)
102
104 return new InlineAsmPrepare();
105}
106
107void InlineAsmPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
109}
110
113 for (BasicBlock &BB : F)
114 if (auto *CBR = dyn_cast<CallBrInst>(BB.getTerminator()))
115 if (!CBR->getType()->isVoidTy() && !CBR->use_empty())
116 CBRs.push_back(CBR);
117 return CBRs;
118}
119
121 bool Changed = false;
123 Options.setMergeIdenticalEdges();
124
125 // The indirect destination might be duplicated between another parameter...
126 // %0 = callbr ... [label %x, label %x]
127 // ...hence MergeIdenticalEdges and AllowIndentical edges, but we don't need
128 // to split the default destination if it's duplicated between an indirect
129 // destination...
130 // %1 = callbr ... to label %x [label %x]
131 // ...hence starting at 1 and checking against successor 0 (aka the default
132 // destination).
133 for (CallBrInst *CBR : CBRs)
134 for (unsigned i = 1, e = CBR->getNumSuccessors(); i != e; ++i)
135 if (CBR->getSuccessor(i) == CBR->getSuccessor(0) ||
136 isCriticalEdge(CBR, i, /*AllowIdenticalEdges*/ true))
137 if (SplitKnownCriticalEdge(CBR, i, Options))
138 Changed = true;
139 return Changed;
140}
141
143 bool Changed = false;
145 IRBuilder<> Builder(CBRs[0]->getContext());
146 for (CallBrInst *CBR : CBRs) {
147 if (!CBR->getNumIndirectDests())
148 continue;
149
150 SSAUpdater SSAUpdate;
151 SSAUpdate.Initialize(CBR->getType(), CBR->getName());
152 SSAUpdate.AddAvailableValue(CBR->getParent(), CBR);
153 SSAUpdate.AddAvailableValue(CBR->getDefaultDest(), CBR);
154
155 for (BasicBlock *IndDest : CBR->getIndirectDests()) {
156 if (!Visited.insert(IndDest).second)
157 continue;
158 Builder.SetInsertPoint(&*IndDest->begin());
159 CallInst *Intrinsic = Builder.CreateIntrinsic(
160 CBR->getType(), Intrinsic::callbr_landingpad, {CBR});
161 SSAUpdate.AddAvailableValue(IndDest, Intrinsic);
162 UpdateSSA(DT, CBR, Intrinsic, SSAUpdate);
163 Changed = true;
164 }
165 }
166 return Changed;
167}
168
169static bool IsInSameBasicBlock(const Use &U, const BasicBlock *BB) {
170 const auto *I = dyn_cast<Instruction>(U.getUser());
171 return I && I->getParent() == BB;
172}
173
174#ifndef NDEBUG
175static void PrintDebugDomInfo(const DominatorTree &DT, const Use &U,
176 const BasicBlock *BB, bool IsDefaultDest) {
177 if (!isa<Instruction>(U.getUser()))
178 return;
179 LLVM_DEBUG(dbgs() << "Use: " << *U.getUser() << ", in block "
180 << cast<Instruction>(U.getUser())->getParent()->getName()
181 << ", is " << (DT.dominates(BB, U) ? "" : "NOT ")
182 << "dominated by " << BB->getName() << " ("
183 << (IsDefaultDest ? "in" : "") << "direct)\n");
184}
185#endif
186
188 SSAUpdater &SSAUpdate) {
189
190 SmallPtrSet<Use *, 4> Visited;
191 BasicBlock *DefaultDest = CBR->getDefaultDest();
192 BasicBlock *LandingPad = Intrinsic->getParent();
193
195 for (Use *U : Uses) {
196 if (!Visited.insert(U).second)
197 continue;
198
199#ifndef NDEBUG
200 PrintDebugDomInfo(DT, *U, LandingPad, /*IsDefaultDest*/ false);
201 PrintDebugDomInfo(DT, *U, DefaultDest, /*IsDefaultDest*/ true);
202#endif
203
204 // Don't rewrite the use in the newly inserted intrinsic.
205 if (const auto *II = dyn_cast<IntrinsicInst>(U->getUser()))
206 if (II->getIntrinsicID() == Intrinsic::callbr_landingpad)
207 continue;
208
209 // If the Use is in the same BasicBlock as the Intrinsic call, replace
210 // the Use with the value of the Intrinsic call.
211 if (IsInSameBasicBlock(*U, LandingPad)) {
212 U->set(Intrinsic);
213 continue;
214 }
215
216 // If the Use is dominated by the default dest, do not touch it.
217 if (DT.dominates(DefaultDest, *U))
218 continue;
219
220 SSAUpdate.RewriteUse(*U);
221 }
222}
223
224bool InlineAsmPrepare::runOnFunction(Function &F) {
225 bool Changed = false;
227
228 if (CBRs.empty())
229 return Changed;
230
231 // It's highly likely that most programs do not contain CallBrInsts. Follow a
232 // similar pattern from SafeStackLegacyPass::runOnFunction to reuse previous
233 // domtree analysis if available, otherwise compute it lazily. This avoids
234 // forcing Dominator Tree Construction at -O0 for programs that likely do not
235 // contain CallBrInsts. It does pessimize programs with callbr at higher
236 // optimization levels, as the DominatorTree created here is not reused by
237 // subsequent passes.
238 DominatorTree *DT;
239 std::optional<DominatorTree> LazilyComputedDomTree;
240 if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
241 DT = &DTWP->getDomTree();
242 else {
243 LazilyComputedDomTree.emplace(F);
244 DT = &*LazilyComputedDomTree;
245 }
246
247 if (SplitCriticalEdges(CBRs, *DT))
248 Changed = true;
249
250 if (InsertIntrinsicCalls(CBRs, *DT))
251 Changed = true;
252
253 return Changed;
254}
static bool runOnFunction(Function &F, bool PostInlining)
static bool InsertIntrinsicCalls(ArrayRef< CallBrInst * > CBRs, DominatorTree &DT)
static bool SplitCriticalEdges(ArrayRef< CallBrInst * > CBRs, DominatorTree &DT)
static SmallVector< CallBrInst *, 2 > FindCallBrs(Function &F)
static bool IsInSameBasicBlock(const Use &U, const BasicBlock *BB)
static void UpdateSSA(DominatorTree &DT, CallBrInst *CBR, CallInst *Intrinsic, SSAUpdater &SSAUpdate)
static void PrintDebugDomInfo(const DominatorTree &DT, const Use &U, const BasicBlock *BB, bool IsDefaultDest)
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
Remove Loads Into Fake Uses
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:114
Represent the analysis usage information of a pass.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
BasicBlock * getDefaultDest() const
This class represents a function call, abstracting a target machine's calling convention.
Analysis pass which computes a DominatorTree.
Definition Dominators.h:283
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:321
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:164
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2787
PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
Helper class for SSA formation on a set of values defined in multiple blocks.
Definition SSAUpdater.h:39
void RewriteUse(Use &U)
Rewrite a use of the symbolic value.
void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type 'Ty'.
void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
iterator_range< use_iterator > uses()
Definition Value.h:380
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
Changed
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
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 BasicBlock * SplitKnownCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions(), const Twine &BBName="")
If it is known that an edge is critical, SplitKnownCriticalEdge can be called directly,...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
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
LLVM_ABI bool isCriticalEdge(const Instruction *TI, unsigned SuccNum, bool AllowIdenticalEdges=false)
Return true if the specified edge is a critical edge.
Definition CFG.cpp:96
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
LLVM_ABI FunctionPass * createInlineAsmPreparePass()
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
Option class for critical edge splitting.