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