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 
1089     Instruction *Param = new AllocaInst(
1090         Builder.getInt8PtrTy(), Launch + "_param_" + std::to_string(Index),
1091         EntryBlock->getTerminator());
1092     Builder.CreateStore(DevArray, Param);
1093     Value *Slot = Builder.CreateGEP(
1094         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1095     Value *ParamTyped =
1096         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1097     Builder.CreateStore(ParamTyped, Slot);
1098     Index++;
1099   }
1100 
1101   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1102 
1103   for (long i = 0; i < NumHostIters; i++) {
1104     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1105     Value *Val = IDToValue[Id];
1106     isl_id_free(Id);
1107     Instruction *Param = new AllocaInst(
1108         Val->getType(), Launch + "_param_" + std::to_string(Index),
1109         EntryBlock->getTerminator());
1110     Builder.CreateStore(Val, Param);
1111     Value *Slot = Builder.CreateGEP(
1112         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1113     Value *ParamTyped =
1114         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1115     Builder.CreateStore(ParamTyped, Slot);
1116     Index++;
1117   }
1118 
1119   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1120 
1121   for (long i = 0; i < NumVars; i++) {
1122     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1123     Value *Val = IDToValue[Id];
1124     isl_id_free(Id);
1125     Instruction *Param = new AllocaInst(
1126         Val->getType(), Launch + "_param_" + std::to_string(Index),
1127         EntryBlock->getTerminator());
1128     Builder.CreateStore(Val, Param);
1129     Value *Slot = Builder.CreateGEP(
1130         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1131     Value *ParamTyped =
1132         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1133     Builder.CreateStore(ParamTyped, Slot);
1134     Index++;
1135   }
1136 
1137   for (auto Val : SubtreeValues) {
1138     Instruction *Param = new AllocaInst(
1139         Val->getType(), Launch + "_param_" + std::to_string(Index),
1140         EntryBlock->getTerminator());
1141     Builder.CreateStore(Val, Param);
1142     Value *Slot = Builder.CreateGEP(
1143         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1144     Value *ParamTyped =
1145         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1146     Builder.CreateStore(ParamTyped, Slot);
1147     Index++;
1148   }
1149 
1150   auto Location = EntryBlock->getTerminator();
1151   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
1152                          Launch + "_params_i8ptr", Location);
1153 }
1154 
1155 void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
1156   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
1157   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
1158   isl_id_free(Id);
1159   isl_ast_node_free(KernelStmt);
1160 
1161   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1162   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1163 
1164   SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel);
1165 
1166   assert(Kernel->tree && "Device AST of kernel node is empty");
1167 
1168   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1169   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1170   ValueMapT HostValueMap = ValueMap;
1171   BlockGenerator::ScalarAllocaMapTy HostScalarMap = ScalarMap;
1172   BlockGenerator::ScalarAllocaMapTy HostPHIOpMap = PHIOpMap;
1173   ScalarMap.clear();
1174   PHIOpMap.clear();
1175 
1176   SetVector<const Loop *> Loops;
1177 
1178   // Create for all loops we depend on values that contain the current loop
1179   // iteration. These values are necessary to generate code for SCEVs that
1180   // depend on such loops. As a result we need to pass them to the subfunction.
1181   for (const Loop *L : Loops) {
1182     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1183                                             SE.getUnknown(Builder.getInt64(1)),
1184                                             L, SCEV::FlagAnyWrap);
1185     Value *V = generateSCEV(OuterLIV);
1186     OutsideLoopIterations[L] = SE.getUnknown(V);
1187     SubtreeValues.insert(V);
1188   }
1189 
1190   createKernelFunction(Kernel, SubtreeValues);
1191 
1192   create(isl_ast_node_copy(Kernel->tree));
1193 
1194   Function *F = Builder.GetInsertBlock()->getParent();
1195   addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
1196   clearDominators(F);
1197   clearScalarEvolution(F);
1198   clearLoops(F);
1199 
1200   Builder.SetInsertPoint(&HostInsertPoint);
1201   IDToValue = HostIDs;
1202 
1203   ValueMap = std::move(HostValueMap);
1204   ScalarMap = std::move(HostScalarMap);
1205   PHIOpMap = std::move(HostPHIOpMap);
1206   EscapeMap.clear();
1207   IDToSAI.clear();
1208   Annotator.resetAlternativeAliasBases();
1209   for (auto &BasePtr : LocalArrays)
1210     S.invalidateScopArrayInfo(BasePtr, ScopArrayInfo::MK_Array);
1211   LocalArrays.clear();
1212 
1213   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
1214 
1215   std::string ASMString = finalizeKernelFunction();
1216   std::string Name = "kernel_" + std::to_string(Kernel->id);
1217   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
1218   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
1219   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
1220 
1221   Value *GridDimX, *GridDimY;
1222   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
1223 
1224   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
1225                          BlockDimZ, Parameters);
1226   createCallFreeKernel(GPUKernel);
1227 
1228   for (auto Id : KernelIds)
1229     isl_id_free(Id);
1230 
1231   KernelIds.clear();
1232 }
1233 
1234 /// Compute the DataLayout string for the NVPTX backend.
1235 ///
1236 /// @param is64Bit Are we looking for a 64 bit architecture?
1237 static std::string computeNVPTXDataLayout(bool is64Bit) {
1238   std::string Ret = "e";
1239 
1240   if (!is64Bit)
1241     Ret += "-p:32:32";
1242 
1243   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
1244 
1245   return Ret;
1246 }
1247 
1248 Function *
1249 GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1250                                          SetVector<Value *> &SubtreeValues) {
1251   std::vector<Type *> Args;
1252   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
1253 
1254   for (long i = 0; i < Prog->n_array; i++) {
1255     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1256       continue;
1257 
1258     Args.push_back(Builder.getInt8PtrTy());
1259   }
1260 
1261   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1262 
1263   for (long i = 0; i < NumHostIters; i++)
1264     Args.push_back(Builder.getInt64Ty());
1265 
1266   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1267 
1268   for (long i = 0; i < NumVars; i++) {
1269     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1270     Value *Val = IDToValue[Id];
1271     isl_id_free(Id);
1272     Args.push_back(Val->getType());
1273   }
1274 
1275   for (auto *V : SubtreeValues)
1276     Args.push_back(V->getType());
1277 
1278   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
1279   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
1280                               GPUModule.get());
1281   FN->setCallingConv(CallingConv::PTX_Kernel);
1282 
1283   auto Arg = FN->arg_begin();
1284   for (long i = 0; i < Kernel->n_array; i++) {
1285     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1286       continue;
1287 
1288     Arg->setName(Kernel->array[i].array->name);
1289 
1290     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1291     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1292     Type *EleTy = SAI->getElementType();
1293     Value *Val = &*Arg;
1294     SmallVector<const SCEV *, 4> Sizes;
1295     isl_ast_build *Build =
1296         isl_ast_build_from_context(isl_set_copy(Prog->context));
1297     Sizes.push_back(nullptr);
1298     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1299       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
1300           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
1301       auto V = ExprBuilder.create(DimSize);
1302       Sizes.push_back(SE.getSCEV(V));
1303     }
1304     const ScopArrayInfo *SAIRep =
1305         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, ScopArrayInfo::MK_Array);
1306     LocalArrays.push_back(Val);
1307 
1308     isl_ast_build_free(Build);
1309     KernelIds.push_back(Id);
1310     IDToSAI[Id] = SAIRep;
1311     Arg++;
1312   }
1313 
1314   for (long i = 0; i < NumHostIters; i++) {
1315     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1316     Arg->setName(isl_id_get_name(Id));
1317     IDToValue[Id] = &*Arg;
1318     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1319     Arg++;
1320   }
1321 
1322   for (long i = 0; i < NumVars; i++) {
1323     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1324     Arg->setName(isl_id_get_name(Id));
1325     Value *Val = IDToValue[Id];
1326     ValueMap[Val] = &*Arg;
1327     IDToValue[Id] = &*Arg;
1328     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1329     Arg++;
1330   }
1331 
1332   for (auto *V : SubtreeValues) {
1333     Arg->setName(V->getName());
1334     ValueMap[V] = &*Arg;
1335     Arg++;
1336   }
1337 
1338   return FN;
1339 }
1340 
1341 void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
1342   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
1343                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
1344 
1345   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
1346                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
1347                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
1348 
1349   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1350     std::string Name = isl_id_get_name(Id);
1351     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1352     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1353     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1354     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1355     IDToValue[Id] = Val;
1356     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1357   };
1358 
1359   for (int i = 0; i < Kernel->n_grid; ++i) {
1360     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1361     addId(Id, IntrinsicsBID[i]);
1362   }
1363 
1364   for (int i = 0; i < Kernel->n_block; ++i) {
1365     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1366     addId(Id, IntrinsicsTID[i]);
1367   }
1368 }
1369 
1370 void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
1371   auto Arg = FN->arg_begin();
1372   for (long i = 0; i < Kernel->n_array; i++) {
1373     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1374       continue;
1375 
1376     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1377     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1378     isl_id_free(Id);
1379 
1380     if (SAI->getNumberOfDimensions() > 0) {
1381       Arg++;
1382       continue;
1383     }
1384 
1385     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
1386     Value *ArgPtr = &*Arg;
1387     Type *TypePtr = SAI->getElementType()->getPointerTo();
1388     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
1389     Value *Val = Builder.CreateLoad(TypedArgPtr);
1390     Builder.CreateStore(Val, Alloca);
1391 
1392     Arg++;
1393   }
1394 }
1395 
1396 void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
1397   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1398 
1399   for (int i = 0; i < Kernel->n_var; ++i) {
1400     struct ppcg_kernel_var &Var = Kernel->var[i];
1401     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
1402     Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType();
1403 
1404     Type *ArrayTy = EleTy;
1405     SmallVector<const SCEV *, 4> Sizes;
1406 
1407     Sizes.push_back(nullptr);
1408     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
1409       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1410       long Bound = isl_val_get_num_si(Val);
1411       isl_val_free(Val);
1412       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
1413     }
1414 
1415     for (int j = Var.array->n_index - 1; j >= 0; --j) {
1416       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1417       long Bound = isl_val_get_num_si(Val);
1418       isl_val_free(Val);
1419       ArrayTy = ArrayType::get(ArrayTy, Bound);
1420     }
1421 
1422     const ScopArrayInfo *SAI;
1423     Value *Allocation;
1424     if (Var.type == ppcg_access_shared) {
1425       auto GlobalVar = new GlobalVariable(
1426           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
1427           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
1428       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
1429       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
1430 
1431       Allocation = GlobalVar;
1432     } else if (Var.type == ppcg_access_private) {
1433       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
1434     } else {
1435       llvm_unreachable("unknown variable type");
1436     }
1437     SAI = S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes,
1438                                      ScopArrayInfo::MK_Array);
1439     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
1440     IDToValue[Id] = Allocation;
1441     LocalArrays.push_back(Allocation);
1442     KernelIds.push_back(Id);
1443     IDToSAI[Id] = SAI;
1444   }
1445 }
1446 
1447 void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel,
1448                                           SetVector<Value *> &SubtreeValues) {
1449 
1450   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
1451   GPUModule.reset(new Module(Identifier, Builder.getContext()));
1452   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
1453   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
1454 
1455   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
1456 
1457   BasicBlock *PrevBlock = Builder.GetInsertBlock();
1458   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
1459 
1460   DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1461   DT.addNewBlock(EntryBlock, PrevBlock);
1462 
1463   Builder.SetInsertPoint(EntryBlock);
1464   Builder.CreateRetVoid();
1465   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
1466 
1467   ScopDetection::markFunctionAsInvalid(FN);
1468 
1469   prepareKernelArguments(Kernel, FN);
1470   createKernelVariables(Kernel, FN);
1471   insertKernelIntrinsics(Kernel);
1472 }
1473 
1474 std::string GPUNodeBuilder::createKernelASM() {
1475   llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda"));
1476   std::string ErrMsg;
1477   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
1478 
1479   if (!GPUTarget) {
1480     errs() << ErrMsg << "\n";
1481     return "";
1482   }
1483 
1484   TargetOptions Options;
1485   Options.UnsafeFPMath = FastMath;
1486   std::unique_ptr<TargetMachine> TargetM(
1487       GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "",
1488                                      Options, Optional<Reloc::Model>()));
1489 
1490   SmallString<0> ASMString;
1491   raw_svector_ostream ASMStream(ASMString);
1492   llvm::legacy::PassManager PM;
1493 
1494   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
1495 
1496   if (TargetM->addPassesToEmitFile(
1497           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
1498     errs() << "The target does not support generation of this file type!\n";
1499     return "";
1500   }
1501 
1502   PM.run(*GPUModule);
1503 
1504   return ASMStream.str();
1505 }
1506 
1507 std::string GPUNodeBuilder::finalizeKernelFunction() {
1508   if (verifyModule(*GPUModule)) {
1509     BuildSuccessful = false;
1510     return "";
1511   }
1512 
1513   if (DumpKernelIR)
1514     outs() << *GPUModule << "\n";
1515 
1516   // Optimize module.
1517   llvm::legacy::PassManager OptPasses;
1518   PassManagerBuilder PassBuilder;
1519   PassBuilder.OptLevel = 3;
1520   PassBuilder.SizeLevel = 0;
1521   PassBuilder.populateModulePassManager(OptPasses);
1522   OptPasses.run(*GPUModule);
1523 
1524   std::string Assembly = createKernelASM();
1525 
1526   if (DumpKernelASM)
1527     outs() << Assembly << "\n";
1528 
1529   GPUModule.release();
1530   KernelIDs.clear();
1531 
1532   return Assembly;
1533 }
1534 
1535 namespace {
1536 class PPCGCodeGeneration : public ScopPass {
1537 public:
1538   static char ID;
1539 
1540   /// The scop that is currently processed.
1541   Scop *S;
1542 
1543   LoopInfo *LI;
1544   DominatorTree *DT;
1545   ScalarEvolution *SE;
1546   const DataLayout *DL;
1547   RegionInfo *RI;
1548 
1549   PPCGCodeGeneration() : ScopPass(ID) {}
1550 
1551   /// Construct compilation options for PPCG.
1552   ///
1553   /// @returns The compilation options.
1554   ppcg_options *createPPCGOptions() {
1555     auto DebugOptions =
1556         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
1557     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
1558 
1559     DebugOptions->dump_schedule_constraints = false;
1560     DebugOptions->dump_schedule = false;
1561     DebugOptions->dump_final_schedule = false;
1562     DebugOptions->dump_sizes = false;
1563     DebugOptions->verbose = false;
1564 
1565     Options->debug = DebugOptions;
1566 
1567     Options->reschedule = true;
1568     Options->scale_tile_loops = false;
1569     Options->wrap = false;
1570 
1571     Options->non_negative_parameters = false;
1572     Options->ctx = nullptr;
1573     Options->sizes = nullptr;
1574 
1575     Options->tile_size = 32;
1576 
1577     Options->use_private_memory = PrivateMemory;
1578     Options->use_shared_memory = SharedMemory;
1579     Options->max_shared_memory = 48 * 1024;
1580 
1581     Options->target = PPCG_TARGET_CUDA;
1582     Options->openmp = false;
1583     Options->linearize_device_arrays = true;
1584     Options->live_range_reordering = false;
1585 
1586     Options->opencl_compiler_options = nullptr;
1587     Options->opencl_use_gpu = false;
1588     Options->opencl_n_include_file = 0;
1589     Options->opencl_include_files = nullptr;
1590     Options->opencl_print_kernel_types = false;
1591     Options->opencl_embed_kernel_code = false;
1592 
1593     Options->save_schedule_file = nullptr;
1594     Options->load_schedule_file = nullptr;
1595 
1596     return Options;
1597   }
1598 
1599   /// Get a tagged access relation containing all accesses of type @p AccessTy.
1600   ///
1601   /// Instead of a normal access of the form:
1602   ///
1603   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
1604   ///
1605   /// a tagged access has the form
1606   ///
1607   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
1608   ///
1609   /// where 'id' is an additional space that references the memory access that
1610   /// triggered the access.
1611   ///
1612   /// @param AccessTy The type of the memory accesses to collect.
1613   ///
1614   /// @return The relation describing all tagged memory accesses.
1615   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
1616     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
1617 
1618     for (auto &Stmt : *S)
1619       for (auto &Acc : Stmt)
1620         if (Acc->getType() == AccessTy) {
1621           isl_map *Relation = Acc->getAccessRelation();
1622           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
1623 
1624           isl_space *Space = isl_map_get_space(Relation);
1625           Space = isl_space_range(Space);
1626           Space = isl_space_from_range(Space);
1627           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1628           isl_map *Universe = isl_map_universe(Space);
1629           Relation = isl_map_domain_product(Relation, Universe);
1630           Accesses = isl_union_map_add_map(Accesses, Relation);
1631         }
1632 
1633     return Accesses;
1634   }
1635 
1636   /// Get the set of all read accesses, tagged with the access id.
1637   ///
1638   /// @see getTaggedAccesses
1639   isl_union_map *getTaggedReads() {
1640     return getTaggedAccesses(MemoryAccess::READ);
1641   }
1642 
1643   /// Get the set of all may (and must) accesses, tagged with the access id.
1644   ///
1645   /// @see getTaggedAccesses
1646   isl_union_map *getTaggedMayWrites() {
1647     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
1648                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
1649   }
1650 
1651   /// Get the set of all must accesses, tagged with the access id.
1652   ///
1653   /// @see getTaggedAccesses
1654   isl_union_map *getTaggedMustWrites() {
1655     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
1656   }
1657 
1658   /// Collect parameter and array names as isl_ids.
1659   ///
1660   /// To reason about the different parameters and arrays used, ppcg requires
1661   /// a list of all isl_ids in use. As PPCG traditionally performs
1662   /// source-to-source compilation each of these isl_ids is mapped to the
1663   /// expression that represents it. As we do not have a corresponding
1664   /// expression in Polly, we just map each id to a 'zero' expression to match
1665   /// the data format that ppcg expects.
1666   ///
1667   /// @returns Retun a map from collected ids to 'zero' ast expressions.
1668   __isl_give isl_id_to_ast_expr *getNames() {
1669     auto *Names = isl_id_to_ast_expr_alloc(
1670         S->getIslCtx(),
1671         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
1672     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
1673     auto *Space = S->getParamSpace();
1674 
1675     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
1676       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
1677       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1678     }
1679 
1680     for (auto &Array : S->arrays()) {
1681       auto Id = Array->getBasePtrId();
1682       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1683     }
1684 
1685     isl_space_free(Space);
1686     isl_ast_expr_free(Zero);
1687 
1688     return Names;
1689   }
1690 
1691   /// Create a new PPCG scop from the current scop.
1692   ///
1693   /// The PPCG scop is initialized with data from the current polly::Scop. From
1694   /// this initial data, the data-dependences in the PPCG scop are initialized.
1695   /// We do not use Polly's dependence analysis for now, to ensure we match
1696   /// the PPCG default behaviour more closely.
1697   ///
1698   /// @returns A new ppcg scop.
1699   ppcg_scop *createPPCGScop() {
1700     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
1701 
1702     PPCGScop->options = createPPCGOptions();
1703 
1704     PPCGScop->start = 0;
1705     PPCGScop->end = 0;
1706 
1707     PPCGScop->context = S->getContext();
1708     PPCGScop->domain = S->getDomains();
1709     PPCGScop->call = nullptr;
1710     PPCGScop->tagged_reads = getTaggedReads();
1711     PPCGScop->reads = S->getReads();
1712     PPCGScop->live_in = nullptr;
1713     PPCGScop->tagged_may_writes = getTaggedMayWrites();
1714     PPCGScop->may_writes = S->getWrites();
1715     PPCGScop->tagged_must_writes = getTaggedMustWrites();
1716     PPCGScop->must_writes = S->getMustWrites();
1717     PPCGScop->live_out = nullptr;
1718     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
1719     PPCGScop->tagger = nullptr;
1720 
1721     PPCGScop->independence = nullptr;
1722     PPCGScop->dep_flow = nullptr;
1723     PPCGScop->tagged_dep_flow = nullptr;
1724     PPCGScop->dep_false = nullptr;
1725     PPCGScop->dep_forced = nullptr;
1726     PPCGScop->dep_order = nullptr;
1727     PPCGScop->tagged_dep_order = nullptr;
1728 
1729     PPCGScop->schedule = S->getScheduleTree();
1730     PPCGScop->names = getNames();
1731 
1732     PPCGScop->pet = nullptr;
1733 
1734     compute_tagger(PPCGScop);
1735     compute_dependences(PPCGScop);
1736 
1737     return PPCGScop;
1738   }
1739 
1740   /// Collect the array acesses in a statement.
1741   ///
1742   /// @param Stmt The statement for which to collect the accesses.
1743   ///
1744   /// @returns A list of array accesses.
1745   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
1746     gpu_stmt_access *Accesses = nullptr;
1747 
1748     for (MemoryAccess *Acc : Stmt) {
1749       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
1750       Access->read = Acc->isRead();
1751       Access->write = Acc->isWrite();
1752       Access->access = Acc->getAccessRelation();
1753       isl_space *Space = isl_map_get_space(Access->access);
1754       Space = isl_space_range(Space);
1755       Space = isl_space_from_range(Space);
1756       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1757       isl_map *Universe = isl_map_universe(Space);
1758       Access->tagged_access =
1759           isl_map_domain_product(Acc->getAccessRelation(), Universe);
1760       Access->exact_write = !Acc->isMayWrite();
1761       Access->ref_id = Acc->getId();
1762       Access->next = Accesses;
1763       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
1764       Accesses = Access;
1765     }
1766 
1767     return Accesses;
1768   }
1769 
1770   /// Collect the list of GPU statements.
1771   ///
1772   /// Each statement has an id, a pointer to the underlying data structure,
1773   /// as well as a list with all memory accesses.
1774   ///
1775   /// TODO: Initialize the list of memory accesses.
1776   ///
1777   /// @returns A linked-list of statements.
1778   gpu_stmt *getStatements() {
1779     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
1780                                        std::distance(S->begin(), S->end()));
1781 
1782     int i = 0;
1783     for (auto &Stmt : *S) {
1784       gpu_stmt *GPUStmt = &Stmts[i];
1785 
1786       GPUStmt->id = Stmt.getDomainId();
1787 
1788       // We use the pet stmt pointer to keep track of the Polly statements.
1789       GPUStmt->stmt = (pet_stmt *)&Stmt;
1790       GPUStmt->accesses = getStmtAccesses(Stmt);
1791       i++;
1792     }
1793 
1794     return Stmts;
1795   }
1796 
1797   /// Derive the extent of an array.
1798   ///
1799   /// The extent of an array is the set of elements that are within the
1800   /// accessed array. For the inner dimensions, the extent constraints are
1801   /// 0 and the size of the corresponding array dimension. For the first
1802   /// (outermost) dimension, the extent constraints are the minimal and maximal
1803   /// subscript value for the first dimension.
1804   ///
1805   /// @param Array The array to derive the extent for.
1806   ///
1807   /// @returns An isl_set describing the extent of the array.
1808   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
1809     unsigned NumDims = Array->getNumberOfDimensions();
1810     isl_union_map *Accesses = S->getAccesses();
1811     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
1812     Accesses = isl_union_map_detect_equalities(Accesses);
1813     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
1814     AccessUSet = isl_union_set_coalesce(AccessUSet);
1815     AccessUSet = isl_union_set_detect_equalities(AccessUSet);
1816     AccessUSet = isl_union_set_coalesce(AccessUSet);
1817 
1818     if (isl_union_set_is_empty(AccessUSet)) {
1819       isl_union_set_free(AccessUSet);
1820       return isl_set_empty(Array->getSpace());
1821     }
1822 
1823     if (Array->getNumberOfDimensions() == 0) {
1824       isl_union_set_free(AccessUSet);
1825       return isl_set_universe(Array->getSpace());
1826     }
1827 
1828     isl_set *AccessSet =
1829         isl_union_set_extract_set(AccessUSet, Array->getSpace());
1830 
1831     isl_union_set_free(AccessUSet);
1832     isl_local_space *LS = isl_local_space_from_space(Array->getSpace());
1833 
1834     isl_pw_aff *Val =
1835         isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0));
1836 
1837     isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0);
1838     isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0);
1839     OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in,
1840                                    isl_pw_aff_dim(Val, isl_dim_in));
1841     OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in,
1842                                    isl_pw_aff_dim(Val, isl_dim_in));
1843     OuterMin =
1844         isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, Array->getBasePtrId());
1845     OuterMax =
1846         isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, Array->getBasePtrId());
1847 
1848     isl_set *Extent = isl_set_universe(Array->getSpace());
1849 
1850     Extent = isl_set_intersect(
1851         Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val)));
1852     Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val));
1853 
1854     for (unsigned i = 1; i < NumDims; ++i)
1855       Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0);
1856 
1857     for (unsigned i = 1; i < NumDims; ++i) {
1858       isl_pw_aff *PwAff =
1859           const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i));
1860       isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain(
1861           isl_local_space_from_space(Array->getSpace()), isl_dim_set, i));
1862       PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in,
1863                                   isl_pw_aff_dim(Val, isl_dim_in));
1864       PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in,
1865                                       isl_pw_aff_get_tuple_id(Val, isl_dim_in));
1866       auto *Set = isl_pw_aff_gt_set(PwAff, Val);
1867       Extent = isl_set_intersect(Set, Extent);
1868     }
1869 
1870     return Extent;
1871   }
1872 
1873   /// Derive the bounds of an array.
1874   ///
1875   /// For the first dimension we derive the bound of the array from the extent
1876   /// of this dimension. For inner dimensions we obtain their size directly from
1877   /// ScopArrayInfo.
1878   ///
1879   /// @param PPCGArray The array to compute bounds for.
1880   /// @param Array The polly array from which to take the information.
1881   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
1882     if (PPCGArray.n_index > 0) {
1883       if (isl_set_is_empty(PPCGArray.extent)) {
1884         isl_set *Dom = isl_set_copy(PPCGArray.extent);
1885         isl_local_space *LS = isl_local_space_from_space(
1886             isl_space_params(isl_set_get_space(Dom)));
1887         isl_set_free(Dom);
1888         isl_aff *Zero = isl_aff_zero_on_domain(LS);
1889         PPCGArray.bound[0] = isl_pw_aff_from_aff(Zero);
1890       } else {
1891         isl_set *Dom = isl_set_copy(PPCGArray.extent);
1892         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
1893         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
1894         isl_set_free(Dom);
1895         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
1896         isl_local_space *LS =
1897             isl_local_space_from_space(isl_set_get_space(Dom));
1898         isl_aff *One = isl_aff_zero_on_domain(LS);
1899         One = isl_aff_add_constant_si(One, 1);
1900         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
1901         Bound = isl_pw_aff_gist(Bound, S->getContext());
1902         PPCGArray.bound[0] = Bound;
1903       }
1904     }
1905 
1906     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
1907       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
1908       auto LS = isl_pw_aff_get_domain_space(Bound);
1909       auto Aff = isl_multi_aff_zero(LS);
1910       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
1911       PPCGArray.bound[i] = Bound;
1912     }
1913   }
1914 
1915   /// Create the arrays for @p PPCGProg.
1916   ///
1917   /// @param PPCGProg The program to compute the arrays for.
1918   void createArrays(gpu_prog *PPCGProg) {
1919     int i = 0;
1920     for (auto &Array : S->arrays()) {
1921       std::string TypeName;
1922       raw_string_ostream OS(TypeName);
1923 
1924       OS << *Array->getElementType();
1925       TypeName = OS.str();
1926 
1927       gpu_array_info &PPCGArray = PPCGProg->array[i];
1928 
1929       PPCGArray.space = Array->getSpace();
1930       PPCGArray.type = strdup(TypeName.c_str());
1931       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
1932       PPCGArray.name = strdup(Array->getName().c_str());
1933       PPCGArray.extent = nullptr;
1934       PPCGArray.n_index = Array->getNumberOfDimensions();
1935       PPCGArray.bound =
1936           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
1937       PPCGArray.extent = getExtent(Array);
1938       PPCGArray.n_ref = 0;
1939       PPCGArray.refs = nullptr;
1940       PPCGArray.accessed = true;
1941       PPCGArray.read_only_scalar = false;
1942       PPCGArray.has_compound_element = false;
1943       PPCGArray.local = false;
1944       PPCGArray.declare_local = false;
1945       PPCGArray.global = false;
1946       PPCGArray.linearize = false;
1947       PPCGArray.dep_order = nullptr;
1948       PPCGArray.user = Array;
1949 
1950       setArrayBounds(PPCGArray, Array);
1951       i++;
1952 
1953       collect_references(PPCGProg, &PPCGArray);
1954     }
1955   }
1956 
1957   /// Create an identity map between the arrays in the scop.
1958   ///
1959   /// @returns An identity map between the arrays in the scop.
1960   isl_union_map *getArrayIdentity() {
1961     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
1962 
1963     for (auto &Array : S->arrays()) {
1964       isl_space *Space = Array->getSpace();
1965       Space = isl_space_map_from_set(Space);
1966       isl_map *Identity = isl_map_identity(Space);
1967       Maps = isl_union_map_add_map(Maps, Identity);
1968     }
1969 
1970     return Maps;
1971   }
1972 
1973   /// Create a default-initialized PPCG GPU program.
1974   ///
1975   /// @returns A new gpu grogram description.
1976   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
1977 
1978     if (!PPCGScop)
1979       return nullptr;
1980 
1981     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
1982 
1983     PPCGProg->ctx = S->getIslCtx();
1984     PPCGProg->scop = PPCGScop;
1985     PPCGProg->context = isl_set_copy(PPCGScop->context);
1986     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
1987     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
1988     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
1989     PPCGProg->tagged_must_kill =
1990         isl_union_map_copy(PPCGScop->tagged_must_kills);
1991     PPCGProg->to_inner = getArrayIdentity();
1992     PPCGProg->to_outer = getArrayIdentity();
1993     PPCGProg->any_to_outer = nullptr;
1994     PPCGProg->array_order = nullptr;
1995     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
1996     PPCGProg->stmts = getStatements();
1997     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
1998     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
1999                                        PPCGProg->n_array);
2000 
2001     createArrays(PPCGProg);
2002 
2003     PPCGProg->may_persist = compute_may_persist(PPCGProg);
2004 
2005     return PPCGProg;
2006   }
2007 
2008   struct PrintGPUUserData {
2009     struct cuda_info *CudaInfo;
2010     struct gpu_prog *PPCGProg;
2011     std::vector<ppcg_kernel *> Kernels;
2012   };
2013 
2014   /// Print a user statement node in the host code.
2015   ///
2016   /// We use ppcg's printing facilities to print the actual statement and
2017   /// additionally build up a list of all kernels that are encountered in the
2018   /// host ast.
2019   ///
2020   /// @param P The printer to print to
2021   /// @param Options The printing options to use
2022   /// @param Node The node to print
2023   /// @param User A user pointer to carry additional data. This pointer is
2024   ///             expected to be of type PrintGPUUserData.
2025   ///
2026   /// @returns A printer to which the output has been printed.
2027   static __isl_give isl_printer *
2028   printHostUser(__isl_take isl_printer *P,
2029                 __isl_take isl_ast_print_options *Options,
2030                 __isl_take isl_ast_node *Node, void *User) {
2031     auto Data = (struct PrintGPUUserData *)User;
2032     auto Id = isl_ast_node_get_annotation(Node);
2033 
2034     if (Id) {
2035       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
2036 
2037       // If this is a user statement, format it ourselves as ppcg would
2038       // otherwise try to call pet functionality that is not available in
2039       // Polly.
2040       if (IsUser) {
2041         P = isl_printer_start_line(P);
2042         P = isl_printer_print_ast_node(P, Node);
2043         P = isl_printer_end_line(P);
2044         isl_id_free(Id);
2045         isl_ast_print_options_free(Options);
2046         return P;
2047       }
2048 
2049       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
2050       isl_id_free(Id);
2051       Data->Kernels.push_back(Kernel);
2052     }
2053 
2054     return print_host_user(P, Options, Node, User);
2055   }
2056 
2057   /// Print C code corresponding to the control flow in @p Kernel.
2058   ///
2059   /// @param Kernel The kernel to print
2060   void printKernel(ppcg_kernel *Kernel) {
2061     auto *P = isl_printer_to_str(S->getIslCtx());
2062     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
2063     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
2064     P = isl_ast_node_print(Kernel->tree, P, Options);
2065     char *String = isl_printer_get_str(P);
2066     printf("%s\n", String);
2067     free(String);
2068     isl_printer_free(P);
2069   }
2070 
2071   /// Print C code corresponding to the GPU code described by @p Tree.
2072   ///
2073   /// @param Tree An AST describing GPU code
2074   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
2075   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
2076     auto *P = isl_printer_to_str(S->getIslCtx());
2077     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
2078 
2079     PrintGPUUserData Data;
2080     Data.PPCGProg = PPCGProg;
2081 
2082     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
2083     Options =
2084         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
2085     P = isl_ast_node_print(Tree, P, Options);
2086     char *String = isl_printer_get_str(P);
2087     printf("# host\n");
2088     printf("%s\n", String);
2089     free(String);
2090     isl_printer_free(P);
2091 
2092     for (auto Kernel : Data.Kernels) {
2093       printf("# kernel%d\n", Kernel->id);
2094       printKernel(Kernel);
2095     }
2096   }
2097 
2098   // Generate a GPU program using PPCG.
2099   //
2100   // GPU mapping consists of multiple steps:
2101   //
2102   //  1) Compute new schedule for the program.
2103   //  2) Map schedule to GPU (TODO)
2104   //  3) Generate code for new schedule (TODO)
2105   //
2106   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
2107   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
2108   // strategy directly from this pass.
2109   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
2110 
2111     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
2112 
2113     PPCGGen->ctx = S->getIslCtx();
2114     PPCGGen->options = PPCGScop->options;
2115     PPCGGen->print = nullptr;
2116     PPCGGen->print_user = nullptr;
2117     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
2118     PPCGGen->prog = PPCGProg;
2119     PPCGGen->tree = nullptr;
2120     PPCGGen->types.n = 0;
2121     PPCGGen->types.name = nullptr;
2122     PPCGGen->sizes = nullptr;
2123     PPCGGen->used_sizes = nullptr;
2124     PPCGGen->kernel_id = 0;
2125 
2126     // Set scheduling strategy to same strategy PPCG is using.
2127     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
2128     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
2129     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
2130 
2131     isl_schedule *Schedule = get_schedule(PPCGGen);
2132 
2133     int has_permutable = has_any_permutable_node(Schedule);
2134 
2135     if (!has_permutable || has_permutable < 0) {
2136       Schedule = isl_schedule_free(Schedule);
2137     } else {
2138       Schedule = map_to_device(PPCGGen, Schedule);
2139       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
2140     }
2141 
2142     if (DumpSchedule) {
2143       isl_printer *P = isl_printer_to_str(S->getIslCtx());
2144       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
2145       P = isl_printer_print_str(P, "Schedule\n");
2146       P = isl_printer_print_str(P, "========\n");
2147       if (Schedule)
2148         P = isl_printer_print_schedule(P, Schedule);
2149       else
2150         P = isl_printer_print_str(P, "No schedule found\n");
2151 
2152       printf("%s\n", isl_printer_get_str(P));
2153       isl_printer_free(P);
2154     }
2155 
2156     if (DumpCode) {
2157       printf("Code\n");
2158       printf("====\n");
2159       if (PPCGGen->tree)
2160         printGPUTree(PPCGGen->tree, PPCGProg);
2161       else
2162         printf("No code generated\n");
2163     }
2164 
2165     isl_schedule_free(Schedule);
2166 
2167     return PPCGGen;
2168   }
2169 
2170   /// Free gpu_gen structure.
2171   ///
2172   /// @param PPCGGen The ppcg_gen object to free.
2173   void freePPCGGen(gpu_gen *PPCGGen) {
2174     isl_ast_node_free(PPCGGen->tree);
2175     isl_union_map_free(PPCGGen->sizes);
2176     isl_union_map_free(PPCGGen->used_sizes);
2177     free(PPCGGen);
2178   }
2179 
2180   /// Free the options in the ppcg scop structure.
2181   ///
2182   /// ppcg is not freeing these options for us. To avoid leaks we do this
2183   /// ourselves.
2184   ///
2185   /// @param PPCGScop The scop referencing the options to free.
2186   void freeOptions(ppcg_scop *PPCGScop) {
2187     free(PPCGScop->options->debug);
2188     PPCGScop->options->debug = nullptr;
2189     free(PPCGScop->options);
2190     PPCGScop->options = nullptr;
2191   }
2192 
2193   /// Generate code for a given GPU AST described by @p Root.
2194   ///
2195   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
2196   /// @param Prog The GPU Program to generate code for.
2197   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
2198     ScopAnnotator Annotator;
2199     Annotator.buildAliasScopes(*S);
2200 
2201     Region *R = &S->getRegion();
2202 
2203     simplifyRegion(R, DT, LI, RI);
2204 
2205     BasicBlock *EnteringBB = R->getEnteringBlock();
2206 
2207     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
2208 
2209     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S,
2210                                Prog);
2211 
2212     // Only build the run-time condition and parameters _after_ having
2213     // introduced the conditional branch. This is important as the conditional
2214     // branch will guard the original scop from new induction variables that
2215     // the SCEVExpander may introduce while code generating the parameters and
2216     // which may introduce scalar dependences that prevent us from correctly
2217     // code generating this scop.
2218     BasicBlock *StartBlock =
2219         executeScopConditionally(*S, this, Builder.getTrue());
2220 
2221     // TODO: Handle LICM
2222     auto SplitBlock = StartBlock->getSinglePredecessor();
2223     Builder.SetInsertPoint(SplitBlock->getTerminator());
2224     NodeBuilder.addParameters(S->getContext());
2225 
2226     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx());
2227     isl_ast_expr *Condition = IslAst::buildRunCondition(S, Build);
2228     isl_ast_build_free(Build);
2229 
2230     Value *RTC = NodeBuilder.createRTC(Condition);
2231     Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
2232 
2233     Builder.SetInsertPoint(&*StartBlock->begin());
2234 
2235     NodeBuilder.initializeAfterRTH();
2236     NodeBuilder.create(Root);
2237     NodeBuilder.finalize();
2238 
2239     if (!NodeBuilder.BuildSuccessful)
2240       SplitBlock->getTerminator()->setOperand(0, Builder.getFalse());
2241   }
2242 
2243   bool runOnScop(Scop &CurrentScop) override {
2244     S = &CurrentScop;
2245     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2246     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2247     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2248     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
2249     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
2250 
2251     // We currently do not support scops with invariant loads.
2252     if (S->hasInvariantAccesses())
2253       return false;
2254 
2255     auto PPCGScop = createPPCGScop();
2256     auto PPCGProg = createPPCGProg(PPCGScop);
2257     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
2258 
2259     if (PPCGGen->tree)
2260       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
2261 
2262     freeOptions(PPCGScop);
2263     freePPCGGen(PPCGGen);
2264     gpu_prog_free(PPCGProg);
2265     ppcg_scop_free(PPCGScop);
2266 
2267     return true;
2268   }
2269 
2270   void printScop(raw_ostream &, Scop &) const override {}
2271 
2272   void getAnalysisUsage(AnalysisUsage &AU) const override {
2273     AU.addRequired<DominatorTreeWrapperPass>();
2274     AU.addRequired<RegionInfoPass>();
2275     AU.addRequired<ScalarEvolutionWrapperPass>();
2276     AU.addRequired<ScopDetection>();
2277     AU.addRequired<ScopInfoRegionPass>();
2278     AU.addRequired<LoopInfoWrapperPass>();
2279 
2280     AU.addPreserved<AAResultsWrapperPass>();
2281     AU.addPreserved<BasicAAWrapperPass>();
2282     AU.addPreserved<LoopInfoWrapperPass>();
2283     AU.addPreserved<DominatorTreeWrapperPass>();
2284     AU.addPreserved<GlobalsAAWrapperPass>();
2285     AU.addPreserved<PostDominatorTreeWrapperPass>();
2286     AU.addPreserved<ScopDetection>();
2287     AU.addPreserved<ScalarEvolutionWrapperPass>();
2288     AU.addPreserved<SCEVAAWrapperPass>();
2289 
2290     // FIXME: We do not yet add regions for the newly generated code to the
2291     //        region tree.
2292     AU.addPreserved<RegionInfoPass>();
2293     AU.addPreserved<ScopInfoRegionPass>();
2294   }
2295 };
2296 }
2297 
2298 char PPCGCodeGeneration::ID = 1;
2299 
2300 Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
2301 
2302 INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
2303                       "Polly - Apply PPCG translation to SCOP", false, false)
2304 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
2305 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
2306 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
2307 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
2308 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
2309 INITIALIZE_PASS_DEPENDENCY(ScopDetection);
2310 INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
2311                     "Polly - Apply PPCG translation to SCOP", false, false)
2312