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