xref: /freebsd/contrib/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUPrintfRuntimeBinding.cpp (revision bdd1243df58e60e85101c09001d9812a789b6bc4)
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"
2281ad6265SDimitry Andric #include "llvm/ADT/Triple.h"
238bcb0991SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
248bcb0991SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
25*bdd1243dSDimitry Andric #include "llvm/Analysis/ValueTracking.h"
26*bdd1243dSDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
278bcb0991SDimitry Andric #include "llvm/IR/Dominators.h"
288bcb0991SDimitry Andric #include "llvm/IR/IRBuilder.h"
298bcb0991SDimitry Andric #include "llvm/IR/Instructions.h"
30480093f4SDimitry Andric #include "llvm/InitializePasses.h"
31*bdd1243dSDimitry Andric #include "llvm/Support/DataExtractor.h"
328bcb0991SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
33e8d8bef9SDimitry Andric 
348bcb0991SDimitry Andric using namespace llvm;
358bcb0991SDimitry Andric 
368bcb0991SDimitry Andric #define DEBUG_TYPE "printfToRuntime"
378bcb0991SDimitry Andric #define DWORD_ALIGN 4
388bcb0991SDimitry Andric 
398bcb0991SDimitry Andric namespace {
40e8d8bef9SDimitry Andric class AMDGPUPrintfRuntimeBinding final : public ModulePass {
418bcb0991SDimitry Andric 
428bcb0991SDimitry Andric public:
438bcb0991SDimitry Andric   static char ID;
448bcb0991SDimitry Andric 
458bcb0991SDimitry Andric   explicit AMDGPUPrintfRuntimeBinding();
468bcb0991SDimitry Andric 
478bcb0991SDimitry Andric private:
488bcb0991SDimitry Andric   bool runOnModule(Module &M) override;
498bcb0991SDimitry Andric 
508bcb0991SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
518bcb0991SDimitry Andric     AU.addRequired<TargetLibraryInfoWrapperPass>();
528bcb0991SDimitry Andric     AU.addRequired<DominatorTreeWrapperPass>();
538bcb0991SDimitry Andric   }
54e8d8bef9SDimitry Andric };
558bcb0991SDimitry Andric 
56e8d8bef9SDimitry Andric class AMDGPUPrintfRuntimeBindingImpl {
57e8d8bef9SDimitry Andric public:
58e8d8bef9SDimitry Andric   AMDGPUPrintfRuntimeBindingImpl(
59e8d8bef9SDimitry Andric       function_ref<const DominatorTree &(Function &)> GetDT,
60e8d8bef9SDimitry Andric       function_ref<const TargetLibraryInfo &(Function &)> GetTLI)
61e8d8bef9SDimitry Andric       : GetDT(GetDT), GetTLI(GetTLI) {}
62e8d8bef9SDimitry Andric   bool run(Module &M);
63e8d8bef9SDimitry Andric 
64e8d8bef9SDimitry Andric private:
65e8d8bef9SDimitry Andric   void getConversionSpecifiers(SmallVectorImpl<char> &OpConvSpecifiers,
66e8d8bef9SDimitry Andric                                StringRef fmt, size_t num_ops) const;
67e8d8bef9SDimitry Andric 
68e8d8bef9SDimitry Andric   bool lowerPrintfForGpu(Module &M);
69e8d8bef9SDimitry Andric 
70e8d8bef9SDimitry Andric   Value *simplify(Instruction *I, const TargetLibraryInfo *TLI,
71e8d8bef9SDimitry Andric                   const DominatorTree *DT) {
7281ad6265SDimitry Andric     return simplifyInstruction(I, {*TD, TLI, DT});
738bcb0991SDimitry Andric   }
748bcb0991SDimitry Andric 
758bcb0991SDimitry Andric   const DataLayout *TD;
76e8d8bef9SDimitry Andric   function_ref<const DominatorTree &(Function &)> GetDT;
77e8d8bef9SDimitry Andric   function_ref<const TargetLibraryInfo &(Function &)> GetTLI;
788bcb0991SDimitry Andric   SmallVector<CallInst *, 32> Printfs;
798bcb0991SDimitry Andric };
808bcb0991SDimitry Andric } // namespace
818bcb0991SDimitry Andric 
828bcb0991SDimitry Andric char AMDGPUPrintfRuntimeBinding::ID = 0;
838bcb0991SDimitry Andric 
848bcb0991SDimitry Andric INITIALIZE_PASS_BEGIN(AMDGPUPrintfRuntimeBinding,
858bcb0991SDimitry Andric                       "amdgpu-printf-runtime-binding", "AMDGPU Printf lowering",
868bcb0991SDimitry Andric                       false, false)
878bcb0991SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
888bcb0991SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
898bcb0991SDimitry Andric INITIALIZE_PASS_END(AMDGPUPrintfRuntimeBinding, "amdgpu-printf-runtime-binding",
908bcb0991SDimitry Andric                     "AMDGPU Printf lowering", false, false)
918bcb0991SDimitry Andric 
928bcb0991SDimitry Andric char &llvm::AMDGPUPrintfRuntimeBindingID = AMDGPUPrintfRuntimeBinding::ID;
938bcb0991SDimitry Andric 
948bcb0991SDimitry Andric namespace llvm {
958bcb0991SDimitry Andric ModulePass *createAMDGPUPrintfRuntimeBinding() {
968bcb0991SDimitry Andric   return new AMDGPUPrintfRuntimeBinding();
978bcb0991SDimitry Andric }
988bcb0991SDimitry Andric } // namespace llvm
998bcb0991SDimitry Andric 
100e8d8bef9SDimitry Andric AMDGPUPrintfRuntimeBinding::AMDGPUPrintfRuntimeBinding() : ModulePass(ID) {
1018bcb0991SDimitry Andric   initializeAMDGPUPrintfRuntimeBindingPass(*PassRegistry::getPassRegistry());
1028bcb0991SDimitry Andric }
1038bcb0991SDimitry Andric 
104e8d8bef9SDimitry Andric void AMDGPUPrintfRuntimeBindingImpl::getConversionSpecifiers(
1058bcb0991SDimitry Andric     SmallVectorImpl<char> &OpConvSpecifiers, StringRef Fmt,
1068bcb0991SDimitry Andric     size_t NumOps) const {
1078bcb0991SDimitry Andric   // not all format characters are collected.
1088bcb0991SDimitry Andric   // At this time the format characters of interest
1098bcb0991SDimitry Andric   // are %p and %s, which use to know if we
1108bcb0991SDimitry Andric   // are either storing a literal string or a
1118bcb0991SDimitry Andric   // pointer to the printf buffer.
1128bcb0991SDimitry Andric   static const char ConvSpecifiers[] = "cdieEfgGaosuxXp";
1138bcb0991SDimitry Andric   size_t CurFmtSpecifierIdx = 0;
1148bcb0991SDimitry Andric   size_t PrevFmtSpecifierIdx = 0;
1158bcb0991SDimitry Andric 
1168bcb0991SDimitry Andric   while ((CurFmtSpecifierIdx = Fmt.find_first_of(
1178bcb0991SDimitry Andric               ConvSpecifiers, CurFmtSpecifierIdx)) != StringRef::npos) {
1188bcb0991SDimitry Andric     bool ArgDump = false;
1198bcb0991SDimitry Andric     StringRef CurFmt = Fmt.substr(PrevFmtSpecifierIdx,
1208bcb0991SDimitry Andric                                   CurFmtSpecifierIdx - PrevFmtSpecifierIdx);
1218bcb0991SDimitry Andric     size_t pTag = CurFmt.find_last_of("%");
1228bcb0991SDimitry Andric     if (pTag != StringRef::npos) {
1238bcb0991SDimitry Andric       ArgDump = true;
1248bcb0991SDimitry Andric       while (pTag && CurFmt[--pTag] == '%') {
1258bcb0991SDimitry Andric         ArgDump = !ArgDump;
1268bcb0991SDimitry Andric       }
1278bcb0991SDimitry Andric     }
1288bcb0991SDimitry Andric 
1298bcb0991SDimitry Andric     if (ArgDump)
1308bcb0991SDimitry Andric       OpConvSpecifiers.push_back(Fmt[CurFmtSpecifierIdx]);
1318bcb0991SDimitry Andric 
1328bcb0991SDimitry Andric     PrevFmtSpecifierIdx = ++CurFmtSpecifierIdx;
1338bcb0991SDimitry Andric   }
1348bcb0991SDimitry Andric }
1358bcb0991SDimitry Andric 
136*bdd1243dSDimitry Andric static bool shouldPrintAsStr(char Specifier, Type *OpType) {
137*bdd1243dSDimitry Andric   return Specifier == 's' && isa<PointerType>(OpType);
138*bdd1243dSDimitry Andric }
139*bdd1243dSDimitry Andric 
140*bdd1243dSDimitry Andric constexpr StringLiteral NonLiteralStr("???");
141*bdd1243dSDimitry Andric static_assert(NonLiteralStr.size() == 3);
142*bdd1243dSDimitry Andric 
143*bdd1243dSDimitry Andric static StringRef getAsConstantStr(Value *V) {
144*bdd1243dSDimitry Andric   StringRef S;
145*bdd1243dSDimitry Andric   if (!getConstantStringInfo(V, S))
146*bdd1243dSDimitry Andric     S = NonLiteralStr;
147*bdd1243dSDimitry Andric 
148*bdd1243dSDimitry Andric   return S;
149*bdd1243dSDimitry Andric }
150*bdd1243dSDimitry Andric 
151*bdd1243dSDimitry Andric static void diagnoseInvalidFormatString(const CallBase *CI) {
152*bdd1243dSDimitry Andric   DiagnosticInfoUnsupported UnsupportedFormatStr(
153*bdd1243dSDimitry Andric       *CI->getParent()->getParent(),
154*bdd1243dSDimitry Andric       "printf format string must be a trivially resolved constant string "
155*bdd1243dSDimitry Andric       "global variable",
156*bdd1243dSDimitry Andric       CI->getDebugLoc());
157*bdd1243dSDimitry Andric   CI->getContext().diagnose(UnsupportedFormatStr);
1588bcb0991SDimitry Andric }
1598bcb0991SDimitry Andric 
160e8d8bef9SDimitry Andric bool AMDGPUPrintfRuntimeBindingImpl::lowerPrintfForGpu(Module &M) {
1618bcb0991SDimitry Andric   LLVMContext &Ctx = M.getContext();
1628bcb0991SDimitry Andric   IRBuilder<> Builder(Ctx);
1638bcb0991SDimitry Andric   Type *I32Ty = Type::getInt32Ty(Ctx);
1648bcb0991SDimitry Andric 
165*bdd1243dSDimitry Andric   // Instead of creating global variables, the printf format strings are
166*bdd1243dSDimitry Andric   // extracted and passed as metadata. This avoids polluting llvm's symbol
167*bdd1243dSDimitry Andric   // tables in this module. Metadata is going to be extracted by the backend
168*bdd1243dSDimitry Andric   // passes and inserted into the OpenCL binary as appropriate.
169*bdd1243dSDimitry Andric   NamedMDNode *metaD = M.getOrInsertNamedMetadata("llvm.printf.fmts");
170*bdd1243dSDimitry Andric   unsigned UniqID = metaD->getNumOperands();
171*bdd1243dSDimitry Andric 
172*bdd1243dSDimitry Andric   for (auto *CI : Printfs) {
173349cc55cSDimitry Andric     unsigned NumOps = CI->arg_size();
1748bcb0991SDimitry Andric 
1758bcb0991SDimitry Andric     SmallString<16> OpConvSpecifiers;
1768bcb0991SDimitry Andric     Value *Op = CI->getArgOperand(0);
1778bcb0991SDimitry Andric 
1788bcb0991SDimitry Andric     if (auto LI = dyn_cast<LoadInst>(Op)) {
1798bcb0991SDimitry Andric       Op = LI->getPointerOperand();
180*bdd1243dSDimitry Andric       for (auto *Use : Op->users()) {
1818bcb0991SDimitry Andric         if (auto SI = dyn_cast<StoreInst>(Use)) {
1828bcb0991SDimitry Andric           Op = SI->getValueOperand();
1838bcb0991SDimitry Andric           break;
1848bcb0991SDimitry Andric         }
1858bcb0991SDimitry Andric       }
1868bcb0991SDimitry Andric     }
1878bcb0991SDimitry Andric 
1888bcb0991SDimitry Andric     if (auto I = dyn_cast<Instruction>(Op)) {
189e8d8bef9SDimitry Andric       Value *Op_simplified =
190e8d8bef9SDimitry Andric           simplify(I, &GetTLI(*I->getFunction()), &GetDT(*I->getFunction()));
1918bcb0991SDimitry Andric       if (Op_simplified)
1928bcb0991SDimitry Andric         Op = Op_simplified;
1938bcb0991SDimitry Andric     }
1948bcb0991SDimitry Andric 
195*bdd1243dSDimitry Andric     StringRef FormatStr;
196*bdd1243dSDimitry Andric     if (!getConstantStringInfo(Op, FormatStr)) {
197*bdd1243dSDimitry Andric       Value *Stripped = Op->stripPointerCasts();
198*bdd1243dSDimitry Andric       if (!isa<UndefValue>(Stripped) && !isa<ConstantPointerNull>(Stripped))
199*bdd1243dSDimitry Andric         diagnoseInvalidFormatString(CI);
200*bdd1243dSDimitry Andric       continue;
2018bcb0991SDimitry Andric     }
202*bdd1243dSDimitry Andric 
203*bdd1243dSDimitry Andric     // We need this call to ascertain that we are printing a string or a
204*bdd1243dSDimitry Andric     // pointer. It takes out the specifiers and fills up the first arg.
205*bdd1243dSDimitry Andric     getConversionSpecifiers(OpConvSpecifiers, FormatStr, NumOps - 1);
206*bdd1243dSDimitry Andric 
2078bcb0991SDimitry Andric     // Add metadata for the string
2088bcb0991SDimitry Andric     std::string AStreamHolder;
2098bcb0991SDimitry Andric     raw_string_ostream Sizes(AStreamHolder);
2108bcb0991SDimitry Andric     int Sum = DWORD_ALIGN;
211349cc55cSDimitry Andric     Sizes << CI->arg_size() - 1;
2128bcb0991SDimitry Andric     Sizes << ':';
213349cc55cSDimitry Andric     for (unsigned ArgCount = 1;
214349cc55cSDimitry Andric          ArgCount < CI->arg_size() && ArgCount <= OpConvSpecifiers.size();
2158bcb0991SDimitry Andric          ArgCount++) {
2168bcb0991SDimitry Andric       Value *Arg = CI->getArgOperand(ArgCount);
2178bcb0991SDimitry Andric       Type *ArgType = Arg->getType();
218*bdd1243dSDimitry Andric       unsigned ArgSize = TD->getTypeAllocSize(ArgType);
2198bcb0991SDimitry Andric       //
2208bcb0991SDimitry Andric       // ArgSize by design should be a multiple of DWORD_ALIGN,
2218bcb0991SDimitry Andric       // expand the arguments that do not follow this rule.
2228bcb0991SDimitry Andric       //
2238bcb0991SDimitry Andric       if (ArgSize % DWORD_ALIGN != 0) {
224*bdd1243dSDimitry Andric         Type *ResType = Type::getInt32Ty(Ctx);
225*bdd1243dSDimitry Andric         if (auto *VecType = dyn_cast<VectorType>(ArgType))
226*bdd1243dSDimitry Andric           ResType = VectorType::get(ResType, VecType->getElementCount());
2278bcb0991SDimitry Andric         Builder.SetInsertPoint(CI);
2288bcb0991SDimitry Andric         Builder.SetCurrentDebugLocation(CI->getDebugLoc());
229*bdd1243dSDimitry Andric 
230*bdd1243dSDimitry Andric         if (ArgType->isFloatingPointTy()) {
231*bdd1243dSDimitry Andric           Arg = Builder.CreateBitCast(
232*bdd1243dSDimitry Andric               Arg,
233*bdd1243dSDimitry Andric               IntegerType::getIntNTy(Ctx, ArgType->getPrimitiveSizeInBits()));
234*bdd1243dSDimitry Andric         }
235*bdd1243dSDimitry Andric 
2368bcb0991SDimitry Andric         if (OpConvSpecifiers[ArgCount - 1] == 'x' ||
2378bcb0991SDimitry Andric             OpConvSpecifiers[ArgCount - 1] == 'X' ||
2388bcb0991SDimitry Andric             OpConvSpecifiers[ArgCount - 1] == 'u' ||
2398bcb0991SDimitry Andric             OpConvSpecifiers[ArgCount - 1] == 'o')
2408bcb0991SDimitry Andric           Arg = Builder.CreateZExt(Arg, ResType);
2418bcb0991SDimitry Andric         else
2428bcb0991SDimitry Andric           Arg = Builder.CreateSExt(Arg, ResType);
2438bcb0991SDimitry Andric         ArgType = Arg->getType();
244*bdd1243dSDimitry Andric         ArgSize = TD->getTypeAllocSize(ArgType);
2458bcb0991SDimitry Andric         CI->setOperand(ArgCount, Arg);
2468bcb0991SDimitry Andric       }
2478bcb0991SDimitry Andric       if (OpConvSpecifiers[ArgCount - 1] == 'f') {
2488bcb0991SDimitry Andric         ConstantFP *FpCons = dyn_cast<ConstantFP>(Arg);
2498bcb0991SDimitry Andric         if (FpCons)
2508bcb0991SDimitry Andric           ArgSize = 4;
2518bcb0991SDimitry Andric         else {
2528bcb0991SDimitry Andric           FPExtInst *FpExt = dyn_cast<FPExtInst>(Arg);
2538bcb0991SDimitry Andric           if (FpExt && FpExt->getType()->isDoubleTy() &&
2548bcb0991SDimitry Andric               FpExt->getOperand(0)->getType()->isFloatTy())
2558bcb0991SDimitry Andric             ArgSize = 4;
2568bcb0991SDimitry Andric         }
2578bcb0991SDimitry Andric       }
258*bdd1243dSDimitry Andric       if (shouldPrintAsStr(OpConvSpecifiers[ArgCount - 1], ArgType))
259*bdd1243dSDimitry Andric         ArgSize = alignTo(getAsConstantStr(Arg).size() + 1, 4);
260*bdd1243dSDimitry Andric 
2618bcb0991SDimitry Andric       LLVM_DEBUG(dbgs() << "Printf ArgSize (in buffer) = " << ArgSize
2628bcb0991SDimitry Andric                         << " for type: " << *ArgType << '\n');
2638bcb0991SDimitry Andric       Sizes << ArgSize << ':';
2648bcb0991SDimitry Andric       Sum += ArgSize;
2658bcb0991SDimitry Andric     }
266*bdd1243dSDimitry Andric     LLVM_DEBUG(dbgs() << "Printf format string in source = " << FormatStr
2678bcb0991SDimitry Andric                       << '\n');
268*bdd1243dSDimitry Andric     for (char C : FormatStr) {
2698bcb0991SDimitry Andric       // Rest of the C escape sequences (e.g. \') are handled correctly
2708bcb0991SDimitry Andric       // by the MDParser
2714824e7fdSDimitry Andric       switch (C) {
2728bcb0991SDimitry Andric       case '\a':
2738bcb0991SDimitry Andric         Sizes << "\\a";
2748bcb0991SDimitry Andric         break;
2758bcb0991SDimitry Andric       case '\b':
2768bcb0991SDimitry Andric         Sizes << "\\b";
2778bcb0991SDimitry Andric         break;
2788bcb0991SDimitry Andric       case '\f':
2798bcb0991SDimitry Andric         Sizes << "\\f";
2808bcb0991SDimitry Andric         break;
2818bcb0991SDimitry Andric       case '\n':
2828bcb0991SDimitry Andric         Sizes << "\\n";
2838bcb0991SDimitry Andric         break;
2848bcb0991SDimitry Andric       case '\r':
2858bcb0991SDimitry Andric         Sizes << "\\r";
2868bcb0991SDimitry Andric         break;
2878bcb0991SDimitry Andric       case '\v':
2888bcb0991SDimitry Andric         Sizes << "\\v";
2898bcb0991SDimitry Andric         break;
2908bcb0991SDimitry Andric       case ':':
2918bcb0991SDimitry Andric         // ':' cannot be scanned by Flex, as it is defined as a delimiter
2928bcb0991SDimitry Andric         // Replace it with it's octal representation \72
2938bcb0991SDimitry Andric         Sizes << "\\72";
2948bcb0991SDimitry Andric         break;
2958bcb0991SDimitry Andric       default:
2964824e7fdSDimitry Andric         Sizes << C;
2978bcb0991SDimitry Andric         break;
2988bcb0991SDimitry Andric       }
2998bcb0991SDimitry Andric     }
3008bcb0991SDimitry Andric 
3018bcb0991SDimitry Andric     // Insert the printf_alloc call
3028bcb0991SDimitry Andric     Builder.SetInsertPoint(CI);
3038bcb0991SDimitry Andric     Builder.SetCurrentDebugLocation(CI->getDebugLoc());
3048bcb0991SDimitry Andric 
3058bcb0991SDimitry Andric     AttributeList Attr = AttributeList::get(Ctx, AttributeList::FunctionIndex,
3068bcb0991SDimitry Andric                                             Attribute::NoUnwind);
3078bcb0991SDimitry Andric 
3088bcb0991SDimitry Andric     Type *SizetTy = Type::getInt32Ty(Ctx);
3098bcb0991SDimitry Andric 
3108bcb0991SDimitry Andric     Type *Tys_alloc[1] = {SizetTy};
311fe6060f1SDimitry Andric     Type *I8Ty = Type::getInt8Ty(Ctx);
312fe6060f1SDimitry Andric     Type *I8Ptr = PointerType::get(I8Ty, 1);
3138bcb0991SDimitry Andric     FunctionType *FTy_alloc = FunctionType::get(I8Ptr, Tys_alloc, false);
3148bcb0991SDimitry Andric     FunctionCallee PrintfAllocFn =
3158bcb0991SDimitry Andric         M.getOrInsertFunction(StringRef("__printf_alloc"), FTy_alloc, Attr);
3168bcb0991SDimitry Andric 
3178bcb0991SDimitry Andric     LLVM_DEBUG(dbgs() << "Printf metadata = " << Sizes.str() << '\n');
318349cc55cSDimitry Andric     std::string fmtstr = itostr(++UniqID) + ":" + Sizes.str();
3198bcb0991SDimitry Andric     MDString *fmtStrArray = MDString::get(Ctx, fmtstr);
3208bcb0991SDimitry Andric 
3218bcb0991SDimitry Andric     MDNode *myMD = MDNode::get(Ctx, fmtStrArray);
3228bcb0991SDimitry Andric     metaD->addOperand(myMD);
3238bcb0991SDimitry Andric     Value *sumC = ConstantInt::get(SizetTy, Sum, false);
3248bcb0991SDimitry Andric     SmallVector<Value *, 1> alloc_args;
3258bcb0991SDimitry Andric     alloc_args.push_back(sumC);
3268bcb0991SDimitry Andric     CallInst *pcall =
3278bcb0991SDimitry Andric         CallInst::Create(PrintfAllocFn, alloc_args, "printf_alloc_fn", CI);
3288bcb0991SDimitry Andric 
3298bcb0991SDimitry Andric     //
3308bcb0991SDimitry Andric     // Insert code to split basicblock with a
3318bcb0991SDimitry Andric     // piece of hammock code.
3328bcb0991SDimitry Andric     // basicblock splits after buffer overflow check
3338bcb0991SDimitry Andric     //
3348bcb0991SDimitry Andric     ConstantPointerNull *zeroIntPtr =
335fe6060f1SDimitry Andric         ConstantPointerNull::get(PointerType::get(I8Ty, 1));
336fe6060f1SDimitry Andric     auto *cmp = cast<ICmpInst>(Builder.CreateICmpNE(pcall, zeroIntPtr, ""));
3378bcb0991SDimitry Andric     if (!CI->use_empty()) {
3388bcb0991SDimitry Andric       Value *result =
3398bcb0991SDimitry Andric           Builder.CreateSExt(Builder.CreateNot(cmp), I32Ty, "printf_res");
3408bcb0991SDimitry Andric       CI->replaceAllUsesWith(result);
3418bcb0991SDimitry Andric     }
3428bcb0991SDimitry Andric     SplitBlock(CI->getParent(), cmp);
3438bcb0991SDimitry Andric     Instruction *Brnch =
3448bcb0991SDimitry Andric         SplitBlockAndInsertIfThen(cmp, cmp->getNextNode(), false);
3458bcb0991SDimitry Andric 
3468bcb0991SDimitry Andric     Builder.SetInsertPoint(Brnch);
3478bcb0991SDimitry Andric 
3488bcb0991SDimitry Andric     // store unique printf id in the buffer
3498bcb0991SDimitry Andric     //
350e8d8bef9SDimitry Andric     GetElementPtrInst *BufferIdx = GetElementPtrInst::Create(
351*bdd1243dSDimitry Andric         I8Ty, pcall, ConstantInt::get(Ctx, APInt(32, 0)), "PrintBuffID", Brnch);
3528bcb0991SDimitry Andric 
3538bcb0991SDimitry Andric     Type *idPointer = PointerType::get(I32Ty, AMDGPUAS::GLOBAL_ADDRESS);
3548bcb0991SDimitry Andric     Value *id_gep_cast =
3558bcb0991SDimitry Andric         new BitCastInst(BufferIdx, idPointer, "PrintBuffIdCast", Brnch);
3568bcb0991SDimitry Andric 
3575ffd83dbSDimitry Andric     new StoreInst(ConstantInt::get(I32Ty, UniqID), id_gep_cast, Brnch);
3588bcb0991SDimitry Andric 
359fe6060f1SDimitry Andric     // 1st 4 bytes hold the printf_id
3608bcb0991SDimitry Andric     // the following GEP is the buffer pointer
361*bdd1243dSDimitry Andric     BufferIdx = GetElementPtrInst::Create(I8Ty, pcall,
362*bdd1243dSDimitry Andric                                           ConstantInt::get(Ctx, APInt(32, 4)),
363*bdd1243dSDimitry Andric                                           "PrintBuffGep", Brnch);
3648bcb0991SDimitry Andric 
3658bcb0991SDimitry Andric     Type *Int32Ty = Type::getInt32Ty(Ctx);
366349cc55cSDimitry Andric     for (unsigned ArgCount = 1;
367349cc55cSDimitry Andric          ArgCount < CI->arg_size() && ArgCount <= OpConvSpecifiers.size();
3688bcb0991SDimitry Andric          ArgCount++) {
3698bcb0991SDimitry Andric       Value *Arg = CI->getArgOperand(ArgCount);
3708bcb0991SDimitry Andric       Type *ArgType = Arg->getType();
3718bcb0991SDimitry Andric       SmallVector<Value *, 32> WhatToStore;
3725ffd83dbSDimitry Andric       if (ArgType->isFPOrFPVectorTy() && !isa<VectorType>(ArgType)) {
3738bcb0991SDimitry Andric         if (OpConvSpecifiers[ArgCount - 1] == 'f') {
374e8d8bef9SDimitry Andric           if (auto *FpCons = dyn_cast<ConstantFP>(Arg)) {
375e8d8bef9SDimitry Andric             APFloat Val(FpCons->getValueAPF());
3768bcb0991SDimitry Andric             bool Lost = false;
3778bcb0991SDimitry Andric             Val.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
3788bcb0991SDimitry Andric                         &Lost);
3798bcb0991SDimitry Andric             Arg = ConstantFP::get(Ctx, Val);
380e8d8bef9SDimitry Andric           } else if (auto *FpExt = dyn_cast<FPExtInst>(Arg)) {
381e8d8bef9SDimitry Andric             if (FpExt->getType()->isDoubleTy() &&
3828bcb0991SDimitry Andric                 FpExt->getOperand(0)->getType()->isFloatTy()) {
3838bcb0991SDimitry Andric               Arg = FpExt->getOperand(0);
3848bcb0991SDimitry Andric             }
3858bcb0991SDimitry Andric           }
3868bcb0991SDimitry Andric         }
3878bcb0991SDimitry Andric         WhatToStore.push_back(Arg);
388*bdd1243dSDimitry Andric       } else if (isa<PointerType>(ArgType)) {
3898bcb0991SDimitry Andric         if (shouldPrintAsStr(OpConvSpecifiers[ArgCount - 1], ArgType)) {
390*bdd1243dSDimitry Andric           StringRef S = getAsConstantStr(Arg);
391*bdd1243dSDimitry Andric           if (!S.empty()) {
392*bdd1243dSDimitry Andric             const uint64_t ReadSize = 4;
393*bdd1243dSDimitry Andric 
394*bdd1243dSDimitry Andric             DataExtractor Extractor(S, /*IsLittleEndian=*/true, 8);
395*bdd1243dSDimitry Andric             DataExtractor::Cursor Offset(0);
396*bdd1243dSDimitry Andric             while (Offset && Offset.tell() < S.size()) {
397*bdd1243dSDimitry Andric               uint64_t ReadNow = std::min(ReadSize, S.size() - Offset.tell());
398*bdd1243dSDimitry Andric               uint64_t ReadBytes = 0;
399*bdd1243dSDimitry Andric               switch (ReadNow) {
400*bdd1243dSDimitry Andric               default: llvm_unreachable("min(4, X) > 4?");
401*bdd1243dSDimitry Andric               case 1:
402*bdd1243dSDimitry Andric                 ReadBytes = Extractor.getU8(Offset);
403*bdd1243dSDimitry Andric                 break;
404*bdd1243dSDimitry Andric               case 2:
405*bdd1243dSDimitry Andric                 ReadBytes = Extractor.getU16(Offset);
406*bdd1243dSDimitry Andric                 break;
407*bdd1243dSDimitry Andric               case 3:
408*bdd1243dSDimitry Andric                 ReadBytes = Extractor.getU24(Offset);
409*bdd1243dSDimitry Andric                 break;
410*bdd1243dSDimitry Andric               case 4:
411*bdd1243dSDimitry Andric                 ReadBytes = Extractor.getU32(Offset);
412*bdd1243dSDimitry Andric                 break;
4138bcb0991SDimitry Andric               }
414*bdd1243dSDimitry Andric 
415*bdd1243dSDimitry Andric               cantFail(Offset.takeError(),
416*bdd1243dSDimitry Andric                        "failed to read bytes from constant array");
417*bdd1243dSDimitry Andric 
418*bdd1243dSDimitry Andric               APInt IntVal(8 * ReadSize, ReadBytes);
419*bdd1243dSDimitry Andric 
420*bdd1243dSDimitry Andric               // TODO: Should not bothering aligning up.
421*bdd1243dSDimitry Andric               if (ReadNow < ReadSize)
422*bdd1243dSDimitry Andric                 IntVal = IntVal.zext(8 * ReadSize);
423*bdd1243dSDimitry Andric 
424*bdd1243dSDimitry Andric               Type *IntTy = Type::getIntNTy(Ctx, IntVal.getBitWidth());
425*bdd1243dSDimitry Andric               WhatToStore.push_back(ConstantInt::get(IntTy, IntVal));
4268bcb0991SDimitry Andric             }
4278bcb0991SDimitry Andric           } else {
4288bcb0991SDimitry Andric             // Empty string, give a hint to RT it is no NULL
4298bcb0991SDimitry Andric             Value *ANumV = ConstantInt::get(Int32Ty, 0xFFFFFF00, false);
4308bcb0991SDimitry Andric             WhatToStore.push_back(ANumV);
4318bcb0991SDimitry Andric           }
4328bcb0991SDimitry Andric         } else {
4338bcb0991SDimitry Andric           WhatToStore.push_back(Arg);
4348bcb0991SDimitry Andric         }
4358bcb0991SDimitry Andric       } else {
4368bcb0991SDimitry Andric         WhatToStore.push_back(Arg);
4378bcb0991SDimitry Andric       }
4388bcb0991SDimitry Andric       for (unsigned I = 0, E = WhatToStore.size(); I != E; ++I) {
4398bcb0991SDimitry Andric         Value *TheBtCast = WhatToStore[I];
440*bdd1243dSDimitry Andric         unsigned ArgSize = TD->getTypeAllocSize(TheBtCast->getType());
4418bcb0991SDimitry Andric         SmallVector<Value *, 1> BuffOffset;
4428bcb0991SDimitry Andric         BuffOffset.push_back(ConstantInt::get(I32Ty, ArgSize));
4438bcb0991SDimitry Andric 
4448bcb0991SDimitry Andric         Type *ArgPointer = PointerType::get(TheBtCast->getType(), 1);
4458bcb0991SDimitry Andric         Value *CastedGEP =
4468bcb0991SDimitry Andric             new BitCastInst(BufferIdx, ArgPointer, "PrintBuffPtrCast", Brnch);
4478bcb0991SDimitry Andric         StoreInst *StBuff = new StoreInst(TheBtCast, CastedGEP, Brnch);
4488bcb0991SDimitry Andric         LLVM_DEBUG(dbgs() << "inserting store to printf buffer:\n"
4498bcb0991SDimitry Andric                           << *StBuff << '\n');
4508bcb0991SDimitry Andric         (void)StBuff;
451349cc55cSDimitry Andric         if (I + 1 == E && ArgCount + 1 == CI->arg_size())
4528bcb0991SDimitry Andric           break;
453fe6060f1SDimitry Andric         BufferIdx = GetElementPtrInst::Create(I8Ty, BufferIdx, BuffOffset,
454e8d8bef9SDimitry Andric                                               "PrintBuffNextPtr", Brnch);
4558bcb0991SDimitry Andric         LLVM_DEBUG(dbgs() << "inserting gep to the printf buffer:\n"
4568bcb0991SDimitry Andric                           << *BufferIdx << '\n');
4578bcb0991SDimitry Andric       }
4588bcb0991SDimitry Andric     }
4598bcb0991SDimitry Andric   }
4608bcb0991SDimitry Andric 
4618bcb0991SDimitry Andric   // erase the printf calls
462*bdd1243dSDimitry Andric   for (auto *CI : Printfs)
4638bcb0991SDimitry Andric     CI->eraseFromParent();
4648bcb0991SDimitry Andric 
4658bcb0991SDimitry Andric   Printfs.clear();
4668bcb0991SDimitry Andric   return true;
4678bcb0991SDimitry Andric }
4688bcb0991SDimitry Andric 
469e8d8bef9SDimitry Andric bool AMDGPUPrintfRuntimeBindingImpl::run(Module &M) {
4708bcb0991SDimitry Andric   Triple TT(M.getTargetTriple());
4718bcb0991SDimitry Andric   if (TT.getArch() == Triple::r600)
4728bcb0991SDimitry Andric     return false;
4738bcb0991SDimitry Andric 
4748bcb0991SDimitry Andric   auto PrintfFunction = M.getFunction("printf");
475*bdd1243dSDimitry Andric   if (!PrintfFunction || !PrintfFunction->isDeclaration())
4768bcb0991SDimitry Andric     return false;
4778bcb0991SDimitry Andric 
4788bcb0991SDimitry Andric   for (auto &U : PrintfFunction->uses()) {
4798bcb0991SDimitry Andric     if (auto *CI = dyn_cast<CallInst>(U.getUser())) {
4808bcb0991SDimitry Andric       if (CI->isCallee(&U))
4818bcb0991SDimitry Andric         Printfs.push_back(CI);
4828bcb0991SDimitry Andric     }
4838bcb0991SDimitry Andric   }
4848bcb0991SDimitry Andric 
4858bcb0991SDimitry Andric   if (Printfs.empty())
4868bcb0991SDimitry Andric     return false;
4878bcb0991SDimitry Andric 
4888bcb0991SDimitry Andric   TD = &M.getDataLayout();
489e8d8bef9SDimitry Andric 
490e8d8bef9SDimitry Andric   return lowerPrintfForGpu(M);
491e8d8bef9SDimitry Andric }
492e8d8bef9SDimitry Andric 
493e8d8bef9SDimitry Andric bool AMDGPUPrintfRuntimeBinding::runOnModule(Module &M) {
494e8d8bef9SDimitry Andric   auto GetDT = [this](Function &F) -> DominatorTree & {
495e8d8bef9SDimitry Andric     return this->getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
496e8d8bef9SDimitry Andric   };
4978bcb0991SDimitry Andric   auto GetTLI = [this](Function &F) -> TargetLibraryInfo & {
4988bcb0991SDimitry Andric     return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
4998bcb0991SDimitry Andric   };
5008bcb0991SDimitry Andric 
501e8d8bef9SDimitry Andric   return AMDGPUPrintfRuntimeBindingImpl(GetDT, GetTLI).run(M);
502e8d8bef9SDimitry Andric }
503e8d8bef9SDimitry Andric 
504e8d8bef9SDimitry Andric PreservedAnalyses
505e8d8bef9SDimitry Andric AMDGPUPrintfRuntimeBindingPass::run(Module &M, ModuleAnalysisManager &AM) {
506e8d8bef9SDimitry Andric   FunctionAnalysisManager &FAM =
507e8d8bef9SDimitry Andric       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
508e8d8bef9SDimitry Andric   auto GetDT = [&FAM](Function &F) -> DominatorTree & {
509e8d8bef9SDimitry Andric     return FAM.getResult<DominatorTreeAnalysis>(F);
510e8d8bef9SDimitry Andric   };
511e8d8bef9SDimitry Andric   auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
512e8d8bef9SDimitry Andric     return FAM.getResult<TargetLibraryAnalysis>(F);
513e8d8bef9SDimitry Andric   };
514e8d8bef9SDimitry Andric   bool Changed = AMDGPUPrintfRuntimeBindingImpl(GetDT, GetTLI).run(M);
515e8d8bef9SDimitry Andric   return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
5168bcb0991SDimitry Andric }
517