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