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/IslNodeBuilder.h"
16 #include "polly/CodeGen/Utils.h"
17 #include "polly/DependenceInfo.h"
18 #include "polly/LinkAllPasses.h"
19 #include "polly/Options.h"
20 #include "polly/ScopInfo.h"
21 #include "polly/Support/SCEVValidator.h"
22 #include "llvm/ADT/PostOrderIterator.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/BasicAliasAnalysis.h"
25 #include "llvm/Analysis/GlobalsModRef.h"
26 #include "llvm/Analysis/PostDominators.h"
27 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/Analysis/TargetTransformInfo.h"
30 #include "llvm/IR/LegacyPassManager.h"
31 #include "llvm/IR/Verifier.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/Support/TargetSelect.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
36 
37 #include "isl/union_map.h"
38 
39 extern "C" {
40 #include "ppcg/cuda.h"
41 #include "ppcg/gpu.h"
42 #include "ppcg/gpu_print.h"
43 #include "ppcg/ppcg.h"
44 #include "ppcg/schedule.h"
45 }
46 
47 #include "llvm/Support/Debug.h"
48 
49 using namespace polly;
50 using namespace llvm;
51 
52 #define DEBUG_TYPE "polly-codegen-ppcg"
53 
54 static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
55                                   cl::desc("Dump the computed GPU Schedule"),
56                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
57                                   cl::cat(PollyCategory));
58 
59 static cl::opt<bool>
60     DumpCode("polly-acc-dump-code",
61              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
62              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
63 
64 static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
65                                   cl::desc("Dump the kernel LLVM-IR"),
66                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
67                                   cl::cat(PollyCategory));
68 
69 static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
70                                    cl::desc("Dump the kernel assembly code"),
71                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
72                                    cl::cat(PollyCategory));
73 
74 static cl::opt<bool> FastMath("polly-acc-fastmath",
75                               cl::desc("Allow unsafe math optimizations"),
76                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
77                               cl::cat(PollyCategory));
78 
79 static cl::opt<std::string>
80     CudaVersion("polly-acc-cuda-version",
81                 cl::desc("The CUDA version to compile for"), cl::Hidden,
82                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
83 
84 /// Create the ast expressions for a ScopStmt.
85 ///
86 /// This function is a callback for to generate the ast expressions for each
87 /// of the scheduled ScopStmts.
88 static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
89     void *StmtT, isl_ast_build *Build,
90     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
91                                        isl_id *Id, void *User),
92     void *UserIndex,
93     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
94     void *UserExpr) {
95 
96   ScopStmt *Stmt = (ScopStmt *)StmtT;
97 
98   isl_ctx *Ctx;
99 
100   if (!Stmt || !Build)
101     return NULL;
102 
103   Ctx = isl_ast_build_get_ctx(Build);
104   isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0);
105 
106   for (MemoryAccess *Acc : *Stmt) {
107     isl_map *AddrFunc = Acc->getAddressFunction();
108     AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain());
109     isl_id *RefId = Acc->getId();
110     isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc);
111     isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA);
112     MPA = isl_multi_pw_aff_coalesce(MPA);
113     MPA = FunctionIndex(MPA, RefId, UserIndex);
114     isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA);
115     Access = FunctionExpr(Access, RefId, UserExpr);
116     RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access);
117   }
118 
119   return RefToExpr;
120 }
121 
122 /// Generate code for a GPU specific isl AST.
123 ///
124 /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
125 /// generates code for general-prupose AST nodes, with special functionality
126 /// for generating GPU specific user nodes.
127 ///
128 /// @see GPUNodeBuilder::createUser
129 class GPUNodeBuilder : public IslNodeBuilder {
130 public:
131   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P,
132                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
133                  DominatorTree &DT, Scop &S, gpu_prog *Prog)
134       : IslNodeBuilder(Builder, Annotator, P, DL, LI, SE, DT, S), Prog(Prog) {
135     getExprBuilder().setIDToSAI(&IDToSAI);
136   }
137 
138   /// Create after-run-time-check initialization code.
139   void initializeAfterRTH();
140 
141   /// Finalize the generated scop.
142   virtual void finalize();
143 
144 private:
145   /// A vector of array base pointers for which a new ScopArrayInfo was created.
146   ///
147   /// This vector is used to delete the ScopArrayInfo when it is not needed any
148   /// more.
149   std::vector<Value *> LocalArrays;
150 
151   /// The current GPU context.
152   Value *GPUContext;
153 
154   /// A module containing GPU code.
155   ///
156   /// This pointer is only set in case we are currently generating GPU code.
157   std::unique_ptr<Module> GPUModule;
158 
159   /// The GPU program we generate code for.
160   gpu_prog *Prog;
161 
162   /// Class to free isl_ids.
163   class IslIdDeleter {
164   public:
165     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
166   };
167 
168   /// A set containing all isl_ids allocated in a GPU kernel.
169   ///
170   /// By releasing this set all isl_ids will be freed.
171   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
172 
173   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
174 
175   /// Create code for user-defined AST nodes.
176   ///
177   /// These AST nodes can be of type:
178   ///
179   ///   - ScopStmt:      A computational statement (TODO)
180   ///   - Kernel:        A GPU kernel call (TODO)
181   ///   - Data-Transfer: A GPU <-> CPU data-transfer (TODO)
182   ///   - In-kernel synchronization
183   ///   - In-kernel memory copy statement
184   ///
185   /// @param UserStmt The ast node to generate code for.
186   virtual void createUser(__isl_take isl_ast_node *UserStmt);
187 
188   /// Find llvm::Values referenced in GPU kernel.
189   ///
190   /// @param Kernel The kernel to scan for llvm::Values
191   ///
192   /// @returns A set of values referenced by the kernel.
193   SetVector<Value *> getReferencesInKernel(ppcg_kernel *Kernel);
194 
195   /// Create GPU kernel.
196   ///
197   /// Code generate the kernel described by @p KernelStmt.
198   ///
199   /// @param KernelStmt The ast node to generate kernel code for.
200   void createKernel(__isl_take isl_ast_node *KernelStmt);
201 
202   /// Create kernel function.
203   ///
204   /// Create a kernel function located in a newly created module that can serve
205   /// as target for device code generation. Set the Builder to point to the
206   /// start block of this newly created function.
207   ///
208   /// @param Kernel The kernel to generate code for.
209   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
210   void createKernelFunction(ppcg_kernel *Kernel,
211                             SetVector<Value *> &SubtreeValues);
212 
213   /// Create the declaration of a kernel function.
214   ///
215   /// The kernel function takes as arguments:
216   ///
217   ///   - One i8 pointer for each external array reference used in the kernel.
218   ///   - Host iterators
219   ///   - Parameters
220   ///   - Other LLVM Value references (TODO)
221   ///
222   /// @param Kernel The kernel to generate the function declaration for.
223   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
224   ///
225   /// @returns The newly declared function.
226   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
227                                      SetVector<Value *> &SubtreeValues);
228 
229   /// Insert intrinsic functions to obtain thread and block ids.
230   ///
231   /// @param The kernel to generate the intrinsic functions for.
232   void insertKernelIntrinsics(ppcg_kernel *Kernel);
233 
234   /// Create code for a ScopStmt called in @p Expr.
235   ///
236   /// @param Expr The expression containing the call.
237   /// @param KernelStmt The kernel statement referenced in the call.
238   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
239 
240   /// Create an in-kernel synchronization call.
241   void createKernelSync();
242 
243   /// Create a PTX assembly string for the current GPU kernel.
244   ///
245   /// @returns A string containing the corresponding PTX assembly code.
246   std::string createKernelASM();
247 
248   /// Remove references from the dominator tree to the kernel function @p F.
249   ///
250   /// @param F The function to remove references to.
251   void clearDominators(Function *F);
252 
253   /// Remove references from scalar evolution to the kernel function @p F.
254   ///
255   /// @param F The function to remove references to.
256   void clearScalarEvolution(Function *F);
257 
258   /// Remove references from loop info to the kernel function @p F.
259   ///
260   /// @param F The function to remove references to.
261   void clearLoops(Function *F);
262 
263   /// Finalize the generation of the kernel function.
264   ///
265   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
266   /// dump its IR to stderr.
267   void finalizeKernelFunction();
268 
269   void allocateDeviceArrays();
270 
271   /// Create a call to initialize the GPU context.
272   ///
273   /// @returns A pointer to the newly initialized context.
274   Value *createCallInitContext();
275 
276   /// Create a call to free the GPU context.
277   ///
278   /// @param Context A pointer to an initialized GPU context.
279   void createCallFreeContext(Value *Context);
280 
281   Value *createCallAllocateMemoryForDevice(Value *Size);
282 };
283 
284 void GPUNodeBuilder::initializeAfterRTH() {
285   GPUContext = createCallInitContext();
286   allocateDeviceArrays();
287 }
288 
289 void GPUNodeBuilder::finalize() {
290   createCallFreeContext(GPUContext);
291   IslNodeBuilder::finalize();
292 }
293 
294 void GPUNodeBuilder::allocateDeviceArrays() {
295   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
296 
297   for (int i = 0; i < Prog->n_array; ++i) {
298     gpu_array_info *Array = &Prog->array[i];
299     std::string DevPtrName("p_devptr_");
300     DevPtrName.append(Array->name);
301 
302     Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
303 
304     if (!gpu_array_is_scalar(Array)) {
305       auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]);
306       isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero);
307 
308       for (unsigned int i = 1; i < Array->n_index; i++) {
309         isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]);
310         isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
311         Res = isl_ast_expr_mul(Res, Expr);
312       }
313 
314       Value *NumElements = ExprBuilder.create(Res);
315       ArraySize = Builder.CreateMul(ArraySize, NumElements);
316     }
317 
318     Value *DevPtr = createCallAllocateMemoryForDevice(ArraySize);
319     DevPtr->setName(DevPtrName);
320   }
321 
322   isl_ast_build_free(Build);
323 }
324 
325 Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
326   const char *Name = "polly_allocateMemoryForDevice";
327   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
328   Function *F = M->getFunction(Name);
329 
330   // If F is not available, declare it.
331   if (!F) {
332     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
333     std::vector<Type *> Args;
334     Args.push_back(Builder.getInt64Ty());
335     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
336     F = Function::Create(Ty, Linkage, Name, M);
337   }
338 
339   return Builder.CreateCall(F, {Size});
340 }
341 
342 Value *GPUNodeBuilder::createCallInitContext() {
343   const char *Name = "polly_initContext";
344   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
345   Function *F = M->getFunction(Name);
346 
347   // If F is not available, declare it.
348   if (!F) {
349     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
350     std::vector<Type *> Args;
351     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
352     F = Function::Create(Ty, Linkage, Name, M);
353   }
354 
355   return Builder.CreateCall(F, {});
356 }
357 
358 void GPUNodeBuilder::createCallFreeContext(Value *Context) {
359   const char *Name = "polly_freeContext";
360   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
361   Function *F = M->getFunction(Name);
362 
363   // If F is not available, declare it.
364   if (!F) {
365     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
366     std::vector<Type *> Args;
367     Args.push_back(Builder.getInt8PtrTy());
368     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
369     F = Function::Create(Ty, Linkage, Name, M);
370   }
371 
372   Builder.CreateCall(F, {Context});
373 }
374 
375 /// Check if one string is a prefix of another.
376 ///
377 /// @param String The string in which to look for the prefix.
378 /// @param Prefix The prefix to look for.
379 static bool isPrefix(std::string String, std::string Prefix) {
380   return String.find(Prefix) == 0;
381 }
382 
383 void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
384   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
385   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
386   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
387   isl_id_free(Id);
388   isl_ast_expr_free(StmtExpr);
389 
390   const char *Str = isl_id_get_name(Id);
391   if (!strcmp(Str, "kernel")) {
392     createKernel(UserStmt);
393     isl_ast_expr_free(Expr);
394     return;
395   }
396 
397   if (isPrefix(Str, "to_device") || isPrefix(Str, "from_device")) {
398     // TODO: Insert memory copies
399     isl_ast_expr_free(Expr);
400     isl_ast_node_free(UserStmt);
401     return;
402   }
403 
404   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
405   struct ppcg_kernel_stmt *KernelStmt =
406       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
407   isl_id_free(Anno);
408 
409   switch (KernelStmt->type) {
410   case ppcg_kernel_domain:
411     createScopStmt(Expr, KernelStmt);
412     isl_ast_node_free(UserStmt);
413     return;
414   case ppcg_kernel_copy:
415     // TODO: Create kernel copy stmt
416     isl_ast_expr_free(Expr);
417     isl_ast_node_free(UserStmt);
418     return;
419   case ppcg_kernel_sync:
420     createKernelSync();
421     isl_ast_expr_free(Expr);
422     isl_ast_node_free(UserStmt);
423     return;
424   }
425 
426   isl_ast_expr_free(Expr);
427   isl_ast_node_free(UserStmt);
428   return;
429 }
430 
431 void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
432                                     ppcg_kernel_stmt *KernelStmt) {
433   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
434   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
435 
436   LoopToScevMapT LTS;
437   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
438 
439   createSubstitutions(Expr, Stmt, LTS);
440 
441   if (Stmt->isBlockStmt())
442     BlockGen.copyStmt(*Stmt, LTS, Indexes);
443   else
444     assert(0 && "Region statement not supported\n");
445 }
446 
447 void GPUNodeBuilder::createKernelSync() {
448   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
449   auto *Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
450   Builder.CreateCall(Sync, {});
451 }
452 
453 /// Collect llvm::Values referenced from @p Node
454 ///
455 /// This function only applies to isl_ast_nodes that are user_nodes referring
456 /// to a ScopStmt. All other node types are ignore.
457 ///
458 /// @param Node The node to collect references for.
459 /// @param User A user pointer used as storage for the data that is collected.
460 ///
461 /// @returns isl_bool_true if data could be collected successfully.
462 isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
463   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
464     return isl_bool_true;
465 
466   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
467   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
468   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
469   const char *Str = isl_id_get_name(Id);
470   isl_id_free(Id);
471   isl_ast_expr_free(StmtExpr);
472   isl_ast_expr_free(Expr);
473 
474   if (!isPrefix(Str, "Stmt"))
475     return isl_bool_true;
476 
477   Id = isl_ast_node_get_annotation(Node);
478   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
479   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
480   isl_id_free(Id);
481 
482   addReferencesFromStmt(Stmt, User);
483 
484   return isl_bool_true;
485 }
486 
487 SetVector<Value *> GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
488   SetVector<Value *> SubtreeValues;
489   SetVector<const SCEV *> SCEVs;
490   SetVector<const Loop *> Loops;
491   SubtreeReferences References = {
492       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
493 
494   for (const auto &I : IDToValue)
495     SubtreeValues.insert(I.second);
496 
497   isl_ast_node_foreach_descendant_top_down(
498       Kernel->tree, collectReferencesInGPUStmt, &References);
499 
500   for (const SCEV *Expr : SCEVs)
501     findValues(Expr, SE, SubtreeValues);
502 
503   for (auto &SAI : S.arrays())
504     SubtreeValues.remove(SAI.second->getBasePtr());
505 
506   isl_space *Space = S.getParamSpace();
507   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
508     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
509     assert(IDToValue.count(Id));
510     Value *Val = IDToValue[Id];
511     SubtreeValues.remove(Val);
512     isl_id_free(Id);
513   }
514   isl_space_free(Space);
515 
516   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
517     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
518     assert(IDToValue.count(Id));
519     Value *Val = IDToValue[Id];
520     SubtreeValues.remove(Val);
521     isl_id_free(Id);
522   }
523 
524   return SubtreeValues;
525 }
526 
527 void GPUNodeBuilder::clearDominators(Function *F) {
528   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
529   std::vector<BasicBlock *> Nodes;
530   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
531     Nodes.push_back(I->getBlock());
532 
533   for (BasicBlock *BB : Nodes)
534     DT.eraseNode(BB);
535 }
536 
537 void GPUNodeBuilder::clearScalarEvolution(Function *F) {
538   for (BasicBlock &BB : *F) {
539     Loop *L = LI.getLoopFor(&BB);
540     if (L)
541       SE.forgetLoop(L);
542   }
543 }
544 
545 void GPUNodeBuilder::clearLoops(Function *F) {
546   for (BasicBlock &BB : *F) {
547     Loop *L = LI.getLoopFor(&BB);
548     if (L)
549       SE.forgetLoop(L);
550     LI.removeBlock(&BB);
551   }
552 }
553 
554 void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
555   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
556   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
557   isl_id_free(Id);
558   isl_ast_node_free(KernelStmt);
559 
560   SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel);
561 
562   assert(Kernel->tree && "Device AST of kernel node is empty");
563 
564   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
565   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
566   ValueMapT HostValueMap = ValueMap;
567 
568   SetVector<const Loop *> Loops;
569 
570   // Create for all loops we depend on values that contain the current loop
571   // iteration. These values are necessary to generate code for SCEVs that
572   // depend on such loops. As a result we need to pass them to the subfunction.
573   for (const Loop *L : Loops) {
574     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
575                                             SE.getUnknown(Builder.getInt64(1)),
576                                             L, SCEV::FlagAnyWrap);
577     Value *V = generateSCEV(OuterLIV);
578     OutsideLoopIterations[L] = SE.getUnknown(V);
579     SubtreeValues.insert(V);
580   }
581 
582   createKernelFunction(Kernel, SubtreeValues);
583 
584   create(isl_ast_node_copy(Kernel->tree));
585 
586   Function *F = Builder.GetInsertBlock()->getParent();
587   clearDominators(F);
588   clearScalarEvolution(F);
589   clearLoops(F);
590 
591   Builder.SetInsertPoint(&HostInsertPoint);
592   IDToValue = HostIDs;
593 
594   ValueMap = HostValueMap;
595   ScalarMap.clear();
596   PHIOpMap.clear();
597   EscapeMap.clear();
598   IDToSAI.clear();
599   Annotator.resetAlternativeAliasBases();
600   for (auto &BasePtr : LocalArrays)
601     S.invalidateScopArrayInfo(BasePtr, ScopArrayInfo::MK_Array);
602   LocalArrays.clear();
603 
604   finalizeKernelFunction();
605 }
606 
607 /// Compute the DataLayout string for the NVPTX backend.
608 ///
609 /// @param is64Bit Are we looking for a 64 bit architecture?
610 static std::string computeNVPTXDataLayout(bool is64Bit) {
611   std::string Ret = "e";
612 
613   if (!is64Bit)
614     Ret += "-p:32:32";
615 
616   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
617 
618   return Ret;
619 }
620 
621 Function *
622 GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
623                                          SetVector<Value *> &SubtreeValues) {
624   std::vector<Type *> Args;
625   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
626 
627   for (long i = 0; i < Prog->n_array; i++) {
628     if (!ppcg_kernel_requires_array_argument(Kernel, i))
629       continue;
630 
631     Args.push_back(Builder.getInt8PtrTy());
632   }
633 
634   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
635 
636   for (long i = 0; i < NumHostIters; i++)
637     Args.push_back(Builder.getInt64Ty());
638 
639   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
640 
641   for (long i = 0; i < NumVars; i++)
642     Args.push_back(Builder.getInt64Ty());
643 
644   for (auto *V : SubtreeValues)
645     Args.push_back(V->getType());
646 
647   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
648   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
649                               GPUModule.get());
650   FN->setCallingConv(CallingConv::PTX_Kernel);
651 
652   auto Arg = FN->arg_begin();
653   for (long i = 0; i < Kernel->n_array; i++) {
654     if (!ppcg_kernel_requires_array_argument(Kernel, i))
655       continue;
656 
657     Arg->setName(Kernel->array[i].array->name);
658 
659     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
660     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
661     Type *EleTy = SAI->getElementType();
662     Value *Val = &*Arg;
663     SmallVector<const SCEV *, 4> Sizes;
664     isl_ast_build *Build =
665         isl_ast_build_from_context(isl_set_copy(Prog->context));
666     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
667       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
668           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
669       auto V = ExprBuilder.create(DimSize);
670       Sizes.push_back(SE.getSCEV(V));
671     }
672     const ScopArrayInfo *SAIRep =
673         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, ScopArrayInfo::MK_Array);
674     LocalArrays.push_back(Val);
675 
676     isl_ast_build_free(Build);
677     isl_id_free(Id);
678     IDToSAI[Id] = SAIRep;
679     Arg++;
680   }
681 
682   for (long i = 0; i < NumHostIters; i++) {
683     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
684     Arg->setName(isl_id_get_name(Id));
685     IDToValue[Id] = &*Arg;
686     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
687     Arg++;
688   }
689 
690   for (long i = 0; i < NumVars; i++) {
691     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
692     Arg->setName(isl_id_get_name(Id));
693     IDToValue[Id] = &*Arg;
694     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
695     Arg++;
696   }
697 
698   for (auto *V : SubtreeValues) {
699     Arg->setName(V->getName());
700     ValueMap[V] = &*Arg;
701     Arg++;
702   }
703 
704   return FN;
705 }
706 
707 void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
708   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
709                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
710 
711   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
712                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
713                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
714 
715   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
716     std::string Name = isl_id_get_name(Id);
717     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
718     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
719     Value *Val = Builder.CreateCall(IntrinsicFn, {});
720     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
721     IDToValue[Id] = Val;
722     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
723   };
724 
725   for (int i = 0; i < Kernel->n_grid; ++i) {
726     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
727     addId(Id, IntrinsicsBID[i]);
728   }
729 
730   for (int i = 0; i < Kernel->n_block; ++i) {
731     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
732     addId(Id, IntrinsicsTID[i]);
733   }
734 }
735 
736 void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel,
737                                           SetVector<Value *> &SubtreeValues) {
738 
739   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
740   GPUModule.reset(new Module(Identifier, Builder.getContext()));
741   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
742   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
743 
744   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
745 
746   BasicBlock *PrevBlock = Builder.GetInsertBlock();
747   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
748 
749   DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
750   DT.addNewBlock(EntryBlock, PrevBlock);
751 
752   Builder.SetInsertPoint(EntryBlock);
753   Builder.CreateRetVoid();
754   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
755 
756   insertKernelIntrinsics(Kernel);
757 }
758 
759 std::string GPUNodeBuilder::createKernelASM() {
760   llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda"));
761   std::string ErrMsg;
762   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
763 
764   if (!GPUTarget) {
765     errs() << ErrMsg << "\n";
766     return "";
767   }
768 
769   TargetOptions Options;
770   Options.UnsafeFPMath = FastMath;
771   std::unique_ptr<TargetMachine> TargetM(
772       GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "",
773                                      Options, Optional<Reloc::Model>()));
774 
775   SmallString<0> ASMString;
776   raw_svector_ostream ASMStream(ASMString);
777   llvm::legacy::PassManager PM;
778 
779   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
780 
781   if (TargetM->addPassesToEmitFile(
782           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
783     errs() << "The target does not support generation of this file type!\n";
784     return "";
785   }
786 
787   PM.run(*GPUModule);
788 
789   return ASMStream.str();
790 }
791 
792 void GPUNodeBuilder::finalizeKernelFunction() {
793   // Verify module.
794   llvm::legacy::PassManager Passes;
795   Passes.add(createVerifierPass());
796   Passes.run(*GPUModule);
797 
798   if (DumpKernelIR)
799     outs() << *GPUModule << "\n";
800 
801   // Optimize module.
802   llvm::legacy::PassManager OptPasses;
803   PassManagerBuilder PassBuilder;
804   PassBuilder.OptLevel = 3;
805   PassBuilder.SizeLevel = 0;
806   PassBuilder.populateModulePassManager(OptPasses);
807   OptPasses.run(*GPUModule);
808 
809   std::string Assembly = createKernelASM();
810 
811   if (DumpKernelASM)
812     outs() << Assembly << "\n";
813 
814   GPUModule.release();
815   KernelIDs.clear();
816 }
817 
818 namespace {
819 class PPCGCodeGeneration : public ScopPass {
820 public:
821   static char ID;
822 
823   /// The scop that is currently processed.
824   Scop *S;
825 
826   LoopInfo *LI;
827   DominatorTree *DT;
828   ScalarEvolution *SE;
829   const DataLayout *DL;
830   RegionInfo *RI;
831 
832   PPCGCodeGeneration() : ScopPass(ID) {}
833 
834   /// Construct compilation options for PPCG.
835   ///
836   /// @returns The compilation options.
837   ppcg_options *createPPCGOptions() {
838     auto DebugOptions =
839         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
840     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
841 
842     DebugOptions->dump_schedule_constraints = false;
843     DebugOptions->dump_schedule = false;
844     DebugOptions->dump_final_schedule = false;
845     DebugOptions->dump_sizes = false;
846 
847     Options->debug = DebugOptions;
848 
849     Options->reschedule = true;
850     Options->scale_tile_loops = false;
851     Options->wrap = false;
852 
853     Options->non_negative_parameters = false;
854     Options->ctx = nullptr;
855     Options->sizes = nullptr;
856 
857     Options->tile_size = 32;
858 
859     Options->use_private_memory = false;
860     Options->use_shared_memory = false;
861     Options->max_shared_memory = 0;
862 
863     Options->target = PPCG_TARGET_CUDA;
864     Options->openmp = false;
865     Options->linearize_device_arrays = true;
866     Options->live_range_reordering = false;
867 
868     Options->opencl_compiler_options = nullptr;
869     Options->opencl_use_gpu = false;
870     Options->opencl_n_include_file = 0;
871     Options->opencl_include_files = nullptr;
872     Options->opencl_print_kernel_types = false;
873     Options->opencl_embed_kernel_code = false;
874 
875     Options->save_schedule_file = nullptr;
876     Options->load_schedule_file = nullptr;
877 
878     return Options;
879   }
880 
881   /// Get a tagged access relation containing all accesses of type @p AccessTy.
882   ///
883   /// Instead of a normal access of the form:
884   ///
885   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
886   ///
887   /// a tagged access has the form
888   ///
889   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
890   ///
891   /// where 'id' is an additional space that references the memory access that
892   /// triggered the access.
893   ///
894   /// @param AccessTy The type of the memory accesses to collect.
895   ///
896   /// @return The relation describing all tagged memory accesses.
897   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
898     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
899 
900     for (auto &Stmt : *S)
901       for (auto &Acc : Stmt)
902         if (Acc->getType() == AccessTy) {
903           isl_map *Relation = Acc->getAccessRelation();
904           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
905 
906           isl_space *Space = isl_map_get_space(Relation);
907           Space = isl_space_range(Space);
908           Space = isl_space_from_range(Space);
909           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
910           isl_map *Universe = isl_map_universe(Space);
911           Relation = isl_map_domain_product(Relation, Universe);
912           Accesses = isl_union_map_add_map(Accesses, Relation);
913         }
914 
915     return Accesses;
916   }
917 
918   /// Get the set of all read accesses, tagged with the access id.
919   ///
920   /// @see getTaggedAccesses
921   isl_union_map *getTaggedReads() {
922     return getTaggedAccesses(MemoryAccess::READ);
923   }
924 
925   /// Get the set of all may (and must) accesses, tagged with the access id.
926   ///
927   /// @see getTaggedAccesses
928   isl_union_map *getTaggedMayWrites() {
929     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
930                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
931   }
932 
933   /// Get the set of all must accesses, tagged with the access id.
934   ///
935   /// @see getTaggedAccesses
936   isl_union_map *getTaggedMustWrites() {
937     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
938   }
939 
940   /// Collect parameter and array names as isl_ids.
941   ///
942   /// To reason about the different parameters and arrays used, ppcg requires
943   /// a list of all isl_ids in use. As PPCG traditionally performs
944   /// source-to-source compilation each of these isl_ids is mapped to the
945   /// expression that represents it. As we do not have a corresponding
946   /// expression in Polly, we just map each id to a 'zero' expression to match
947   /// the data format that ppcg expects.
948   ///
949   /// @returns Retun a map from collected ids to 'zero' ast expressions.
950   __isl_give isl_id_to_ast_expr *getNames() {
951     auto *Names = isl_id_to_ast_expr_alloc(
952         S->getIslCtx(),
953         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
954     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
955     auto *Space = S->getParamSpace();
956 
957     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
958       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
959       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
960     }
961 
962     for (auto &Array : S->arrays()) {
963       auto Id = Array.second->getBasePtrId();
964       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
965     }
966 
967     isl_space_free(Space);
968     isl_ast_expr_free(Zero);
969 
970     return Names;
971   }
972 
973   /// Create a new PPCG scop from the current scop.
974   ///
975   /// The PPCG scop is initialized with data from the current polly::Scop. From
976   /// this initial data, the data-dependences in the PPCG scop are initialized.
977   /// We do not use Polly's dependence analysis for now, to ensure we match
978   /// the PPCG default behaviour more closely.
979   ///
980   /// @returns A new ppcg scop.
981   ppcg_scop *createPPCGScop() {
982     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
983 
984     PPCGScop->options = createPPCGOptions();
985 
986     PPCGScop->start = 0;
987     PPCGScop->end = 0;
988 
989     PPCGScop->context = S->getContext();
990     PPCGScop->domain = S->getDomains();
991     PPCGScop->call = nullptr;
992     PPCGScop->tagged_reads = getTaggedReads();
993     PPCGScop->reads = S->getReads();
994     PPCGScop->live_in = nullptr;
995     PPCGScop->tagged_may_writes = getTaggedMayWrites();
996     PPCGScop->may_writes = S->getWrites();
997     PPCGScop->tagged_must_writes = getTaggedMustWrites();
998     PPCGScop->must_writes = S->getMustWrites();
999     PPCGScop->live_out = nullptr;
1000     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
1001     PPCGScop->tagger = nullptr;
1002 
1003     PPCGScop->independence = nullptr;
1004     PPCGScop->dep_flow = nullptr;
1005     PPCGScop->tagged_dep_flow = nullptr;
1006     PPCGScop->dep_false = nullptr;
1007     PPCGScop->dep_forced = nullptr;
1008     PPCGScop->dep_order = nullptr;
1009     PPCGScop->tagged_dep_order = nullptr;
1010 
1011     PPCGScop->schedule = S->getScheduleTree();
1012     PPCGScop->names = getNames();
1013 
1014     PPCGScop->pet = nullptr;
1015 
1016     compute_tagger(PPCGScop);
1017     compute_dependences(PPCGScop);
1018 
1019     return PPCGScop;
1020   }
1021 
1022   /// Collect the array acesses in a statement.
1023   ///
1024   /// @param Stmt The statement for which to collect the accesses.
1025   ///
1026   /// @returns A list of array accesses.
1027   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
1028     gpu_stmt_access *Accesses = nullptr;
1029 
1030     for (MemoryAccess *Acc : Stmt) {
1031       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
1032       Access->read = Acc->isRead();
1033       Access->write = Acc->isWrite();
1034       Access->access = Acc->getAccessRelation();
1035       isl_space *Space = isl_map_get_space(Access->access);
1036       Space = isl_space_range(Space);
1037       Space = isl_space_from_range(Space);
1038       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1039       isl_map *Universe = isl_map_universe(Space);
1040       Access->tagged_access =
1041           isl_map_domain_product(Acc->getAccessRelation(), Universe);
1042       Access->exact_write = Acc->isWrite();
1043       Access->ref_id = Acc->getId();
1044       Access->next = Accesses;
1045       Accesses = Access;
1046     }
1047 
1048     return Accesses;
1049   }
1050 
1051   /// Collect the list of GPU statements.
1052   ///
1053   /// Each statement has an id, a pointer to the underlying data structure,
1054   /// as well as a list with all memory accesses.
1055   ///
1056   /// TODO: Initialize the list of memory accesses.
1057   ///
1058   /// @returns A linked-list of statements.
1059   gpu_stmt *getStatements() {
1060     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
1061                                        std::distance(S->begin(), S->end()));
1062 
1063     int i = 0;
1064     for (auto &Stmt : *S) {
1065       gpu_stmt *GPUStmt = &Stmts[i];
1066 
1067       GPUStmt->id = Stmt.getDomainId();
1068 
1069       // We use the pet stmt pointer to keep track of the Polly statements.
1070       GPUStmt->stmt = (pet_stmt *)&Stmt;
1071       GPUStmt->accesses = getStmtAccesses(Stmt);
1072       i++;
1073     }
1074 
1075     return Stmts;
1076   }
1077 
1078   /// Derive the extent of an array.
1079   ///
1080   /// The extent of an array is defined by the set of memory locations for
1081   /// which a memory access in the iteration domain exists.
1082   ///
1083   /// @param Array The array to derive the extent for.
1084   ///
1085   /// @returns An isl_set describing the extent of the array.
1086   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
1087     isl_union_map *Accesses = S->getAccesses();
1088     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
1089     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
1090     isl_set *AccessSet =
1091         isl_union_set_extract_set(AccessUSet, Array->getSpace());
1092     isl_union_set_free(AccessUSet);
1093 
1094     return AccessSet;
1095   }
1096 
1097   /// Derive the bounds of an array.
1098   ///
1099   /// For the first dimension we derive the bound of the array from the extent
1100   /// of this dimension. For inner dimensions we obtain their size directly from
1101   /// ScopArrayInfo.
1102   ///
1103   /// @param PPCGArray The array to compute bounds for.
1104   /// @param Array The polly array from which to take the information.
1105   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
1106     if (PPCGArray.n_index > 0) {
1107       isl_set *Dom = isl_set_copy(PPCGArray.extent);
1108       Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
1109       isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
1110       isl_set_free(Dom);
1111       Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
1112       isl_local_space *LS = isl_local_space_from_space(isl_set_get_space(Dom));
1113       isl_aff *One = isl_aff_zero_on_domain(LS);
1114       One = isl_aff_add_constant_si(One, 1);
1115       Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
1116       Bound = isl_pw_aff_gist(Bound, S->getContext());
1117       PPCGArray.bound[0] = Bound;
1118     }
1119 
1120     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
1121       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
1122       auto LS = isl_pw_aff_get_domain_space(Bound);
1123       auto Aff = isl_multi_aff_zero(LS);
1124       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
1125       PPCGArray.bound[i] = Bound;
1126     }
1127   }
1128 
1129   /// Create the arrays for @p PPCGProg.
1130   ///
1131   /// @param PPCGProg The program to compute the arrays for.
1132   void createArrays(gpu_prog *PPCGProg) {
1133     int i = 0;
1134     for (auto &Element : S->arrays()) {
1135       ScopArrayInfo *Array = Element.second.get();
1136 
1137       std::string TypeName;
1138       raw_string_ostream OS(TypeName);
1139 
1140       OS << *Array->getElementType();
1141       TypeName = OS.str();
1142 
1143       gpu_array_info &PPCGArray = PPCGProg->array[i];
1144 
1145       PPCGArray.space = Array->getSpace();
1146       PPCGArray.type = strdup(TypeName.c_str());
1147       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
1148       PPCGArray.name = strdup(Array->getName().c_str());
1149       PPCGArray.extent = nullptr;
1150       PPCGArray.n_index = Array->getNumberOfDimensions();
1151       PPCGArray.bound =
1152           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
1153       PPCGArray.extent = getExtent(Array);
1154       PPCGArray.n_ref = 0;
1155       PPCGArray.refs = nullptr;
1156       PPCGArray.accessed = true;
1157       PPCGArray.read_only_scalar = false;
1158       PPCGArray.has_compound_element = false;
1159       PPCGArray.local = false;
1160       PPCGArray.declare_local = false;
1161       PPCGArray.global = false;
1162       PPCGArray.linearize = false;
1163       PPCGArray.dep_order = nullptr;
1164 
1165       setArrayBounds(PPCGArray, Array);
1166       i++;
1167 
1168       collect_references(PPCGProg, &PPCGArray);
1169     }
1170   }
1171 
1172   /// Create an identity map between the arrays in the scop.
1173   ///
1174   /// @returns An identity map between the arrays in the scop.
1175   isl_union_map *getArrayIdentity() {
1176     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
1177 
1178     for (auto &Item : S->arrays()) {
1179       ScopArrayInfo *Array = Item.second.get();
1180       isl_space *Space = Array->getSpace();
1181       Space = isl_space_map_from_set(Space);
1182       isl_map *Identity = isl_map_identity(Space);
1183       Maps = isl_union_map_add_map(Maps, Identity);
1184     }
1185 
1186     return Maps;
1187   }
1188 
1189   /// Create a default-initialized PPCG GPU program.
1190   ///
1191   /// @returns A new gpu grogram description.
1192   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
1193 
1194     if (!PPCGScop)
1195       return nullptr;
1196 
1197     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
1198 
1199     PPCGProg->ctx = S->getIslCtx();
1200     PPCGProg->scop = PPCGScop;
1201     PPCGProg->context = isl_set_copy(PPCGScop->context);
1202     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
1203     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
1204     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
1205     PPCGProg->tagged_must_kill =
1206         isl_union_map_copy(PPCGScop->tagged_must_kills);
1207     PPCGProg->to_inner = getArrayIdentity();
1208     PPCGProg->to_outer = getArrayIdentity();
1209     PPCGProg->may_persist = compute_may_persist(PPCGProg);
1210     PPCGProg->any_to_outer = nullptr;
1211     PPCGProg->array_order = nullptr;
1212     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
1213     PPCGProg->stmts = getStatements();
1214     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
1215     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
1216                                        PPCGProg->n_array);
1217 
1218     createArrays(PPCGProg);
1219 
1220     return PPCGProg;
1221   }
1222 
1223   struct PrintGPUUserData {
1224     struct cuda_info *CudaInfo;
1225     struct gpu_prog *PPCGProg;
1226     std::vector<ppcg_kernel *> Kernels;
1227   };
1228 
1229   /// Print a user statement node in the host code.
1230   ///
1231   /// We use ppcg's printing facilities to print the actual statement and
1232   /// additionally build up a list of all kernels that are encountered in the
1233   /// host ast.
1234   ///
1235   /// @param P The printer to print to
1236   /// @param Options The printing options to use
1237   /// @param Node The node to print
1238   /// @param User A user pointer to carry additional data. This pointer is
1239   ///             expected to be of type PrintGPUUserData.
1240   ///
1241   /// @returns A printer to which the output has been printed.
1242   static __isl_give isl_printer *
1243   printHostUser(__isl_take isl_printer *P,
1244                 __isl_take isl_ast_print_options *Options,
1245                 __isl_take isl_ast_node *Node, void *User) {
1246     auto Data = (struct PrintGPUUserData *)User;
1247     auto Id = isl_ast_node_get_annotation(Node);
1248 
1249     if (Id) {
1250       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
1251 
1252       // If this is a user statement, format it ourselves as ppcg would
1253       // otherwise try to call pet functionality that is not available in
1254       // Polly.
1255       if (IsUser) {
1256         P = isl_printer_start_line(P);
1257         P = isl_printer_print_ast_node(P, Node);
1258         P = isl_printer_end_line(P);
1259         isl_id_free(Id);
1260         isl_ast_print_options_free(Options);
1261         return P;
1262       }
1263 
1264       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
1265       isl_id_free(Id);
1266       Data->Kernels.push_back(Kernel);
1267     }
1268 
1269     return print_host_user(P, Options, Node, User);
1270   }
1271 
1272   /// Print C code corresponding to the control flow in @p Kernel.
1273   ///
1274   /// @param Kernel The kernel to print
1275   void printKernel(ppcg_kernel *Kernel) {
1276     auto *P = isl_printer_to_str(S->getIslCtx());
1277     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
1278     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
1279     P = isl_ast_node_print(Kernel->tree, P, Options);
1280     char *String = isl_printer_get_str(P);
1281     printf("%s\n", String);
1282     free(String);
1283     isl_printer_free(P);
1284   }
1285 
1286   /// Print C code corresponding to the GPU code described by @p Tree.
1287   ///
1288   /// @param Tree An AST describing GPU code
1289   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
1290   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
1291     auto *P = isl_printer_to_str(S->getIslCtx());
1292     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
1293 
1294     PrintGPUUserData Data;
1295     Data.PPCGProg = PPCGProg;
1296 
1297     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
1298     Options =
1299         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
1300     P = isl_ast_node_print(Tree, P, Options);
1301     char *String = isl_printer_get_str(P);
1302     printf("# host\n");
1303     printf("%s\n", String);
1304     free(String);
1305     isl_printer_free(P);
1306 
1307     for (auto Kernel : Data.Kernels) {
1308       printf("# kernel%d\n", Kernel->id);
1309       printKernel(Kernel);
1310     }
1311   }
1312 
1313   // Generate a GPU program using PPCG.
1314   //
1315   // GPU mapping consists of multiple steps:
1316   //
1317   //  1) Compute new schedule for the program.
1318   //  2) Map schedule to GPU (TODO)
1319   //  3) Generate code for new schedule (TODO)
1320   //
1321   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
1322   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
1323   // strategy directly from this pass.
1324   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
1325 
1326     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
1327 
1328     PPCGGen->ctx = S->getIslCtx();
1329     PPCGGen->options = PPCGScop->options;
1330     PPCGGen->print = nullptr;
1331     PPCGGen->print_user = nullptr;
1332     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
1333     PPCGGen->prog = PPCGProg;
1334     PPCGGen->tree = nullptr;
1335     PPCGGen->types.n = 0;
1336     PPCGGen->types.name = nullptr;
1337     PPCGGen->sizes = nullptr;
1338     PPCGGen->used_sizes = nullptr;
1339     PPCGGen->kernel_id = 0;
1340 
1341     // Set scheduling strategy to same strategy PPCG is using.
1342     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
1343     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
1344     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
1345 
1346     isl_schedule *Schedule = get_schedule(PPCGGen);
1347 
1348     int has_permutable = has_any_permutable_node(Schedule);
1349 
1350     if (!has_permutable || has_permutable < 0) {
1351       Schedule = isl_schedule_free(Schedule);
1352     } else {
1353       Schedule = map_to_device(PPCGGen, Schedule);
1354       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
1355     }
1356 
1357     if (DumpSchedule) {
1358       isl_printer *P = isl_printer_to_str(S->getIslCtx());
1359       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
1360       P = isl_printer_print_str(P, "Schedule\n");
1361       P = isl_printer_print_str(P, "========\n");
1362       if (Schedule)
1363         P = isl_printer_print_schedule(P, Schedule);
1364       else
1365         P = isl_printer_print_str(P, "No schedule found\n");
1366 
1367       printf("%s\n", isl_printer_get_str(P));
1368       isl_printer_free(P);
1369     }
1370 
1371     if (DumpCode) {
1372       printf("Code\n");
1373       printf("====\n");
1374       if (PPCGGen->tree)
1375         printGPUTree(PPCGGen->tree, PPCGProg);
1376       else
1377         printf("No code generated\n");
1378     }
1379 
1380     isl_schedule_free(Schedule);
1381 
1382     return PPCGGen;
1383   }
1384 
1385   /// Free gpu_gen structure.
1386   ///
1387   /// @param PPCGGen The ppcg_gen object to free.
1388   void freePPCGGen(gpu_gen *PPCGGen) {
1389     isl_ast_node_free(PPCGGen->tree);
1390     isl_union_map_free(PPCGGen->sizes);
1391     isl_union_map_free(PPCGGen->used_sizes);
1392     free(PPCGGen);
1393   }
1394 
1395   /// Free the options in the ppcg scop structure.
1396   ///
1397   /// ppcg is not freeing these options for us. To avoid leaks we do this
1398   /// ourselves.
1399   ///
1400   /// @param PPCGScop The scop referencing the options to free.
1401   void freeOptions(ppcg_scop *PPCGScop) {
1402     free(PPCGScop->options->debug);
1403     PPCGScop->options->debug = nullptr;
1404     free(PPCGScop->options);
1405     PPCGScop->options = nullptr;
1406   }
1407 
1408   /// Generate code for a given GPU AST described by @p Root.
1409   ///
1410   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
1411   /// @param Prog The GPU Program to generate code for.
1412   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
1413     ScopAnnotator Annotator;
1414     Annotator.buildAliasScopes(*S);
1415 
1416     Region *R = &S->getRegion();
1417 
1418     simplifyRegion(R, DT, LI, RI);
1419 
1420     BasicBlock *EnteringBB = R->getEnteringBlock();
1421 
1422     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
1423 
1424     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S,
1425                                Prog);
1426 
1427     // Only build the run-time condition and parameters _after_ having
1428     // introduced the conditional branch. This is important as the conditional
1429     // branch will guard the original scop from new induction variables that
1430     // the SCEVExpander may introduce while code generating the parameters and
1431     // which may introduce scalar dependences that prevent us from correctly
1432     // code generating this scop.
1433     BasicBlock *StartBlock =
1434         executeScopConditionally(*S, this, Builder.getTrue());
1435 
1436     // TODO: Handle LICM
1437     // TODO: Verify run-time checks
1438     auto SplitBlock = StartBlock->getSinglePredecessor();
1439     Builder.SetInsertPoint(SplitBlock->getTerminator());
1440     NodeBuilder.addParameters(S->getContext());
1441     Builder.SetInsertPoint(&*StartBlock->begin());
1442 
1443     NodeBuilder.initializeAfterRTH();
1444     NodeBuilder.create(Root);
1445     NodeBuilder.finalize();
1446   }
1447 
1448   bool runOnScop(Scop &CurrentScop) override {
1449     S = &CurrentScop;
1450     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1451     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1452     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1453     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
1454     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
1455 
1456     // We currently do not support scops with invariant loads.
1457     if (S->hasInvariantAccesses())
1458       return false;
1459 
1460     auto PPCGScop = createPPCGScop();
1461     auto PPCGProg = createPPCGProg(PPCGScop);
1462     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
1463 
1464     if (PPCGGen->tree)
1465       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
1466 
1467     freeOptions(PPCGScop);
1468     freePPCGGen(PPCGGen);
1469     gpu_prog_free(PPCGProg);
1470     ppcg_scop_free(PPCGScop);
1471 
1472     return true;
1473   }
1474 
1475   void printScop(raw_ostream &, Scop &) const override {}
1476 
1477   void getAnalysisUsage(AnalysisUsage &AU) const override {
1478     AU.addRequired<DominatorTreeWrapperPass>();
1479     AU.addRequired<RegionInfoPass>();
1480     AU.addRequired<ScalarEvolutionWrapperPass>();
1481     AU.addRequired<ScopDetection>();
1482     AU.addRequired<ScopInfoRegionPass>();
1483     AU.addRequired<LoopInfoWrapperPass>();
1484 
1485     AU.addPreserved<AAResultsWrapperPass>();
1486     AU.addPreserved<BasicAAWrapperPass>();
1487     AU.addPreserved<LoopInfoWrapperPass>();
1488     AU.addPreserved<DominatorTreeWrapperPass>();
1489     AU.addPreserved<GlobalsAAWrapperPass>();
1490     AU.addPreserved<PostDominatorTreeWrapperPass>();
1491     AU.addPreserved<ScopDetection>();
1492     AU.addPreserved<ScalarEvolutionWrapperPass>();
1493     AU.addPreserved<SCEVAAWrapperPass>();
1494 
1495     // FIXME: We do not yet add regions for the newly generated code to the
1496     //        region tree.
1497     AU.addPreserved<RegionInfoPass>();
1498     AU.addPreserved<ScopInfoRegionPass>();
1499   }
1500 };
1501 }
1502 
1503 char PPCGCodeGeneration::ID = 1;
1504 
1505 Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
1506 
1507 INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
1508                       "Polly - Apply PPCG translation to SCOP", false, false)
1509 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
1510 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
1511 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
1512 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
1513 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
1514 INITIALIZE_PASS_DEPENDENCY(ScopDetection);
1515 INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
1516                     "Polly - Apply PPCG translation to SCOP", false, false)
1517