1 //===--- RuntimeDebugBuilder.cpp - Helper to insert prints into LLVM-IR ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //===----------------------------------------------------------------------===//
11 
12 #include "polly/CodeGen/RuntimeDebugBuilder.h"
13 #include "llvm/IR/Intrinsics.h"
14 #include "llvm/IR/Module.h"
15 #include "llvm/Support/Debug.h"
16 #include <string>
17 #include <vector>
18 
19 using namespace llvm;
20 using namespace polly;
21 
22 Function *RuntimeDebugBuilder::getVPrintF(PollyIRBuilder &Builder) {
23   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
24   const char *Name = "vprintf";
25   Function *F = M->getFunction(Name);
26 
27   if (!F) {
28     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
29     FunctionType *Ty = FunctionType::get(
30         Builder.getInt32Ty(), {Builder.getInt8PtrTy(), Builder.getInt8PtrTy()},
31         false);
32     F = Function::Create(Ty, Linkage, Name, M);
33   }
34 
35   return F;
36 }
37 
38 Function *RuntimeDebugBuilder::getAddressSpaceCast(PollyIRBuilder &Builder,
39                                                    unsigned Src, unsigned Dst,
40                                                    unsigned SrcBits,
41                                                    unsigned DstBits) {
42   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
43   auto Name = std::string("llvm.nvvm.ptr.constant.to.gen.p") +
44               std::to_string(Dst) + "i" + std::to_string(DstBits) + ".p" +
45               std::to_string(Src) + "i" + std::to_string(SrcBits);
46   Function *F = M->getFunction(Name);
47 
48   if (!F) {
49     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
50     FunctionType *Ty = FunctionType::get(
51         PointerType::get(Builder.getIntNTy(DstBits), Dst),
52         PointerType::get(Builder.getIntNTy(SrcBits), Src), false);
53     F = Function::Create(Ty, Linkage, Name, M);
54   }
55 
56   return F;
57 }
58 
59 std::vector<Value *>
60 RuntimeDebugBuilder::getGPUThreadIdentifiers(PollyIRBuilder &Builder) {
61   std::vector<Value *> Identifiers;
62 
63   auto M = Builder.GetInsertBlock()->getParent()->getParent();
64 
65   std::vector<Function *> BlockIDs = {
66       Intrinsic::getDeclaration(M, Intrinsic::ptx_read_ctaid_x),
67       Intrinsic::getDeclaration(M, Intrinsic::ptx_read_ctaid_y),
68       Intrinsic::getDeclaration(M, Intrinsic::ptx_read_ctaid_z),
69   };
70 
71   Identifiers.push_back(Builder.CreateGlobalStringPtr("> block-id: ", "", 4));
72   for (auto GetID : BlockIDs) {
73     Value *Id = Builder.CreateCall(GetID, {});
74     Id = Builder.CreateIntCast(Id, Builder.getInt64Ty(), false);
75     Identifiers.push_back(Id);
76     Identifiers.push_back(Builder.CreateGlobalStringPtr(" ", "", 4));
77   }
78 
79   Identifiers.push_back(Builder.CreateGlobalStringPtr("| ", "", 4));
80 
81   std::vector<Function *> ThreadIDs = {
82       Intrinsic::getDeclaration(M, Intrinsic::ptx_read_tid_x),
83       Intrinsic::getDeclaration(M, Intrinsic::ptx_read_tid_y),
84       Intrinsic::getDeclaration(M, Intrinsic::ptx_read_tid_z),
85   };
86 
87   Identifiers.push_back(Builder.CreateGlobalStringPtr("thread-id: ", "", 4));
88   for (auto GetId : ThreadIDs) {
89     Value *Id = Builder.CreateCall(GetId, {});
90     Id = Builder.CreateIntCast(Id, Builder.getInt64Ty(), false);
91     Identifiers.push_back(Id);
92     Identifiers.push_back(Builder.CreateGlobalStringPtr(" ", "", 4));
93   }
94 
95   return Identifiers;
96 }
97 
98 void RuntimeDebugBuilder::createGPUVAPrinter(PollyIRBuilder &Builder,
99                                              ArrayRef<Value *> Values) {
100   std::string str;
101 
102   // Allocate print buffer (assuming 2*32 bit per element)
103   auto T = ArrayType::get(Builder.getInt32Ty(), Values.size() * 2);
104   Value *Data = new AllocaInst(
105       T, "polly.vprint.buffer",
106       Builder.GetInsertBlock()->getParent()->getEntryBlock().begin());
107 
108   auto *Zero = Builder.getInt64(0);
109   auto *DataPtr = Builder.CreateGEP(Data, {Zero, Zero});
110 
111   auto ToPrint = getGPUThreadIdentifiers(Builder);
112 
113   ToPrint.push_back(Builder.CreateGlobalStringPtr("\n  ", "", 4));
114   ToPrint.insert(ToPrint.end(), Values.begin(), Values.end());
115 
116   int Offset = 0;
117   for (auto Val : ToPrint) {
118     auto Ptr = Builder.CreateGEP(DataPtr, Builder.getInt64(Offset));
119     Type *Ty = Val->getType();
120 
121     if (Ty->isFloatingPointTy()) {
122       if (!Ty->isDoubleTy())
123         Val = Builder.CreateFPExt(Val, Builder.getDoubleTy());
124     } else if (Ty->isIntegerTy()) {
125       if (Ty->getIntegerBitWidth() < 64)
126         Val = Builder.CreateSExt(Val, Builder.getInt64Ty());
127       else
128         assert(Ty->getIntegerBitWidth() &&
129                "Integer types larger 64 bit not supported");
130     } else if (auto PtTy = dyn_cast<PointerType>(Ty)) {
131       if (PtTy->getAddressSpace() == 4) {
132         // Pointers in constant address space are printed as strings
133         Val = Builder.CreateGEP(Val, Builder.getInt64(0));
134         auto F = RuntimeDebugBuilder::getAddressSpaceCast(Builder, 4, 0);
135         Val = Builder.CreateCall(F, Val);
136       } else {
137         Val = Builder.CreatePtrToInt(Val, Builder.getInt64Ty());
138       }
139     } else {
140       llvm_unreachable("Unknown type");
141     }
142 
143     Ty = Val->getType();
144     Ptr = Builder.CreatePointerBitCastOrAddrSpaceCast(Ptr, Ty->getPointerTo(5));
145     Builder.CreateAlignedStore(Val, Ptr, 4);
146 
147     if (Ty->isFloatingPointTy())
148       str += "%f";
149     else if (Ty->isIntegerTy())
150       str += "%ld";
151     else
152       str += "%s";
153 
154     Offset += 2;
155   }
156 
157   Value *Format = Builder.CreateGlobalStringPtr(str, "polly.vprintf.buffer", 4);
158   Format = Builder.CreateCall(getAddressSpaceCast(Builder, 4, 0), Format);
159 
160   Data = Builder.CreateBitCast(Data, Builder.getInt8PtrTy());
161 
162   Builder.CreateCall(getVPrintF(Builder), {Format, Data});
163 }
164 
165 Function *RuntimeDebugBuilder::getPrintF(PollyIRBuilder &Builder) {
166   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
167   const char *Name = "printf";
168   Function *F = M->getFunction(Name);
169 
170   if (!F) {
171     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
172     FunctionType *Ty =
173         FunctionType::get(Builder.getInt32Ty(), Builder.getInt8PtrTy(), true);
174     F = Function::Create(Ty, Linkage, Name, M);
175   }
176 
177   return F;
178 }
179 
180 void RuntimeDebugBuilder::createFlush(PollyIRBuilder &Builder) {
181   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
182   const char *Name = "fflush";
183   Function *F = M->getFunction(Name);
184 
185   if (!F) {
186     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
187     FunctionType *Ty =
188         FunctionType::get(Builder.getInt32Ty(), Builder.getInt8PtrTy(), false);
189     F = Function::Create(Ty, Linkage, Name, M);
190   }
191 
192   // fflush(NULL) flushes _all_ open output streams.
193   //
194   // fflush is declared as 'int fflush(FILE *stream)'. As we only pass on a NULL
195   // pointer, the type we point to does conceptually not matter. However, if
196   // fflush is already declared in this translation unit, we use the very same
197   // type to ensure that LLVM does not complain about mismatching types.
198   Builder.CreateCall(F, Constant::getNullValue(F->arg_begin()->getType()));
199 }
200 
201 void RuntimeDebugBuilder::createStrPrinter(PollyIRBuilder &Builder,
202                                            const std::string &String) {
203   Value *StringValue = Builder.CreateGlobalStringPtr(String);
204   Builder.CreateCall(getPrintF(Builder), StringValue);
205 
206   createFlush(Builder);
207 }
208 
209 void RuntimeDebugBuilder::createValuePrinter(PollyIRBuilder &Builder,
210                                              Value *V) {
211   const char *Format = nullptr;
212 
213   Type *Ty = V->getType();
214   if (Ty->isIntegerTy())
215     Format = "%ld";
216   else if (Ty->isFloatingPointTy())
217     Format = "%lf";
218   else if (Ty->isPointerTy())
219     Format = "%p";
220 
221   assert(Format && Ty->getPrimitiveSizeInBits() <= 64 && "Bad type to print.");
222 
223   Value *FormatString = Builder.CreateGlobalStringPtr(Format);
224   Builder.CreateCall(getPrintF(Builder), {FormatString, V});
225   createFlush(Builder);
226 }
227