LLVM 24.0.0git
InlineAsmPrepare.cpp
Go to the documentation of this file.
1//===-- InlineAsmPrepare - Prepare inline asm for code generation ---------===//
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 inline asm calls in LLVM IR in order to to assist
10// SelectionDAG's codegen.
11//
12// CallBrInst:
13//
14// Assists in inserting register copies for the output values of a callbr
15// along the edges leading to the indirect target blocks. Though the output
16// SSA value is defined by the callbr instruction itself in the IR
17// representation, the value cannot be copied to the appropriate virtual
18// registers prior to jumping to an indirect label, since the jump occurs
19// within the user-provided assembly blob.
20//
21// Instead, those copies must occur separately at the beginning of each
22// indirect target. That requires that we create a separate SSA definition in
23// each of them (via llvm.callbr.landingpad), and may require splitting
24// critical edges so we have a location to place the intrinsic. Finally, we
25// remap users of the original callbr output SSA value to instead point to
26// the appropriate llvm.callbr.landingpad value.
27//
28// Ideally, this could be done inside SelectionDAG, or in the
29// MachineInstruction representation, without the use of an IR-level
30// intrinsic. But, within the current framework, it’s simpler to implement
31// as an IR pass. (If support for callbr in GlobalISel is implemented, it’s
32// worth considering whether this is still required.)
33//
34//===----------------------------------------------------------------------===//
35
37#include "llvm/ADT/ArrayRef.h"
40#include "llvm/ADT/iterator.h"
41#include "llvm/Analysis/CFG.h"
42#include "llvm/CodeGen/Passes.h"
43#include "llvm/IR/BasicBlock.h"
44#include "llvm/IR/Dominators.h"
45#include "llvm/IR/Function.h"
46#include "llvm/IR/IRBuilder.h"
49#include "llvm/IR/Intrinsics.h"
51#include "llvm/Pass.h"
54
55using namespace llvm;
56
57#define DEBUG_TYPE "inline-asm-prepare"
58
59namespace {
60
61class InlineAsmPrepare : public FunctionPass {
62public:
63 InlineAsmPrepare() : FunctionPass(ID) {}
64
65 void getAnalysisUsage(AnalysisUsage &AU) const override {
67 }
68 bool runOnFunction(Function &F) override;
69
70 static char ID;
71};
72
73char InlineAsmPrepare::ID = 0;
74
75} // end anonymous namespace
76
77INITIALIZE_PASS_BEGIN(InlineAsmPrepare, "inline-asm-prepare",
78 "Prepare inline asm insts", false, false)
80INITIALIZE_PASS_END(InlineAsmPrepare, "inline-asm-prepare",
81 "Prepare inline asm insts", false, false)
82
84 return new InlineAsmPrepare();
85}
86
87#ifndef NDEBUG
88static void printDebugDomInfo(const DominatorTree &DT, const Use &U,
89 const BasicBlock *BB, bool IsDefaultDest) {
90 if (isa<Instruction>(U.getUser()))
91 LLVM_DEBUG(dbgs() << "Use: " << *U.getUser() << ", in block "
92 << cast<Instruction>(U.getUser())->getParent()->getName()
93 << ", is " << (DT.dominates(BB, U) ? "" : "NOT ")
94 << "dominated by " << BB->getName() << " ("
95 << (IsDefaultDest ? "in" : "") << "direct)\n");
96}
97#endif
98
99/// The Use is in the same BasicBlock as the intrinsic call.
100static bool isInSameBasicBlock(const Use &U, const BasicBlock *BB) {
101 const auto *I = dyn_cast<Instruction>(U.getUser());
102 return I && I->getParent() == BB;
103}
104
106 SSAUpdater &SSAUpdate) {
107 SmallPtrSet<Use *, 4> Visited;
108 BasicBlock *DefaultDest = CBR->getDefaultDest();
109 BasicBlockEdge DefaultEdge(CBR->getParent(), DefaultDest);
110 BasicBlock *LandingPad = Intrinsic->getParent();
111
113 for (Use *U : Uses) {
114 if (!Visited.insert(U).second)
115 continue;
116
117#ifndef NDEBUG
118 printDebugDomInfo(DT, *U, LandingPad, /*IsDefaultDest*/ false);
119 printDebugDomInfo(DT, *U, DefaultDest, /*IsDefaultDest*/ true);
120#endif
121
122 // Don't rewrite the use in the newly inserted intrinsic.
123 if (const auto *II = dyn_cast<IntrinsicInst>(U->getUser()))
124 if (II->getIntrinsicID() == Intrinsic::callbr_landingpad)
125 continue;
126
127 // If the Use is in the same BasicBlock as the Intrinsic call, replace
128 // the Use with the value of the Intrinsic call.
129 if (isInSameBasicBlock(*U, LandingPad)) {
130 U->set(Intrinsic);
131 continue;
132 }
133
134 // If the Use is dominated by the edge to the default dest, do not touch it.
135 // The default dest itself may also be reached from an indirect dest.
136 if (DT.dominates(DefaultEdge, *U))
137 continue;
138
139 SSAUpdate.RewriteUse(*U);
140 }
141}
142
144 bool Changed = false;
145
147 Options.setMergeIdenticalEdges();
148
149 // The indirect destination might be duplicated between another parameter...
150 //
151 // %0 = callbr ... [label %x, label %x]
152 //
153 // ...hence MergeIdenticalEdges and AllowIndentical edges, but we don't need
154 // to split the default destination if it's duplicated between an indirect
155 // destination...
156 //
157 // %1 = callbr ... to label %x [label %x]
158 //
159 // ...hence starting at 1 and checking against successor 0 (aka the default
160 // destination).
161 for (unsigned I = 1, E = CBR->getNumSuccessors(); I != E; ++I)
162 if (CBR->getSuccessor(I) == CBR->getSuccessor(0) ||
163 isCriticalEdge(CBR, I, /*AllowIdenticalEdges*/ true))
165 Changed = true;
166
167 return Changed;
168}
169
170/// Create a separate SSA definition in each indirect target (via
171/// llvm.callbr.landingpad). This may require splitting critical edges so we
172/// have a location to place the intrinsic. Then remap users of the original
173/// callbr output SSA value to instead point to the appropriate
174/// llvm.callbr.landingpad value.
176 bool Changed = false;
178 IRBuilder<> Builder(*CBR->getModule());
179
180 if (!CBR->getNumIndirectDests())
181 return false;
182
183 SSAUpdater SSAUpdate;
184 SSAUpdate.Initialize(CBR->getType(), CBR->getName());
185 SSAUpdate.AddAvailableValue(CBR->getParent(), CBR);
186
187 for (BasicBlock *IndDest : CBR->getIndirectDests()) {
188 if (!Visited.insert(IndDest).second)
189 continue;
190
191 Builder.SetInsertPoint(&*IndDest->begin());
192 CallInst *Intrinsic = Builder.CreateIntrinsicWithoutFolding(
193 CBR->getType(), Intrinsic::callbr_landingpad, {CBR});
194 SSAUpdate.AddAvailableValue(IndDest, Intrinsic);
195 updateSSA(DT, CBR, Intrinsic, SSAUpdate);
196 Changed = true;
197 }
198
199 return Changed;
200}
201
203 bool Changed = false;
204
205 Changed |= splitCriticalEdges(CBR, DT);
206 Changed |= insertIntrinsicCalls(CBR, *DT);
207
208 return Changed;
209}
210
213 for (BasicBlock &BB : F)
214 if (auto *CBR = dyn_cast<CallBrInst>(BB.getTerminator()))
215 if (!CBR->getType()->isVoidTy() && !CBR->use_empty())
216 CBRs.push_back(CBR);
217 return CBRs;
218}
219
221 DominatorTree *DT) {
222 bool Changed = false;
223
224 for (CallBrInst *CBR : CBRs)
225 Changed |= processCallBrInst(F, CBR, DT);
226
227 return Changed;
228}
229
230bool InlineAsmPrepare::runOnFunction(Function &F) {
232 if (CBRs.empty())
233 return false;
234
235 // It's highly likely that most programs do not contain CallBrInsts. Follow a
236 // similar pattern from SafeStackLegacyPass::runOnFunction to reuse previous
237 // domtree analysis if available, otherwise compute it lazily. This avoids
238 // forcing Dominator Tree Construction at -O0 for programs that likely do not
239 // contain CallBrInsts. It does pessimize programs with callbr at higher
240 // optimization levels, as the DominatorTree created here is not reused by
241 // subsequent passes.
242 DominatorTree *DT;
243 std::optional<DominatorTree> LazilyComputedDomTree;
244 if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
245 DT = &DTWP->getDomTree();
246 else {
247 LazilyComputedDomTree.emplace(F);
248 DT = &*LazilyComputedDomTree;
249 }
250
251 return runImpl(F, CBRs, DT);
252}
253
257 if (CBRs.empty())
258 return PreservedAnalyses::all();
259
260 auto *DT = &FAM.getResult<DominatorTreeAnalysis>(F);
261
262 if (runImpl(F, CBRs, DT)) {
265 return PA;
266 }
267
268 return PreservedAnalyses::all();
269}
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static bool runImpl(MachineFunction &MF)
Definition CFIFixup.cpp:304
static bool runOnFunction(Function &F, bool PostInlining)
static void printDebugDomInfo(const DominatorTree &DT, const Use &U, const BasicBlock *BB, bool IsDefaultDest)
static bool runImpl(Function &F, ArrayRef< CallBrInst * > CBRs, DominatorTree *DT)
static SmallVector< CallBrInst *, 2 > findCallBrs(Function &F)
static bool processCallBrInst(Function &F, CallBrInst *CBR, DominatorTree *DT)
static bool isInSameBasicBlock(const Use &U, const BasicBlock *BB)
The Use is in the same BasicBlock as the intrinsic call.
static bool splitCriticalEdges(CallBrInst *CBR, DominatorTree *DT)
static bool insertIntrinsicCalls(CallBrInst *CBR, DominatorTree &DT)
Create a separate SSA definition in each indirect target (via llvm.callbr.landingpad).
static void updateSSA(DominatorTree &DT, CallBrInst *CBR, CallInst *Intrinsic, SSAUpdater &SSAUpdate)
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:119
Represent the analysis usage information of a pass.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
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 ...
SmallVector< BasicBlock *, 16 > getIndirectDests() const
BasicBlock * getSuccessor(unsigned i) const
unsigned getNumSuccessors() const
BasicBlock * getDefaultDest() const
unsigned getNumIndirectDests() const
Return the number of callbr indirect dest labels.
This class represents a function call, abstracting a target machine's calling convention.
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
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:312
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
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:133
Helper class for SSA formation on a set of values defined in multiple blocks.
Definition SSAUpdater.h:39
LLVM_ABI void RewriteUse(Use &U)
Rewrite a use of the symbolic value.
LLVM_ABI void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type 'Ty'.
LLVM_ABI 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
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
iterator_range< use_iterator > uses()
Definition Value.h:382
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
const ParentTy * getParent() const
Definition ilist_node.h:34
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.
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:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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:106
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.