1//===- AMDGPUEmitPrintf.cpp -----------------------------------------------===//
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// Utility function to lower a printf call into a series of device
10// library calls on the AMDGPU target.
11//
12// WARNING: This file knows about certain library functions. It recognizes them
13// by name, and hardwires knowledge of their semantics.
14//
15//===----------------------------------------------------------------------===//
16
17#include "llvm/Transforms/Utils/AMDGPUEmitPrintf.h"
18#include "llvm/ADT/SparseBitVector.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/Analysis/ValueTracking.h"
21#include "llvm/IR/Module.h"
22#include "llvm/Support/DataExtractor.h"
23#include "llvm/Support/ErrorHandling.h"
24#include "llvm/Support/MD5.h"
25#include "llvm/Support/MathExtras.h"
26
27using namespace llvm;
28
29#define DEBUG_TYPE "amdgpu-emit-printf"
30
31static Value *fitArgInto64Bits(IRBuilder<> &Builder, Value *Arg) {
32 auto Int64Ty = Builder.getInt64Ty();
33 auto Ty = Arg->getType();
34
35 if (auto IntTy = dyn_cast<IntegerType>(Val: Ty)) {
36 switch (IntTy->getBitWidth()) {
37 case 32:
38 return Builder.CreateZExt(V: Arg, DestTy: Int64Ty);
39 case 64:
40 return Arg;
41 }
42 }
43
44 if (Ty->getTypeID() == Type::DoubleTyID) {
45 return Builder.CreateBitCast(V: Arg, DestTy: Int64Ty);
46 }
47
48 if (isa<PointerType>(Val: Ty)) {
49 return Builder.CreatePtrToInt(V: Arg, DestTy: Int64Ty);
50 }
51
52 llvm_unreachable("unexpected type");
53}
54
55static Value *callPrintfBegin(IRBuilder<> &Builder, Value *Version) {
56 auto Int64Ty = Builder.getInt64Ty();
57 auto M = Builder.getModule();
58 auto Fn = M->getOrInsertFunction(Name: "__ockl_printf_begin", RetTy: Int64Ty, Args: Int64Ty);
59 return Builder.CreateCall(Callee: Fn, Args: Version);
60}
61
62static Value *callAppendArgs(IRBuilder<> &Builder, Value *Desc, int NumArgs,
63 Value *Arg0, Value *Arg1, Value *Arg2, Value *Arg3,
64 Value *Arg4, Value *Arg5, Value *Arg6,
65 bool IsLast) {
66 auto Int64Ty = Builder.getInt64Ty();
67 auto Int32Ty = Builder.getInt32Ty();
68 auto M = Builder.getModule();
69 auto Fn = M->getOrInsertFunction(Name: "__ockl_printf_append_args", RetTy: Int64Ty,
70 Args: Int64Ty, Args: Int32Ty, Args: Int64Ty, Args: Int64Ty, Args: Int64Ty,
71 Args: Int64Ty, Args: Int64Ty, Args: Int64Ty, Args: Int64Ty, Args: Int32Ty);
72 auto IsLastValue = Builder.getInt32(C: IsLast);
73 auto NumArgsValue = Builder.getInt32(C: NumArgs);
74 return Builder.CreateCall(Callee: Fn, Args: {Desc, NumArgsValue, Arg0, Arg1, Arg2, Arg3,
75 Arg4, Arg5, Arg6, IsLastValue});
76}
77
78static Value *appendArg(IRBuilder<> &Builder, Value *Desc, Value *Arg,
79 bool IsLast) {
80 auto Arg0 = fitArgInto64Bits(Builder, Arg);
81 auto Zero = Builder.getInt64(C: 0);
82 return callAppendArgs(Builder, Desc, NumArgs: 1, Arg0, Arg1: Zero, Arg2: Zero, Arg3: Zero, Arg4: Zero, Arg5: Zero,
83 Arg6: Zero, IsLast);
84}
85
86// The device library does not provide strlen, so we build our own loop
87// here. While we are at it, we also include the terminating null in the length.
88static Value *getStrlenWithNull(IRBuilder<> &Builder, Value *Str) {
89 auto *Prev = Builder.GetInsertBlock();
90 Module *M = Prev->getModule();
91
92 auto CharZero = Builder.getInt8(C: 0);
93 auto One = Builder.getInt64(C: 1);
94 auto Zero = Builder.getInt64(C: 0);
95 auto Int64Ty = Builder.getInt64Ty();
96
97 // The length is either zero for a null pointer, or the computed value for an
98 // actual string. We need a join block for a phi that represents the final
99 // value.
100 //
101 // Strictly speaking, the zero does not matter since
102 // __ockl_printf_append_string_n ignores the length if the pointer is null.
103 BasicBlock *Join = nullptr;
104 if (Prev->hasTerminator()) {
105 Join = Prev->splitBasicBlock(I: Builder.GetInsertPoint(),
106 BBName: "strlen.join");
107 Prev->getTerminator()->eraseFromParent();
108 } else {
109 Join = BasicBlock::Create(Context&: M->getContext(), Name: "strlen.join",
110 Parent: Prev->getParent());
111 }
112 BasicBlock *While =
113 BasicBlock::Create(Context&: M->getContext(), Name: "strlen.while",
114 Parent: Prev->getParent(), InsertBefore: Join);
115 BasicBlock *WhileDone = BasicBlock::Create(
116 Context&: M->getContext(), Name: "strlen.while.done",
117 Parent: Prev->getParent(), InsertBefore: Join);
118
119 // Emit an early return for when the pointer is null.
120 Builder.SetInsertPoint(Prev);
121 auto CmpNull =
122 Builder.CreateICmpEQ(LHS: Str, RHS: Constant::getNullValue(Ty: Str->getType()));
123 Builder.CreateCondBr(Cond: CmpNull, True: Join, False: While);
124
125 // Entry to the while loop.
126 Builder.SetInsertPoint(While);
127
128 auto PtrPhi = Builder.CreatePHI(Ty: Str->getType(), NumReservedValues: 2);
129 PtrPhi->addIncoming(V: Str, BB: Prev);
130 auto PtrNext = Builder.CreateGEP(Ty: Builder.getInt8Ty(), Ptr: PtrPhi, IdxList: One);
131 PtrPhi->addIncoming(V: PtrNext, BB: While);
132
133 // Condition for the while loop.
134 auto Data = Builder.CreateLoad(Ty: Builder.getInt8Ty(), Ptr: PtrPhi);
135 auto Cmp = Builder.CreateICmpEQ(LHS: Data, RHS: CharZero);
136 Builder.CreateCondBr(Cond: Cmp, True: WhileDone, False: While);
137
138 // Add one to the computed length.
139 Builder.SetInsertPoint(WhileDone->begin());
140 auto Len = Builder.CreatePtrDiff(LHS: PtrPhi, RHS: Str);
141 Len = Builder.CreateZExt(V: Len, DestTy: Int64Ty);
142 Len = Builder.CreateAdd(LHS: Len, RHS: One);
143
144 // Final join.
145 UncondBrInst::Create(Target: Join, InsertBefore: WhileDone);
146 Builder.SetInsertPoint(Join->begin());
147 auto LenPhi = Builder.CreatePHI(Ty: Len->getType(), NumReservedValues: 2);
148 LenPhi->addIncoming(V: Len, BB: WhileDone);
149 LenPhi->addIncoming(V: Zero, BB: Prev);
150
151 return LenPhi;
152}
153
154static Value *callAppendStringN(IRBuilder<> &Builder, Value *Desc, Value *Str,
155 Value *Length, bool isLast) {
156 auto Int64Ty = Builder.getInt64Ty();
157 auto IsLastInt32 = Builder.getInt32(C: isLast);
158 auto M = Builder.getModule();
159 auto Fn = M->getOrInsertFunction(Name: "__ockl_printf_append_string_n", RetTy: Int64Ty,
160 Args: Desc->getType(), Args: Str->getType(),
161 Args: Length->getType(), Args: IsLastInt32->getType());
162 return Builder.CreateCall(Callee: Fn, Args: {Desc, Str, Length, IsLastInt32});
163}
164
165static Value *appendString(IRBuilder<> &Builder, Value *Desc, Value *Arg,
166 bool IsLast) {
167 auto Length = getStrlenWithNull(Builder, Str: Arg);
168 return callAppendStringN(Builder, Desc, Str: Arg, Length, isLast: IsLast);
169}
170
171static Value *processArg(IRBuilder<> &Builder, Value *Desc, Value *Arg,
172 bool SpecIsCString, bool IsLast) {
173 if (SpecIsCString && isa<PointerType>(Val: Arg->getType())) {
174 return appendString(Builder, Desc, Arg, IsLast);
175 }
176 // If the format specifies a string but the argument is not, the frontend will
177 // have printed a warning. We just rely on undefined behaviour and send the
178 // argument anyway.
179 return appendArg(Builder, Desc, Arg, IsLast);
180}
181
182// Scan the format string to locate all specifiers, and mark the ones that
183// specify a string, i.e, the "%s" specifier with optional '*' characters.
184void llvm::locateAMDGPUPrintfCStrings(SparseBitVector<8> &BV, StringRef Str) {
185 static const char ConvSpecifiers[] = "diouxXfFeEgGaAcspn";
186 // Skip the first argument, the format string.
187 unsigned ArgIdx = 1;
188
189 size_t SpecPos;
190 while ((SpecPos = Str.find(C: '%')) != StringRef::npos) {
191 Str = Str.drop_front(N: SpecPos + 1);
192 // "%%" prints a '%' and takes no argument.
193 if (Str.consume_front(Prefix: "%"))
194 continue;
195 size_t SpecEnd = Str.find_first_of(Chars: ConvSpecifiers);
196 if (SpecEnd == StringRef::npos)
197 return;
198 // Each '*' in the specifier takes an argument of its own.
199 ArgIdx += Str.take_front(N: SpecEnd).count(C: '*');
200 if (Str[SpecEnd] == 's')
201 BV.set(ArgIdx);
202 Str = Str.drop_front(N: SpecEnd + 1);
203 ++ArgIdx;
204 }
205}
206
207uint64_t llvm::getAMDGPUPrintfFormatHash(StringRef Fmt) {
208 MD5 Hasher;
209 MD5::MD5Result Hash;
210 Hasher.update(Str: Fmt);
211 Hasher.final(Result&: Hash);
212 return Hash.low();
213}
214
215std::string llvm::getAMDGPUPrintfFormatMetadata(StringRef Fmt) {
216 // Try sticking to llvm.printf.fmts format, although we are not going to
217 // use the ID and argument size fields while printing,
218 return "0:0:" +
219 llvm::utohexstr(X: getAMDGPUPrintfFormatHash(Fmt), /*LowerCase=*/true) +
220 "," + Fmt.str();
221}
222
223void llvm::packAMDGPUPrintfConstantString(StringRef S,
224 SmallVectorImpl<uint32_t> &Words) {
225 std::string Str(S.str() + '\0');
226
227 DataExtractor Extractor(Str, /*IsLittleEndian=*/true);
228 DataExtractor::Cursor Offset(0);
229 while (Offset && Offset.tell() < Str.size()) {
230 const uint64_t ReadSize = 4;
231 uint64_t ReadNow = std::min(a: ReadSize, b: Str.size() - Offset.tell());
232 uint64_t ReadBytes = 0;
233 switch (ReadNow) {
234 default:
235 llvm_unreachable("min(4, X) > 4?");
236 case 1:
237 ReadBytes = Extractor.getU8(C&: Offset);
238 break;
239 case 2:
240 ReadBytes = Extractor.getU16(C&: Offset);
241 break;
242 case 3:
243 ReadBytes = Extractor.getU24(C&: Offset);
244 break;
245 case 4:
246 ReadBytes = Extractor.getU32(C&: Offset);
247 break;
248 }
249 cantFail(Err: Offset.takeError(), Msg: "failed to read bytes from constant array");
250 Words.push_back(Elt: static_cast<uint32_t>(ReadBytes));
251 }
252 // Additional padding for 8 byte alignment
253 int Rem = (Str.size() % 8);
254 if (Rem > 0 && Rem <= 4)
255 Words.push_back(Elt: 0);
256}
257
258// helper struct to package the string related data
259struct StringData {
260 StringRef Str;
261 Value *RealSize = nullptr;
262 Value *AlignedSize = nullptr;
263 bool IsConst = true;
264
265 StringData(StringRef ST, Value *RS, Value *AS, bool IC)
266 : Str(ST), RealSize(RS), AlignedSize(AS), IsConst(IC) {}
267};
268
269// Calculates frame size required for current printf expansion and allocates
270// space on printf buffer. Printf frame includes following contents
271// [ ControlDWord , format string/Hash , Arguments (each aligned to 8 byte) ]
272static Value *callBufferedPrintfStart(
273 IRBuilder<> &Builder, ArrayRef<Value *> Args, Value *Fmt,
274 bool isConstFmtStr, SparseBitVector<8> &SpecIsCString,
275 SmallVectorImpl<StringData> &StringContents, Value *&ArgSize) {
276 Module *M = Builder.getModule();
277 Value *NonConstStrLen = nullptr;
278 Value *LenWithNull = nullptr;
279 Value *LenWithNullAligned = nullptr;
280 Value *TempAdd = nullptr;
281
282 // First 4 bytes to be reserved for control dword
283 size_t BufSize = 4;
284 if (isConstFmtStr)
285 // First 8 bytes of MD5 hash
286 BufSize += 8;
287 else {
288 LenWithNull = getStrlenWithNull(Builder, Str: Fmt);
289
290 // Align the computed length to next 8 byte boundary
291 TempAdd = Builder.CreateAdd(LHS: LenWithNull,
292 RHS: ConstantInt::get(Ty: LenWithNull->getType(), V: 7U));
293 NonConstStrLen = Builder.CreateAnd(
294 LHS: TempAdd, RHS: ConstantInt::get(Ty: LenWithNull->getType(), V: ~7U));
295
296 StringContents.push_back(
297 Elt: StringData(StringRef(), LenWithNull, NonConstStrLen, false));
298 }
299
300 for (size_t i = 1; i < Args.size(); i++) {
301 if (SpecIsCString.test(Idx: i)) {
302 StringRef ArgStr;
303 if (getConstantStringInfo(V: Args[i], Str&: ArgStr)) {
304 auto alignedLen = alignTo(Value: ArgStr.size() + 1, Align: 8);
305 StringContents.push_back(Elt: StringData(
306 ArgStr,
307 /*RealSize*/ nullptr, /*AlignedSize*/ nullptr, /*IsConst*/ true));
308 BufSize += alignedLen;
309 } else {
310 LenWithNull = getStrlenWithNull(Builder, Str: Args[i]);
311
312 // Align the computed length to next 8 byte boundary
313 TempAdd = Builder.CreateAdd(
314 LHS: LenWithNull, RHS: ConstantInt::get(Ty: LenWithNull->getType(), V: 7U));
315 LenWithNullAligned = Builder.CreateAnd(
316 LHS: TempAdd, RHS: ConstantInt::get(Ty: LenWithNull->getType(), V: ~7U));
317
318 if (NonConstStrLen) {
319 auto Val = Builder.CreateAdd(LHS: LenWithNullAligned, RHS: NonConstStrLen,
320 Name: "cumulativeAdd");
321 NonConstStrLen = Val;
322 } else
323 NonConstStrLen = LenWithNullAligned;
324
325 StringContents.push_back(
326 Elt: StringData(StringRef(), LenWithNull, LenWithNullAligned, false));
327 }
328 } else {
329 int AllocSize = M->getDataLayout().getTypeAllocSize(Ty: Args[i]->getType());
330 // We end up expanding non string arguments to 8 bytes
331 // (args smaller than 8 bytes)
332 BufSize += std::max(a: AllocSize, b: 8);
333 }
334 }
335
336 // calculate final size value to be passed to printf_alloc
337 Value *SizeToReserve = ConstantInt::get(Ty: Builder.getInt64Ty(), V: BufSize, IsSigned: false);
338 SmallVector<Value *, 1> Alloc_args;
339 if (NonConstStrLen)
340 SizeToReserve = Builder.CreateAdd(LHS: NonConstStrLen, RHS: SizeToReserve);
341
342 ArgSize = Builder.CreateTrunc(V: SizeToReserve, DestTy: Builder.getInt32Ty());
343 Alloc_args.push_back(Elt: ArgSize);
344
345 // call the printf_alloc function
346 AttributeList Attr = AttributeList::get(
347 C&: Builder.getContext(), Index: AttributeList::FunctionIndex, Kinds: Attribute::NoUnwind);
348
349 Type *Tys_alloc[1] = {Builder.getInt32Ty()};
350 Type *PtrTy =
351 Builder.getPtrTy(AddrSpace: M->getDataLayout().getDefaultGlobalsAddressSpace());
352 FunctionType *FTy_alloc = FunctionType::get(Result: PtrTy, Params: Tys_alloc, isVarArg: false);
353 auto PrintfAllocFn =
354 M->getOrInsertFunction(Name: StringRef("__printf_alloc"), T: FTy_alloc, AttributeList: Attr);
355
356 return Builder.CreateCall(Callee: PrintfAllocFn, Args: Alloc_args, Name: "printf_alloc_fn");
357}
358
359// Prepare constant string argument to push onto the buffer
360static void processConstantStringArg(StringData *SD, IRBuilder<> &Builder,
361 SmallVectorImpl<Value *> &WhatToStore) {
362 SmallVector<uint32_t, 16> Words;
363 packAMDGPUPrintfConstantString(S: SD->Str, Words);
364 for (uint32_t Word : Words)
365 WhatToStore.push_back(Elt: Builder.getInt32(C: Word));
366}
367
368static Value *processNonStringArg(Value *Arg, IRBuilder<> &Builder) {
369 const DataLayout &DL = Builder.getDataLayout();
370 auto Ty = Arg->getType();
371
372 if (auto IntTy = dyn_cast<IntegerType>(Val: Ty)) {
373 if (IntTy->getBitWidth() < 64) {
374 return Builder.CreateZExt(V: Arg, DestTy: Builder.getInt64Ty());
375 }
376 }
377
378 if (Ty->isFloatingPointTy()) {
379 if (DL.getTypeAllocSize(Ty) < 8) {
380 return Builder.CreateFPExt(V: Arg, DestTy: Builder.getDoubleTy());
381 }
382 }
383
384 return Arg;
385}
386
387static void
388callBufferedPrintfArgPush(IRBuilder<> &Builder, ArrayRef<Value *> Args,
389 Value *PtrToStore, SparseBitVector<8> &SpecIsCString,
390 SmallVectorImpl<StringData> &StringContents,
391 bool IsConstFmtStr) {
392 Module *M = Builder.getModule();
393 const DataLayout &DL = M->getDataLayout();
394 auto StrIt = StringContents.begin();
395 size_t i = IsConstFmtStr ? 1 : 0;
396 for (; i < Args.size(); i++) {
397 SmallVector<Value *, 32> WhatToStore;
398 if ((i == 0) || SpecIsCString.test(Idx: i)) {
399 if (StrIt->IsConst) {
400 processConstantStringArg(SD: StrIt, Builder, WhatToStore);
401 StrIt++;
402 } else {
403 // This copies the contents of the string, however the next offset
404 // is at aligned length, the extra space that might be created due
405 // to alignment padding is not populated with any specific value
406 // here. This would be safe as long as runtime is sync with
407 // the offsets.
408 Builder.CreateMemCpy(Dst: PtrToStore, /*DstAlign*/ Align(1), Src: Args[i],
409 /*SrcAlign*/ Args[i]->getPointerAlignment(DL),
410 Size: StrIt->RealSize);
411
412 PtrToStore =
413 Builder.CreateInBoundsGEP(Ty: Builder.getInt8Ty(), Ptr: PtrToStore,
414 IdxList: {StrIt->AlignedSize}, Name: "PrintBuffNextPtr");
415 LLVM_DEBUG(dbgs() << "inserting gep to the printf buffer:"
416 << *PtrToStore << '\n');
417
418 // done with current argument, move to next
419 StrIt++;
420 continue;
421 }
422 } else {
423 WhatToStore.push_back(Elt: processNonStringArg(Arg: Args[i], Builder));
424 }
425
426 for (Value *toStore : WhatToStore) {
427 StoreInst *StBuff = Builder.CreateStore(Val: toStore, Ptr: PtrToStore);
428 LLVM_DEBUG(dbgs() << "inserting store to printf buffer:" << *StBuff
429 << '\n');
430 (void)StBuff;
431 PtrToStore = Builder.CreateConstInBoundsGEP1_32(
432 Ty: Builder.getInt8Ty(), Ptr: PtrToStore,
433 Idx0: M->getDataLayout().getTypeAllocSize(Ty: toStore->getType()),
434 Name: "PrintBuffNextPtr");
435 LLVM_DEBUG(dbgs() << "inserting gep to the printf buffer:" << *PtrToStore
436 << '\n');
437 }
438 }
439}
440
441Value *llvm::emitAMDGPUPrintfCall(IRBuilder<> &Builder, ArrayRef<Value *> Args,
442 bool IsBuffered) {
443 auto NumOps = Args.size();
444 assert(NumOps >= 1);
445
446 auto Fmt = Args[0];
447 SparseBitVector<8> SpecIsCString;
448 StringRef FmtStr;
449
450 if (getConstantStringInfo(V: Fmt, Str&: FmtStr))
451 locateAMDGPUPrintfCStrings(BV&: SpecIsCString, Str: FmtStr);
452
453 if (IsBuffered) {
454 SmallVector<StringData, 8> StringContents;
455 Module *M = Builder.getModule();
456 LLVMContext &Ctx = Builder.getContext();
457 auto Int8Ty = Builder.getInt8Ty();
458 auto Int32Ty = Builder.getInt32Ty();
459 bool IsConstFmtStr = !FmtStr.empty();
460
461 Value *ArgSize = nullptr;
462 Value *Ptr =
463 callBufferedPrintfStart(Builder, Args, Fmt, isConstFmtStr: IsConstFmtStr,
464 SpecIsCString, StringContents, ArgSize);
465
466 // The buffered version still follows OpenCL printf standards for
467 // printf return value, i.e 0 on success, -1 on failure.
468 ConstantPointerNull *zeroIntPtr =
469 ConstantPointerNull::get(T: cast<PointerType>(Val: Ptr->getType()));
470
471 auto *Cmp = cast<ICmpInst>(Val: Builder.CreateICmpNE(LHS: Ptr, RHS: zeroIntPtr, Name: ""));
472
473 BasicBlock *End = BasicBlock::Create(Context&: Ctx, Name: "end.block",
474 Parent: Builder.GetInsertBlock()->getParent());
475 BasicBlock *ArgPush = BasicBlock::Create(
476 Context&: Ctx, Name: "argpush.block", Parent: Builder.GetInsertBlock()->getParent());
477
478 CondBrInst::Create(Cond: Cmp, IfTrue: ArgPush, IfFalse: End, InsertBefore: Builder.GetInsertBlock());
479 Builder.SetInsertPoint(ArgPush);
480
481 // Create controlDWord and store as the first entry, format as follows
482 // Bit 0 (LSB) -> stream (1 if stderr, 0 if stdout, printf always outputs to
483 // stdout) Bit 1 -> constant format string (1 if constant) Bits 2-31 -> size
484 // of printf data frame
485 auto ConstantTwo = Builder.getInt32(C: 2);
486 auto ControlDWord = Builder.CreateShl(LHS: ArgSize, RHS: ConstantTwo);
487 if (IsConstFmtStr)
488 ControlDWord = Builder.CreateOr(LHS: ControlDWord, RHS: ConstantTwo);
489
490 Builder.CreateStore(Val: ControlDWord, Ptr);
491
492 Ptr = Builder.CreateConstInBoundsGEP1_32(Ty: Int8Ty, Ptr, Idx0: 4);
493
494 // Create MD5 hash for constant format string, push low 64 bits of the
495 // same onto buffer and metadata.
496 NamedMDNode *metaD = M->getOrInsertNamedMetadata(Name: "llvm.printf.fmts");
497 if (IsConstFmtStr) {
498 MDString *fmtStrArray =
499 MDString::get(Context&: Ctx, Str: getAMDGPUPrintfFormatMetadata(Fmt: FmtStr));
500 MDNode *myMD = MDNode::get(Context&: Ctx, MDs: fmtStrArray);
501 metaD->addOperand(M: myMD);
502
503 Builder.CreateStore(Val: Builder.getInt64(C: getAMDGPUPrintfFormatHash(Fmt: FmtStr)),
504 Ptr);
505 Ptr = Builder.CreateConstInBoundsGEP1_32(Ty: Int8Ty, Ptr, Idx0: 8);
506 } else {
507 // Include a dummy metadata instance in case of only non constant
508 // format string usage, This might be an absurd usecase but needs to
509 // be done for completeness
510 if (metaD->getNumOperands() == 0) {
511 MDString *fmtStrArray =
512 MDString::get(Context&: Ctx, Str: AMDGPUPrintfNonConstFormatMetadata);
513 MDNode *myMD = MDNode::get(Context&: Ctx, MDs: fmtStrArray);
514 metaD->addOperand(M: myMD);
515 }
516 }
517
518 // Push The printf arguments onto buffer
519 callBufferedPrintfArgPush(Builder, Args, PtrToStore: Ptr, SpecIsCString, StringContents,
520 IsConstFmtStr);
521
522 // End block, returns -1 on failure
523 UncondBrInst::Create(Target: End, InsertBefore: ArgPush);
524 Builder.SetInsertPoint(End);
525 return Builder.CreateSExt(V: Builder.CreateNot(V: Cmp), DestTy: Int32Ty, Name: "printf_result");
526 }
527
528 auto Desc = callPrintfBegin(Builder, Version: Builder.getIntN(N: 64, C: 0));
529 Desc = appendString(Builder, Desc, Arg: Fmt, IsLast: NumOps == 1);
530
531 // FIXME: This invokes hostcall once for each argument. We can pack up to
532 // seven scalar printf arguments in a single hostcall. See the signature of
533 // callAppendArgs().
534 for (unsigned int i = 1; i != NumOps; ++i) {
535 bool IsLast = i == NumOps - 1;
536 bool IsCString = SpecIsCString.test(Idx: i);
537 Desc = processArg(Builder, Desc, Arg: Args[i], SpecIsCString: IsCString, IsLast);
538 }
539
540 return Builder.CreateTrunc(V: Desc, DestTy: Builder.getInt32Ty());
541}
542