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