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