1 //===------ PPCGCodeGeneration.cpp - Polly Accelerator Code Generation. ---===//
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 // Take a scop created by ScopInfo and map it to GPU code using the ppcg
11 // GPU mapping strategy.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "polly/CodeGen/IslNodeBuilder.h"
16 #include "polly/CodeGen/Utils.h"
17 #include "polly/DependenceInfo.h"
18 #include "polly/LinkAllPasses.h"
19 #include "polly/Options.h"
20 #include "polly/ScopDetection.h"
21 #include "polly/ScopInfo.h"
22 #include "polly/Support/SCEVValidator.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/Analysis/BasicAliasAnalysis.h"
26 #include "llvm/Analysis/GlobalsModRef.h"
27 #include "llvm/Analysis/PostDominators.h"
28 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
29 #include "llvm/Analysis/TargetLibraryInfo.h"
30 #include "llvm/Analysis/TargetTransformInfo.h"
31 #include "llvm/IR/LegacyPassManager.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Support/TargetSelect.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
37 
38 #include "isl/union_map.h"
39 
40 extern "C" {
41 #include "ppcg/cuda.h"
42 #include "ppcg/gpu.h"
43 #include "ppcg/gpu_print.h"
44 #include "ppcg/ppcg.h"
45 #include "ppcg/schedule.h"
46 }
47 
48 #include "llvm/Support/Debug.h"
49 
50 using namespace polly;
51 using namespace llvm;
52 
53 #define DEBUG_TYPE "polly-codegen-ppcg"
54 
55 static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
56                                   cl::desc("Dump the computed GPU Schedule"),
57                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
58                                   cl::cat(PollyCategory));
59 
60 static cl::opt<bool>
61     DumpCode("polly-acc-dump-code",
62              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
63              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
64 
65 static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
66                                   cl::desc("Dump the kernel LLVM-IR"),
67                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
68                                   cl::cat(PollyCategory));
69 
70 static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
71                                    cl::desc("Dump the kernel assembly code"),
72                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
73                                    cl::cat(PollyCategory));
74 
75 static cl::opt<bool> FastMath("polly-acc-fastmath",
76                               cl::desc("Allow unsafe math optimizations"),
77                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
78                               cl::cat(PollyCategory));
79 static cl::opt<bool> SharedMemory("polly-acc-use-shared",
80                                   cl::desc("Use shared memory"), cl::Hidden,
81                                   cl::init(false), cl::ZeroOrMore,
82                                   cl::cat(PollyCategory));
83 static cl::opt<bool> PrivateMemory("polly-acc-use-private",
84                                    cl::desc("Use private memory"), cl::Hidden,
85                                    cl::init(false), cl::ZeroOrMore,
86                                    cl::cat(PollyCategory));
87 
88 static cl::opt<std::string>
89     CudaVersion("polly-acc-cuda-version",
90                 cl::desc("The CUDA version to compile for"), cl::Hidden,
91                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
92 
93 /// Create the ast expressions for a ScopStmt.
94 ///
95 /// This function is a callback for to generate the ast expressions for each
96 /// of the scheduled ScopStmts.
97 static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
98     void *StmtT, isl_ast_build *Build,
99     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
100                                        isl_id *Id, void *User),
101     void *UserIndex,
102     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
103     void *UserExpr) {
104 
105   ScopStmt *Stmt = (ScopStmt *)StmtT;
106 
107   isl_ctx *Ctx;
108 
109   if (!Stmt || !Build)
110     return NULL;
111 
112   Ctx = isl_ast_build_get_ctx(Build);
113   isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0);
114 
115   for (MemoryAccess *Acc : *Stmt) {
116     isl_map *AddrFunc = Acc->getAddressFunction();
117     AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain());
118     isl_id *RefId = Acc->getId();
119     isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc);
120     isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA);
121     MPA = isl_multi_pw_aff_coalesce(MPA);
122     MPA = FunctionIndex(MPA, RefId, UserIndex);
123     isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA);
124     Access = FunctionExpr(Access, RefId, UserExpr);
125     RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access);
126   }
127 
128   return RefToExpr;
129 }
130 
131 /// Generate code for a GPU specific isl AST.
132 ///
133 /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
134 /// generates code for general-prupose AST nodes, with special functionality
135 /// for generating GPU specific user nodes.
136 ///
137 /// @see GPUNodeBuilder::createUser
138 class GPUNodeBuilder : public IslNodeBuilder {
139 public:
140   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P,
141                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
142                  DominatorTree &DT, Scop &S, gpu_prog *Prog)
143       : IslNodeBuilder(Builder, Annotator, P, DL, LI, SE, DT, S), Prog(Prog) {
144     getExprBuilder().setIDToSAI(&IDToSAI);
145   }
146 
147   /// Create after-run-time-check initialization code.
148   void initializeAfterRTH();
149 
150   /// Finalize the generated scop.
151   virtual void finalize();
152 
153 private:
154   /// A vector of array base pointers for which a new ScopArrayInfo was created.
155   ///
156   /// This vector is used to delete the ScopArrayInfo when it is not needed any
157   /// more.
158   std::vector<Value *> LocalArrays;
159 
160   /// A map from ScopArrays to their corresponding device allocations.
161   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
162 
163   /// The current GPU context.
164   Value *GPUContext;
165 
166   /// The set of isl_ids allocated in the kernel
167   std::vector<isl_id *> KernelIds;
168 
169   /// A module containing GPU code.
170   ///
171   /// This pointer is only set in case we are currently generating GPU code.
172   std::unique_ptr<Module> GPUModule;
173 
174   /// The GPU program we generate code for.
175   gpu_prog *Prog;
176 
177   /// Class to free isl_ids.
178   class IslIdDeleter {
179   public:
180     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
181   };
182 
183   /// A set containing all isl_ids allocated in a GPU kernel.
184   ///
185   /// By releasing this set all isl_ids will be freed.
186   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
187 
188   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
189 
190   /// Create code for user-defined AST nodes.
191   ///
192   /// These AST nodes can be of type:
193   ///
194   ///   - ScopStmt:      A computational statement (TODO)
195   ///   - Kernel:        A GPU kernel call (TODO)
196   ///   - Data-Transfer: A GPU <-> CPU data-transfer
197   ///   - In-kernel synchronization
198   ///   - In-kernel memory copy statement
199   ///
200   /// @param UserStmt The ast node to generate code for.
201   virtual void createUser(__isl_take isl_ast_node *UserStmt);
202 
203   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
204 
205   /// Create code for a data transfer statement
206   ///
207   /// @param TransferStmt The data transfer statement.
208   /// @param Direction The direction in which to transfer data.
209   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
210                           enum DataDirection Direction);
211 
212   /// Find llvm::Values referenced in GPU kernel.
213   ///
214   /// @param Kernel The kernel to scan for llvm::Values
215   ///
216   /// @returns A set of values referenced by the kernel.
217   SetVector<Value *> getReferencesInKernel(ppcg_kernel *Kernel);
218 
219   /// Compute the sizes of the execution grid for a given kernel.
220   ///
221   /// @param Kernel The kernel to compute grid sizes for.
222   ///
223   /// @returns A tuple with grid sizes for X and Y dimension
224   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
225 
226   /// Compute the sizes of the thread blocks for a given kernel.
227   ///
228   /// @param Kernel The kernel to compute thread block sizes for.
229   ///
230   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
231   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
232 
233   /// Create kernel launch parameters.
234   ///
235   /// @param Kernel        The kernel to create parameters for.
236   /// @param F             The kernel function that has been created.
237   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
238   ///
239   /// @returns A stack allocated array with pointers to the parameter
240   ///          values that are passed to the kernel.
241   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
242                                 SetVector<Value *> SubtreeValues);
243 
244   /// Create declarations for kernel variable.
245   ///
246   /// This includes shared memory declarations.
247   ///
248   /// @param Kernel        The kernel definition to create variables for.
249   /// @param FN            The function into which to generate the variables.
250   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
251 
252   /// Create GPU kernel.
253   ///
254   /// Code generate the kernel described by @p KernelStmt.
255   ///
256   /// @param KernelStmt The ast node to generate kernel code for.
257   void createKernel(__isl_take isl_ast_node *KernelStmt);
258 
259   /// Generate code that computes the size of an array.
260   ///
261   /// @param Array The array for which to compute a size.
262   Value *getArraySize(gpu_array_info *Array);
263 
264   /// Prepare the kernel arguments for kernel code generation
265   ///
266   /// @param Kernel The kernel to generate code for.
267   /// @param FN     The function created for the kernel.
268   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
269 
270   /// Create kernel function.
271   ///
272   /// Create a kernel function located in a newly created module that can serve
273   /// as target for device code generation. Set the Builder to point to the
274   /// start block of this newly created function.
275   ///
276   /// @param Kernel The kernel to generate code for.
277   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
278   void createKernelFunction(ppcg_kernel *Kernel,
279                             SetVector<Value *> &SubtreeValues);
280 
281   /// Create the declaration of a kernel function.
282   ///
283   /// The kernel function takes as arguments:
284   ///
285   ///   - One i8 pointer for each external array reference used in the kernel.
286   ///   - Host iterators
287   ///   - Parameters
288   ///   - Other LLVM Value references (TODO)
289   ///
290   /// @param Kernel The kernel to generate the function declaration for.
291   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
292   ///
293   /// @returns The newly declared function.
294   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
295                                      SetVector<Value *> &SubtreeValues);
296 
297   /// Insert intrinsic functions to obtain thread and block ids.
298   ///
299   /// @param The kernel to generate the intrinsic functions for.
300   void insertKernelIntrinsics(ppcg_kernel *Kernel);
301 
302   /// Create a global-to-shared or shared-to-global copy statement.
303   ///
304   /// @param CopyStmt The copy statement to generate code for
305   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
306 
307   /// Create code for a ScopStmt called in @p Expr.
308   ///
309   /// @param Expr The expression containing the call.
310   /// @param KernelStmt The kernel statement referenced in the call.
311   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
312 
313   /// Create an in-kernel synchronization call.
314   void createKernelSync();
315 
316   /// Create a PTX assembly string for the current GPU kernel.
317   ///
318   /// @returns A string containing the corresponding PTX assembly code.
319   std::string createKernelASM();
320 
321   /// Remove references from the dominator tree to the kernel function @p F.
322   ///
323   /// @param F The function to remove references to.
324   void clearDominators(Function *F);
325 
326   /// Remove references from scalar evolution to the kernel function @p F.
327   ///
328   /// @param F The function to remove references to.
329   void clearScalarEvolution(Function *F);
330 
331   /// Remove references from loop info to the kernel function @p F.
332   ///
333   /// @param F The function to remove references to.
334   void clearLoops(Function *F);
335 
336   /// Finalize the generation of the kernel function.
337   ///
338   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
339   /// dump its IR to stderr.
340   ///
341   /// @returns The Assembly string of the kernel.
342   std::string finalizeKernelFunction();
343 
344   /// Create code that allocates memory to store arrays on device.
345   void allocateDeviceArrays();
346 
347   /// Free all allocated device arrays.
348   void freeDeviceArrays();
349 
350   /// Create a call to initialize the GPU context.
351   ///
352   /// @returns A pointer to the newly initialized context.
353   Value *createCallInitContext();
354 
355   /// Create a call to get the device pointer for a kernel allocation.
356   ///
357   /// @param Allocation The Polly GPU allocation
358   ///
359   /// @returns The device parameter corresponding to this allocation.
360   Value *createCallGetDevicePtr(Value *Allocation);
361 
362   /// Create a call to free the GPU context.
363   ///
364   /// @param Context A pointer to an initialized GPU context.
365   void createCallFreeContext(Value *Context);
366 
367   /// Create a call to allocate memory on the device.
368   ///
369   /// @param Size The size of memory to allocate
370   ///
371   /// @returns A pointer that identifies this allocation.
372   Value *createCallAllocateMemoryForDevice(Value *Size);
373 
374   /// Create a call to free a device array.
375   ///
376   /// @param Array The device array to free.
377   void createCallFreeDeviceMemory(Value *Array);
378 
379   /// Create a call to copy data from host to device.
380   ///
381   /// @param HostPtr A pointer to the host data that should be copied.
382   /// @param DevicePtr A device pointer specifying the location to copy to.
383   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
384                                       Value *Size);
385 
386   /// Create a call to copy data from device to host.
387   ///
388   /// @param DevicePtr A pointer to the device data that should be copied.
389   /// @param HostPtr A host pointer specifying the location to copy to.
390   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
391                                       Value *Size);
392 
393   /// Create a call to get a kernel from an assembly string.
394   ///
395   /// @param Buffer The string describing the kernel.
396   /// @param Entry  The name of the kernel function to call.
397   ///
398   /// @returns A pointer to a kernel object
399   Value *createCallGetKernel(Value *Buffer, Value *Entry);
400 
401   /// Create a call to free a GPU kernel.
402   ///
403   /// @param GPUKernel THe kernel to free.
404   void createCallFreeKernel(Value *GPUKernel);
405 
406   /// Create a call to launch a GPU kernel.
407   ///
408   /// @param GPUKernel  The kernel to launch.
409   /// @param GridDimX   The size of the first grid dimension.
410   /// @param GridDimY   The size of the second grid dimension.
411   /// @param GridBlockX The size of the first block dimension.
412   /// @param GridBlockY The size of the second block dimension.
413   /// @param GridBlockZ The size of the third block dimension.
414   /// @param Paramters  A pointer to an array that contains itself pointers to
415   ///                   the parameter values passed for each kernel argument.
416   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
417                               Value *GridDimY, Value *BlockDimX,
418                               Value *BlockDimY, Value *BlockDimZ,
419                               Value *Parameters);
420 };
421 
422 void GPUNodeBuilder::initializeAfterRTH() {
423   GPUContext = createCallInitContext();
424   allocateDeviceArrays();
425 }
426 
427 void GPUNodeBuilder::finalize() {
428   freeDeviceArrays();
429   createCallFreeContext(GPUContext);
430   IslNodeBuilder::finalize();
431 }
432 
433 void GPUNodeBuilder::allocateDeviceArrays() {
434   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
435 
436   for (int i = 0; i < Prog->n_array; ++i) {
437     gpu_array_info *Array = &Prog->array[i];
438     auto *ScopArray = (ScopArrayInfo *)Array->user;
439     std::string DevArrayName("p_dev_array_");
440     DevArrayName.append(Array->name);
441 
442     Value *ArraySize = getArraySize(Array);
443     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
444     DevArray->setName(DevArrayName);
445     DeviceAllocations[ScopArray] = DevArray;
446   }
447 
448   isl_ast_build_free(Build);
449 }
450 
451 void GPUNodeBuilder::freeDeviceArrays() {
452   for (auto &Array : DeviceAllocations)
453     createCallFreeDeviceMemory(Array.second);
454 }
455 
456 Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
457   const char *Name = "polly_getKernel";
458   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
459   Function *F = M->getFunction(Name);
460 
461   // If F is not available, declare it.
462   if (!F) {
463     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
464     std::vector<Type *> Args;
465     Args.push_back(Builder.getInt8PtrTy());
466     Args.push_back(Builder.getInt8PtrTy());
467     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
468     F = Function::Create(Ty, Linkage, Name, M);
469   }
470 
471   return Builder.CreateCall(F, {Buffer, Entry});
472 }
473 
474 Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
475   const char *Name = "polly_getDevicePtr";
476   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
477   Function *F = M->getFunction(Name);
478 
479   // If F is not available, declare it.
480   if (!F) {
481     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
482     std::vector<Type *> Args;
483     Args.push_back(Builder.getInt8PtrTy());
484     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
485     F = Function::Create(Ty, Linkage, Name, M);
486   }
487 
488   return Builder.CreateCall(F, {Allocation});
489 }
490 
491 void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
492                                             Value *GridDimY, Value *BlockDimX,
493                                             Value *BlockDimY, Value *BlockDimZ,
494                                             Value *Parameters) {
495   const char *Name = "polly_launchKernel";
496   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
497   Function *F = M->getFunction(Name);
498 
499   // If F is not available, declare it.
500   if (!F) {
501     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
502     std::vector<Type *> Args;
503     Args.push_back(Builder.getInt8PtrTy());
504     Args.push_back(Builder.getInt32Ty());
505     Args.push_back(Builder.getInt32Ty());
506     Args.push_back(Builder.getInt32Ty());
507     Args.push_back(Builder.getInt32Ty());
508     Args.push_back(Builder.getInt32Ty());
509     Args.push_back(Builder.getInt8PtrTy());
510     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
511     F = Function::Create(Ty, Linkage, Name, M);
512   }
513 
514   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
515                          BlockDimZ, Parameters});
516 }
517 
518 void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
519   const char *Name = "polly_freeKernel";
520   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
521   Function *F = M->getFunction(Name);
522 
523   // If F is not available, declare it.
524   if (!F) {
525     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
526     std::vector<Type *> Args;
527     Args.push_back(Builder.getInt8PtrTy());
528     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
529     F = Function::Create(Ty, Linkage, Name, M);
530   }
531 
532   Builder.CreateCall(F, {GPUKernel});
533 }
534 
535 void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
536   const char *Name = "polly_freeDeviceMemory";
537   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
538   Function *F = M->getFunction(Name);
539 
540   // If F is not available, declare it.
541   if (!F) {
542     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
543     std::vector<Type *> Args;
544     Args.push_back(Builder.getInt8PtrTy());
545     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
546     F = Function::Create(Ty, Linkage, Name, M);
547   }
548 
549   Builder.CreateCall(F, {Array});
550 }
551 
552 Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
553   const char *Name = "polly_allocateMemoryForDevice";
554   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
555   Function *F = M->getFunction(Name);
556 
557   // If F is not available, declare it.
558   if (!F) {
559     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
560     std::vector<Type *> Args;
561     Args.push_back(Builder.getInt64Ty());
562     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
563     F = Function::Create(Ty, Linkage, Name, M);
564   }
565 
566   return Builder.CreateCall(F, {Size});
567 }
568 
569 void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
570                                                     Value *DeviceData,
571                                                     Value *Size) {
572   const char *Name = "polly_copyFromHostToDevice";
573   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
574   Function *F = M->getFunction(Name);
575 
576   // If F is not available, declare it.
577   if (!F) {
578     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
579     std::vector<Type *> Args;
580     Args.push_back(Builder.getInt8PtrTy());
581     Args.push_back(Builder.getInt8PtrTy());
582     Args.push_back(Builder.getInt64Ty());
583     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
584     F = Function::Create(Ty, Linkage, Name, M);
585   }
586 
587   Builder.CreateCall(F, {HostData, DeviceData, Size});
588 }
589 
590 void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
591                                                     Value *HostData,
592                                                     Value *Size) {
593   const char *Name = "polly_copyFromDeviceToHost";
594   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
595   Function *F = M->getFunction(Name);
596 
597   // If F is not available, declare it.
598   if (!F) {
599     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
600     std::vector<Type *> Args;
601     Args.push_back(Builder.getInt8PtrTy());
602     Args.push_back(Builder.getInt8PtrTy());
603     Args.push_back(Builder.getInt64Ty());
604     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
605     F = Function::Create(Ty, Linkage, Name, M);
606   }
607 
608   Builder.CreateCall(F, {DeviceData, HostData, Size});
609 }
610 
611 Value *GPUNodeBuilder::createCallInitContext() {
612   const char *Name = "polly_initContext";
613   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
614   Function *F = M->getFunction(Name);
615 
616   // If F is not available, declare it.
617   if (!F) {
618     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
619     std::vector<Type *> Args;
620     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
621     F = Function::Create(Ty, Linkage, Name, M);
622   }
623 
624   return Builder.CreateCall(F, {});
625 }
626 
627 void GPUNodeBuilder::createCallFreeContext(Value *Context) {
628   const char *Name = "polly_freeContext";
629   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
630   Function *F = M->getFunction(Name);
631 
632   // If F is not available, declare it.
633   if (!F) {
634     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
635     std::vector<Type *> Args;
636     Args.push_back(Builder.getInt8PtrTy());
637     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
638     F = Function::Create(Ty, Linkage, Name, M);
639   }
640 
641   Builder.CreateCall(F, {Context});
642 }
643 
644 /// Check if one string is a prefix of another.
645 ///
646 /// @param String The string in which to look for the prefix.
647 /// @param Prefix The prefix to look for.
648 static bool isPrefix(std::string String, std::string Prefix) {
649   return String.find(Prefix) == 0;
650 }
651 
652 Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
653   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
654   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
655 
656   if (!gpu_array_is_scalar(Array)) {
657     auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]);
658     isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero);
659 
660     for (unsigned int i = 1; i < Array->n_index; i++) {
661       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]);
662       isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
663       Res = isl_ast_expr_mul(Res, Expr);
664     }
665 
666     Value *NumElements = ExprBuilder.create(Res);
667     ArraySize = Builder.CreateMul(ArraySize, NumElements);
668   }
669   isl_ast_build_free(Build);
670   return ArraySize;
671 }
672 
673 void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
674                                         enum DataDirection Direction) {
675   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
676   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
677   isl_id *Id = isl_ast_expr_get_id(Arg);
678   auto Array = (gpu_array_info *)isl_id_get_user(Id);
679   auto ScopArray = (ScopArrayInfo *)(Array->user);
680 
681   Value *Size = getArraySize(Array);
682   Value *HostPtr = ScopArray->getBasePtr();
683 
684   Value *DevPtr = DeviceAllocations[ScopArray];
685 
686   if (gpu_array_is_scalar(Array)) {
687     HostPtr = Builder.CreateAlloca(ScopArray->getElementType());
688     Builder.CreateStore(ScopArray->getBasePtr(), HostPtr);
689   }
690 
691   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
692 
693   if (Direction == HOST_TO_DEVICE)
694     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
695   else
696     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
697 
698   isl_id_free(Id);
699   isl_ast_expr_free(Arg);
700   isl_ast_expr_free(Expr);
701   isl_ast_node_free(TransferStmt);
702 }
703 
704 void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
705   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
706   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
707   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
708   isl_id_free(Id);
709   isl_ast_expr_free(StmtExpr);
710 
711   const char *Str = isl_id_get_name(Id);
712   if (!strcmp(Str, "kernel")) {
713     createKernel(UserStmt);
714     isl_ast_expr_free(Expr);
715     return;
716   }
717 
718   if (isPrefix(Str, "to_device")) {
719     createDataTransfer(UserStmt, HOST_TO_DEVICE);
720     isl_ast_expr_free(Expr);
721     return;
722   }
723 
724   if (isPrefix(Str, "from_device")) {
725     createDataTransfer(UserStmt, DEVICE_TO_HOST);
726     isl_ast_expr_free(Expr);
727     return;
728   }
729 
730   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
731   struct ppcg_kernel_stmt *KernelStmt =
732       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
733   isl_id_free(Anno);
734 
735   switch (KernelStmt->type) {
736   case ppcg_kernel_domain:
737     createScopStmt(Expr, KernelStmt);
738     isl_ast_node_free(UserStmt);
739     return;
740   case ppcg_kernel_copy:
741     createKernelCopy(KernelStmt);
742     isl_ast_expr_free(Expr);
743     isl_ast_node_free(UserStmt);
744     return;
745   case ppcg_kernel_sync:
746     createKernelSync();
747     isl_ast_expr_free(Expr);
748     isl_ast_node_free(UserStmt);
749     return;
750   }
751 
752   isl_ast_expr_free(Expr);
753   isl_ast_node_free(UserStmt);
754   return;
755 }
756 void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
757   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
758   LocalIndex = isl_ast_expr_address_of(LocalIndex);
759   Value *LocalAddr = ExprBuilder.create(LocalIndex);
760   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
761   Index = isl_ast_expr_address_of(Index);
762   Value *GlobalAddr = ExprBuilder.create(Index);
763 
764   if (KernelStmt->u.c.read) {
765     LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read");
766     Builder.CreateStore(Load, LocalAddr);
767   } else {
768     LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write");
769     Builder.CreateStore(Load, GlobalAddr);
770   }
771 }
772 
773 void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
774                                     ppcg_kernel_stmt *KernelStmt) {
775   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
776   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
777 
778   LoopToScevMapT LTS;
779   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
780 
781   createSubstitutions(Expr, Stmt, LTS);
782 
783   if (Stmt->isBlockStmt())
784     BlockGen.copyStmt(*Stmt, LTS, Indexes);
785   else
786     assert(0 && "Region statement not supported\n");
787 }
788 
789 void GPUNodeBuilder::createKernelSync() {
790   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
791   auto *Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
792   Builder.CreateCall(Sync, {});
793 }
794 
795 /// Collect llvm::Values referenced from @p Node
796 ///
797 /// This function only applies to isl_ast_nodes that are user_nodes referring
798 /// to a ScopStmt. All other node types are ignore.
799 ///
800 /// @param Node The node to collect references for.
801 /// @param User A user pointer used as storage for the data that is collected.
802 ///
803 /// @returns isl_bool_true if data could be collected successfully.
804 isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
805   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
806     return isl_bool_true;
807 
808   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
809   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
810   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
811   const char *Str = isl_id_get_name(Id);
812   isl_id_free(Id);
813   isl_ast_expr_free(StmtExpr);
814   isl_ast_expr_free(Expr);
815 
816   if (!isPrefix(Str, "Stmt"))
817     return isl_bool_true;
818 
819   Id = isl_ast_node_get_annotation(Node);
820   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
821   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
822   isl_id_free(Id);
823 
824   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
825 
826   return isl_bool_true;
827 }
828 
829 SetVector<Value *> GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
830   SetVector<Value *> SubtreeValues;
831   SetVector<const SCEV *> SCEVs;
832   SetVector<const Loop *> Loops;
833   SubtreeReferences References = {
834       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
835 
836   for (const auto &I : IDToValue)
837     SubtreeValues.insert(I.second);
838 
839   isl_ast_node_foreach_descendant_top_down(
840       Kernel->tree, collectReferencesInGPUStmt, &References);
841 
842   for (const SCEV *Expr : SCEVs)
843     findValues(Expr, SE, SubtreeValues);
844 
845   for (auto &SAI : S.arrays())
846     SubtreeValues.remove(SAI->getBasePtr());
847 
848   isl_space *Space = S.getParamSpace();
849   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
850     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
851     assert(IDToValue.count(Id));
852     Value *Val = IDToValue[Id];
853     SubtreeValues.remove(Val);
854     isl_id_free(Id);
855   }
856   isl_space_free(Space);
857 
858   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
859     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
860     assert(IDToValue.count(Id));
861     Value *Val = IDToValue[Id];
862     SubtreeValues.remove(Val);
863     isl_id_free(Id);
864   }
865 
866   return SubtreeValues;
867 }
868 
869 void GPUNodeBuilder::clearDominators(Function *F) {
870   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
871   std::vector<BasicBlock *> Nodes;
872   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
873     Nodes.push_back(I->getBlock());
874 
875   for (BasicBlock *BB : Nodes)
876     DT.eraseNode(BB);
877 }
878 
879 void GPUNodeBuilder::clearScalarEvolution(Function *F) {
880   for (BasicBlock &BB : *F) {
881     Loop *L = LI.getLoopFor(&BB);
882     if (L)
883       SE.forgetLoop(L);
884   }
885 }
886 
887 void GPUNodeBuilder::clearLoops(Function *F) {
888   for (BasicBlock &BB : *F) {
889     Loop *L = LI.getLoopFor(&BB);
890     if (L)
891       SE.forgetLoop(L);
892     LI.removeBlock(&BB);
893   }
894 }
895 
896 std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
897   std::vector<Value *> Sizes;
898   isl_ast_build *Context = isl_ast_build_from_context(S.getContext());
899 
900   for (long i = 0; i < Kernel->n_grid; i++) {
901     isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i);
902     isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size);
903     Value *Res = ExprBuilder.create(GridSize);
904     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
905     Sizes.push_back(Res);
906   }
907   isl_ast_build_free(Context);
908 
909   for (long i = Kernel->n_grid; i < 3; i++)
910     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
911 
912   return std::make_tuple(Sizes[0], Sizes[1]);
913 }
914 
915 std::tuple<Value *, Value *, Value *>
916 GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
917   std::vector<Value *> Sizes;
918 
919   for (long i = 0; i < Kernel->n_block; i++) {
920     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
921     Sizes.push_back(Res);
922   }
923 
924   for (long i = Kernel->n_block; i < 3; i++)
925     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
926 
927   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
928 }
929 
930 Value *
931 GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
932                                        SetVector<Value *> SubtreeValues) {
933   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(),
934                                  std::distance(F->arg_begin(), F->arg_end()));
935 
936   BasicBlock *EntryBlock =
937       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
938   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
939   Instruction *Parameters =
940       new AllocaInst(ArrayTy, Launch + "_params", EntryBlock->getTerminator());
941 
942   int Index = 0;
943   for (long i = 0; i < Prog->n_array; i++) {
944     if (!ppcg_kernel_requires_array_argument(Kernel, i))
945       continue;
946 
947     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
948     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
949 
950     Value *DevArray = DeviceAllocations[(ScopArrayInfo *)SAI];
951     DevArray = createCallGetDevicePtr(DevArray);
952     Instruction *Param = new AllocaInst(
953         Builder.getInt8PtrTy(), Launch + "_param_" + std::to_string(Index),
954         EntryBlock->getTerminator());
955     Builder.CreateStore(DevArray, Param);
956     Value *Slot = Builder.CreateGEP(
957         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
958     Value *ParamTyped =
959         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
960     Builder.CreateStore(ParamTyped, Slot);
961     Index++;
962   }
963 
964   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
965 
966   for (long i = 0; i < NumHostIters; i++) {
967     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
968     Value *Val = IDToValue[Id];
969     isl_id_free(Id);
970     Instruction *Param = new AllocaInst(
971         Val->getType(), Launch + "_param_" + std::to_string(Index),
972         EntryBlock->getTerminator());
973     Builder.CreateStore(Val, Param);
974     Value *Slot = Builder.CreateGEP(
975         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
976     Value *ParamTyped =
977         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
978     Builder.CreateStore(ParamTyped, Slot);
979     Index++;
980   }
981 
982   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
983 
984   for (long i = 0; i < NumVars; i++) {
985     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
986     Value *Val = IDToValue[Id];
987     isl_id_free(Id);
988     Instruction *Param = new AllocaInst(
989         Val->getType(), Launch + "_param_" + std::to_string(Index),
990         EntryBlock->getTerminator());
991     Builder.CreateStore(Val, Param);
992     Value *Slot = Builder.CreateGEP(
993         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
994     Value *ParamTyped =
995         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
996     Builder.CreateStore(ParamTyped, Slot);
997     Index++;
998   }
999 
1000   for (auto Val : SubtreeValues) {
1001     Instruction *Param = new AllocaInst(
1002         Val->getType(), Launch + "_param_" + std::to_string(Index),
1003         EntryBlock->getTerminator());
1004     Builder.CreateStore(Val, Param);
1005     Value *Slot = Builder.CreateGEP(
1006         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1007     Value *ParamTyped =
1008         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1009     Builder.CreateStore(ParamTyped, Slot);
1010     Index++;
1011   }
1012 
1013   auto Location = EntryBlock->getTerminator();
1014   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
1015                          Launch + "_params_i8ptr", Location);
1016 }
1017 
1018 void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
1019   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
1020   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
1021   isl_id_free(Id);
1022   isl_ast_node_free(KernelStmt);
1023 
1024   SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel);
1025 
1026   assert(Kernel->tree && "Device AST of kernel node is empty");
1027 
1028   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1029   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1030   ValueMapT HostValueMap = ValueMap;
1031 
1032   SetVector<const Loop *> Loops;
1033 
1034   // Create for all loops we depend on values that contain the current loop
1035   // iteration. These values are necessary to generate code for SCEVs that
1036   // depend on such loops. As a result we need to pass them to the subfunction.
1037   for (const Loop *L : Loops) {
1038     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1039                                             SE.getUnknown(Builder.getInt64(1)),
1040                                             L, SCEV::FlagAnyWrap);
1041     Value *V = generateSCEV(OuterLIV);
1042     OutsideLoopIterations[L] = SE.getUnknown(V);
1043     SubtreeValues.insert(V);
1044   }
1045 
1046   createKernelFunction(Kernel, SubtreeValues);
1047 
1048   create(isl_ast_node_copy(Kernel->tree));
1049 
1050   Function *F = Builder.GetInsertBlock()->getParent();
1051   clearDominators(F);
1052   clearScalarEvolution(F);
1053   clearLoops(F);
1054 
1055   Builder.SetInsertPoint(&HostInsertPoint);
1056   IDToValue = HostIDs;
1057 
1058   ValueMap = HostValueMap;
1059   ScalarMap.clear();
1060   PHIOpMap.clear();
1061   EscapeMap.clear();
1062   IDToSAI.clear();
1063   Annotator.resetAlternativeAliasBases();
1064   for (auto &BasePtr : LocalArrays)
1065     S.invalidateScopArrayInfo(BasePtr, ScopArrayInfo::MK_Array);
1066   LocalArrays.clear();
1067 
1068   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
1069 
1070   std::string ASMString = finalizeKernelFunction();
1071   std::string Name = "kernel_" + std::to_string(Kernel->id);
1072   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
1073   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
1074   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
1075 
1076   Value *GridDimX, *GridDimY;
1077   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
1078 
1079   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1080   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1081 
1082   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
1083                          BlockDimZ, Parameters);
1084   createCallFreeKernel(GPUKernel);
1085 
1086   for (auto Id : KernelIds)
1087     isl_id_free(Id);
1088 
1089   KernelIds.clear();
1090 }
1091 
1092 /// Compute the DataLayout string for the NVPTX backend.
1093 ///
1094 /// @param is64Bit Are we looking for a 64 bit architecture?
1095 static std::string computeNVPTXDataLayout(bool is64Bit) {
1096   std::string Ret = "e";
1097 
1098   if (!is64Bit)
1099     Ret += "-p:32:32";
1100 
1101   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
1102 
1103   return Ret;
1104 }
1105 
1106 Function *
1107 GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1108                                          SetVector<Value *> &SubtreeValues) {
1109   std::vector<Type *> Args;
1110   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
1111 
1112   for (long i = 0; i < Prog->n_array; i++) {
1113     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1114       continue;
1115 
1116     Args.push_back(Builder.getInt8PtrTy());
1117   }
1118 
1119   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1120 
1121   for (long i = 0; i < NumHostIters; i++)
1122     Args.push_back(Builder.getInt64Ty());
1123 
1124   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1125 
1126   for (long i = 0; i < NumVars; i++)
1127     Args.push_back(Builder.getInt64Ty());
1128 
1129   for (auto *V : SubtreeValues)
1130     Args.push_back(V->getType());
1131 
1132   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
1133   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
1134                               GPUModule.get());
1135   FN->setCallingConv(CallingConv::PTX_Kernel);
1136 
1137   auto Arg = FN->arg_begin();
1138   for (long i = 0; i < Kernel->n_array; i++) {
1139     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1140       continue;
1141 
1142     Arg->setName(Kernel->array[i].array->name);
1143 
1144     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1145     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1146     Type *EleTy = SAI->getElementType();
1147     Value *Val = &*Arg;
1148     SmallVector<const SCEV *, 4> Sizes;
1149     isl_ast_build *Build =
1150         isl_ast_build_from_context(isl_set_copy(Prog->context));
1151     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1152       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
1153           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
1154       auto V = ExprBuilder.create(DimSize);
1155       Sizes.push_back(SE.getSCEV(V));
1156     }
1157     const ScopArrayInfo *SAIRep =
1158         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, ScopArrayInfo::MK_Array);
1159     LocalArrays.push_back(Val);
1160 
1161     isl_ast_build_free(Build);
1162     KernelIds.push_back(Id);
1163     IDToSAI[Id] = SAIRep;
1164     Arg++;
1165   }
1166 
1167   for (long i = 0; i < NumHostIters; i++) {
1168     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1169     Arg->setName(isl_id_get_name(Id));
1170     IDToValue[Id] = &*Arg;
1171     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1172     Arg++;
1173   }
1174 
1175   for (long i = 0; i < NumVars; i++) {
1176     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1177     Arg->setName(isl_id_get_name(Id));
1178     IDToValue[Id] = &*Arg;
1179     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1180     Arg++;
1181   }
1182 
1183   for (auto *V : SubtreeValues) {
1184     Arg->setName(V->getName());
1185     ValueMap[V] = &*Arg;
1186     Arg++;
1187   }
1188 
1189   return FN;
1190 }
1191 
1192 void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
1193   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
1194                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
1195 
1196   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
1197                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
1198                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
1199 
1200   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1201     std::string Name = isl_id_get_name(Id);
1202     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1203     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1204     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1205     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1206     IDToValue[Id] = Val;
1207     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1208   };
1209 
1210   for (int i = 0; i < Kernel->n_grid; ++i) {
1211     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1212     addId(Id, IntrinsicsBID[i]);
1213   }
1214 
1215   for (int i = 0; i < Kernel->n_block; ++i) {
1216     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1217     addId(Id, IntrinsicsTID[i]);
1218   }
1219 }
1220 
1221 void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
1222   auto Arg = FN->arg_begin();
1223   for (long i = 0; i < Kernel->n_array; i++) {
1224     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1225       continue;
1226 
1227     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1228     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1229     isl_id_free(Id);
1230 
1231     if (SAI->getNumberOfDimensions() > 0) {
1232       Arg++;
1233       continue;
1234     }
1235 
1236     Value *Alloca = BlockGen.getOrCreateScalarAlloca(SAI->getBasePtr());
1237     Value *ArgPtr = &*Arg;
1238     Type *TypePtr = SAI->getElementType()->getPointerTo();
1239     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
1240     Value *Val = Builder.CreateLoad(TypedArgPtr);
1241     Builder.CreateStore(Val, Alloca);
1242 
1243     Arg++;
1244   }
1245 }
1246 
1247 void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
1248   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1249 
1250   for (int i = 0; i < Kernel->n_var; ++i) {
1251     struct ppcg_kernel_var &Var = Kernel->var[i];
1252     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
1253     Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType();
1254 
1255     SmallVector<const SCEV *, 4> Sizes;
1256     isl_val *V0 = isl_vec_get_element_val(Var.size, 0);
1257     long Bound = isl_val_get_num_si(V0);
1258     isl_val_free(V0);
1259     Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
1260 
1261     ArrayType *ArrayTy = ArrayType::get(EleTy, Bound);
1262     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
1263       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1264       Bound = isl_val_get_num_si(Val);
1265       isl_val_free(Val);
1266       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
1267       ArrayTy = ArrayType::get(ArrayTy, Bound);
1268     }
1269 
1270     const ScopArrayInfo *SAI;
1271     Value *Allocation;
1272     if (Var.type == ppcg_access_shared) {
1273       auto GlobalVar = new GlobalVariable(
1274           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
1275           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
1276       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
1277       ConstantAggregateZero *Zero = ConstantAggregateZero::get(ArrayTy);
1278       GlobalVar->setInitializer(Zero);
1279       Allocation = GlobalVar;
1280     } else if (Var.type == ppcg_access_private) {
1281       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
1282     } else {
1283       llvm_unreachable("unknown variable type");
1284     }
1285     Builder.GetInsertBlock()->dump();
1286     SAI = S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes,
1287                                      ScopArrayInfo::MK_Array);
1288     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
1289     IDToValue[Id] = Allocation;
1290     LocalArrays.push_back(Allocation);
1291     KernelIds.push_back(Id);
1292     IDToSAI[Id] = SAI;
1293   }
1294 }
1295 
1296 void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel,
1297                                           SetVector<Value *> &SubtreeValues) {
1298 
1299   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
1300   GPUModule.reset(new Module(Identifier, Builder.getContext()));
1301   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
1302   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
1303 
1304   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
1305 
1306   BasicBlock *PrevBlock = Builder.GetInsertBlock();
1307   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
1308 
1309   DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1310   DT.addNewBlock(EntryBlock, PrevBlock);
1311 
1312   Builder.SetInsertPoint(EntryBlock);
1313   Builder.CreateRetVoid();
1314   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
1315 
1316   ScopDetection::markFunctionAsInvalid(FN);
1317 
1318   prepareKernelArguments(Kernel, FN);
1319   createKernelVariables(Kernel, FN);
1320   insertKernelIntrinsics(Kernel);
1321 }
1322 
1323 std::string GPUNodeBuilder::createKernelASM() {
1324   llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda"));
1325   std::string ErrMsg;
1326   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
1327 
1328   if (!GPUTarget) {
1329     errs() << ErrMsg << "\n";
1330     return "";
1331   }
1332 
1333   TargetOptions Options;
1334   Options.UnsafeFPMath = FastMath;
1335   std::unique_ptr<TargetMachine> TargetM(
1336       GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "",
1337                                      Options, Optional<Reloc::Model>()));
1338 
1339   SmallString<0> ASMString;
1340   raw_svector_ostream ASMStream(ASMString);
1341   llvm::legacy::PassManager PM;
1342 
1343   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
1344 
1345   if (TargetM->addPassesToEmitFile(
1346           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
1347     errs() << "The target does not support generation of this file type!\n";
1348     return "";
1349   }
1350 
1351   PM.run(*GPUModule);
1352 
1353   return ASMStream.str();
1354 }
1355 
1356 std::string GPUNodeBuilder::finalizeKernelFunction() {
1357   // Verify module.
1358   llvm::legacy::PassManager Passes;
1359   Passes.add(createVerifierPass());
1360   Passes.run(*GPUModule);
1361 
1362   if (DumpKernelIR)
1363     outs() << *GPUModule << "\n";
1364 
1365   // Optimize module.
1366   llvm::legacy::PassManager OptPasses;
1367   PassManagerBuilder PassBuilder;
1368   PassBuilder.OptLevel = 3;
1369   PassBuilder.SizeLevel = 0;
1370   PassBuilder.populateModulePassManager(OptPasses);
1371   OptPasses.run(*GPUModule);
1372 
1373   std::string Assembly = createKernelASM();
1374 
1375   if (DumpKernelASM)
1376     outs() << Assembly << "\n";
1377 
1378   GPUModule.release();
1379   KernelIDs.clear();
1380 
1381   return Assembly;
1382 }
1383 
1384 namespace {
1385 class PPCGCodeGeneration : public ScopPass {
1386 public:
1387   static char ID;
1388 
1389   /// The scop that is currently processed.
1390   Scop *S;
1391 
1392   LoopInfo *LI;
1393   DominatorTree *DT;
1394   ScalarEvolution *SE;
1395   const DataLayout *DL;
1396   RegionInfo *RI;
1397 
1398   PPCGCodeGeneration() : ScopPass(ID) {}
1399 
1400   /// Construct compilation options for PPCG.
1401   ///
1402   /// @returns The compilation options.
1403   ppcg_options *createPPCGOptions() {
1404     auto DebugOptions =
1405         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
1406     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
1407 
1408     DebugOptions->dump_schedule_constraints = false;
1409     DebugOptions->dump_schedule = false;
1410     DebugOptions->dump_final_schedule = false;
1411     DebugOptions->dump_sizes = false;
1412 
1413     Options->debug = DebugOptions;
1414 
1415     Options->reschedule = true;
1416     Options->scale_tile_loops = false;
1417     Options->wrap = false;
1418 
1419     Options->non_negative_parameters = false;
1420     Options->ctx = nullptr;
1421     Options->sizes = nullptr;
1422 
1423     Options->tile_size = 32;
1424 
1425     Options->use_private_memory = PrivateMemory;
1426     Options->use_shared_memory = SharedMemory;
1427     Options->max_shared_memory = 48 * 1024;
1428 
1429     Options->target = PPCG_TARGET_CUDA;
1430     Options->openmp = false;
1431     Options->linearize_device_arrays = true;
1432     Options->live_range_reordering = false;
1433 
1434     Options->opencl_compiler_options = nullptr;
1435     Options->opencl_use_gpu = false;
1436     Options->opencl_n_include_file = 0;
1437     Options->opencl_include_files = nullptr;
1438     Options->opencl_print_kernel_types = false;
1439     Options->opencl_embed_kernel_code = false;
1440 
1441     Options->save_schedule_file = nullptr;
1442     Options->load_schedule_file = nullptr;
1443 
1444     return Options;
1445   }
1446 
1447   /// Get a tagged access relation containing all accesses of type @p AccessTy.
1448   ///
1449   /// Instead of a normal access of the form:
1450   ///
1451   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
1452   ///
1453   /// a tagged access has the form
1454   ///
1455   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
1456   ///
1457   /// where 'id' is an additional space that references the memory access that
1458   /// triggered the access.
1459   ///
1460   /// @param AccessTy The type of the memory accesses to collect.
1461   ///
1462   /// @return The relation describing all tagged memory accesses.
1463   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
1464     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
1465 
1466     for (auto &Stmt : *S)
1467       for (auto &Acc : Stmt)
1468         if (Acc->getType() == AccessTy) {
1469           isl_map *Relation = Acc->getAccessRelation();
1470           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
1471 
1472           isl_space *Space = isl_map_get_space(Relation);
1473           Space = isl_space_range(Space);
1474           Space = isl_space_from_range(Space);
1475           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1476           isl_map *Universe = isl_map_universe(Space);
1477           Relation = isl_map_domain_product(Relation, Universe);
1478           Accesses = isl_union_map_add_map(Accesses, Relation);
1479         }
1480 
1481     return Accesses;
1482   }
1483 
1484   /// Get the set of all read accesses, tagged with the access id.
1485   ///
1486   /// @see getTaggedAccesses
1487   isl_union_map *getTaggedReads() {
1488     return getTaggedAccesses(MemoryAccess::READ);
1489   }
1490 
1491   /// Get the set of all may (and must) accesses, tagged with the access id.
1492   ///
1493   /// @see getTaggedAccesses
1494   isl_union_map *getTaggedMayWrites() {
1495     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
1496                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
1497   }
1498 
1499   /// Get the set of all must accesses, tagged with the access id.
1500   ///
1501   /// @see getTaggedAccesses
1502   isl_union_map *getTaggedMustWrites() {
1503     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
1504   }
1505 
1506   /// Collect parameter and array names as isl_ids.
1507   ///
1508   /// To reason about the different parameters and arrays used, ppcg requires
1509   /// a list of all isl_ids in use. As PPCG traditionally performs
1510   /// source-to-source compilation each of these isl_ids is mapped to the
1511   /// expression that represents it. As we do not have a corresponding
1512   /// expression in Polly, we just map each id to a 'zero' expression to match
1513   /// the data format that ppcg expects.
1514   ///
1515   /// @returns Retun a map from collected ids to 'zero' ast expressions.
1516   __isl_give isl_id_to_ast_expr *getNames() {
1517     auto *Names = isl_id_to_ast_expr_alloc(
1518         S->getIslCtx(),
1519         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
1520     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
1521     auto *Space = S->getParamSpace();
1522 
1523     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
1524       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
1525       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1526     }
1527 
1528     for (auto &Array : S->arrays()) {
1529       auto Id = Array->getBasePtrId();
1530       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1531     }
1532 
1533     isl_space_free(Space);
1534     isl_ast_expr_free(Zero);
1535 
1536     return Names;
1537   }
1538 
1539   /// Create a new PPCG scop from the current scop.
1540   ///
1541   /// The PPCG scop is initialized with data from the current polly::Scop. From
1542   /// this initial data, the data-dependences in the PPCG scop are initialized.
1543   /// We do not use Polly's dependence analysis for now, to ensure we match
1544   /// the PPCG default behaviour more closely.
1545   ///
1546   /// @returns A new ppcg scop.
1547   ppcg_scop *createPPCGScop() {
1548     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
1549 
1550     PPCGScop->options = createPPCGOptions();
1551 
1552     PPCGScop->start = 0;
1553     PPCGScop->end = 0;
1554 
1555     PPCGScop->context = S->getContext();
1556     PPCGScop->domain = S->getDomains();
1557     PPCGScop->call = nullptr;
1558     PPCGScop->tagged_reads = getTaggedReads();
1559     PPCGScop->reads = S->getReads();
1560     PPCGScop->live_in = nullptr;
1561     PPCGScop->tagged_may_writes = getTaggedMayWrites();
1562     PPCGScop->may_writes = S->getWrites();
1563     PPCGScop->tagged_must_writes = getTaggedMustWrites();
1564     PPCGScop->must_writes = S->getMustWrites();
1565     PPCGScop->live_out = nullptr;
1566     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
1567     PPCGScop->tagger = nullptr;
1568 
1569     PPCGScop->independence = nullptr;
1570     PPCGScop->dep_flow = nullptr;
1571     PPCGScop->tagged_dep_flow = nullptr;
1572     PPCGScop->dep_false = nullptr;
1573     PPCGScop->dep_forced = nullptr;
1574     PPCGScop->dep_order = nullptr;
1575     PPCGScop->tagged_dep_order = nullptr;
1576 
1577     PPCGScop->schedule = S->getScheduleTree();
1578     PPCGScop->names = getNames();
1579 
1580     PPCGScop->pet = nullptr;
1581 
1582     compute_tagger(PPCGScop);
1583     compute_dependences(PPCGScop);
1584 
1585     return PPCGScop;
1586   }
1587 
1588   /// Collect the array acesses in a statement.
1589   ///
1590   /// @param Stmt The statement for which to collect the accesses.
1591   ///
1592   /// @returns A list of array accesses.
1593   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
1594     gpu_stmt_access *Accesses = nullptr;
1595 
1596     for (MemoryAccess *Acc : Stmt) {
1597       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
1598       Access->read = Acc->isRead();
1599       Access->write = Acc->isWrite();
1600       Access->access = Acc->getAccessRelation();
1601       isl_space *Space = isl_map_get_space(Access->access);
1602       Space = isl_space_range(Space);
1603       Space = isl_space_from_range(Space);
1604       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1605       isl_map *Universe = isl_map_universe(Space);
1606       Access->tagged_access =
1607           isl_map_domain_product(Acc->getAccessRelation(), Universe);
1608       Access->exact_write = !Acc->isMayWrite();
1609       Access->ref_id = Acc->getId();
1610       Access->next = Accesses;
1611       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
1612       Accesses = Access;
1613     }
1614 
1615     return Accesses;
1616   }
1617 
1618   /// Collect the list of GPU statements.
1619   ///
1620   /// Each statement has an id, a pointer to the underlying data structure,
1621   /// as well as a list with all memory accesses.
1622   ///
1623   /// TODO: Initialize the list of memory accesses.
1624   ///
1625   /// @returns A linked-list of statements.
1626   gpu_stmt *getStatements() {
1627     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
1628                                        std::distance(S->begin(), S->end()));
1629 
1630     int i = 0;
1631     for (auto &Stmt : *S) {
1632       gpu_stmt *GPUStmt = &Stmts[i];
1633 
1634       GPUStmt->id = Stmt.getDomainId();
1635 
1636       // We use the pet stmt pointer to keep track of the Polly statements.
1637       GPUStmt->stmt = (pet_stmt *)&Stmt;
1638       GPUStmt->accesses = getStmtAccesses(Stmt);
1639       i++;
1640     }
1641 
1642     return Stmts;
1643   }
1644 
1645   /// Derive the extent of an array.
1646   ///
1647   /// The extent of an array is defined by the set of memory locations for
1648   /// which a memory access in the iteration domain exists.
1649   ///
1650   /// @param Array The array to derive the extent for.
1651   ///
1652   /// @returns An isl_set describing the extent of the array.
1653   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
1654     isl_union_map *Accesses = S->getAccesses();
1655     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
1656     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
1657     isl_set *AccessSet =
1658         isl_union_set_extract_set(AccessUSet, Array->getSpace());
1659     isl_union_set_free(AccessUSet);
1660 
1661     return AccessSet;
1662   }
1663 
1664   /// Derive the bounds of an array.
1665   ///
1666   /// For the first dimension we derive the bound of the array from the extent
1667   /// of this dimension. For inner dimensions we obtain their size directly from
1668   /// ScopArrayInfo.
1669   ///
1670   /// @param PPCGArray The array to compute bounds for.
1671   /// @param Array The polly array from which to take the information.
1672   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
1673     if (PPCGArray.n_index > 0) {
1674       isl_set *Dom = isl_set_copy(PPCGArray.extent);
1675       Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
1676       isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
1677       isl_set_free(Dom);
1678       Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
1679       isl_local_space *LS = isl_local_space_from_space(isl_set_get_space(Dom));
1680       isl_aff *One = isl_aff_zero_on_domain(LS);
1681       One = isl_aff_add_constant_si(One, 1);
1682       Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
1683       Bound = isl_pw_aff_gist(Bound, S->getContext());
1684       PPCGArray.bound[0] = Bound;
1685     }
1686 
1687     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
1688       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
1689       auto LS = isl_pw_aff_get_domain_space(Bound);
1690       auto Aff = isl_multi_aff_zero(LS);
1691       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
1692       PPCGArray.bound[i] = Bound;
1693     }
1694   }
1695 
1696   /// Create the arrays for @p PPCGProg.
1697   ///
1698   /// @param PPCGProg The program to compute the arrays for.
1699   void createArrays(gpu_prog *PPCGProg) {
1700     int i = 0;
1701     for (auto &Array : S->arrays()) {
1702       std::string TypeName;
1703       raw_string_ostream OS(TypeName);
1704 
1705       OS << *Array->getElementType();
1706       TypeName = OS.str();
1707 
1708       gpu_array_info &PPCGArray = PPCGProg->array[i];
1709 
1710       PPCGArray.space = Array->getSpace();
1711       PPCGArray.type = strdup(TypeName.c_str());
1712       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
1713       PPCGArray.name = strdup(Array->getName().c_str());
1714       PPCGArray.extent = nullptr;
1715       PPCGArray.n_index = Array->getNumberOfDimensions();
1716       PPCGArray.bound =
1717           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
1718       PPCGArray.extent = getExtent(Array);
1719       PPCGArray.n_ref = 0;
1720       PPCGArray.refs = nullptr;
1721       PPCGArray.accessed = true;
1722       PPCGArray.read_only_scalar = false;
1723       PPCGArray.has_compound_element = false;
1724       PPCGArray.local = false;
1725       PPCGArray.declare_local = false;
1726       PPCGArray.global = false;
1727       PPCGArray.linearize = false;
1728       PPCGArray.dep_order = nullptr;
1729       PPCGArray.user = Array;
1730 
1731       setArrayBounds(PPCGArray, Array);
1732       i++;
1733 
1734       collect_references(PPCGProg, &PPCGArray);
1735     }
1736   }
1737 
1738   /// Create an identity map between the arrays in the scop.
1739   ///
1740   /// @returns An identity map between the arrays in the scop.
1741   isl_union_map *getArrayIdentity() {
1742     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
1743 
1744     for (auto &Array : S->arrays()) {
1745       isl_space *Space = Array->getSpace();
1746       Space = isl_space_map_from_set(Space);
1747       isl_map *Identity = isl_map_identity(Space);
1748       Maps = isl_union_map_add_map(Maps, Identity);
1749     }
1750 
1751     return Maps;
1752   }
1753 
1754   /// Create a default-initialized PPCG GPU program.
1755   ///
1756   /// @returns A new gpu grogram description.
1757   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
1758 
1759     if (!PPCGScop)
1760       return nullptr;
1761 
1762     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
1763 
1764     PPCGProg->ctx = S->getIslCtx();
1765     PPCGProg->scop = PPCGScop;
1766     PPCGProg->context = isl_set_copy(PPCGScop->context);
1767     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
1768     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
1769     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
1770     PPCGProg->tagged_must_kill =
1771         isl_union_map_copy(PPCGScop->tagged_must_kills);
1772     PPCGProg->to_inner = getArrayIdentity();
1773     PPCGProg->to_outer = getArrayIdentity();
1774     PPCGProg->may_persist = compute_may_persist(PPCGProg);
1775     PPCGProg->any_to_outer = nullptr;
1776     PPCGProg->array_order = nullptr;
1777     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
1778     PPCGProg->stmts = getStatements();
1779     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
1780     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
1781                                        PPCGProg->n_array);
1782 
1783     createArrays(PPCGProg);
1784 
1785     return PPCGProg;
1786   }
1787 
1788   struct PrintGPUUserData {
1789     struct cuda_info *CudaInfo;
1790     struct gpu_prog *PPCGProg;
1791     std::vector<ppcg_kernel *> Kernels;
1792   };
1793 
1794   /// Print a user statement node in the host code.
1795   ///
1796   /// We use ppcg's printing facilities to print the actual statement and
1797   /// additionally build up a list of all kernels that are encountered in the
1798   /// host ast.
1799   ///
1800   /// @param P The printer to print to
1801   /// @param Options The printing options to use
1802   /// @param Node The node to print
1803   /// @param User A user pointer to carry additional data. This pointer is
1804   ///             expected to be of type PrintGPUUserData.
1805   ///
1806   /// @returns A printer to which the output has been printed.
1807   static __isl_give isl_printer *
1808   printHostUser(__isl_take isl_printer *P,
1809                 __isl_take isl_ast_print_options *Options,
1810                 __isl_take isl_ast_node *Node, void *User) {
1811     auto Data = (struct PrintGPUUserData *)User;
1812     auto Id = isl_ast_node_get_annotation(Node);
1813 
1814     if (Id) {
1815       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
1816 
1817       // If this is a user statement, format it ourselves as ppcg would
1818       // otherwise try to call pet functionality that is not available in
1819       // Polly.
1820       if (IsUser) {
1821         P = isl_printer_start_line(P);
1822         P = isl_printer_print_ast_node(P, Node);
1823         P = isl_printer_end_line(P);
1824         isl_id_free(Id);
1825         isl_ast_print_options_free(Options);
1826         return P;
1827       }
1828 
1829       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
1830       isl_id_free(Id);
1831       Data->Kernels.push_back(Kernel);
1832     }
1833 
1834     return print_host_user(P, Options, Node, User);
1835   }
1836 
1837   /// Print C code corresponding to the control flow in @p Kernel.
1838   ///
1839   /// @param Kernel The kernel to print
1840   void printKernel(ppcg_kernel *Kernel) {
1841     auto *P = isl_printer_to_str(S->getIslCtx());
1842     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
1843     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
1844     P = isl_ast_node_print(Kernel->tree, P, Options);
1845     char *String = isl_printer_get_str(P);
1846     printf("%s\n", String);
1847     free(String);
1848     isl_printer_free(P);
1849   }
1850 
1851   /// Print C code corresponding to the GPU code described by @p Tree.
1852   ///
1853   /// @param Tree An AST describing GPU code
1854   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
1855   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
1856     auto *P = isl_printer_to_str(S->getIslCtx());
1857     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
1858 
1859     PrintGPUUserData Data;
1860     Data.PPCGProg = PPCGProg;
1861 
1862     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
1863     Options =
1864         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
1865     P = isl_ast_node_print(Tree, P, Options);
1866     char *String = isl_printer_get_str(P);
1867     printf("# host\n");
1868     printf("%s\n", String);
1869     free(String);
1870     isl_printer_free(P);
1871 
1872     for (auto Kernel : Data.Kernels) {
1873       printf("# kernel%d\n", Kernel->id);
1874       printKernel(Kernel);
1875     }
1876   }
1877 
1878   // Generate a GPU program using PPCG.
1879   //
1880   // GPU mapping consists of multiple steps:
1881   //
1882   //  1) Compute new schedule for the program.
1883   //  2) Map schedule to GPU (TODO)
1884   //  3) Generate code for new schedule (TODO)
1885   //
1886   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
1887   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
1888   // strategy directly from this pass.
1889   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
1890 
1891     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
1892 
1893     PPCGGen->ctx = S->getIslCtx();
1894     PPCGGen->options = PPCGScop->options;
1895     PPCGGen->print = nullptr;
1896     PPCGGen->print_user = nullptr;
1897     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
1898     PPCGGen->prog = PPCGProg;
1899     PPCGGen->tree = nullptr;
1900     PPCGGen->types.n = 0;
1901     PPCGGen->types.name = nullptr;
1902     PPCGGen->sizes = nullptr;
1903     PPCGGen->used_sizes = nullptr;
1904     PPCGGen->kernel_id = 0;
1905 
1906     // Set scheduling strategy to same strategy PPCG is using.
1907     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
1908     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
1909     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
1910 
1911     isl_schedule *Schedule = get_schedule(PPCGGen);
1912 
1913     int has_permutable = has_any_permutable_node(Schedule);
1914 
1915     if (!has_permutable || has_permutable < 0) {
1916       Schedule = isl_schedule_free(Schedule);
1917     } else {
1918       Schedule = map_to_device(PPCGGen, Schedule);
1919       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
1920     }
1921 
1922     if (DumpSchedule) {
1923       isl_printer *P = isl_printer_to_str(S->getIslCtx());
1924       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
1925       P = isl_printer_print_str(P, "Schedule\n");
1926       P = isl_printer_print_str(P, "========\n");
1927       if (Schedule)
1928         P = isl_printer_print_schedule(P, Schedule);
1929       else
1930         P = isl_printer_print_str(P, "No schedule found\n");
1931 
1932       printf("%s\n", isl_printer_get_str(P));
1933       isl_printer_free(P);
1934     }
1935 
1936     if (DumpCode) {
1937       printf("Code\n");
1938       printf("====\n");
1939       if (PPCGGen->tree)
1940         printGPUTree(PPCGGen->tree, PPCGProg);
1941       else
1942         printf("No code generated\n");
1943     }
1944 
1945     isl_schedule_free(Schedule);
1946 
1947     return PPCGGen;
1948   }
1949 
1950   /// Free gpu_gen structure.
1951   ///
1952   /// @param PPCGGen The ppcg_gen object to free.
1953   void freePPCGGen(gpu_gen *PPCGGen) {
1954     isl_ast_node_free(PPCGGen->tree);
1955     isl_union_map_free(PPCGGen->sizes);
1956     isl_union_map_free(PPCGGen->used_sizes);
1957     free(PPCGGen);
1958   }
1959 
1960   /// Free the options in the ppcg scop structure.
1961   ///
1962   /// ppcg is not freeing these options for us. To avoid leaks we do this
1963   /// ourselves.
1964   ///
1965   /// @param PPCGScop The scop referencing the options to free.
1966   void freeOptions(ppcg_scop *PPCGScop) {
1967     free(PPCGScop->options->debug);
1968     PPCGScop->options->debug = nullptr;
1969     free(PPCGScop->options);
1970     PPCGScop->options = nullptr;
1971   }
1972 
1973   /// Generate code for a given GPU AST described by @p Root.
1974   ///
1975   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
1976   /// @param Prog The GPU Program to generate code for.
1977   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
1978     ScopAnnotator Annotator;
1979     Annotator.buildAliasScopes(*S);
1980 
1981     Region *R = &S->getRegion();
1982 
1983     simplifyRegion(R, DT, LI, RI);
1984 
1985     BasicBlock *EnteringBB = R->getEnteringBlock();
1986 
1987     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
1988 
1989     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S,
1990                                Prog);
1991 
1992     // Only build the run-time condition and parameters _after_ having
1993     // introduced the conditional branch. This is important as the conditional
1994     // branch will guard the original scop from new induction variables that
1995     // the SCEVExpander may introduce while code generating the parameters and
1996     // which may introduce scalar dependences that prevent us from correctly
1997     // code generating this scop.
1998     BasicBlock *StartBlock =
1999         executeScopConditionally(*S, this, Builder.getTrue());
2000 
2001     // TODO: Handle LICM
2002     // TODO: Verify run-time checks
2003     auto SplitBlock = StartBlock->getSinglePredecessor();
2004     Builder.SetInsertPoint(SplitBlock->getTerminator());
2005     NodeBuilder.addParameters(S->getContext());
2006     Builder.SetInsertPoint(&*StartBlock->begin());
2007 
2008     NodeBuilder.initializeAfterRTH();
2009     NodeBuilder.create(Root);
2010     NodeBuilder.finalize();
2011   }
2012 
2013   bool runOnScop(Scop &CurrentScop) override {
2014     S = &CurrentScop;
2015     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2016     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2017     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2018     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
2019     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
2020 
2021     // We currently do not support scops with invariant loads.
2022     if (S->hasInvariantAccesses())
2023       return false;
2024 
2025     auto PPCGScop = createPPCGScop();
2026     auto PPCGProg = createPPCGProg(PPCGScop);
2027     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
2028 
2029     if (PPCGGen->tree)
2030       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
2031 
2032     freeOptions(PPCGScop);
2033     freePPCGGen(PPCGGen);
2034     gpu_prog_free(PPCGProg);
2035     ppcg_scop_free(PPCGScop);
2036 
2037     return true;
2038   }
2039 
2040   void printScop(raw_ostream &, Scop &) const override {}
2041 
2042   void getAnalysisUsage(AnalysisUsage &AU) const override {
2043     AU.addRequired<DominatorTreeWrapperPass>();
2044     AU.addRequired<RegionInfoPass>();
2045     AU.addRequired<ScalarEvolutionWrapperPass>();
2046     AU.addRequired<ScopDetection>();
2047     AU.addRequired<ScopInfoRegionPass>();
2048     AU.addRequired<LoopInfoWrapperPass>();
2049 
2050     AU.addPreserved<AAResultsWrapperPass>();
2051     AU.addPreserved<BasicAAWrapperPass>();
2052     AU.addPreserved<LoopInfoWrapperPass>();
2053     AU.addPreserved<DominatorTreeWrapperPass>();
2054     AU.addPreserved<GlobalsAAWrapperPass>();
2055     AU.addPreserved<PostDominatorTreeWrapperPass>();
2056     AU.addPreserved<ScopDetection>();
2057     AU.addPreserved<ScalarEvolutionWrapperPass>();
2058     AU.addPreserved<SCEVAAWrapperPass>();
2059 
2060     // FIXME: We do not yet add regions for the newly generated code to the
2061     //        region tree.
2062     AU.addPreserved<RegionInfoPass>();
2063     AU.addPreserved<ScopInfoRegionPass>();
2064   }
2065 };
2066 }
2067 
2068 char PPCGCodeGeneration::ID = 1;
2069 
2070 Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
2071 
2072 INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
2073                       "Polly - Apply PPCG translation to SCOP", false, false)
2074 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
2075 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
2076 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
2077 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
2078 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
2079 INITIALIZE_PASS_DEPENDENCY(ScopDetection);
2080 INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
2081                     "Polly - Apply PPCG translation to SCOP", false, false)
2082