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