19dfe4e7cSTobias Grosser //===------ PPCGCodeGeneration.cpp - Polly Accelerator Code Generation. ---===//
29dfe4e7cSTobias Grosser //
39dfe4e7cSTobias Grosser //                     The LLVM Compiler Infrastructure
49dfe4e7cSTobias Grosser //
59dfe4e7cSTobias Grosser // This file is distributed under the University of Illinois Open Source
69dfe4e7cSTobias Grosser // License. See LICENSE.TXT for details.
79dfe4e7cSTobias Grosser //
89dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===//
99dfe4e7cSTobias Grosser //
109dfe4e7cSTobias Grosser // Take a scop created by ScopInfo and map it to GPU code using the ppcg
119dfe4e7cSTobias Grosser // GPU mapping strategy.
129dfe4e7cSTobias Grosser //
139dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===//
149dfe4e7cSTobias Grosser 
159dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h"
1638fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h"
179dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h"
189dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h"
19f384594dSTobias Grosser #include "polly/Options.h"
209dfe4e7cSTobias Grosser #include "polly/ScopInfo.h"
219dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h"
229dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h"
239dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h"
249dfe4e7cSTobias Grosser #include "llvm/Analysis/PostDominators.h"
259dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
269dfe4e7cSTobias Grosser 
27f384594dSTobias Grosser #include "isl/union_map.h"
28f384594dSTobias Grosser 
29e938517eSTobias Grosser extern "C" {
30a56f8f8eSTobias Grosser #include "ppcg/cuda.h"
31a56f8f8eSTobias Grosser #include "ppcg/gpu.h"
32a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h"
33a56f8f8eSTobias Grosser #include "ppcg/ppcg.h"
34a56f8f8eSTobias Grosser #include "ppcg/schedule.h"
35e938517eSTobias Grosser }
36e938517eSTobias Grosser 
379dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h"
389dfe4e7cSTobias Grosser 
399dfe4e7cSTobias Grosser using namespace polly;
409dfe4e7cSTobias Grosser using namespace llvm;
419dfe4e7cSTobias Grosser 
429dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg"
439dfe4e7cSTobias Grosser 
44f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
45f384594dSTobias Grosser                                   cl::desc("Dump the computed GPU Schedule"),
46681bd568STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
47f384594dSTobias Grosser                                   cl::cat(PollyCategory));
4869b46751STobias Grosser 
4969b46751STobias Grosser static cl::opt<bool>
5069b46751STobias Grosser     DumpCode("polly-acc-dump-code",
5169b46751STobias Grosser              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
5269b46751STobias Grosser              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
5369b46751STobias Grosser 
54*32837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
55*32837fe3STobias Grosser                                   cl::desc("Dump the kernel LLVM-IR"),
56*32837fe3STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
57*32837fe3STobias Grosser                                   cl::cat(PollyCategory));
58*32837fe3STobias Grosser 
5960c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
6060c60025STobias Grosser ///
6160c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
6260c60025STobias Grosser /// of the scheduled ScopStmts.
6360c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
6460c60025STobias Grosser     void *Stmt, isl_ast_build *Build,
6560c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
6660c60025STobias Grosser                                        isl_id *Id, void *User),
6760c60025STobias Grosser     void *UserIndex,
6860c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
6960c60025STobias Grosser     void *User_expr) {
7060c60025STobias Grosser 
7160c60025STobias Grosser   // TODO: Implement the AST expression generation. For now we just return a
7260c60025STobias Grosser   // nullptr to ensure that we do not free uninitialized pointers.
7360c60025STobias Grosser 
7460c60025STobias Grosser   return nullptr;
7560c60025STobias Grosser }
76f384594dSTobias Grosser 
7738fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
7838fc0aedSTobias Grosser ///
7938fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
8038fc0aedSTobias Grosser /// generates code for general-prupose AST nodes, with special functionality
8138fc0aedSTobias Grosser /// for generating GPU specific user nodes.
8238fc0aedSTobias Grosser ///
8338fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
8438fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
8538fc0aedSTobias Grosser public:
8638fc0aedSTobias Grosser   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P,
8738fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
88*32837fe3STobias Grosser                  DominatorTree &DT, Scop &S, gpu_prog *Prog)
89*32837fe3STobias Grosser       : IslNodeBuilder(Builder, Annotator, P, DL, LI, SE, DT, S), Prog(Prog) {}
9038fc0aedSTobias Grosser 
9138fc0aedSTobias Grosser private:
92*32837fe3STobias Grosser   /// A module containing GPU code.
93*32837fe3STobias Grosser   ///
94*32837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
95*32837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
96*32837fe3STobias Grosser 
97*32837fe3STobias Grosser   /// The GPU program we generate code for.
98*32837fe3STobias Grosser   gpu_prog *Prog;
99*32837fe3STobias Grosser 
10038fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
10138fc0aedSTobias Grosser   ///
10238fc0aedSTobias Grosser   /// These AST nodes can be of type:
10338fc0aedSTobias Grosser   ///
10438fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
10538fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
10638fc0aedSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer (TODO)
10738fc0aedSTobias Grosser   ///
1081fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
1091fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
110*32837fe3STobias Grosser 
111*32837fe3STobias Grosser   /// Create GPU kernel.
112*32837fe3STobias Grosser   ///
113*32837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
114*32837fe3STobias Grosser   ///
115*32837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
116*32837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
117*32837fe3STobias Grosser 
118*32837fe3STobias Grosser   /// Create kernel function.
119*32837fe3STobias Grosser   ///
120*32837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
121*32837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
122*32837fe3STobias Grosser   /// start block of this newly created function.
123*32837fe3STobias Grosser   ///
124*32837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
125*32837fe3STobias Grosser   void createKernelFunction(ppcg_kernel *Kernel);
126*32837fe3STobias Grosser 
127*32837fe3STobias Grosser   /// Create the declaration of a kernel function.
128*32837fe3STobias Grosser   ///
129*32837fe3STobias Grosser   /// The kernel function takes as arguments:
130*32837fe3STobias Grosser   ///
131*32837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
132*32837fe3STobias Grosser   ///   - Host iterators (TODO)
133*32837fe3STobias Grosser   ///   - Parameters (TODO)
134*32837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
135*32837fe3STobias Grosser   ///
136*32837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
137*32837fe3STobias Grosser   /// @returns The newly declared function.
138*32837fe3STobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel);
139*32837fe3STobias Grosser 
140*32837fe3STobias Grosser   /// Finalize the generation of the kernel function.
141*32837fe3STobias Grosser   ///
142*32837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
143*32837fe3STobias Grosser   /// dump its IR to stderr.
144*32837fe3STobias Grosser   void finalizeKernelFunction();
1451fb9b64dSTobias Grosser };
1461fb9b64dSTobias Grosser 
1471fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
148*32837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
149*32837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
150*32837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
151*32837fe3STobias Grosser   isl_id_free(Id);
152*32837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
153*32837fe3STobias Grosser 
154*32837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
155*32837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
156*32837fe3STobias Grosser     createKernel(UserStmt);
157*32837fe3STobias Grosser     isl_ast_expr_free(Expr);
158*32837fe3STobias Grosser     return;
159*32837fe3STobias Grosser   }
160*32837fe3STobias Grosser 
161*32837fe3STobias Grosser   isl_ast_expr_free(Expr);
1621fb9b64dSTobias Grosser   isl_ast_node_free(UserStmt);
16338fc0aedSTobias Grosser   return;
16438fc0aedSTobias Grosser }
16538fc0aedSTobias Grosser 
166*32837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
167*32837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
168*32837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
169*32837fe3STobias Grosser   isl_id_free(Id);
170*32837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
171*32837fe3STobias Grosser 
172*32837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
173*32837fe3STobias Grosser 
174*32837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
175*32837fe3STobias Grosser 
176*32837fe3STobias Grosser   createKernelFunction(Kernel);
177*32837fe3STobias Grosser 
178*32837fe3STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
179*32837fe3STobias Grosser 
180*32837fe3STobias Grosser   finalizeKernelFunction();
181*32837fe3STobias Grosser }
182*32837fe3STobias Grosser 
183*32837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
184*32837fe3STobias Grosser ///
185*32837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
186*32837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
187*32837fe3STobias Grosser   std::string Ret = "e";
188*32837fe3STobias Grosser 
189*32837fe3STobias Grosser   if (!is64Bit)
190*32837fe3STobias Grosser     Ret += "-p:32:32";
191*32837fe3STobias Grosser 
192*32837fe3STobias Grosser   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
193*32837fe3STobias Grosser 
194*32837fe3STobias Grosser   return Ret;
195*32837fe3STobias Grosser }
196*32837fe3STobias Grosser 
197*32837fe3STobias Grosser Function *GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel) {
198*32837fe3STobias Grosser   std::vector<Type *> Args;
199*32837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
200*32837fe3STobias Grosser 
201*32837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
202*32837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
203*32837fe3STobias Grosser       continue;
204*32837fe3STobias Grosser 
205*32837fe3STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
206*32837fe3STobias Grosser   }
207*32837fe3STobias Grosser 
208*32837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
209*32837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
210*32837fe3STobias Grosser                               GPUModule.get());
211*32837fe3STobias Grosser   FN->setCallingConv(CallingConv::PTX_Kernel);
212*32837fe3STobias Grosser 
213*32837fe3STobias Grosser   auto Arg = FN->arg_begin();
214*32837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
215*32837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
216*32837fe3STobias Grosser       continue;
217*32837fe3STobias Grosser 
218*32837fe3STobias Grosser     Arg->setName(Prog->array[i].name);
219*32837fe3STobias Grosser     Arg++;
220*32837fe3STobias Grosser   }
221*32837fe3STobias Grosser 
222*32837fe3STobias Grosser   return FN;
223*32837fe3STobias Grosser }
224*32837fe3STobias Grosser 
225*32837fe3STobias Grosser void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel) {
226*32837fe3STobias Grosser 
227*32837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
228*32837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
229*32837fe3STobias Grosser   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
230*32837fe3STobias Grosser   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
231*32837fe3STobias Grosser 
232*32837fe3STobias Grosser   Function *FN = createKernelFunctionDecl(Kernel);
233*32837fe3STobias Grosser 
234*32837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
235*32837fe3STobias Grosser 
236*32837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
237*32837fe3STobias Grosser   Builder.CreateRetVoid();
238*32837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
239*32837fe3STobias Grosser }
240*32837fe3STobias Grosser 
241*32837fe3STobias Grosser void GPUNodeBuilder::finalizeKernelFunction() {
242*32837fe3STobias Grosser 
243*32837fe3STobias Grosser   if (DumpKernelIR)
244*32837fe3STobias Grosser     outs() << *GPUModule << "\n";
245*32837fe3STobias Grosser 
246*32837fe3STobias Grosser   GPUModule.release();
247*32837fe3STobias Grosser }
248*32837fe3STobias Grosser 
2499dfe4e7cSTobias Grosser namespace {
2509dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
2519dfe4e7cSTobias Grosser public:
2529dfe4e7cSTobias Grosser   static char ID;
2539dfe4e7cSTobias Grosser 
254e938517eSTobias Grosser   /// The scop that is currently processed.
255e938517eSTobias Grosser   Scop *S;
256e938517eSTobias Grosser 
25738fc0aedSTobias Grosser   LoopInfo *LI;
25838fc0aedSTobias Grosser   DominatorTree *DT;
25938fc0aedSTobias Grosser   ScalarEvolution *SE;
26038fc0aedSTobias Grosser   const DataLayout *DL;
26138fc0aedSTobias Grosser   RegionInfo *RI;
26238fc0aedSTobias Grosser 
2639dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
2649dfe4e7cSTobias Grosser 
265e938517eSTobias Grosser   /// Construct compilation options for PPCG.
266e938517eSTobias Grosser   ///
267e938517eSTobias Grosser   /// @returns The compilation options.
268e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
269e938517eSTobias Grosser     auto DebugOptions =
270e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
271e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
272e938517eSTobias Grosser 
273e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
274e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
275e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
276e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
277e938517eSTobias Grosser 
278e938517eSTobias Grosser     Options->debug = DebugOptions;
279e938517eSTobias Grosser 
280e938517eSTobias Grosser     Options->reschedule = true;
281e938517eSTobias Grosser     Options->scale_tile_loops = false;
282e938517eSTobias Grosser     Options->wrap = false;
283e938517eSTobias Grosser 
284e938517eSTobias Grosser     Options->non_negative_parameters = false;
285e938517eSTobias Grosser     Options->ctx = nullptr;
286e938517eSTobias Grosser     Options->sizes = nullptr;
287e938517eSTobias Grosser 
2884eaedde5STobias Grosser     Options->tile_size = 32;
2894eaedde5STobias Grosser 
290e938517eSTobias Grosser     Options->use_private_memory = false;
291e938517eSTobias Grosser     Options->use_shared_memory = false;
292e938517eSTobias Grosser     Options->max_shared_memory = 0;
293e938517eSTobias Grosser 
294e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
295e938517eSTobias Grosser     Options->openmp = false;
296e938517eSTobias Grosser     Options->linearize_device_arrays = true;
297e938517eSTobias Grosser     Options->live_range_reordering = false;
298e938517eSTobias Grosser 
299e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
300e938517eSTobias Grosser     Options->opencl_use_gpu = false;
301e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
302e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
303e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
304e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
305e938517eSTobias Grosser 
306e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
307e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
308e938517eSTobias Grosser 
309e938517eSTobias Grosser     return Options;
310e938517eSTobias Grosser   }
311e938517eSTobias Grosser 
312f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
313f384594dSTobias Grosser   ///
314f384594dSTobias Grosser   /// Instead of a normal access of the form:
315f384594dSTobias Grosser   ///
316f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
317f384594dSTobias Grosser   ///
318f384594dSTobias Grosser   /// a tagged access has the form
319f384594dSTobias Grosser   ///
320f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
321f384594dSTobias Grosser   ///
322f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
323f384594dSTobias Grosser   /// triggered the access.
324f384594dSTobias Grosser   ///
325f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
326f384594dSTobias Grosser   ///
327f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
328f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
329f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
330f384594dSTobias Grosser 
331f384594dSTobias Grosser     for (auto &Stmt : *S)
332f384594dSTobias Grosser       for (auto &Acc : Stmt)
333f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
334f384594dSTobias Grosser           isl_map *Relation = Acc->getAccessRelation();
335f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
336f384594dSTobias Grosser 
337f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
338f384594dSTobias Grosser           Space = isl_space_range(Space);
339f384594dSTobias Grosser           Space = isl_space_from_range(Space);
3406293ba69STobias Grosser           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
341f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
342f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
343f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
344f384594dSTobias Grosser         }
345f384594dSTobias Grosser 
346f384594dSTobias Grosser     return Accesses;
347f384594dSTobias Grosser   }
348f384594dSTobias Grosser 
349f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
350f384594dSTobias Grosser   ///
351f384594dSTobias Grosser   /// @see getTaggedAccesses
352f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
353f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
354f384594dSTobias Grosser   }
355f384594dSTobias Grosser 
356f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
357f384594dSTobias Grosser   ///
358f384594dSTobias Grosser   /// @see getTaggedAccesses
359f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
360f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
361f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
362f384594dSTobias Grosser   }
363f384594dSTobias Grosser 
364f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
365f384594dSTobias Grosser   ///
366f384594dSTobias Grosser   /// @see getTaggedAccesses
367f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
368f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
369f384594dSTobias Grosser   }
370f384594dSTobias Grosser 
371aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
372aef5196fSTobias Grosser   ///
373aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
374aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
375aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
376aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
377aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
378aef5196fSTobias Grosser   /// the data format that ppcg expects.
379aef5196fSTobias Grosser   ///
380aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
381aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
382aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
383bd81a7eeSTobias Grosser         S->getIslCtx(),
384bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
385aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
386aef5196fSTobias Grosser     auto *Space = S->getParamSpace();
387aef5196fSTobias Grosser 
388aef5196fSTobias Grosser     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
389aef5196fSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
390aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
391aef5196fSTobias Grosser     }
392aef5196fSTobias Grosser 
393aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
394aef5196fSTobias Grosser       auto Id = Array.second->getBasePtrId();
395aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
396aef5196fSTobias Grosser     }
397aef5196fSTobias Grosser 
398aef5196fSTobias Grosser     isl_space_free(Space);
399aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
400aef5196fSTobias Grosser 
401aef5196fSTobias Grosser     return Names;
402aef5196fSTobias Grosser   }
403aef5196fSTobias Grosser 
404e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
405e938517eSTobias Grosser   ///
406f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
407f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
408f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
409f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
410e938517eSTobias Grosser   ///
411e938517eSTobias Grosser   /// @returns A new ppcg scop.
412e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
413e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
414e938517eSTobias Grosser 
415e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
416e938517eSTobias Grosser 
417e938517eSTobias Grosser     PPCGScop->start = 0;
418e938517eSTobias Grosser     PPCGScop->end = 0;
419e938517eSTobias Grosser 
420f384594dSTobias Grosser     PPCGScop->context = S->getContext();
421f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
422e938517eSTobias Grosser     PPCGScop->call = nullptr;
423f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
424f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
425e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
426f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
427f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
428f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
429f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
430e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
431f384594dSTobias Grosser     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
432e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
433e938517eSTobias Grosser 
434e938517eSTobias Grosser     PPCGScop->independence = nullptr;
435e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
436e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
437e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
438e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
439e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
440e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
441e938517eSTobias Grosser 
442f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
443aef5196fSTobias Grosser     PPCGScop->names = getNames();
444e938517eSTobias Grosser 
445e938517eSTobias Grosser     PPCGScop->pet = nullptr;
446e938517eSTobias Grosser 
447f384594dSTobias Grosser     compute_tagger(PPCGScop);
448f384594dSTobias Grosser     compute_dependences(PPCGScop);
449f384594dSTobias Grosser 
450e938517eSTobias Grosser     return PPCGScop;
451e938517eSTobias Grosser   }
452e938517eSTobias Grosser 
45360f63b49STobias Grosser   /// Collect the array acesses in a statement.
45460f63b49STobias Grosser   ///
45560f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
45660f63b49STobias Grosser   ///
45760f63b49STobias Grosser   /// @returns A list of array accesses.
45860f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
45960f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
46060f63b49STobias Grosser 
46160f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
46260f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
46360f63b49STobias Grosser       Access->read = Acc->isRead();
46460f63b49STobias Grosser       Access->write = Acc->isWrite();
46560f63b49STobias Grosser       Access->access = Acc->getAccessRelation();
46660f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
46760f63b49STobias Grosser       Space = isl_space_range(Space);
46860f63b49STobias Grosser       Space = isl_space_from_range(Space);
4696293ba69STobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
47060f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
47160f63b49STobias Grosser       Access->tagged_access =
47260f63b49STobias Grosser           isl_map_domain_product(Acc->getAccessRelation(), Universe);
47360f63b49STobias Grosser       Access->exact_write = Acc->isWrite();
47460f63b49STobias Grosser       Access->ref_id = Acc->getId();
47560f63b49STobias Grosser       Access->next = Accesses;
47660f63b49STobias Grosser       Accesses = Access;
47760f63b49STobias Grosser     }
47860f63b49STobias Grosser 
47960f63b49STobias Grosser     return Accesses;
48060f63b49STobias Grosser   }
48160f63b49STobias Grosser 
48269b46751STobias Grosser   /// Collect the list of GPU statements.
48369b46751STobias Grosser   ///
48469b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
48569b46751STobias Grosser   /// as well as a list with all memory accesses.
48669b46751STobias Grosser   ///
48769b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
48869b46751STobias Grosser   ///
48969b46751STobias Grosser   /// @returns A linked-list of statements.
49069b46751STobias Grosser   gpu_stmt *getStatements() {
49169b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
49269b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
49369b46751STobias Grosser 
49469b46751STobias Grosser     int i = 0;
49569b46751STobias Grosser     for (auto &Stmt : *S) {
49669b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
49769b46751STobias Grosser 
49869b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
49969b46751STobias Grosser 
50069b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
50169b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
50260f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
50369b46751STobias Grosser       i++;
50469b46751STobias Grosser     }
50569b46751STobias Grosser 
50669b46751STobias Grosser     return Stmts;
50769b46751STobias Grosser   }
50869b46751STobias Grosser 
50960f63b49STobias Grosser   /// Derive the extent of an array.
51060f63b49STobias Grosser   ///
51160f63b49STobias Grosser   /// The extent of an array is defined by the set of memory locations for
51260f63b49STobias Grosser   /// which a memory access in the iteration domain exists.
51360f63b49STobias Grosser   ///
51460f63b49STobias Grosser   /// @param Array The array to derive the extent for.
51560f63b49STobias Grosser   ///
51660f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
51760f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
51860f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
51960f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
52060f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
52160f63b49STobias Grosser     isl_set *AccessSet =
52260f63b49STobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace());
52360f63b49STobias Grosser     isl_union_set_free(AccessUSet);
52460f63b49STobias Grosser 
52560f63b49STobias Grosser     return AccessSet;
52660f63b49STobias Grosser   }
52760f63b49STobias Grosser 
52860f63b49STobias Grosser   /// Derive the bounds of an array.
52960f63b49STobias Grosser   ///
53060f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
53160f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
53260f63b49STobias Grosser   /// ScopArrayInfo.
53360f63b49STobias Grosser   ///
53460f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
53560f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
53660f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
53760f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
53860f63b49STobias Grosser       isl_set *Dom = isl_set_copy(PPCGArray.extent);
53960f63b49STobias Grosser       Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
54060f63b49STobias Grosser       isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
54160f63b49STobias Grosser       isl_set_free(Dom);
54260f63b49STobias Grosser       Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
54360f63b49STobias Grosser       isl_local_space *LS = isl_local_space_from_space(isl_set_get_space(Dom));
54460f63b49STobias Grosser       isl_aff *One = isl_aff_zero_on_domain(LS);
54560f63b49STobias Grosser       One = isl_aff_add_constant_si(One, 1);
54660f63b49STobias Grosser       Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
54760f63b49STobias Grosser       Bound = isl_pw_aff_gist(Bound, S->getContext());
54860f63b49STobias Grosser       PPCGArray.bound[0] = Bound;
54960f63b49STobias Grosser     }
55060f63b49STobias Grosser 
55160f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
55260f63b49STobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
55360f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
55460f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
55560f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
55660f63b49STobias Grosser       PPCGArray.bound[i] = Bound;
55760f63b49STobias Grosser     }
55860f63b49STobias Grosser   }
55960f63b49STobias Grosser 
56060f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
56160f63b49STobias Grosser   ///
56260f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
56360f63b49STobias Grosser   void createArrays(gpu_prog *PPCGProg) {
56460f63b49STobias Grosser     int i = 0;
56560f63b49STobias Grosser     for (auto &Element : S->arrays()) {
56660f63b49STobias Grosser       ScopArrayInfo *Array = Element.second.get();
56760f63b49STobias Grosser 
56860f63b49STobias Grosser       std::string TypeName;
56960f63b49STobias Grosser       raw_string_ostream OS(TypeName);
57060f63b49STobias Grosser 
57160f63b49STobias Grosser       OS << *Array->getElementType();
57260f63b49STobias Grosser       TypeName = OS.str();
57360f63b49STobias Grosser 
57460f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
57560f63b49STobias Grosser 
57660f63b49STobias Grosser       PPCGArray.space = Array->getSpace();
57760f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
57860f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
57960f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
58060f63b49STobias Grosser       PPCGArray.extent = nullptr;
58160f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
58260f63b49STobias Grosser       PPCGArray.bound =
58360f63b49STobias Grosser           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
58460f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
58560f63b49STobias Grosser       PPCGArray.n_ref = 0;
58660f63b49STobias Grosser       PPCGArray.refs = nullptr;
58760f63b49STobias Grosser       PPCGArray.accessed = true;
58860f63b49STobias Grosser       PPCGArray.read_only_scalar = false;
58960f63b49STobias Grosser       PPCGArray.has_compound_element = false;
59060f63b49STobias Grosser       PPCGArray.local = false;
59160f63b49STobias Grosser       PPCGArray.declare_local = false;
59260f63b49STobias Grosser       PPCGArray.global = false;
59360f63b49STobias Grosser       PPCGArray.linearize = false;
59460f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
59560f63b49STobias Grosser 
59660f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
5972d010dafSTobias Grosser       i++;
598b9fc860aSTobias Grosser 
599b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
60060f63b49STobias Grosser     }
60160f63b49STobias Grosser   }
60260f63b49STobias Grosser 
60360f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
60460f63b49STobias Grosser   ///
60560f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
60660f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
60760f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
60860f63b49STobias Grosser 
60960f63b49STobias Grosser     for (auto &Item : S->arrays()) {
61060f63b49STobias Grosser       ScopArrayInfo *Array = Item.second.get();
61160f63b49STobias Grosser       isl_space *Space = Array->getSpace();
61260f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
61360f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
61460f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
61560f63b49STobias Grosser     }
61660f63b49STobias Grosser 
61760f63b49STobias Grosser     return Maps;
61860f63b49STobias Grosser   }
61960f63b49STobias Grosser 
620e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
621e938517eSTobias Grosser   ///
622e938517eSTobias Grosser   /// @returns A new gpu grogram description.
623e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
624e938517eSTobias Grosser 
625e938517eSTobias Grosser     if (!PPCGScop)
626e938517eSTobias Grosser       return nullptr;
627e938517eSTobias Grosser 
628e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
629e938517eSTobias Grosser 
630e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
631e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
632aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
63360f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
63460f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
63560f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
63660f63b49STobias Grosser     PPCGProg->tagged_must_kill =
63760f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
63860f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
63960f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
64060f63b49STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
641e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
642e938517eSTobias Grosser     PPCGProg->array_order = nullptr;
64369b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
64469b46751STobias Grosser     PPCGProg->stmts = getStatements();
64560f63b49STobias Grosser     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
64660f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
64760f63b49STobias Grosser                                        PPCGProg->n_array);
64860f63b49STobias Grosser 
64960f63b49STobias Grosser     createArrays(PPCGProg);
650e938517eSTobias Grosser 
651e938517eSTobias Grosser     return PPCGProg;
652e938517eSTobias Grosser   }
653e938517eSTobias Grosser 
65469b46751STobias Grosser   struct PrintGPUUserData {
65569b46751STobias Grosser     struct cuda_info *CudaInfo;
65669b46751STobias Grosser     struct gpu_prog *PPCGProg;
65769b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
65869b46751STobias Grosser   };
65969b46751STobias Grosser 
66069b46751STobias Grosser   /// Print a user statement node in the host code.
66169b46751STobias Grosser   ///
66269b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
66369b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
66469b46751STobias Grosser   /// host ast.
66569b46751STobias Grosser   ///
66669b46751STobias Grosser   /// @param P The printer to print to
66769b46751STobias Grosser   /// @param Options The printing options to use
66869b46751STobias Grosser   /// @param Node The node to print
66969b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
67069b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
67169b46751STobias Grosser   ///
67269b46751STobias Grosser   /// @returns A printer to which the output has been printed.
67369b46751STobias Grosser   static __isl_give isl_printer *
67469b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
67569b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
67669b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
67769b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
67869b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
67969b46751STobias Grosser 
68069b46751STobias Grosser     if (Id) {
68120251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
68220251734STobias Grosser 
68320251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
68420251734STobias Grosser       // otherwise try to call pet functionality that is not available in
68520251734STobias Grosser       // Polly.
68620251734STobias Grosser       if (IsUser) {
68720251734STobias Grosser         P = isl_printer_start_line(P);
68820251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
68920251734STobias Grosser         P = isl_printer_end_line(P);
69020251734STobias Grosser         isl_id_free(Id);
69120251734STobias Grosser         isl_ast_print_options_free(Options);
69220251734STobias Grosser         return P;
69320251734STobias Grosser       }
69420251734STobias Grosser 
69569b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
69669b46751STobias Grosser       isl_id_free(Id);
69769b46751STobias Grosser       Data->Kernels.push_back(Kernel);
69869b46751STobias Grosser     }
69969b46751STobias Grosser 
70069b46751STobias Grosser     return print_host_user(P, Options, Node, User);
70169b46751STobias Grosser   }
70269b46751STobias Grosser 
70369b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
70469b46751STobias Grosser   ///
70569b46751STobias Grosser   /// @param Kernel The kernel to print
70669b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
70769b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
70869b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
70969b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
71069b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
71169b46751STobias Grosser     char *String = isl_printer_get_str(P);
71269b46751STobias Grosser     printf("%s\n", String);
71369b46751STobias Grosser     free(String);
71469b46751STobias Grosser     isl_printer_free(P);
71569b46751STobias Grosser   }
71669b46751STobias Grosser 
71769b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
71869b46751STobias Grosser   ///
71969b46751STobias Grosser   /// @param Tree An AST describing GPU code
72069b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
72169b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
72269b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
72369b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
72469b46751STobias Grosser 
72569b46751STobias Grosser     PrintGPUUserData Data;
72669b46751STobias Grosser     Data.PPCGProg = PPCGProg;
72769b46751STobias Grosser 
72869b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
72969b46751STobias Grosser     Options =
73069b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
73169b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
73269b46751STobias Grosser     char *String = isl_printer_get_str(P);
73369b46751STobias Grosser     printf("# host\n");
73469b46751STobias Grosser     printf("%s\n", String);
73569b46751STobias Grosser     free(String);
73669b46751STobias Grosser     isl_printer_free(P);
73769b46751STobias Grosser 
73869b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
73969b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
74069b46751STobias Grosser       printKernel(Kernel);
74169b46751STobias Grosser     }
74269b46751STobias Grosser   }
74369b46751STobias Grosser 
744f384594dSTobias Grosser   // Generate a GPU program using PPCG.
745f384594dSTobias Grosser   //
746f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
747f384594dSTobias Grosser   //
748f384594dSTobias Grosser   //  1) Compute new schedule for the program.
749f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
750f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
751f384594dSTobias Grosser   //
752f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
753f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
754f384594dSTobias Grosser   // strategy directly from this pass.
755f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
756f384594dSTobias Grosser 
757f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
758f384594dSTobias Grosser 
759f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
760f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
761f384594dSTobias Grosser     PPCGGen->print = nullptr;
762f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
76360c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
764f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
765f384594dSTobias Grosser     PPCGGen->tree = nullptr;
766f384594dSTobias Grosser     PPCGGen->types.n = 0;
767f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
768f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
769f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
770f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
771f384594dSTobias Grosser 
772f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
773f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
774f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
7752341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
776f384594dSTobias Grosser 
777f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
778f384594dSTobias Grosser 
779aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
780aef5196fSTobias Grosser 
78169b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
782aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
78369b46751STobias Grosser     } else {
784aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
78569b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
78669b46751STobias Grosser     }
787aef5196fSTobias Grosser 
788f384594dSTobias Grosser     if (DumpSchedule) {
789f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
790f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
791f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
792f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
793f384594dSTobias Grosser       if (Schedule)
794f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
795f384594dSTobias Grosser       else
796f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
797f384594dSTobias Grosser 
798f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
799f384594dSTobias Grosser       isl_printer_free(P);
800f384594dSTobias Grosser     }
801f384594dSTobias Grosser 
80269b46751STobias Grosser     if (DumpCode) {
80369b46751STobias Grosser       printf("Code\n");
80469b46751STobias Grosser       printf("====\n");
80569b46751STobias Grosser       if (PPCGGen->tree)
80669b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
80769b46751STobias Grosser       else
80869b46751STobias Grosser         printf("No code generated\n");
80969b46751STobias Grosser     }
81069b46751STobias Grosser 
811f384594dSTobias Grosser     isl_schedule_free(Schedule);
812f384594dSTobias Grosser 
813f384594dSTobias Grosser     return PPCGGen;
814f384594dSTobias Grosser   }
815f384594dSTobias Grosser 
816f384594dSTobias Grosser   /// Free gpu_gen structure.
817f384594dSTobias Grosser   ///
818f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
819f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
820f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
821f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
822f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
823f384594dSTobias Grosser     free(PPCGGen);
824f384594dSTobias Grosser   }
825f384594dSTobias Grosser 
826b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
827b307ed4dSTobias Grosser   ///
828b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
829b307ed4dSTobias Grosser   /// ourselves.
830b307ed4dSTobias Grosser   ///
831b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
832b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
833b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
834b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
835b307ed4dSTobias Grosser     free(PPCGScop->options);
836b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
837b307ed4dSTobias Grosser   }
838b307ed4dSTobias Grosser 
83938fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
84038fc0aedSTobias Grosser   ///
841*32837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
842*32837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
843*32837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
84438fc0aedSTobias Grosser     ScopAnnotator Annotator;
84538fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
84638fc0aedSTobias Grosser 
84738fc0aedSTobias Grosser     Region *R = &S->getRegion();
84838fc0aedSTobias Grosser 
84938fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
85038fc0aedSTobias Grosser 
85138fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
85238fc0aedSTobias Grosser 
85338fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
85438fc0aedSTobias Grosser 
855*32837fe3STobias Grosser     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S,
856*32837fe3STobias Grosser                                Prog);
85738fc0aedSTobias Grosser 
85838fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
85938fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
86038fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
86138fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
86238fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
86338fc0aedSTobias Grosser     // code generating this scop.
86438fc0aedSTobias Grosser     BasicBlock *StartBlock =
86538fc0aedSTobias Grosser         executeScopConditionally(*S, this, Builder.getTrue());
86638fc0aedSTobias Grosser 
86738fc0aedSTobias Grosser     // TODO: Handle LICM
86838fc0aedSTobias Grosser     // TODO: Verify run-time checks
86938fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
87038fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
87138fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
87238fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
87338fc0aedSTobias Grosser     NodeBuilder.create(Root);
87438fc0aedSTobias Grosser     NodeBuilder.finalizeSCoP(*S);
87538fc0aedSTobias Grosser   }
87638fc0aedSTobias Grosser 
877e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
878e938517eSTobias Grosser     S = &CurrentScop;
87938fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
88038fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
88138fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
88238fc0aedSTobias Grosser     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
88338fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
884e938517eSTobias Grosser 
885e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
886e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
887f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
88838fc0aedSTobias Grosser 
88938fc0aedSTobias Grosser     if (PPCGGen->tree)
890*32837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
89138fc0aedSTobias Grosser 
892b307ed4dSTobias Grosser     freeOptions(PPCGScop);
893f384594dSTobias Grosser     freePPCGGen(PPCGGen);
894e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
895e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
896e938517eSTobias Grosser 
897e938517eSTobias Grosser     return true;
898e938517eSTobias Grosser   }
8999dfe4e7cSTobias Grosser 
9009dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
9019dfe4e7cSTobias Grosser 
9029dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
9039dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
9049dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
9059dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
9069dfe4e7cSTobias Grosser     AU.addRequired<ScopDetection>();
9079dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
9089dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
9099dfe4e7cSTobias Grosser 
9109dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
9119dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
9129dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
9139dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
9149dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
9159dfe4e7cSTobias Grosser     AU.addPreserved<PostDominatorTreeWrapperPass>();
9169dfe4e7cSTobias Grosser     AU.addPreserved<ScopDetection>();
9179dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
9189dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
9199dfe4e7cSTobias Grosser 
9209dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
9219dfe4e7cSTobias Grosser     //        region tree.
9229dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
9239dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
9249dfe4e7cSTobias Grosser   }
9259dfe4e7cSTobias Grosser };
9269dfe4e7cSTobias Grosser }
9279dfe4e7cSTobias Grosser 
9289dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
9299dfe4e7cSTobias Grosser 
9309dfe4e7cSTobias Grosser Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
9319dfe4e7cSTobias Grosser 
9329dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
9339dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
9349dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
9359dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
9369dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
9379dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
9389dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
9399dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScopDetection);
9409dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
9419dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
942