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