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 "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/BasicAliasAnalysis.h"
23 #include "llvm/Analysis/GlobalsModRef.h"
24 #include "llvm/Analysis/PostDominators.h"
25 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
26 
27 #include "isl/union_map.h"
28 
29 extern "C" {
30 #include "ppcg/cuda.h"
31 #include "ppcg/gpu.h"
32 #include "ppcg/gpu_print.h"
33 #include "ppcg/ppcg.h"
34 #include "ppcg/schedule.h"
35 }
36 
37 #include "llvm/Support/Debug.h"
38 
39 using namespace polly;
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "polly-codegen-ppcg"
43 
44 static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
45                                   cl::desc("Dump the computed GPU Schedule"),
46                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
47                                   cl::cat(PollyCategory));
48 
49 static cl::opt<bool>
50     DumpCode("polly-acc-dump-code",
51              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
52              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
53 
54 static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
55                                   cl::desc("Dump the kernel LLVM-IR"),
56                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
57                                   cl::cat(PollyCategory));
58 
59 /// Create the ast expressions for a ScopStmt.
60 ///
61 /// This function is a callback for to generate the ast expressions for each
62 /// of the scheduled ScopStmts.
63 static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
64     void *Stmt, isl_ast_build *Build,
65     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
66                                        isl_id *Id, void *User),
67     void *UserIndex,
68     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
69     void *User_expr) {
70 
71   // TODO: Implement the AST expression generation. For now we just return a
72   // nullptr to ensure that we do not free uninitialized pointers.
73 
74   return nullptr;
75 }
76 
77 /// Generate code for a GPU specific isl AST.
78 ///
79 /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
80 /// generates code for general-prupose AST nodes, with special functionality
81 /// for generating GPU specific user nodes.
82 ///
83 /// @see GPUNodeBuilder::createUser
84 class GPUNodeBuilder : public IslNodeBuilder {
85 public:
86   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P,
87                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
88                  DominatorTree &DT, Scop &S, gpu_prog *Prog)
89       : IslNodeBuilder(Builder, Annotator, P, DL, LI, SE, DT, S), Prog(Prog) {}
90 
91 private:
92   /// A module containing GPU code.
93   ///
94   /// This pointer is only set in case we are currently generating GPU code.
95   std::unique_ptr<Module> GPUModule;
96 
97   /// The GPU program we generate code for.
98   gpu_prog *Prog;
99 
100   /// Class to free isl_ids.
101   class IslIdDeleter {
102   public:
103     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
104   };
105 
106   /// A set containing all isl_ids allocated in a GPU kernel.
107   ///
108   /// By releasing this set all isl_ids will be freed.
109   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
110 
111   /// Create code for user-defined AST nodes.
112   ///
113   /// These AST nodes can be of type:
114   ///
115   ///   - ScopStmt:      A computational statement (TODO)
116   ///   - Kernel:        A GPU kernel call (TODO)
117   ///   - Data-Transfer: A GPU <-> CPU data-transfer (TODO)
118   ///
119   /// @param UserStmt The ast node to generate code for.
120   virtual void createUser(__isl_take isl_ast_node *UserStmt);
121 
122   /// Create GPU kernel.
123   ///
124   /// Code generate the kernel described by @p KernelStmt.
125   ///
126   /// @param KernelStmt The ast node to generate kernel code for.
127   void createKernel(__isl_take isl_ast_node *KernelStmt);
128 
129   /// Create kernel function.
130   ///
131   /// Create a kernel function located in a newly created module that can serve
132   /// as target for device code generation. Set the Builder to point to the
133   /// start block of this newly created function.
134   ///
135   /// @param Kernel The kernel to generate code for.
136   void createKernelFunction(ppcg_kernel *Kernel);
137 
138   /// Create the declaration of a kernel function.
139   ///
140   /// The kernel function takes as arguments:
141   ///
142   ///   - One i8 pointer for each external array reference used in the kernel.
143   ///   - Host iterators
144   ///   - Parameters
145   ///   - Other LLVM Value references (TODO)
146   ///
147   /// @param Kernel The kernel to generate the function declaration for.
148   /// @returns The newly declared function.
149   Function *createKernelFunctionDecl(ppcg_kernel *Kernel);
150 
151   /// Insert intrinsic functions to obtain thread and block ids.
152   ///
153   /// @param The kernel to generate the intrinsic functions for.
154   void insertKernelIntrinsics(ppcg_kernel *Kernel);
155 
156   /// Finalize the generation of the kernel function.
157   ///
158   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
159   /// dump its IR to stderr.
160   void finalizeKernelFunction();
161 };
162 
163 void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
164   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
165   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
166   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
167   isl_id_free(Id);
168   isl_ast_expr_free(StmtExpr);
169 
170   const char *Str = isl_id_get_name(Id);
171   if (!strcmp(Str, "kernel")) {
172     createKernel(UserStmt);
173     isl_ast_expr_free(Expr);
174     return;
175   }
176 
177   isl_ast_expr_free(Expr);
178   isl_ast_node_free(UserStmt);
179   return;
180 }
181 
182 void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
183   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
184   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
185   isl_id_free(Id);
186   isl_ast_node_free(KernelStmt);
187 
188   assert(Kernel->tree && "Device AST of kernel node is empty");
189 
190   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
191   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
192 
193   createKernelFunction(Kernel);
194 
195   create(isl_ast_node_copy(Kernel->tree));
196 
197   Builder.SetInsertPoint(&HostInsertPoint);
198   IDToValue = HostIDs;
199 
200   finalizeKernelFunction();
201 }
202 
203 /// Compute the DataLayout string for the NVPTX backend.
204 ///
205 /// @param is64Bit Are we looking for a 64 bit architecture?
206 static std::string computeNVPTXDataLayout(bool is64Bit) {
207   std::string Ret = "e";
208 
209   if (!is64Bit)
210     Ret += "-p:32:32";
211 
212   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
213 
214   return Ret;
215 }
216 
217 Function *GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel) {
218   std::vector<Type *> Args;
219   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
220 
221   for (long i = 0; i < Prog->n_array; i++) {
222     if (!ppcg_kernel_requires_array_argument(Kernel, i))
223       continue;
224 
225     Args.push_back(Builder.getInt8PtrTy());
226   }
227 
228   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
229 
230   for (long i = 0; i < NumHostIters; i++)
231     Args.push_back(Builder.getInt64Ty());
232 
233   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
234 
235   for (long i = 0; i < NumVars; i++)
236     Args.push_back(Builder.getInt64Ty());
237 
238   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
239   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
240                               GPUModule.get());
241   FN->setCallingConv(CallingConv::PTX_Kernel);
242 
243   auto Arg = FN->arg_begin();
244   for (long i = 0; i < Kernel->n_array; i++) {
245     if (!ppcg_kernel_requires_array_argument(Kernel, i))
246       continue;
247 
248     Arg->setName(Prog->array[i].name);
249     Arg++;
250   }
251 
252   for (long i = 0; i < NumHostIters; i++) {
253     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
254     Arg->setName(isl_id_get_name(Id));
255     IDToValue[Id] = &*Arg;
256     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
257     Arg++;
258   }
259 
260   for (long i = 0; i < NumVars; i++) {
261     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
262     Arg->setName(isl_id_get_name(Id));
263     IDToValue[Id] = &*Arg;
264     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
265     Arg++;
266   }
267 
268   return FN;
269 }
270 
271 void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
272   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
273                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
274 
275   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
276                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
277                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
278 
279   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
280     std::string Name = isl_id_get_name(Id);
281     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
282     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
283     Value *Val = Builder.CreateCall(IntrinsicFn, {});
284     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
285     IDToValue[Id] = Val;
286     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
287   };
288 
289   for (int i = 0; i < Kernel->n_grid; ++i) {
290     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
291     addId(Id, IntrinsicsBID[i]);
292   }
293 
294   for (int i = 0; i < Kernel->n_block; ++i) {
295     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
296     addId(Id, IntrinsicsTID[i]);
297   }
298 }
299 
300 void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel) {
301 
302   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
303   GPUModule.reset(new Module(Identifier, Builder.getContext()));
304   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
305   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
306 
307   Function *FN = createKernelFunctionDecl(Kernel);
308 
309   BasicBlock *PrevBlock = Builder.GetInsertBlock();
310   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
311 
312   DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
313   DT.addNewBlock(EntryBlock, PrevBlock);
314 
315   Builder.SetInsertPoint(EntryBlock);
316   Builder.CreateRetVoid();
317   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
318 
319   insertKernelIntrinsics(Kernel);
320 }
321 
322 void GPUNodeBuilder::finalizeKernelFunction() {
323 
324   if (DumpKernelIR)
325     outs() << *GPUModule << "\n";
326 
327   GPUModule.release();
328   KernelIDs.clear();
329 }
330 
331 namespace {
332 class PPCGCodeGeneration : public ScopPass {
333 public:
334   static char ID;
335 
336   /// The scop that is currently processed.
337   Scop *S;
338 
339   LoopInfo *LI;
340   DominatorTree *DT;
341   ScalarEvolution *SE;
342   const DataLayout *DL;
343   RegionInfo *RI;
344 
345   PPCGCodeGeneration() : ScopPass(ID) {}
346 
347   /// Construct compilation options for PPCG.
348   ///
349   /// @returns The compilation options.
350   ppcg_options *createPPCGOptions() {
351     auto DebugOptions =
352         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
353     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
354 
355     DebugOptions->dump_schedule_constraints = false;
356     DebugOptions->dump_schedule = false;
357     DebugOptions->dump_final_schedule = false;
358     DebugOptions->dump_sizes = false;
359 
360     Options->debug = DebugOptions;
361 
362     Options->reschedule = true;
363     Options->scale_tile_loops = false;
364     Options->wrap = false;
365 
366     Options->non_negative_parameters = false;
367     Options->ctx = nullptr;
368     Options->sizes = nullptr;
369 
370     Options->tile_size = 32;
371 
372     Options->use_private_memory = false;
373     Options->use_shared_memory = false;
374     Options->max_shared_memory = 0;
375 
376     Options->target = PPCG_TARGET_CUDA;
377     Options->openmp = false;
378     Options->linearize_device_arrays = true;
379     Options->live_range_reordering = false;
380 
381     Options->opencl_compiler_options = nullptr;
382     Options->opencl_use_gpu = false;
383     Options->opencl_n_include_file = 0;
384     Options->opencl_include_files = nullptr;
385     Options->opencl_print_kernel_types = false;
386     Options->opencl_embed_kernel_code = false;
387 
388     Options->save_schedule_file = nullptr;
389     Options->load_schedule_file = nullptr;
390 
391     return Options;
392   }
393 
394   /// Get a tagged access relation containing all accesses of type @p AccessTy.
395   ///
396   /// Instead of a normal access of the form:
397   ///
398   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
399   ///
400   /// a tagged access has the form
401   ///
402   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
403   ///
404   /// where 'id' is an additional space that references the memory access that
405   /// triggered the access.
406   ///
407   /// @param AccessTy The type of the memory accesses to collect.
408   ///
409   /// @return The relation describing all tagged memory accesses.
410   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
411     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
412 
413     for (auto &Stmt : *S)
414       for (auto &Acc : Stmt)
415         if (Acc->getType() == AccessTy) {
416           isl_map *Relation = Acc->getAccessRelation();
417           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
418 
419           isl_space *Space = isl_map_get_space(Relation);
420           Space = isl_space_range(Space);
421           Space = isl_space_from_range(Space);
422           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
423           isl_map *Universe = isl_map_universe(Space);
424           Relation = isl_map_domain_product(Relation, Universe);
425           Accesses = isl_union_map_add_map(Accesses, Relation);
426         }
427 
428     return Accesses;
429   }
430 
431   /// Get the set of all read accesses, tagged with the access id.
432   ///
433   /// @see getTaggedAccesses
434   isl_union_map *getTaggedReads() {
435     return getTaggedAccesses(MemoryAccess::READ);
436   }
437 
438   /// Get the set of all may (and must) accesses, tagged with the access id.
439   ///
440   /// @see getTaggedAccesses
441   isl_union_map *getTaggedMayWrites() {
442     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
443                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
444   }
445 
446   /// Get the set of all must accesses, tagged with the access id.
447   ///
448   /// @see getTaggedAccesses
449   isl_union_map *getTaggedMustWrites() {
450     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
451   }
452 
453   /// Collect parameter and array names as isl_ids.
454   ///
455   /// To reason about the different parameters and arrays used, ppcg requires
456   /// a list of all isl_ids in use. As PPCG traditionally performs
457   /// source-to-source compilation each of these isl_ids is mapped to the
458   /// expression that represents it. As we do not have a corresponding
459   /// expression in Polly, we just map each id to a 'zero' expression to match
460   /// the data format that ppcg expects.
461   ///
462   /// @returns Retun a map from collected ids to 'zero' ast expressions.
463   __isl_give isl_id_to_ast_expr *getNames() {
464     auto *Names = isl_id_to_ast_expr_alloc(
465         S->getIslCtx(),
466         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
467     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
468     auto *Space = S->getParamSpace();
469 
470     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
471       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
472       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
473     }
474 
475     for (auto &Array : S->arrays()) {
476       auto Id = Array.second->getBasePtrId();
477       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
478     }
479 
480     isl_space_free(Space);
481     isl_ast_expr_free(Zero);
482 
483     return Names;
484   }
485 
486   /// Create a new PPCG scop from the current scop.
487   ///
488   /// The PPCG scop is initialized with data from the current polly::Scop. From
489   /// this initial data, the data-dependences in the PPCG scop are initialized.
490   /// We do not use Polly's dependence analysis for now, to ensure we match
491   /// the PPCG default behaviour more closely.
492   ///
493   /// @returns A new ppcg scop.
494   ppcg_scop *createPPCGScop() {
495     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
496 
497     PPCGScop->options = createPPCGOptions();
498 
499     PPCGScop->start = 0;
500     PPCGScop->end = 0;
501 
502     PPCGScop->context = S->getContext();
503     PPCGScop->domain = S->getDomains();
504     PPCGScop->call = nullptr;
505     PPCGScop->tagged_reads = getTaggedReads();
506     PPCGScop->reads = S->getReads();
507     PPCGScop->live_in = nullptr;
508     PPCGScop->tagged_may_writes = getTaggedMayWrites();
509     PPCGScop->may_writes = S->getWrites();
510     PPCGScop->tagged_must_writes = getTaggedMustWrites();
511     PPCGScop->must_writes = S->getMustWrites();
512     PPCGScop->live_out = nullptr;
513     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
514     PPCGScop->tagger = nullptr;
515 
516     PPCGScop->independence = nullptr;
517     PPCGScop->dep_flow = nullptr;
518     PPCGScop->tagged_dep_flow = nullptr;
519     PPCGScop->dep_false = nullptr;
520     PPCGScop->dep_forced = nullptr;
521     PPCGScop->dep_order = nullptr;
522     PPCGScop->tagged_dep_order = nullptr;
523 
524     PPCGScop->schedule = S->getScheduleTree();
525     PPCGScop->names = getNames();
526 
527     PPCGScop->pet = nullptr;
528 
529     compute_tagger(PPCGScop);
530     compute_dependences(PPCGScop);
531 
532     return PPCGScop;
533   }
534 
535   /// Collect the array acesses in a statement.
536   ///
537   /// @param Stmt The statement for which to collect the accesses.
538   ///
539   /// @returns A list of array accesses.
540   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
541     gpu_stmt_access *Accesses = nullptr;
542 
543     for (MemoryAccess *Acc : Stmt) {
544       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
545       Access->read = Acc->isRead();
546       Access->write = Acc->isWrite();
547       Access->access = Acc->getAccessRelation();
548       isl_space *Space = isl_map_get_space(Access->access);
549       Space = isl_space_range(Space);
550       Space = isl_space_from_range(Space);
551       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
552       isl_map *Universe = isl_map_universe(Space);
553       Access->tagged_access =
554           isl_map_domain_product(Acc->getAccessRelation(), Universe);
555       Access->exact_write = Acc->isWrite();
556       Access->ref_id = Acc->getId();
557       Access->next = Accesses;
558       Accesses = Access;
559     }
560 
561     return Accesses;
562   }
563 
564   /// Collect the list of GPU statements.
565   ///
566   /// Each statement has an id, a pointer to the underlying data structure,
567   /// as well as a list with all memory accesses.
568   ///
569   /// TODO: Initialize the list of memory accesses.
570   ///
571   /// @returns A linked-list of statements.
572   gpu_stmt *getStatements() {
573     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
574                                        std::distance(S->begin(), S->end()));
575 
576     int i = 0;
577     for (auto &Stmt : *S) {
578       gpu_stmt *GPUStmt = &Stmts[i];
579 
580       GPUStmt->id = Stmt.getDomainId();
581 
582       // We use the pet stmt pointer to keep track of the Polly statements.
583       GPUStmt->stmt = (pet_stmt *)&Stmt;
584       GPUStmt->accesses = getStmtAccesses(Stmt);
585       i++;
586     }
587 
588     return Stmts;
589   }
590 
591   /// Derive the extent of an array.
592   ///
593   /// The extent of an array is defined by the set of memory locations for
594   /// which a memory access in the iteration domain exists.
595   ///
596   /// @param Array The array to derive the extent for.
597   ///
598   /// @returns An isl_set describing the extent of the array.
599   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
600     isl_union_map *Accesses = S->getAccesses();
601     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
602     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
603     isl_set *AccessSet =
604         isl_union_set_extract_set(AccessUSet, Array->getSpace());
605     isl_union_set_free(AccessUSet);
606 
607     return AccessSet;
608   }
609 
610   /// Derive the bounds of an array.
611   ///
612   /// For the first dimension we derive the bound of the array from the extent
613   /// of this dimension. For inner dimensions we obtain their size directly from
614   /// ScopArrayInfo.
615   ///
616   /// @param PPCGArray The array to compute bounds for.
617   /// @param Array The polly array from which to take the information.
618   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
619     if (PPCGArray.n_index > 0) {
620       isl_set *Dom = isl_set_copy(PPCGArray.extent);
621       Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
622       isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
623       isl_set_free(Dom);
624       Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
625       isl_local_space *LS = isl_local_space_from_space(isl_set_get_space(Dom));
626       isl_aff *One = isl_aff_zero_on_domain(LS);
627       One = isl_aff_add_constant_si(One, 1);
628       Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
629       Bound = isl_pw_aff_gist(Bound, S->getContext());
630       PPCGArray.bound[0] = Bound;
631     }
632 
633     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
634       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
635       auto LS = isl_pw_aff_get_domain_space(Bound);
636       auto Aff = isl_multi_aff_zero(LS);
637       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
638       PPCGArray.bound[i] = Bound;
639     }
640   }
641 
642   /// Create the arrays for @p PPCGProg.
643   ///
644   /// @param PPCGProg The program to compute the arrays for.
645   void createArrays(gpu_prog *PPCGProg) {
646     int i = 0;
647     for (auto &Element : S->arrays()) {
648       ScopArrayInfo *Array = Element.second.get();
649 
650       std::string TypeName;
651       raw_string_ostream OS(TypeName);
652 
653       OS << *Array->getElementType();
654       TypeName = OS.str();
655 
656       gpu_array_info &PPCGArray = PPCGProg->array[i];
657 
658       PPCGArray.space = Array->getSpace();
659       PPCGArray.type = strdup(TypeName.c_str());
660       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
661       PPCGArray.name = strdup(Array->getName().c_str());
662       PPCGArray.extent = nullptr;
663       PPCGArray.n_index = Array->getNumberOfDimensions();
664       PPCGArray.bound =
665           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
666       PPCGArray.extent = getExtent(Array);
667       PPCGArray.n_ref = 0;
668       PPCGArray.refs = nullptr;
669       PPCGArray.accessed = true;
670       PPCGArray.read_only_scalar = false;
671       PPCGArray.has_compound_element = false;
672       PPCGArray.local = false;
673       PPCGArray.declare_local = false;
674       PPCGArray.global = false;
675       PPCGArray.linearize = false;
676       PPCGArray.dep_order = nullptr;
677 
678       setArrayBounds(PPCGArray, Array);
679       i++;
680 
681       collect_references(PPCGProg, &PPCGArray);
682     }
683   }
684 
685   /// Create an identity map between the arrays in the scop.
686   ///
687   /// @returns An identity map between the arrays in the scop.
688   isl_union_map *getArrayIdentity() {
689     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
690 
691     for (auto &Item : S->arrays()) {
692       ScopArrayInfo *Array = Item.second.get();
693       isl_space *Space = Array->getSpace();
694       Space = isl_space_map_from_set(Space);
695       isl_map *Identity = isl_map_identity(Space);
696       Maps = isl_union_map_add_map(Maps, Identity);
697     }
698 
699     return Maps;
700   }
701 
702   /// Create a default-initialized PPCG GPU program.
703   ///
704   /// @returns A new gpu grogram description.
705   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
706 
707     if (!PPCGScop)
708       return nullptr;
709 
710     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
711 
712     PPCGProg->ctx = S->getIslCtx();
713     PPCGProg->scop = PPCGScop;
714     PPCGProg->context = isl_set_copy(PPCGScop->context);
715     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
716     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
717     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
718     PPCGProg->tagged_must_kill =
719         isl_union_map_copy(PPCGScop->tagged_must_kills);
720     PPCGProg->to_inner = getArrayIdentity();
721     PPCGProg->to_outer = getArrayIdentity();
722     PPCGProg->may_persist = compute_may_persist(PPCGProg);
723     PPCGProg->any_to_outer = nullptr;
724     PPCGProg->array_order = nullptr;
725     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
726     PPCGProg->stmts = getStatements();
727     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
728     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
729                                        PPCGProg->n_array);
730 
731     createArrays(PPCGProg);
732 
733     return PPCGProg;
734   }
735 
736   struct PrintGPUUserData {
737     struct cuda_info *CudaInfo;
738     struct gpu_prog *PPCGProg;
739     std::vector<ppcg_kernel *> Kernels;
740   };
741 
742   /// Print a user statement node in the host code.
743   ///
744   /// We use ppcg's printing facilities to print the actual statement and
745   /// additionally build up a list of all kernels that are encountered in the
746   /// host ast.
747   ///
748   /// @param P The printer to print to
749   /// @param Options The printing options to use
750   /// @param Node The node to print
751   /// @param User A user pointer to carry additional data. This pointer is
752   ///             expected to be of type PrintGPUUserData.
753   ///
754   /// @returns A printer to which the output has been printed.
755   static __isl_give isl_printer *
756   printHostUser(__isl_take isl_printer *P,
757                 __isl_take isl_ast_print_options *Options,
758                 __isl_take isl_ast_node *Node, void *User) {
759     auto Data = (struct PrintGPUUserData *)User;
760     auto Id = isl_ast_node_get_annotation(Node);
761 
762     if (Id) {
763       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
764 
765       // If this is a user statement, format it ourselves as ppcg would
766       // otherwise try to call pet functionality that is not available in
767       // Polly.
768       if (IsUser) {
769         P = isl_printer_start_line(P);
770         P = isl_printer_print_ast_node(P, Node);
771         P = isl_printer_end_line(P);
772         isl_id_free(Id);
773         isl_ast_print_options_free(Options);
774         return P;
775       }
776 
777       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
778       isl_id_free(Id);
779       Data->Kernels.push_back(Kernel);
780     }
781 
782     return print_host_user(P, Options, Node, User);
783   }
784 
785   /// Print C code corresponding to the control flow in @p Kernel.
786   ///
787   /// @param Kernel The kernel to print
788   void printKernel(ppcg_kernel *Kernel) {
789     auto *P = isl_printer_to_str(S->getIslCtx());
790     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
791     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
792     P = isl_ast_node_print(Kernel->tree, P, Options);
793     char *String = isl_printer_get_str(P);
794     printf("%s\n", String);
795     free(String);
796     isl_printer_free(P);
797   }
798 
799   /// Print C code corresponding to the GPU code described by @p Tree.
800   ///
801   /// @param Tree An AST describing GPU code
802   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
803   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
804     auto *P = isl_printer_to_str(S->getIslCtx());
805     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
806 
807     PrintGPUUserData Data;
808     Data.PPCGProg = PPCGProg;
809 
810     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
811     Options =
812         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
813     P = isl_ast_node_print(Tree, P, Options);
814     char *String = isl_printer_get_str(P);
815     printf("# host\n");
816     printf("%s\n", String);
817     free(String);
818     isl_printer_free(P);
819 
820     for (auto Kernel : Data.Kernels) {
821       printf("# kernel%d\n", Kernel->id);
822       printKernel(Kernel);
823     }
824   }
825 
826   // Generate a GPU program using PPCG.
827   //
828   // GPU mapping consists of multiple steps:
829   //
830   //  1) Compute new schedule for the program.
831   //  2) Map schedule to GPU (TODO)
832   //  3) Generate code for new schedule (TODO)
833   //
834   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
835   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
836   // strategy directly from this pass.
837   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
838 
839     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
840 
841     PPCGGen->ctx = S->getIslCtx();
842     PPCGGen->options = PPCGScop->options;
843     PPCGGen->print = nullptr;
844     PPCGGen->print_user = nullptr;
845     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
846     PPCGGen->prog = PPCGProg;
847     PPCGGen->tree = nullptr;
848     PPCGGen->types.n = 0;
849     PPCGGen->types.name = nullptr;
850     PPCGGen->sizes = nullptr;
851     PPCGGen->used_sizes = nullptr;
852     PPCGGen->kernel_id = 0;
853 
854     // Set scheduling strategy to same strategy PPCG is using.
855     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
856     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
857     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
858 
859     isl_schedule *Schedule = get_schedule(PPCGGen);
860 
861     int has_permutable = has_any_permutable_node(Schedule);
862 
863     if (!has_permutable || has_permutable < 0) {
864       Schedule = isl_schedule_free(Schedule);
865     } else {
866       Schedule = map_to_device(PPCGGen, Schedule);
867       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
868     }
869 
870     if (DumpSchedule) {
871       isl_printer *P = isl_printer_to_str(S->getIslCtx());
872       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
873       P = isl_printer_print_str(P, "Schedule\n");
874       P = isl_printer_print_str(P, "========\n");
875       if (Schedule)
876         P = isl_printer_print_schedule(P, Schedule);
877       else
878         P = isl_printer_print_str(P, "No schedule found\n");
879 
880       printf("%s\n", isl_printer_get_str(P));
881       isl_printer_free(P);
882     }
883 
884     if (DumpCode) {
885       printf("Code\n");
886       printf("====\n");
887       if (PPCGGen->tree)
888         printGPUTree(PPCGGen->tree, PPCGProg);
889       else
890         printf("No code generated\n");
891     }
892 
893     isl_schedule_free(Schedule);
894 
895     return PPCGGen;
896   }
897 
898   /// Free gpu_gen structure.
899   ///
900   /// @param PPCGGen The ppcg_gen object to free.
901   void freePPCGGen(gpu_gen *PPCGGen) {
902     isl_ast_node_free(PPCGGen->tree);
903     isl_union_map_free(PPCGGen->sizes);
904     isl_union_map_free(PPCGGen->used_sizes);
905     free(PPCGGen);
906   }
907 
908   /// Free the options in the ppcg scop structure.
909   ///
910   /// ppcg is not freeing these options for us. To avoid leaks we do this
911   /// ourselves.
912   ///
913   /// @param PPCGScop The scop referencing the options to free.
914   void freeOptions(ppcg_scop *PPCGScop) {
915     free(PPCGScop->options->debug);
916     PPCGScop->options->debug = nullptr;
917     free(PPCGScop->options);
918     PPCGScop->options = nullptr;
919   }
920 
921   /// Generate code for a given GPU AST described by @p Root.
922   ///
923   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
924   /// @param Prog The GPU Program to generate code for.
925   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
926     ScopAnnotator Annotator;
927     Annotator.buildAliasScopes(*S);
928 
929     Region *R = &S->getRegion();
930 
931     simplifyRegion(R, DT, LI, RI);
932 
933     BasicBlock *EnteringBB = R->getEnteringBlock();
934 
935     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
936 
937     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S,
938                                Prog);
939 
940     // Only build the run-time condition and parameters _after_ having
941     // introduced the conditional branch. This is important as the conditional
942     // branch will guard the original scop from new induction variables that
943     // the SCEVExpander may introduce while code generating the parameters and
944     // which may introduce scalar dependences that prevent us from correctly
945     // code generating this scop.
946     BasicBlock *StartBlock =
947         executeScopConditionally(*S, this, Builder.getTrue());
948 
949     // TODO: Handle LICM
950     // TODO: Verify run-time checks
951     auto SplitBlock = StartBlock->getSinglePredecessor();
952     Builder.SetInsertPoint(SplitBlock->getTerminator());
953     NodeBuilder.addParameters(S->getContext());
954     Builder.SetInsertPoint(&*StartBlock->begin());
955     NodeBuilder.create(Root);
956     NodeBuilder.finalizeSCoP(*S);
957   }
958 
959   bool runOnScop(Scop &CurrentScop) override {
960     S = &CurrentScop;
961     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
962     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
963     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
964     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
965     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
966 
967     auto PPCGScop = createPPCGScop();
968     auto PPCGProg = createPPCGProg(PPCGScop);
969     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
970 
971     if (PPCGGen->tree)
972       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
973 
974     freeOptions(PPCGScop);
975     freePPCGGen(PPCGGen);
976     gpu_prog_free(PPCGProg);
977     ppcg_scop_free(PPCGScop);
978 
979     return true;
980   }
981 
982   void printScop(raw_ostream &, Scop &) const override {}
983 
984   void getAnalysisUsage(AnalysisUsage &AU) const override {
985     AU.addRequired<DominatorTreeWrapperPass>();
986     AU.addRequired<RegionInfoPass>();
987     AU.addRequired<ScalarEvolutionWrapperPass>();
988     AU.addRequired<ScopDetection>();
989     AU.addRequired<ScopInfoRegionPass>();
990     AU.addRequired<LoopInfoWrapperPass>();
991 
992     AU.addPreserved<AAResultsWrapperPass>();
993     AU.addPreserved<BasicAAWrapperPass>();
994     AU.addPreserved<LoopInfoWrapperPass>();
995     AU.addPreserved<DominatorTreeWrapperPass>();
996     AU.addPreserved<GlobalsAAWrapperPass>();
997     AU.addPreserved<PostDominatorTreeWrapperPass>();
998     AU.addPreserved<ScopDetection>();
999     AU.addPreserved<ScalarEvolutionWrapperPass>();
1000     AU.addPreserved<SCEVAAWrapperPass>();
1001 
1002     // FIXME: We do not yet add regions for the newly generated code to the
1003     //        region tree.
1004     AU.addPreserved<RegionInfoPass>();
1005     AU.addPreserved<ScopInfoRegionPass>();
1006   }
1007 };
1008 }
1009 
1010 char PPCGCodeGeneration::ID = 1;
1011 
1012 Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
1013 
1014 INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
1015                       "Polly - Apply PPCG translation to SCOP", false, false)
1016 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
1017 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
1018 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
1019 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
1020 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
1021 INITIALIZE_PASS_DEPENDENCY(ScopDetection);
1022 INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
1023                     "Polly - Apply PPCG translation to SCOP", false, false)
1024