58#define DEBUG_TYPE "amdgpu-rewrite-out-arguments"
63 "amdgpu-any-address-space-out-arguments",
64 cl::desc(
"Replace pointer out arguments with "
65 "struct returns for non-private address space"),
70 "amdgpu-max-return-arg-num-regs",
71 cl::desc(
"Approximately limit number of return registers for replacing out arguments"),
76 "Number out arguments moved to struct return values");
78 "Number of functions with out arguments moved to struct return values");
97 void getAnalysisUsage(AnalysisUsage &AU)
const override {
100 FunctionPass::getAnalysisUsage(AU);
103 bool doInitialization(
Module &M)
override;
110 "AMDGPU Rewrite Out Arguments",
false,
false)
115char AMDGPURewriteOutArguments::
ID = 0;
117Type *AMDGPURewriteOutArguments::getStoredType(
Value &Arg)
const {
118 const int MaxUses = 10;
123 Type *StoredType =
nullptr;
124 while (!Worklist.
empty()) {
134 if (UseCount++ > MaxUses)
137 if (!
SI->isSimple() ||
141 if (StoredType && StoredType !=
SI->getValueOperand()->getType())
143 StoredType =
SI->getValueOperand()->getType();
154Type *AMDGPURewriteOutArguments::getOutArgumentType(
Argument &Arg)
const {
159 if (!ArgTy || (ArgTy->getAddressSpace() !=
DL->getAllocaAddrSpace() &&
165 Type *StoredType = getStoredType(Arg);
166 if (!StoredType ||
DL->getTypeStoreSize(StoredType) > MaxOutArgSizeBytes)
172bool AMDGPURewriteOutArguments::doInitialization(
Module &M) {
173 DL = &
M.getDataLayout();
194 if (Store->getPointerOperand() == OutArg)
202 if (LI->isAtomic()) {
220bool AMDGPURewriteOutArguments::runOnFunction(Function &
F) {
225 if (
F.isVarArg() ||
F.hasStructRetAttr() ||
229 unsigned ReturnNumRegs = 0;
233 SmallDenseMap<unsigned, unsigned, 4> OutArgIndexes;
235 Type *RetTy =
F.getReturnType();
237 ReturnNumRegs =
DL->getTypeStoreSize(RetTy) / 4;
246 for (Argument &Arg :
F.args()) {
247 if (
Type *Ty = getOutArgumentType(Arg)) {
249 <<
" in function " <<
F.getName() <<
'\n');
259 DenseMap<ReturnInst *, ReplacementVec> Replacements;
262 for (BasicBlock &BB :
F) {
270 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
271 MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
273 BatchAAResults BatchAA(*AA);
274 MemorySSAUpdater MSSAUpdater(MSSA);
275 MSSAU = &MSSAUpdater;
288 for (
const auto &Pair : OutArgs) {
289 bool ThisReplaceable =
true;
293 Type *ArgTy = Pair.second;
300 unsigned ArgNumRegs =
DL->getTypeStoreSize(ArgTy) / 4;
306 for (ReturnInst *RI : Returns) {
311 LLVM_DEBUG(
dbgs() <<
"Found out argument store: " << *SI <<
'\n');
314 ThisReplaceable =
false;
319 if (!ThisReplaceable)
322 for (std::pair<ReturnInst *, StoreInst *> Store : ReplaceableStores) {
323 Value *ReplVal =
Store.second->getValueOperand();
325 auto &ValVec = Replacements[
Store.first];
328 <<
"Saw multiple out arg stores" << *OutArg <<
'\n');
331 ThisReplaceable =
false;
335 ValVec.emplace_back(OutArg, ReplVal);
337 Store.second->eraseFromParent();
340 if (ThisReplaceable) {
343 ++NumOutArgumentsReplaced;
349 if (Replacements.
empty())
352 LLVMContext &Ctx =
F.getContext();
355 FunctionType *NewFuncTy = FunctionType::get(NewRetTy,
356 F.getFunctionType()->params(),
359 LLVM_DEBUG(
dbgs() <<
"Computed new return type: " << *NewRetTy <<
'\n');
362 F.getName() +
".body");
363 F.getParent()->getFunctionList().insert(
F.getIterator(), NewFunc);
371 AttributeMask RetAttrs;
382 for (std::pair<ReturnInst *, ReplacementVec> &Replacement : Replacements) {
383 ReturnInst *RI = Replacement.first;
391 NewRetVal =
B.CreateInsertValue(NewRetVal, RetVal, 0);
394 for (std::pair<Argument *, Value *> ReturnPoint : Replacement.second) {
395 unsigned FieldIdx = OutArgIndexes.
lookup(ReturnPoint.first->getArgNo());
396 NewRetVal =
B.CreateInsertValue(NewRetVal, ReturnPoint.second, FieldIdx);
402 B.CreateRet(NewRetVal);
407 SmallVector<Value *, 16> StubCallArgs;
408 for (Argument &Arg :
F.args()) {
420 CallInst *StubCall =
B.CreateCall(NewFunc, StubCallArgs);
422 for (Argument &Arg :
F.args()) {
424 if (It == OutArgIndexes.
end())
427 unsigned FieldIdx = It->second;
432 Value *Val =
B.CreateExtractValue(StubCall, FieldIdx);
433 B.CreateAlignedStore(Val, &Arg, Align);
437 B.CreateRet(
B.CreateExtractValue(StubCall, 0));
443 F.addFnAttr(Attribute::AlwaysInline);
445 ++NumOutArgumentFunctionsReplaced;
450 return new AMDGPURewriteOutArguments();
static cl::opt< unsigned > MaxNumRetRegs("amdgpu-max-return-arg-num-regs", cl::desc("Approximately limit number of return registers for replacing out arguments"), cl::Hidden, cl::init(16))
static cl::opt< bool > AnyAddressSpace("amdgpu-any-address-space-out-arguments", cl::desc("Replace pointer out arguments with " "struct returns for non-private address space"), cl::Hidden, cl::init(false))
static StoreInst * findStoreForOutArgument(BasicBlock *BB, Argument *OutArg, MemorySSA &MSSA, BatchAAResults &BAA)
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
DXIL Forward Handle Accesses
static bool runOnFunction(Function &F, bool PostInlining)
Machine Check Debug Module
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
AnalysisUsage & addRequired()
This class represents an incoming formal argument to a Function.
LLVM_ABI bool hasByValAttr() const
Return true if this argument has the byval attribute.
unsigned getArgNo() const
Return the index of this formal argument in its containing function.
LLVM_ABI MaybeAlign getParamAlign() const
If this is a byval or inalloca argument, return its alignment.
LLVM_ABI bool hasStructRetAttr() const
Return true if this argument has the sret attribute.
AttributeMask & addAttribute(Attribute::AttrKind Val)
Add an attribute to the mask.
LLVM Basic Block Representation.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
A parsed version of the target data layout string in and methods for querying it.
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
iterator find(const_arg_type_t< KeyT > Val)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
FunctionPass class - This class is used to implement most global optimizations.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
void splice(Function::iterator ToIt, Function *FromF)
Transfer all blocks from FromF to this function at ToIt.
void stealArgumentListFrom(Function &Src)
Steal arguments from another function.
void removeRetAttrs(const AttributeMask &Attrs)
removes the attributes from the return value list of attributes.
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
LLVM_ABI void setComdat(Comdat *C)
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Representation for a specific memory location.
static MemoryLocation getBeforeOrAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location before or after Ptr, while remaining within the underl...
LLVM_ABI void removeMemoryAccess(MemoryAccess *, bool OptimizePhis=false)
Remove a MemoryAccess from MemorySSA, including updating all definitions and uses.
Legacy analysis pass which computes MemorySSA.
Encapsulates MemorySSA, including all data associated with memory accesses.
AccessList * getBlockAccesses(const BasicBlock *BB) const
Return the list of MemoryAccess's for a given basic block.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
static unsigned getPointerOperandIndex()
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Type * getElementType(unsigned N) const
The instances of the Type class are immutable: once they are created, they are never changed.
bool isVoidTy() const
Return true if this is 'void'.
A Use represents the edge between a Value definition and its users.
void setOperand(unsigned i, Value *Val)
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
iterator_range< use_iterator > uses()
Abstract Attribute helper functions.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
LLVM_READNONE constexpr bool isEntryFunctionCC(CallingConv::ID CC)
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ BasicBlock
Various leaf nodes.
initializer< Ty > init(const Ty &Val)
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.
FunctionPass * createAMDGPURewriteOutArgumentsPass()
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
auto reverse(ContainerTy &&C)
bool isModSet(const ModRefInfo MRI)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
bool isStrongerThan(AtomicOrdering AO, AtomicOrdering Other)
Returns true if ao is stronger than other as defined by the AtomicOrdering lattice,...