18bcb0991SDimitry Andric //=== AMDGPUPrintfRuntimeBinding.cpp - OpenCL printf implementation -------===// 28bcb0991SDimitry Andric // 38bcb0991SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 48bcb0991SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 58bcb0991SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 68bcb0991SDimitry Andric // 78bcb0991SDimitry Andric //===----------------------------------------------------------------------===// 88bcb0991SDimitry Andric // \file 98bcb0991SDimitry Andric // 108bcb0991SDimitry Andric // The pass bind printfs to a kernel arg pointer that will be bound to a buffer 118bcb0991SDimitry Andric // later by the runtime. 128bcb0991SDimitry Andric // 138bcb0991SDimitry Andric // This pass traverses the functions in the module and converts 148bcb0991SDimitry Andric // each call to printf to a sequence of operations that 158bcb0991SDimitry Andric // store the following into the printf buffer: 168bcb0991SDimitry Andric // - format string (passed as a module's metadata unique ID) 178bcb0991SDimitry Andric // - bitwise copies of printf arguments 188bcb0991SDimitry Andric // The backend passes will need to store metadata in the kernel 198bcb0991SDimitry Andric //===----------------------------------------------------------------------===// 208bcb0991SDimitry Andric 218bcb0991SDimitry Andric #include "AMDGPU.h" 22*81ad6265SDimitry Andric #include "llvm/ADT/Triple.h" 238bcb0991SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h" 248bcb0991SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h" 258bcb0991SDimitry Andric #include "llvm/IR/Dominators.h" 268bcb0991SDimitry Andric #include "llvm/IR/IRBuilder.h" 278bcb0991SDimitry Andric #include "llvm/IR/Instructions.h" 28480093f4SDimitry Andric #include "llvm/InitializePasses.h" 298bcb0991SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h" 30e8d8bef9SDimitry Andric 318bcb0991SDimitry Andric using namespace llvm; 328bcb0991SDimitry Andric 338bcb0991SDimitry Andric #define DEBUG_TYPE "printfToRuntime" 348bcb0991SDimitry Andric #define DWORD_ALIGN 4 358bcb0991SDimitry Andric 368bcb0991SDimitry Andric namespace { 37e8d8bef9SDimitry Andric class AMDGPUPrintfRuntimeBinding final : public ModulePass { 388bcb0991SDimitry Andric 398bcb0991SDimitry Andric public: 408bcb0991SDimitry Andric static char ID; 418bcb0991SDimitry Andric 428bcb0991SDimitry Andric explicit AMDGPUPrintfRuntimeBinding(); 438bcb0991SDimitry Andric 448bcb0991SDimitry Andric private: 458bcb0991SDimitry Andric bool runOnModule(Module &M) override; 468bcb0991SDimitry Andric 478bcb0991SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override { 488bcb0991SDimitry Andric AU.addRequired<TargetLibraryInfoWrapperPass>(); 498bcb0991SDimitry Andric AU.addRequired<DominatorTreeWrapperPass>(); 508bcb0991SDimitry Andric } 51e8d8bef9SDimitry Andric }; 528bcb0991SDimitry Andric 53e8d8bef9SDimitry Andric class AMDGPUPrintfRuntimeBindingImpl { 54e8d8bef9SDimitry Andric public: 55e8d8bef9SDimitry Andric AMDGPUPrintfRuntimeBindingImpl( 56e8d8bef9SDimitry Andric function_ref<const DominatorTree &(Function &)> GetDT, 57e8d8bef9SDimitry Andric function_ref<const TargetLibraryInfo &(Function &)> GetTLI) 58e8d8bef9SDimitry Andric : GetDT(GetDT), GetTLI(GetTLI) {} 59e8d8bef9SDimitry Andric bool run(Module &M); 60e8d8bef9SDimitry Andric 61e8d8bef9SDimitry Andric private: 62e8d8bef9SDimitry Andric void getConversionSpecifiers(SmallVectorImpl<char> &OpConvSpecifiers, 63e8d8bef9SDimitry Andric StringRef fmt, size_t num_ops) const; 64e8d8bef9SDimitry Andric 65e8d8bef9SDimitry Andric bool shouldPrintAsStr(char Specifier, Type *OpType) const; 66e8d8bef9SDimitry Andric bool lowerPrintfForGpu(Module &M); 67e8d8bef9SDimitry Andric 68e8d8bef9SDimitry Andric Value *simplify(Instruction *I, const TargetLibraryInfo *TLI, 69e8d8bef9SDimitry Andric const DominatorTree *DT) { 70*81ad6265SDimitry Andric return simplifyInstruction(I, {*TD, TLI, DT}); 718bcb0991SDimitry Andric } 728bcb0991SDimitry Andric 738bcb0991SDimitry Andric const DataLayout *TD; 74e8d8bef9SDimitry Andric function_ref<const DominatorTree &(Function &)> GetDT; 75e8d8bef9SDimitry Andric function_ref<const TargetLibraryInfo &(Function &)> GetTLI; 768bcb0991SDimitry Andric SmallVector<CallInst *, 32> Printfs; 778bcb0991SDimitry Andric }; 788bcb0991SDimitry Andric } // namespace 798bcb0991SDimitry Andric 808bcb0991SDimitry Andric char AMDGPUPrintfRuntimeBinding::ID = 0; 818bcb0991SDimitry Andric 828bcb0991SDimitry Andric INITIALIZE_PASS_BEGIN(AMDGPUPrintfRuntimeBinding, 838bcb0991SDimitry Andric "amdgpu-printf-runtime-binding", "AMDGPU Printf lowering", 848bcb0991SDimitry Andric false, false) 858bcb0991SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 868bcb0991SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 878bcb0991SDimitry Andric INITIALIZE_PASS_END(AMDGPUPrintfRuntimeBinding, "amdgpu-printf-runtime-binding", 888bcb0991SDimitry Andric "AMDGPU Printf lowering", false, false) 898bcb0991SDimitry Andric 908bcb0991SDimitry Andric char &llvm::AMDGPUPrintfRuntimeBindingID = AMDGPUPrintfRuntimeBinding::ID; 918bcb0991SDimitry Andric 928bcb0991SDimitry Andric namespace llvm { 938bcb0991SDimitry Andric ModulePass *createAMDGPUPrintfRuntimeBinding() { 948bcb0991SDimitry Andric return new AMDGPUPrintfRuntimeBinding(); 958bcb0991SDimitry Andric } 968bcb0991SDimitry Andric } // namespace llvm 978bcb0991SDimitry Andric 98e8d8bef9SDimitry Andric AMDGPUPrintfRuntimeBinding::AMDGPUPrintfRuntimeBinding() : ModulePass(ID) { 998bcb0991SDimitry Andric initializeAMDGPUPrintfRuntimeBindingPass(*PassRegistry::getPassRegistry()); 1008bcb0991SDimitry Andric } 1018bcb0991SDimitry Andric 102e8d8bef9SDimitry Andric void AMDGPUPrintfRuntimeBindingImpl::getConversionSpecifiers( 1038bcb0991SDimitry Andric SmallVectorImpl<char> &OpConvSpecifiers, StringRef Fmt, 1048bcb0991SDimitry Andric size_t NumOps) const { 1058bcb0991SDimitry Andric // not all format characters are collected. 1068bcb0991SDimitry Andric // At this time the format characters of interest 1078bcb0991SDimitry Andric // are %p and %s, which use to know if we 1088bcb0991SDimitry Andric // are either storing a literal string or a 1098bcb0991SDimitry Andric // pointer to the printf buffer. 1108bcb0991SDimitry Andric static const char ConvSpecifiers[] = "cdieEfgGaosuxXp"; 1118bcb0991SDimitry Andric size_t CurFmtSpecifierIdx = 0; 1128bcb0991SDimitry Andric size_t PrevFmtSpecifierIdx = 0; 1138bcb0991SDimitry Andric 1148bcb0991SDimitry Andric while ((CurFmtSpecifierIdx = Fmt.find_first_of( 1158bcb0991SDimitry Andric ConvSpecifiers, CurFmtSpecifierIdx)) != StringRef::npos) { 1168bcb0991SDimitry Andric bool ArgDump = false; 1178bcb0991SDimitry Andric StringRef CurFmt = Fmt.substr(PrevFmtSpecifierIdx, 1188bcb0991SDimitry Andric CurFmtSpecifierIdx - PrevFmtSpecifierIdx); 1198bcb0991SDimitry Andric size_t pTag = CurFmt.find_last_of("%"); 1208bcb0991SDimitry Andric if (pTag != StringRef::npos) { 1218bcb0991SDimitry Andric ArgDump = true; 1228bcb0991SDimitry Andric while (pTag && CurFmt[--pTag] == '%') { 1238bcb0991SDimitry Andric ArgDump = !ArgDump; 1248bcb0991SDimitry Andric } 1258bcb0991SDimitry Andric } 1268bcb0991SDimitry Andric 1278bcb0991SDimitry Andric if (ArgDump) 1288bcb0991SDimitry Andric OpConvSpecifiers.push_back(Fmt[CurFmtSpecifierIdx]); 1298bcb0991SDimitry Andric 1308bcb0991SDimitry Andric PrevFmtSpecifierIdx = ++CurFmtSpecifierIdx; 1318bcb0991SDimitry Andric } 1328bcb0991SDimitry Andric } 1338bcb0991SDimitry Andric 134e8d8bef9SDimitry Andric bool AMDGPUPrintfRuntimeBindingImpl::shouldPrintAsStr(char Specifier, 1358bcb0991SDimitry Andric Type *OpType) const { 1368bcb0991SDimitry Andric if (Specifier != 's') 1378bcb0991SDimitry Andric return false; 1388bcb0991SDimitry Andric const PointerType *PT = dyn_cast<PointerType>(OpType); 1398bcb0991SDimitry Andric if (!PT || PT->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS) 1408bcb0991SDimitry Andric return false; 1418bcb0991SDimitry Andric Type *ElemType = PT->getContainedType(0); 1428bcb0991SDimitry Andric if (ElemType->getTypeID() != Type::IntegerTyID) 1438bcb0991SDimitry Andric return false; 1448bcb0991SDimitry Andric IntegerType *ElemIType = cast<IntegerType>(ElemType); 1458bcb0991SDimitry Andric return ElemIType->getBitWidth() == 8; 1468bcb0991SDimitry Andric } 1478bcb0991SDimitry Andric 148e8d8bef9SDimitry Andric bool AMDGPUPrintfRuntimeBindingImpl::lowerPrintfForGpu(Module &M) { 1498bcb0991SDimitry Andric LLVMContext &Ctx = M.getContext(); 1508bcb0991SDimitry Andric IRBuilder<> Builder(Ctx); 1518bcb0991SDimitry Andric Type *I32Ty = Type::getInt32Ty(Ctx); 1528bcb0991SDimitry Andric unsigned UniqID = 0; 153349cc55cSDimitry Andric // NB: This is important for this string size to be divisible by 4 1548bcb0991SDimitry Andric const char NonLiteralStr[4] = "???"; 1558bcb0991SDimitry Andric 1568bcb0991SDimitry Andric for (auto CI : Printfs) { 157349cc55cSDimitry Andric unsigned NumOps = CI->arg_size(); 1588bcb0991SDimitry Andric 1598bcb0991SDimitry Andric SmallString<16> OpConvSpecifiers; 1608bcb0991SDimitry Andric Value *Op = CI->getArgOperand(0); 1618bcb0991SDimitry Andric 1628bcb0991SDimitry Andric if (auto LI = dyn_cast<LoadInst>(Op)) { 1638bcb0991SDimitry Andric Op = LI->getPointerOperand(); 1648bcb0991SDimitry Andric for (auto Use : Op->users()) { 1658bcb0991SDimitry Andric if (auto SI = dyn_cast<StoreInst>(Use)) { 1668bcb0991SDimitry Andric Op = SI->getValueOperand(); 1678bcb0991SDimitry Andric break; 1688bcb0991SDimitry Andric } 1698bcb0991SDimitry Andric } 1708bcb0991SDimitry Andric } 1718bcb0991SDimitry Andric 1728bcb0991SDimitry Andric if (auto I = dyn_cast<Instruction>(Op)) { 173e8d8bef9SDimitry Andric Value *Op_simplified = 174e8d8bef9SDimitry Andric simplify(I, &GetTLI(*I->getFunction()), &GetDT(*I->getFunction())); 1758bcb0991SDimitry Andric if (Op_simplified) 1768bcb0991SDimitry Andric Op = Op_simplified; 1778bcb0991SDimitry Andric } 1788bcb0991SDimitry Andric 1798bcb0991SDimitry Andric ConstantExpr *ConstExpr = dyn_cast<ConstantExpr>(Op); 1808bcb0991SDimitry Andric 1818bcb0991SDimitry Andric if (ConstExpr) { 1828bcb0991SDimitry Andric GlobalVariable *GVar = dyn_cast<GlobalVariable>(ConstExpr->getOperand(0)); 1838bcb0991SDimitry Andric 1848bcb0991SDimitry Andric StringRef Str("unknown"); 1858bcb0991SDimitry Andric if (GVar && GVar->hasInitializer()) { 186e8d8bef9SDimitry Andric auto *Init = GVar->getInitializer(); 187e8d8bef9SDimitry Andric if (auto *CA = dyn_cast<ConstantDataArray>(Init)) { 1888bcb0991SDimitry Andric if (CA->isString()) 1898bcb0991SDimitry Andric Str = CA->getAsCString(); 1908bcb0991SDimitry Andric } else if (isa<ConstantAggregateZero>(Init)) { 1918bcb0991SDimitry Andric Str = ""; 1928bcb0991SDimitry Andric } 1938bcb0991SDimitry Andric // 1948bcb0991SDimitry Andric // we need this call to ascertain 1958bcb0991SDimitry Andric // that we are printing a string 1968bcb0991SDimitry Andric // or a pointer. It takes out the 1978bcb0991SDimitry Andric // specifiers and fills up the first 1988bcb0991SDimitry Andric // arg 1998bcb0991SDimitry Andric getConversionSpecifiers(OpConvSpecifiers, Str, NumOps - 1); 2008bcb0991SDimitry Andric } 2018bcb0991SDimitry Andric // Add metadata for the string 2028bcb0991SDimitry Andric std::string AStreamHolder; 2038bcb0991SDimitry Andric raw_string_ostream Sizes(AStreamHolder); 2048bcb0991SDimitry Andric int Sum = DWORD_ALIGN; 205349cc55cSDimitry Andric Sizes << CI->arg_size() - 1; 2068bcb0991SDimitry Andric Sizes << ':'; 207349cc55cSDimitry Andric for (unsigned ArgCount = 1; 208349cc55cSDimitry Andric ArgCount < CI->arg_size() && ArgCount <= OpConvSpecifiers.size(); 2098bcb0991SDimitry Andric ArgCount++) { 2108bcb0991SDimitry Andric Value *Arg = CI->getArgOperand(ArgCount); 2118bcb0991SDimitry Andric Type *ArgType = Arg->getType(); 2128bcb0991SDimitry Andric unsigned ArgSize = TD->getTypeAllocSizeInBits(ArgType); 2138bcb0991SDimitry Andric ArgSize = ArgSize / 8; 2148bcb0991SDimitry Andric // 2158bcb0991SDimitry Andric // ArgSize by design should be a multiple of DWORD_ALIGN, 2168bcb0991SDimitry Andric // expand the arguments that do not follow this rule. 2178bcb0991SDimitry Andric // 2188bcb0991SDimitry Andric if (ArgSize % DWORD_ALIGN != 0) { 2198bcb0991SDimitry Andric llvm::Type *ResType = llvm::Type::getInt32Ty(Ctx); 2205ffd83dbSDimitry Andric auto *LLVMVecType = llvm::dyn_cast<llvm::FixedVectorType>(ArgType); 2218bcb0991SDimitry Andric int NumElem = LLVMVecType ? LLVMVecType->getNumElements() : 1; 2228bcb0991SDimitry Andric if (LLVMVecType && NumElem > 1) 2235ffd83dbSDimitry Andric ResType = llvm::FixedVectorType::get(ResType, NumElem); 2248bcb0991SDimitry Andric Builder.SetInsertPoint(CI); 2258bcb0991SDimitry Andric Builder.SetCurrentDebugLocation(CI->getDebugLoc()); 2268bcb0991SDimitry Andric if (OpConvSpecifiers[ArgCount - 1] == 'x' || 2278bcb0991SDimitry Andric OpConvSpecifiers[ArgCount - 1] == 'X' || 2288bcb0991SDimitry Andric OpConvSpecifiers[ArgCount - 1] == 'u' || 2298bcb0991SDimitry Andric OpConvSpecifiers[ArgCount - 1] == 'o') 2308bcb0991SDimitry Andric Arg = Builder.CreateZExt(Arg, ResType); 2318bcb0991SDimitry Andric else 2328bcb0991SDimitry Andric Arg = Builder.CreateSExt(Arg, ResType); 2338bcb0991SDimitry Andric ArgType = Arg->getType(); 2348bcb0991SDimitry Andric ArgSize = TD->getTypeAllocSizeInBits(ArgType); 2358bcb0991SDimitry Andric ArgSize = ArgSize / 8; 2368bcb0991SDimitry Andric CI->setOperand(ArgCount, Arg); 2378bcb0991SDimitry Andric } 2388bcb0991SDimitry Andric if (OpConvSpecifiers[ArgCount - 1] == 'f') { 2398bcb0991SDimitry Andric ConstantFP *FpCons = dyn_cast<ConstantFP>(Arg); 2408bcb0991SDimitry Andric if (FpCons) 2418bcb0991SDimitry Andric ArgSize = 4; 2428bcb0991SDimitry Andric else { 2438bcb0991SDimitry Andric FPExtInst *FpExt = dyn_cast<FPExtInst>(Arg); 2448bcb0991SDimitry Andric if (FpExt && FpExt->getType()->isDoubleTy() && 2458bcb0991SDimitry Andric FpExt->getOperand(0)->getType()->isFloatTy()) 2468bcb0991SDimitry Andric ArgSize = 4; 2478bcb0991SDimitry Andric } 2488bcb0991SDimitry Andric } 2498bcb0991SDimitry Andric if (shouldPrintAsStr(OpConvSpecifiers[ArgCount - 1], ArgType)) { 250e8d8bef9SDimitry Andric if (auto *ConstExpr = dyn_cast<ConstantExpr>(Arg)) { 251e8d8bef9SDimitry Andric auto *GV = dyn_cast<GlobalVariable>(ConstExpr->getOperand(0)); 2528bcb0991SDimitry Andric if (GV && GV->hasInitializer()) { 2538bcb0991SDimitry Andric Constant *Init = GV->getInitializer(); 254e8d8bef9SDimitry Andric bool IsZeroValue = Init->isZeroValue(); 255e8d8bef9SDimitry Andric auto *CA = dyn_cast<ConstantDataArray>(Init); 256e8d8bef9SDimitry Andric if (IsZeroValue || (CA && CA->isString())) { 257e8d8bef9SDimitry Andric size_t SizeStr = 258e8d8bef9SDimitry Andric IsZeroValue ? 1 : (strlen(CA->getAsCString().data()) + 1); 2598bcb0991SDimitry Andric size_t Rem = SizeStr % DWORD_ALIGN; 2608bcb0991SDimitry Andric size_t NSizeStr = 0; 2618bcb0991SDimitry Andric LLVM_DEBUG(dbgs() << "Printf string original size = " << SizeStr 2628bcb0991SDimitry Andric << '\n'); 2638bcb0991SDimitry Andric if (Rem) { 2648bcb0991SDimitry Andric NSizeStr = SizeStr + (DWORD_ALIGN - Rem); 2658bcb0991SDimitry Andric } else { 2668bcb0991SDimitry Andric NSizeStr = SizeStr; 2678bcb0991SDimitry Andric } 2688bcb0991SDimitry Andric ArgSize = NSizeStr; 2698bcb0991SDimitry Andric } 2708bcb0991SDimitry Andric } else { 2718bcb0991SDimitry Andric ArgSize = sizeof(NonLiteralStr); 2728bcb0991SDimitry Andric } 2738bcb0991SDimitry Andric } else { 2748bcb0991SDimitry Andric ArgSize = sizeof(NonLiteralStr); 2758bcb0991SDimitry Andric } 2768bcb0991SDimitry Andric } 2778bcb0991SDimitry Andric LLVM_DEBUG(dbgs() << "Printf ArgSize (in buffer) = " << ArgSize 2788bcb0991SDimitry Andric << " for type: " << *ArgType << '\n'); 2798bcb0991SDimitry Andric Sizes << ArgSize << ':'; 2808bcb0991SDimitry Andric Sum += ArgSize; 2818bcb0991SDimitry Andric } 2828bcb0991SDimitry Andric LLVM_DEBUG(dbgs() << "Printf format string in source = " << Str.str() 2838bcb0991SDimitry Andric << '\n'); 2844824e7fdSDimitry Andric for (char C : Str) { 2858bcb0991SDimitry Andric // Rest of the C escape sequences (e.g. \') are handled correctly 2868bcb0991SDimitry Andric // by the MDParser 2874824e7fdSDimitry Andric switch (C) { 2888bcb0991SDimitry Andric case '\a': 2898bcb0991SDimitry Andric Sizes << "\\a"; 2908bcb0991SDimitry Andric break; 2918bcb0991SDimitry Andric case '\b': 2928bcb0991SDimitry Andric Sizes << "\\b"; 2938bcb0991SDimitry Andric break; 2948bcb0991SDimitry Andric case '\f': 2958bcb0991SDimitry Andric Sizes << "\\f"; 2968bcb0991SDimitry Andric break; 2978bcb0991SDimitry Andric case '\n': 2988bcb0991SDimitry Andric Sizes << "\\n"; 2998bcb0991SDimitry Andric break; 3008bcb0991SDimitry Andric case '\r': 3018bcb0991SDimitry Andric Sizes << "\\r"; 3028bcb0991SDimitry Andric break; 3038bcb0991SDimitry Andric case '\v': 3048bcb0991SDimitry Andric Sizes << "\\v"; 3058bcb0991SDimitry Andric break; 3068bcb0991SDimitry Andric case ':': 3078bcb0991SDimitry Andric // ':' cannot be scanned by Flex, as it is defined as a delimiter 3088bcb0991SDimitry Andric // Replace it with it's octal representation \72 3098bcb0991SDimitry Andric Sizes << "\\72"; 3108bcb0991SDimitry Andric break; 3118bcb0991SDimitry Andric default: 3124824e7fdSDimitry Andric Sizes << C; 3138bcb0991SDimitry Andric break; 3148bcb0991SDimitry Andric } 3158bcb0991SDimitry Andric } 3168bcb0991SDimitry Andric 3178bcb0991SDimitry Andric // Insert the printf_alloc call 3188bcb0991SDimitry Andric Builder.SetInsertPoint(CI); 3198bcb0991SDimitry Andric Builder.SetCurrentDebugLocation(CI->getDebugLoc()); 3208bcb0991SDimitry Andric 3218bcb0991SDimitry Andric AttributeList Attr = AttributeList::get(Ctx, AttributeList::FunctionIndex, 3228bcb0991SDimitry Andric Attribute::NoUnwind); 3238bcb0991SDimitry Andric 3248bcb0991SDimitry Andric Type *SizetTy = Type::getInt32Ty(Ctx); 3258bcb0991SDimitry Andric 3268bcb0991SDimitry Andric Type *Tys_alloc[1] = {SizetTy}; 327fe6060f1SDimitry Andric Type *I8Ty = Type::getInt8Ty(Ctx); 328fe6060f1SDimitry Andric Type *I8Ptr = PointerType::get(I8Ty, 1); 3298bcb0991SDimitry Andric FunctionType *FTy_alloc = FunctionType::get(I8Ptr, Tys_alloc, false); 3308bcb0991SDimitry Andric FunctionCallee PrintfAllocFn = 3318bcb0991SDimitry Andric M.getOrInsertFunction(StringRef("__printf_alloc"), FTy_alloc, Attr); 3328bcb0991SDimitry Andric 3338bcb0991SDimitry Andric LLVM_DEBUG(dbgs() << "Printf metadata = " << Sizes.str() << '\n'); 334349cc55cSDimitry Andric std::string fmtstr = itostr(++UniqID) + ":" + Sizes.str(); 3358bcb0991SDimitry Andric MDString *fmtStrArray = MDString::get(Ctx, fmtstr); 3368bcb0991SDimitry Andric 3378bcb0991SDimitry Andric // Instead of creating global variables, the 3388bcb0991SDimitry Andric // printf format strings are extracted 3398bcb0991SDimitry Andric // and passed as metadata. This avoids 3408bcb0991SDimitry Andric // polluting llvm's symbol tables in this module. 3418bcb0991SDimitry Andric // Metadata is going to be extracted 3428bcb0991SDimitry Andric // by the backend passes and inserted 3438bcb0991SDimitry Andric // into the OpenCL binary as appropriate. 3448bcb0991SDimitry Andric StringRef amd("llvm.printf.fmts"); 3458bcb0991SDimitry Andric NamedMDNode *metaD = M.getOrInsertNamedMetadata(amd); 3468bcb0991SDimitry Andric MDNode *myMD = MDNode::get(Ctx, fmtStrArray); 3478bcb0991SDimitry Andric metaD->addOperand(myMD); 3488bcb0991SDimitry Andric Value *sumC = ConstantInt::get(SizetTy, Sum, false); 3498bcb0991SDimitry Andric SmallVector<Value *, 1> alloc_args; 3508bcb0991SDimitry Andric alloc_args.push_back(sumC); 3518bcb0991SDimitry Andric CallInst *pcall = 3528bcb0991SDimitry Andric CallInst::Create(PrintfAllocFn, alloc_args, "printf_alloc_fn", CI); 3538bcb0991SDimitry Andric 3548bcb0991SDimitry Andric // 3558bcb0991SDimitry Andric // Insert code to split basicblock with a 3568bcb0991SDimitry Andric // piece of hammock code. 3578bcb0991SDimitry Andric // basicblock splits after buffer overflow check 3588bcb0991SDimitry Andric // 3598bcb0991SDimitry Andric ConstantPointerNull *zeroIntPtr = 360fe6060f1SDimitry Andric ConstantPointerNull::get(PointerType::get(I8Ty, 1)); 361fe6060f1SDimitry Andric auto *cmp = cast<ICmpInst>(Builder.CreateICmpNE(pcall, zeroIntPtr, "")); 3628bcb0991SDimitry Andric if (!CI->use_empty()) { 3638bcb0991SDimitry Andric Value *result = 3648bcb0991SDimitry Andric Builder.CreateSExt(Builder.CreateNot(cmp), I32Ty, "printf_res"); 3658bcb0991SDimitry Andric CI->replaceAllUsesWith(result); 3668bcb0991SDimitry Andric } 3678bcb0991SDimitry Andric SplitBlock(CI->getParent(), cmp); 3688bcb0991SDimitry Andric Instruction *Brnch = 3698bcb0991SDimitry Andric SplitBlockAndInsertIfThen(cmp, cmp->getNextNode(), false); 3708bcb0991SDimitry Andric 3718bcb0991SDimitry Andric Builder.SetInsertPoint(Brnch); 3728bcb0991SDimitry Andric 3738bcb0991SDimitry Andric // store unique printf id in the buffer 3748bcb0991SDimitry Andric // 375e8d8bef9SDimitry Andric GetElementPtrInst *BufferIdx = GetElementPtrInst::Create( 376fe6060f1SDimitry Andric I8Ty, pcall, ConstantInt::get(Ctx, APInt(32, 0)), "PrintBuffID", 377fe6060f1SDimitry Andric Brnch); 3788bcb0991SDimitry Andric 3798bcb0991SDimitry Andric Type *idPointer = PointerType::get(I32Ty, AMDGPUAS::GLOBAL_ADDRESS); 3808bcb0991SDimitry Andric Value *id_gep_cast = 3818bcb0991SDimitry Andric new BitCastInst(BufferIdx, idPointer, "PrintBuffIdCast", Brnch); 3828bcb0991SDimitry Andric 3835ffd83dbSDimitry Andric new StoreInst(ConstantInt::get(I32Ty, UniqID), id_gep_cast, Brnch); 3848bcb0991SDimitry Andric 385fe6060f1SDimitry Andric // 1st 4 bytes hold the printf_id 3868bcb0991SDimitry Andric // the following GEP is the buffer pointer 387fe6060f1SDimitry Andric BufferIdx = GetElementPtrInst::Create( 388fe6060f1SDimitry Andric I8Ty, pcall, ConstantInt::get(Ctx, APInt(32, 4)), "PrintBuffGep", 389fe6060f1SDimitry Andric Brnch); 3908bcb0991SDimitry Andric 3918bcb0991SDimitry Andric Type *Int32Ty = Type::getInt32Ty(Ctx); 3928bcb0991SDimitry Andric Type *Int64Ty = Type::getInt64Ty(Ctx); 393349cc55cSDimitry Andric for (unsigned ArgCount = 1; 394349cc55cSDimitry Andric ArgCount < CI->arg_size() && ArgCount <= OpConvSpecifiers.size(); 3958bcb0991SDimitry Andric ArgCount++) { 3968bcb0991SDimitry Andric Value *Arg = CI->getArgOperand(ArgCount); 3978bcb0991SDimitry Andric Type *ArgType = Arg->getType(); 3988bcb0991SDimitry Andric SmallVector<Value *, 32> WhatToStore; 3995ffd83dbSDimitry Andric if (ArgType->isFPOrFPVectorTy() && !isa<VectorType>(ArgType)) { 4008bcb0991SDimitry Andric Type *IType = (ArgType->isFloatTy()) ? Int32Ty : Int64Ty; 4018bcb0991SDimitry Andric if (OpConvSpecifiers[ArgCount - 1] == 'f') { 402e8d8bef9SDimitry Andric if (auto *FpCons = dyn_cast<ConstantFP>(Arg)) { 403e8d8bef9SDimitry Andric APFloat Val(FpCons->getValueAPF()); 4048bcb0991SDimitry Andric bool Lost = false; 4058bcb0991SDimitry Andric Val.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 4068bcb0991SDimitry Andric &Lost); 4078bcb0991SDimitry Andric Arg = ConstantFP::get(Ctx, Val); 4088bcb0991SDimitry Andric IType = Int32Ty; 409e8d8bef9SDimitry Andric } else if (auto *FpExt = dyn_cast<FPExtInst>(Arg)) { 410e8d8bef9SDimitry Andric if (FpExt->getType()->isDoubleTy() && 4118bcb0991SDimitry Andric FpExt->getOperand(0)->getType()->isFloatTy()) { 4128bcb0991SDimitry Andric Arg = FpExt->getOperand(0); 4138bcb0991SDimitry Andric IType = Int32Ty; 4148bcb0991SDimitry Andric } 4158bcb0991SDimitry Andric } 4168bcb0991SDimitry Andric } 4178bcb0991SDimitry Andric Arg = new BitCastInst(Arg, IType, "PrintArgFP", Brnch); 4188bcb0991SDimitry Andric WhatToStore.push_back(Arg); 4198bcb0991SDimitry Andric } else if (ArgType->getTypeID() == Type::PointerTyID) { 4208bcb0991SDimitry Andric if (shouldPrintAsStr(OpConvSpecifiers[ArgCount - 1], ArgType)) { 4218bcb0991SDimitry Andric const char *S = NonLiteralStr; 422e8d8bef9SDimitry Andric if (auto *ConstExpr = dyn_cast<ConstantExpr>(Arg)) { 423e8d8bef9SDimitry Andric auto *GV = dyn_cast<GlobalVariable>(ConstExpr->getOperand(0)); 4248bcb0991SDimitry Andric if (GV && GV->hasInitializer()) { 4258bcb0991SDimitry Andric Constant *Init = GV->getInitializer(); 426e8d8bef9SDimitry Andric bool IsZeroValue = Init->isZeroValue(); 427e8d8bef9SDimitry Andric auto *CA = dyn_cast<ConstantDataArray>(Init); 428e8d8bef9SDimitry Andric if (IsZeroValue || (CA && CA->isString())) { 429e8d8bef9SDimitry Andric S = IsZeroValue ? "" : CA->getAsCString().data(); 4308bcb0991SDimitry Andric } 4318bcb0991SDimitry Andric } 4328bcb0991SDimitry Andric } 4338bcb0991SDimitry Andric size_t SizeStr = strlen(S) + 1; 4348bcb0991SDimitry Andric size_t Rem = SizeStr % DWORD_ALIGN; 4358bcb0991SDimitry Andric size_t NSizeStr = 0; 4368bcb0991SDimitry Andric if (Rem) { 4378bcb0991SDimitry Andric NSizeStr = SizeStr + (DWORD_ALIGN - Rem); 4388bcb0991SDimitry Andric } else { 4398bcb0991SDimitry Andric NSizeStr = SizeStr; 4408bcb0991SDimitry Andric } 4418bcb0991SDimitry Andric if (S[0]) { 4428bcb0991SDimitry Andric char *MyNewStr = new char[NSizeStr](); 4438bcb0991SDimitry Andric strcpy(MyNewStr, S); 4448bcb0991SDimitry Andric int NumInts = NSizeStr / 4; 4458bcb0991SDimitry Andric int CharC = 0; 4468bcb0991SDimitry Andric while (NumInts) { 4478bcb0991SDimitry Andric int ANum = *(int *)(MyNewStr + CharC); 4488bcb0991SDimitry Andric CharC += 4; 4498bcb0991SDimitry Andric NumInts--; 4508bcb0991SDimitry Andric Value *ANumV = ConstantInt::get(Int32Ty, ANum, false); 4518bcb0991SDimitry Andric WhatToStore.push_back(ANumV); 4528bcb0991SDimitry Andric } 4538bcb0991SDimitry Andric delete[] MyNewStr; 4548bcb0991SDimitry Andric } else { 4558bcb0991SDimitry Andric // Empty string, give a hint to RT it is no NULL 4568bcb0991SDimitry Andric Value *ANumV = ConstantInt::get(Int32Ty, 0xFFFFFF00, false); 4578bcb0991SDimitry Andric WhatToStore.push_back(ANumV); 4588bcb0991SDimitry Andric } 4598bcb0991SDimitry Andric } else { 4608bcb0991SDimitry Andric uint64_t Size = TD->getTypeAllocSizeInBits(ArgType); 4618bcb0991SDimitry Andric assert((Size == 32 || Size == 64) && "unsupported size"); 4628bcb0991SDimitry Andric Type *DstType = (Size == 32) ? Int32Ty : Int64Ty; 4638bcb0991SDimitry Andric Arg = new PtrToIntInst(Arg, DstType, "PrintArgPtr", Brnch); 4648bcb0991SDimitry Andric WhatToStore.push_back(Arg); 4658bcb0991SDimitry Andric } 4665ffd83dbSDimitry Andric } else if (isa<FixedVectorType>(ArgType)) { 46704eeddc0SDimitry Andric Type *IType = nullptr; 4685ffd83dbSDimitry Andric uint32_t EleCount = cast<FixedVectorType>(ArgType)->getNumElements(); 4698bcb0991SDimitry Andric uint32_t EleSize = ArgType->getScalarSizeInBits(); 4708bcb0991SDimitry Andric uint32_t TotalSize = EleCount * EleSize; 4718bcb0991SDimitry Andric if (EleCount == 3) { 4725ffd83dbSDimitry Andric ShuffleVectorInst *Shuffle = 4735ffd83dbSDimitry Andric new ShuffleVectorInst(Arg, Arg, ArrayRef<int>{0, 1, 2, 2}); 4748bcb0991SDimitry Andric Shuffle->insertBefore(Brnch); 4758bcb0991SDimitry Andric Arg = Shuffle; 4768bcb0991SDimitry Andric ArgType = Arg->getType(); 4778bcb0991SDimitry Andric TotalSize += EleSize; 4788bcb0991SDimitry Andric } 4798bcb0991SDimitry Andric switch (EleSize) { 4808bcb0991SDimitry Andric default: 4818bcb0991SDimitry Andric EleCount = TotalSize / 64; 482e8d8bef9SDimitry Andric IType = Type::getInt64Ty(ArgType->getContext()); 4838bcb0991SDimitry Andric break; 4848bcb0991SDimitry Andric case 8: 4858bcb0991SDimitry Andric if (EleCount >= 8) { 4868bcb0991SDimitry Andric EleCount = TotalSize / 64; 487e8d8bef9SDimitry Andric IType = Type::getInt64Ty(ArgType->getContext()); 4888bcb0991SDimitry Andric } else if (EleCount >= 3) { 4898bcb0991SDimitry Andric EleCount = 1; 490e8d8bef9SDimitry Andric IType = Type::getInt32Ty(ArgType->getContext()); 4918bcb0991SDimitry Andric } else { 4928bcb0991SDimitry Andric EleCount = 1; 493e8d8bef9SDimitry Andric IType = Type::getInt16Ty(ArgType->getContext()); 4948bcb0991SDimitry Andric } 4958bcb0991SDimitry Andric break; 4968bcb0991SDimitry Andric case 16: 4978bcb0991SDimitry Andric if (EleCount >= 3) { 4988bcb0991SDimitry Andric EleCount = TotalSize / 64; 499e8d8bef9SDimitry Andric IType = Type::getInt64Ty(ArgType->getContext()); 5008bcb0991SDimitry Andric } else { 5018bcb0991SDimitry Andric EleCount = 1; 502e8d8bef9SDimitry Andric IType = Type::getInt32Ty(ArgType->getContext()); 5038bcb0991SDimitry Andric } 5048bcb0991SDimitry Andric break; 5058bcb0991SDimitry Andric } 5068bcb0991SDimitry Andric if (EleCount > 1) { 5075ffd83dbSDimitry Andric IType = FixedVectorType::get(IType, EleCount); 5088bcb0991SDimitry Andric } 5098bcb0991SDimitry Andric Arg = new BitCastInst(Arg, IType, "PrintArgVect", Brnch); 5108bcb0991SDimitry Andric WhatToStore.push_back(Arg); 5118bcb0991SDimitry Andric } else { 5128bcb0991SDimitry Andric WhatToStore.push_back(Arg); 5138bcb0991SDimitry Andric } 5148bcb0991SDimitry Andric for (unsigned I = 0, E = WhatToStore.size(); I != E; ++I) { 5158bcb0991SDimitry Andric Value *TheBtCast = WhatToStore[I]; 5168bcb0991SDimitry Andric unsigned ArgSize = 5178bcb0991SDimitry Andric TD->getTypeAllocSizeInBits(TheBtCast->getType()) / 8; 5188bcb0991SDimitry Andric SmallVector<Value *, 1> BuffOffset; 5198bcb0991SDimitry Andric BuffOffset.push_back(ConstantInt::get(I32Ty, ArgSize)); 5208bcb0991SDimitry Andric 5218bcb0991SDimitry Andric Type *ArgPointer = PointerType::get(TheBtCast->getType(), 1); 5228bcb0991SDimitry Andric Value *CastedGEP = 5238bcb0991SDimitry Andric new BitCastInst(BufferIdx, ArgPointer, "PrintBuffPtrCast", Brnch); 5248bcb0991SDimitry Andric StoreInst *StBuff = new StoreInst(TheBtCast, CastedGEP, Brnch); 5258bcb0991SDimitry Andric LLVM_DEBUG(dbgs() << "inserting store to printf buffer:\n" 5268bcb0991SDimitry Andric << *StBuff << '\n'); 5278bcb0991SDimitry Andric (void)StBuff; 528349cc55cSDimitry Andric if (I + 1 == E && ArgCount + 1 == CI->arg_size()) 5298bcb0991SDimitry Andric break; 530fe6060f1SDimitry Andric BufferIdx = GetElementPtrInst::Create(I8Ty, BufferIdx, BuffOffset, 531e8d8bef9SDimitry Andric "PrintBuffNextPtr", Brnch); 5328bcb0991SDimitry Andric LLVM_DEBUG(dbgs() << "inserting gep to the printf buffer:\n" 5338bcb0991SDimitry Andric << *BufferIdx << '\n'); 5348bcb0991SDimitry Andric } 5358bcb0991SDimitry Andric } 5368bcb0991SDimitry Andric } 5378bcb0991SDimitry Andric } 5388bcb0991SDimitry Andric 5398bcb0991SDimitry Andric // erase the printf calls 5408bcb0991SDimitry Andric for (auto CI : Printfs) 5418bcb0991SDimitry Andric CI->eraseFromParent(); 5428bcb0991SDimitry Andric 5438bcb0991SDimitry Andric Printfs.clear(); 5448bcb0991SDimitry Andric return true; 5458bcb0991SDimitry Andric } 5468bcb0991SDimitry Andric 547e8d8bef9SDimitry Andric bool AMDGPUPrintfRuntimeBindingImpl::run(Module &M) { 5488bcb0991SDimitry Andric Triple TT(M.getTargetTriple()); 5498bcb0991SDimitry Andric if (TT.getArch() == Triple::r600) 5508bcb0991SDimitry Andric return false; 5518bcb0991SDimitry Andric 5528bcb0991SDimitry Andric auto PrintfFunction = M.getFunction("printf"); 5538bcb0991SDimitry Andric if (!PrintfFunction) 5548bcb0991SDimitry Andric return false; 5558bcb0991SDimitry Andric 5568bcb0991SDimitry Andric for (auto &U : PrintfFunction->uses()) { 5578bcb0991SDimitry Andric if (auto *CI = dyn_cast<CallInst>(U.getUser())) { 5588bcb0991SDimitry Andric if (CI->isCallee(&U)) 5598bcb0991SDimitry Andric Printfs.push_back(CI); 5608bcb0991SDimitry Andric } 5618bcb0991SDimitry Andric } 5628bcb0991SDimitry Andric 5638bcb0991SDimitry Andric if (Printfs.empty()) 5648bcb0991SDimitry Andric return false; 5658bcb0991SDimitry Andric 5668bcb0991SDimitry Andric TD = &M.getDataLayout(); 567e8d8bef9SDimitry Andric 568e8d8bef9SDimitry Andric return lowerPrintfForGpu(M); 569e8d8bef9SDimitry Andric } 570e8d8bef9SDimitry Andric 571e8d8bef9SDimitry Andric bool AMDGPUPrintfRuntimeBinding::runOnModule(Module &M) { 572e8d8bef9SDimitry Andric auto GetDT = [this](Function &F) -> DominatorTree & { 573e8d8bef9SDimitry Andric return this->getAnalysis<DominatorTreeWrapperPass>(F).getDomTree(); 574e8d8bef9SDimitry Andric }; 5758bcb0991SDimitry Andric auto GetTLI = [this](Function &F) -> TargetLibraryInfo & { 5768bcb0991SDimitry Andric return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 5778bcb0991SDimitry Andric }; 5788bcb0991SDimitry Andric 579e8d8bef9SDimitry Andric return AMDGPUPrintfRuntimeBindingImpl(GetDT, GetTLI).run(M); 580e8d8bef9SDimitry Andric } 581e8d8bef9SDimitry Andric 582e8d8bef9SDimitry Andric PreservedAnalyses 583e8d8bef9SDimitry Andric AMDGPUPrintfRuntimeBindingPass::run(Module &M, ModuleAnalysisManager &AM) { 584e8d8bef9SDimitry Andric FunctionAnalysisManager &FAM = 585e8d8bef9SDimitry Andric AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 586e8d8bef9SDimitry Andric auto GetDT = [&FAM](Function &F) -> DominatorTree & { 587e8d8bef9SDimitry Andric return FAM.getResult<DominatorTreeAnalysis>(F); 588e8d8bef9SDimitry Andric }; 589e8d8bef9SDimitry Andric auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & { 590e8d8bef9SDimitry Andric return FAM.getResult<TargetLibraryAnalysis>(F); 591e8d8bef9SDimitry Andric }; 592e8d8bef9SDimitry Andric bool Changed = AMDGPUPrintfRuntimeBindingImpl(GetDT, GetTLI).run(M); 593e8d8bef9SDimitry Andric return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all(); 5948bcb0991SDimitry Andric } 595