58#define DEBUG_TYPE "amdgpu-rewrite-out-arguments"
63 "Number out arguments moved to struct return values");
65 "Number of functions with out arguments moved to struct return values");
71 const AMDGPUOptions *CLOpts =
nullptr;
85 void getAnalysisUsage(AnalysisUsage &AU)
const override {
88 FunctionPass::getAnalysisUsage(AU);
91 bool doInitialization(
Module &M)
override;
98 "AMDGPU Rewrite Out Arguments",
false,
false)
103char AMDGPURewriteOutArguments::ID = 0;
105Type *AMDGPURewriteOutArguments::getStoredType(
Value &Arg)
const {
106 const int MaxUses = 10;
111 Type *StoredType =
nullptr;
112 while (!Worklist.
empty()) {
122 if (UseCount++ > MaxUses)
125 if (!
SI->isSimple() ||
129 if (StoredType && StoredType !=
SI->getValueOperand()->getType())
131 StoredType =
SI->getValueOperand()->getType();
142Type *AMDGPURewriteOutArguments::getOutArgumentType(
Argument &Arg)
const {
143 const unsigned MaxOutArgSizeBytes = 4 * CLOpts->max_return_arg_num_regs;
148 (ArgTy->getAddressSpace() !=
DL->getAllocaAddrSpace() &&
149 !CLOpts->any_address_space_out_arguments) ||
154 Type *StoredType = getStoredType(Arg);
155 if (!StoredType ||
DL->getTypeStoreSize(StoredType) > MaxOutArgSizeBytes)
161bool AMDGPURewriteOutArguments::doInitialization(
Module &M) {
162 DL = &
M.getDataLayout();
183 if (
Store->getPointerOperand() == OutArg)
191 if (LI->isAtomic()) {
208bool AMDGPURewriteOutArguments::runOnFunction(
Function &
F) {
212 CLOpts = &
F.getContext().getLibraryOptions().get<AMDGPUOptions>();
213 const unsigned MaxNumRetRegs = CLOpts->max_return_arg_num_regs;
216 if (
F.isVarArg() ||
F.hasStructRetAttr() ||
220 unsigned ReturnNumRegs = 0;
224 SmallDenseMap<unsigned, unsigned, 4> OutArgIndexes;
226 Type *RetTy =
F.getReturnType();
228 ReturnNumRegs =
DL->getTypeStoreSize(RetTy) / 4;
230 if (ReturnNumRegs >= MaxNumRetRegs)
237 for (Argument &Arg :
F.args()) {
238 if (
Type *Ty = getOutArgumentType(Arg)) {
240 <<
" in function " <<
F.getName() <<
'\n');
250 DenseMap<ReturnInst *, ReplacementVec> Replacements;
253 for (BasicBlock &BB :
F) {
261 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
262 MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
264 BatchAAResults BatchAA(*AA);
265 MemorySSAUpdater MSSAUpdater(MSSA);
266 MSSAU = &MSSAUpdater;
279 for (
const auto &Pair : OutArgs) {
280 bool ThisReplaceable =
true;
284 Type *ArgTy = Pair.second;
291 unsigned ArgNumRegs =
DL->getTypeStoreSize(ArgTy) / 4;
292 if (ArgNumRegs + ReturnNumRegs > MaxNumRetRegs)
297 for (ReturnInst *RI : Returns) {
302 LLVM_DEBUG(
dbgs() <<
"Found out argument store: " << *SI <<
'\n');
305 ThisReplaceable =
false;
310 if (!ThisReplaceable)
313 for (std::pair<ReturnInst *, StoreInst *>
Store : ReplaceableStores) {
314 Value *ReplVal =
Store.second->getValueOperand();
316 auto &ValVec = Replacements[
Store.first];
319 <<
"Saw multiple out arg stores" << *OutArg <<
'\n');
322 ThisReplaceable =
false;
326 ValVec.emplace_back(OutArg, ReplVal);
328 Store.second->eraseFromParent();
331 if (ThisReplaceable) {
334 ++NumOutArgumentsReplaced;
340 if (Replacements.
empty())
343 LLVMContext &Ctx =
F.getContext();
346 FunctionType *NewFuncTy = FunctionType::get(NewRetTy,
347 F.getFunctionType()->params(),
350 LLVM_DEBUG(
dbgs() <<
"Computed new return type: " << *NewRetTy <<
'\n');
353 F.getName() +
".body");
354 F.getParent()->getFunctionList().insert(
F.getIterator(), NewFunc);
370 for (
auto &Replacement : Replacements) {
371 ReturnInst *RI = Replacement.first;
379 NewRetVal =
B.CreateInsertValue(NewRetVal, RetVal, 0);
382 for (std::pair<Argument *, Value *> ReturnPoint : Replacement.second) {
383 unsigned FieldIdx = OutArgIndexes.
lookup(ReturnPoint.first->getArgNo());
384 NewRetVal =
B.CreateInsertValue(NewRetVal, ReturnPoint.second, FieldIdx);
390 B.CreateRet(NewRetVal);
395 SmallVector<Value *, 16> StubCallArgs;
396 for (Argument &Arg :
F.args()) {
408 CallInst *StubCall =
B.CreateCall(NewFunc, StubCallArgs);
410 for (Argument &Arg :
F.args()) {
412 if (It == OutArgIndexes.
end())
415 unsigned FieldIdx = It->second;
420 Value *Val =
B.CreateExtractValue(StubCall, FieldIdx);
421 B.CreateAlignedStore(Val, &Arg, Align);
425 B.CreateRet(
B.CreateExtractValue(StubCall, 0));
431 F.addFnAttr(Attribute::AlwaysInline);
433 ++NumOutArgumentFunctionsReplaced;
static StoreInst * findStoreForOutArgument(BasicBlock *BB, Argument *OutArg, MemorySSA &MSSA, BatchAAResults &BAA)
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the simple types necessary to represent the attributes associated with functions a...
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.
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.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
iterator find(const_arg_type_t< KeyT > Val)
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.
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.
AttributeList getAttributes() const
Return the attribute list for this Function.
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)
@ BasicBlock
Various leaf nodes.
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.
@ Store
The extracted value is stored (ExtractElement only).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
auto reverse(ContainerTy &&C)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
bool isModOrRefSet(const ModRefInfo MRI)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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,...