LLVM 24.0.0git
CalledValuePropagation.cpp
Go to the documentation of this file.
1//===- CalledValuePropagation.cpp - Propagate called values -----*- 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//
9// This file implements a transformation that attaches !callees metadata to
10// indirect call sites. For a given call site, the metadata, if present,
11// indicates the set of functions the call site could possibly target at
12// run-time. This metadata is added to indirect call sites when the set of
13// possible targets can be determined by analysis and is known to be small. The
14// analysis driving the transformation is similar to constant propagation and
15// makes uses of the generic sparse propagation solver.
16//
17//===----------------------------------------------------------------------===//
18
20#include "IPOOptions.h"
21#include "llvm/ADT/SetVector.h"
24#include "llvm/IR/Constants.h"
25#include "llvm/IR/MDBuilder.h"
26#include "llvm/IR/Module.h"
27#include "llvm/Transforms/IPO.h"
28
29using namespace llvm;
30
31#define DEBUG_TYPE "called-value-propagation"
32
33namespace {
34/// To enable interprocedural analysis, we assign LLVM values to the following
35/// groups. The register group represents SSA registers, the return group
36/// represents the return values of functions, and the memory group represents
37/// in-memory values. An LLVM Value can technically be in more than one group.
38/// It's necessary to distinguish these groups so we can, for example, track a
39/// global variable separately from the value stored at its location.
40enum class IPOGrouping { Register, Return, Memory };
41
42/// Our LatticeKeys are PointerIntPairs composed of LLVM values and groupings.
43using CVPLatticeKey = PointerIntPair<Value *, 2, IPOGrouping>;
44
45/// The lattice value type used by our custom lattice function. It holds the
46/// lattice state, and a set of functions.
47class CVPLatticeVal {
48public:
49 /// The states of the lattice values. Only the FunctionSet state is
50 /// interesting. It indicates the set of functions to which an LLVM value may
51 /// refer.
52 enum CVPLatticeStateTy { Undefined, FunctionSet, Overdefined, Untracked };
53
54 /// Comparator for sorting the functions set. Compare using the unique and
55 /// deterministic function indices for deterministic output.
56 struct Compare {
57 const DenseMap<const Function *, uint32_t> &FunctionIndices;
58 bool operator()(const Function *LHS, const Function *RHS) const {
59 return FunctionIndices.at(LHS) < FunctionIndices.at(RHS);
60 }
61 };
62
63 CVPLatticeVal() = default;
64 CVPLatticeVal(CVPLatticeStateTy LatticeState) : LatticeState(LatticeState) {}
65 CVPLatticeVal(std::vector<Function *> &&Functions,
66 const DenseMap<const Function *, uint32_t> &FunctionIndices)
67 : LatticeState(FunctionSet), Functions(std::move(Functions)) {
68 assert(llvm::is_sorted(this->Functions, Compare{FunctionIndices}));
69 }
70
71 /// Get a reference to the functions held by this lattice value. The number
72 /// of functions will be zero for states other than FunctionSet.
73 const std::vector<Function *> &getFunctions() const {
74 return Functions;
75 }
76
77 /// Returns true if the lattice value is in the FunctionSet state.
78 bool isFunctionSet() const { return LatticeState == FunctionSet; }
79
80 bool operator==(const CVPLatticeVal &RHS) const {
81 return LatticeState == RHS.LatticeState && Functions == RHS.Functions;
82 }
83
84 bool operator!=(const CVPLatticeVal &RHS) const {
85 return LatticeState != RHS.LatticeState || Functions != RHS.Functions;
86 }
87
88private:
89 /// Holds the state this lattice value is in.
90 CVPLatticeStateTy LatticeState = Undefined;
91
92 /// Holds functions indicating the possible targets of call sites. This set
93 /// is empty for lattice values in the undefined, overdefined, and untracked
94 /// states. The maximum size of the set is controlled by
95 /// -cvp-max-functions-per-value. Since most LLVM values are expected to be in
96 /// uninteresting states (i.e., overdefined), CVPLatticeVal objects should be
97 /// small and efficiently copyable.
98 // FIXME: This could be a TinyPtrVector and/or merge with LatticeState.
99 std::vector<Function *> Functions;
100};
101
102/// The custom lattice function used by the generic sparse propagation solver.
103/// It handles merging lattice values and computing new lattice values for
104/// constants, arguments, values returned from trackable functions, and values
105/// located in trackable global variables. It also computes the lattice values
106/// that change as a result of executing instructions.
107class CVPLatticeFunc
108 : public AbstractLatticeFunction<CVPLatticeKey, CVPLatticeVal> {
109 const IPOOptions &Opts;
110 const DenseMap<const Function *, uint32_t> &FunctionIndices;
111
112public:
113 explicit CVPLatticeFunc(
114 const IPOOptions &Opts,
115 const DenseMap<const Function *, uint32_t> &FunctionIndices)
116 : AbstractLatticeFunction(CVPLatticeVal(CVPLatticeVal::Undefined),
117 CVPLatticeVal(CVPLatticeVal::Overdefined),
118 CVPLatticeVal(CVPLatticeVal::Untracked)),
119 Opts(Opts), FunctionIndices(FunctionIndices) {}
120
121 /// Compute and return a CVPLatticeVal for the given CVPLatticeKey.
122 CVPLatticeVal ComputeLatticeVal(CVPLatticeKey Key) override {
123 switch (Key.getInt()) {
124 case IPOGrouping::Register:
125 if (isa<Instruction>(Key.getPointer())) {
126 return getUndefVal();
127 } else if (auto *A = dyn_cast<Argument>(Key.getPointer())) {
128 if (canTrackArgumentsInterprocedurally(A->getParent()))
129 return getUndefVal();
130 } else if (auto *C = dyn_cast<Constant>(Key.getPointer())) {
131 return computeConstant(C);
132 }
133 return getOverdefinedVal();
134 case IPOGrouping::Memory:
135 case IPOGrouping::Return:
136 if (auto *GV = dyn_cast<GlobalVariable>(Key.getPointer())) {
138 return computeConstant(GV->getInitializer());
139 } else if (auto *F = cast<Function>(Key.getPointer()))
141 return getUndefVal();
142 }
143 return getOverdefinedVal();
144 }
145
146 /// Merge the two given lattice values. The interesting cases are merging two
147 /// FunctionSet values and a FunctionSet value with an Undefined value. For
148 /// these cases, we simply union the function sets. If the size of the union
149 /// is greater than the maximum functions we track, the merged value is
150 /// overdefined.
151 CVPLatticeVal MergeValues(CVPLatticeVal X, CVPLatticeVal Y) override {
152 if (X == getOverdefinedVal() || Y == getOverdefinedVal())
153 return getOverdefinedVal();
154 if (X == getUndefVal() && Y == getUndefVal())
155 return getUndefVal();
156 std::vector<Function *> Union;
157 std::set_union(X.getFunctions().begin(), X.getFunctions().end(),
158 Y.getFunctions().begin(), Y.getFunctions().end(),
159 std::back_inserter(Union),
160 CVPLatticeVal::Compare{FunctionIndices});
161 if (Union.size() > Opts.cvp_max_functions_per_value)
162 return getOverdefinedVal();
163 return CVPLatticeVal(std::move(Union), FunctionIndices);
164 }
165
166 /// Compute the lattice values that change as a result of executing the given
167 /// instruction. The changed values are stored in \p ChangedValues. We handle
168 /// just a few kinds of instructions since we're only propagating values that
169 /// can be called.
170 void ComputeInstructionState(
171 Instruction &I,
174 switch (I.getOpcode()) {
175 case Instruction::Call:
176 case Instruction::Invoke:
177 return visitCallBase(cast<CallBase>(I), ChangedValues, SS);
178 case Instruction::Load:
179 return visitLoad(*cast<LoadInst>(&I), ChangedValues, SS);
180 case Instruction::Ret:
181 return visitReturn(*cast<ReturnInst>(&I), ChangedValues, SS);
182 case Instruction::Select:
183 return visitSelect(*cast<SelectInst>(&I), ChangedValues, SS);
184 case Instruction::Store:
185 return visitStore(*cast<StoreInst>(&I), ChangedValues, SS);
186 default:
187 return visitInst(I, ChangedValues, SS);
188 }
189 }
190
191 /// Print the given CVPLatticeVal to the specified stream.
192 void PrintLatticeVal(CVPLatticeVal LV, raw_ostream &OS) override {
193 if (LV == getUndefVal())
194 OS << "Undefined ";
195 else if (LV == getOverdefinedVal())
196 OS << "Overdefined";
197 else if (LV == getUntrackedVal())
198 OS << "Untracked ";
199 else
200 OS << "FunctionSet";
201 }
202
203 /// Print the given CVPLatticeKey to the specified stream.
204 void PrintLatticeKey(CVPLatticeKey Key, raw_ostream &OS) override {
205 if (Key.getInt() == IPOGrouping::Register)
206 OS << "<reg> ";
207 else if (Key.getInt() == IPOGrouping::Memory)
208 OS << "<mem> ";
209 else if (Key.getInt() == IPOGrouping::Return)
210 OS << "<ret> ";
211 if (isa<Function>(Key.getPointer()))
212 OS << Key.getPointer()->getName();
213 else
214 OS << *Key.getPointer();
215 }
216
217 /// We collect a set of indirect calls when visiting call sites. This method
218 /// returns a reference to that set.
219 ArrayRef<CallBase *> getIndirectCalls() const {
220 return IndirectCalls.getArrayRef();
221 }
222
223private:
224 /// Holds the indirect calls we encounter during the analysis. We will attach
225 /// metadata to these calls after the analysis indicating the functions the
226 /// calls can possibly target.
227 SmallSetVector<CallBase *, 32> IndirectCalls;
228
229 /// Compute a new lattice value for the given constant. The constant, after
230 /// stripping any pointer casts, should be a Function. We ignore null
231 /// pointers as an optimization, since calling these values is undefined
232 /// behavior.
233 CVPLatticeVal computeConstant(Constant *C) {
235 return CVPLatticeVal(CVPLatticeVal::FunctionSet);
236 if (auto *F = dyn_cast<Function>(C->stripPointerCasts()))
237 return CVPLatticeVal({F}, FunctionIndices);
238 return getOverdefinedVal();
239 }
240
241 /// Handle return instructions. The function's return state is the merge of
242 /// the returned value state and the function's return state.
243 void
244 visitReturn(ReturnInst &I,
247 Function *F = I.getParent()->getParent();
248 if (F->getReturnType()->isVoidTy())
249 return;
250 auto RegI = CVPLatticeKey(I.getReturnValue(), IPOGrouping::Register);
251 auto RetF = CVPLatticeKey(F, IPOGrouping::Return);
252 ChangedValues[RetF] =
253 MergeValues(SS.getValueState(RegI), SS.getValueState(RetF));
254 }
255
256 /// Handle call sites. The state of a called function's formal arguments is
257 /// the merge of the argument state with the call sites corresponding actual
258 /// argument state. The call site state is the merge of the call site state
259 /// with the returned value state of the called function.
260 void
261 visitCallBase(CallBase &CB,
265 auto RegI = CVPLatticeKey(&CB, IPOGrouping::Register);
266
267 // If this is an indirect call, save it so we can quickly revisit it when
268 // attaching metadata.
269 if (!F)
270 IndirectCalls.insert(&CB);
271
272 // If we can't track the function's return values, there's nothing to do.
274 // Void return, No need to create and update CVPLattice state as no one
275 // can use it.
276 if (CB.getType()->isVoidTy())
277 return;
278 ChangedValues[RegI] = getOverdefinedVal();
279 return;
280 }
281
282 // Inform the solver that the called function is executable, and perform
283 // the merges for the arguments and return value.
284 SS.MarkBlockExecutable(&F->front());
285 auto RetF = CVPLatticeKey(F, IPOGrouping::Return);
286 for (Argument &A : F->args()) {
287 auto RegFormal = CVPLatticeKey(&A, IPOGrouping::Register);
288 auto RegActual =
289 CVPLatticeKey(CB.getArgOperand(A.getArgNo()), IPOGrouping::Register);
290 ChangedValues[RegFormal] =
291 MergeValues(SS.getValueState(RegFormal), SS.getValueState(RegActual));
292 }
293
294 // Void return, No need to create and update CVPLattice state as no one can
295 // use it.
296 if (CB.getType()->isVoidTy())
297 return;
298
299 ChangedValues[RegI] =
300 MergeValues(SS.getValueState(RegI), SS.getValueState(RetF));
301 }
302
303 /// Handle select instructions. The select instruction state is the merge the
304 /// true and false value states.
305 void
306 visitSelect(SelectInst &I,
309 auto RegI = CVPLatticeKey(&I, IPOGrouping::Register);
310 auto RegT = CVPLatticeKey(I.getTrueValue(), IPOGrouping::Register);
311 auto RegF = CVPLatticeKey(I.getFalseValue(), IPOGrouping::Register);
312 ChangedValues[RegI] =
313 MergeValues(SS.getValueState(RegT), SS.getValueState(RegF));
314 }
315
316 /// Handle load instructions. If the pointer operand of the load is a global
317 /// variable, we attempt to track the value. The loaded value state is the
318 /// merge of the loaded value state with the global variable state.
319 void
320 visitLoad(LoadInst &I,
323 auto RegI = CVPLatticeKey(&I, IPOGrouping::Register);
324 if (auto *GV = dyn_cast<GlobalVariable>(I.getPointerOperand())) {
325 auto MemGV = CVPLatticeKey(GV, IPOGrouping::Memory);
326 ChangedValues[RegI] =
327 MergeValues(SS.getValueState(RegI), SS.getValueState(MemGV));
328 } else {
329 ChangedValues[RegI] = getOverdefinedVal();
330 }
331 }
332
333 /// Handle store instructions. If the pointer operand of the store is a
334 /// global variable, we attempt to track the value. The global variable state
335 /// is the merge of the stored value state with the global variable state.
336 void
337 visitStore(StoreInst &I,
340 auto *GV = dyn_cast<GlobalVariable>(I.getPointerOperand());
341 if (!GV)
342 return;
343 auto RegI = CVPLatticeKey(I.getValueOperand(), IPOGrouping::Register);
344 auto MemGV = CVPLatticeKey(GV, IPOGrouping::Memory);
345 ChangedValues[MemGV] =
346 MergeValues(SS.getValueState(RegI), SS.getValueState(MemGV));
347 }
348
349 /// Handle all other instructions. All other instructions are marked
350 /// overdefined.
351 void
352 visitInst(Instruction &I,
355 // Simply bail if this instruction has no user.
356 if (I.use_empty())
357 return;
358 auto RegI = CVPLatticeKey(&I, IPOGrouping::Register);
359 ChangedValues[RegI] = getOverdefinedVal();
360 }
361};
362} // namespace
363
364namespace llvm {
365/// A specialization of LatticeKeyInfo for CVPLatticeKeys. The generic solver
366/// must translate between LatticeKeys and LLVM Values when adding Values to
367/// its work list and inspecting the state of control-flow related values.
368template <> struct LatticeKeyInfo<CVPLatticeKey> {
369 static inline Value *getValueFromLatticeKey(CVPLatticeKey Key) {
370 return Key.getPointer();
371 }
372 static inline CVPLatticeKey getLatticeKeyFromValue(Value *V) {
373 return CVPLatticeKey(V, IPOGrouping::Register);
374 }
375};
376} // namespace llvm
377
378static bool runCVP(Module &M) {
379 // Assign unique numbers to functions, to be used when ordering the functions
380 // in the lattice.
382 for (const auto &[Idx, F] : enumerate(M))
383 FunctionIndices.try_emplace(&F, Idx);
384
385 // Our custom lattice function and generic sparse propagation solver.
386 CVPLatticeFunc Lattice(getIPOOptions(M), FunctionIndices);
388
389 // For each function in the module, if we can't track its arguments, let the
390 // generic solver assume it is executable.
391 for (Function &F : M)
392 if (!F.isDeclaration() && !canTrackArgumentsInterprocedurally(&F))
393 Solver.MarkBlockExecutable(&F.front());
394
395 // Solver our custom lattice. In doing so, we will also build a set of
396 // indirect call sites.
397 Solver.Solve();
398
399 // Attach metadata to the indirect call sites that were collected indicating
400 // the set of functions they can possibly target.
401 bool Changed = false;
402 MDBuilder MDB(M.getContext());
403 for (CallBase *C : Lattice.getIndirectCalls()) {
404 auto RegI = CVPLatticeKey(C->getCalledOperand(), IPOGrouping::Register);
405 CVPLatticeVal LV = Solver.getExistingValueState(RegI);
406 if (!LV.isFunctionSet() || LV.getFunctions().empty())
407 continue;
408 MDNode *Callees = MDB.createCallees(LV.getFunctions());
409 C->setMetadata(LLVMContext::MD_callees, Callees);
410 Changed = true;
411 }
412
413 return Changed;
414}
415
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static bool runCVP(Module &M)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file implements a set that has insertion order iteration characteristics.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Value * RHS
Value * LHS
AbstractLatticeFunction - This class is implemented by the dataflow instance to specify what the latt...
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
Value * getArgOperand(unsigned i) const
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &)
This is an important base class in LLVM.
Definition Constant.h:44
ValueT & at(const_arg_type_t< KeyT > Val)
Return the entry for the specified key, or abort if no such entry exists.
Definition DenseMap.h:811
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
An instruction for reading from memory.
LLVM_ABI MDNode * createCallees(ArrayRef< Function * > Callees)
Return metadata indicating the possible callees of indirect calls.
Metadata node.
Definition Metadata.h:1087
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
PointerIntPair - This class implements a pair of a pointer and small integer.
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
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Return a value (possibly void), from a function.
This class represents the LLVM 'select' instruction.
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
SparseSolver - This class is a general purpose solver for Sparse Conditional Propagation with a progr...
void MarkBlockExecutable(BasicBlock *BB)
MarkBlockExecutable - This method can be used by clients to mark all of the blocks that are known to ...
void Solve()
Solve - Solve for constants and executable blocks.
LatticeVal getExistingValueState(LatticeKey Key) const
getExistingValueState - Return the LatticeVal object corresponding to the given value from the ValueS...
An instruction for storing to memory.
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
This class provides various memory handling functions that manipulate MemoryBlock instances.
Definition Memory.h:54
This is an optimization pass for GlobalISel generic memory operations.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool operator!=(uint64_t V1, const APInt &V2)
Definition APInt.h:2139
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
const IPOOptions & getIPOOptions(const LLVMContext &C)
Definition IPOOptions.h:36
LLVM_ABI bool canTrackGlobalVariableInterprocedurally(GlobalVariable *GV)
Determine if the value maintained in the given global variable can be tracked interprocedurally.
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
Definition STLExtras.h:1986
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_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI bool canTrackReturnsInterprocedurally(Function *F)
Determine if the values of the given function's returns can be tracked interprocedurally.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool canTrackArgumentsInterprocedurally(Function *F)
Determine if the values of the given function's arguments can be tracked interprocedurally.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
static CVPLatticeKey getLatticeKeyFromValue(Value *V)
static Value * getValueFromLatticeKey(CVPLatticeKey Key)
A template for translating between LLVM Values and LatticeKeys.
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:344