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"
21*edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h"
229dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h"
239dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h"
249dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h"
259dfe4e7cSTobias Grosser #include "llvm/Analysis/PostDominators.h"
269dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
279dfe4e7cSTobias Grosser 
28f384594dSTobias Grosser #include "isl/union_map.h"
29f384594dSTobias Grosser 
30e938517eSTobias Grosser extern "C" {
31a56f8f8eSTobias Grosser #include "ppcg/cuda.h"
32a56f8f8eSTobias Grosser #include "ppcg/gpu.h"
33a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h"
34a56f8f8eSTobias Grosser #include "ppcg/ppcg.h"
35a56f8f8eSTobias Grosser #include "ppcg/schedule.h"
36e938517eSTobias Grosser }
37e938517eSTobias Grosser 
389dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h"
399dfe4e7cSTobias Grosser 
409dfe4e7cSTobias Grosser using namespace polly;
419dfe4e7cSTobias Grosser using namespace llvm;
429dfe4e7cSTobias Grosser 
439dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg"
449dfe4e7cSTobias Grosser 
45f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
46f384594dSTobias Grosser                                   cl::desc("Dump the computed GPU Schedule"),
47681bd568STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
48f384594dSTobias Grosser                                   cl::cat(PollyCategory));
4969b46751STobias Grosser 
5069b46751STobias Grosser static cl::opt<bool>
5169b46751STobias Grosser     DumpCode("polly-acc-dump-code",
5269b46751STobias Grosser              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
5369b46751STobias Grosser              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
5469b46751STobias Grosser 
5532837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
5632837fe3STobias Grosser                                   cl::desc("Dump the kernel LLVM-IR"),
5732837fe3STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
5832837fe3STobias Grosser                                   cl::cat(PollyCategory));
5932837fe3STobias Grosser 
6060c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
6160c60025STobias Grosser ///
6260c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
6360c60025STobias Grosser /// of the scheduled ScopStmts.
6460c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
65*edb885cbSTobias Grosser     void *StmtT, isl_ast_build *Build,
6660c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
6760c60025STobias Grosser                                        isl_id *Id, void *User),
6860c60025STobias Grosser     void *UserIndex,
6960c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
70*edb885cbSTobias Grosser     void *UserExpr) {
7160c60025STobias Grosser 
72*edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
7360c60025STobias Grosser 
74*edb885cbSTobias Grosser   isl_ctx *Ctx;
75*edb885cbSTobias Grosser 
76*edb885cbSTobias Grosser   if (!Stmt || !Build)
77*edb885cbSTobias Grosser     return NULL;
78*edb885cbSTobias Grosser 
79*edb885cbSTobias Grosser   Ctx = isl_ast_build_get_ctx(Build);
80*edb885cbSTobias Grosser   isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0);
81*edb885cbSTobias Grosser 
82*edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
83*edb885cbSTobias Grosser     isl_map *AddrFunc = Acc->getAddressFunction();
84*edb885cbSTobias Grosser     AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain());
85*edb885cbSTobias Grosser     isl_id *RefId = Acc->getId();
86*edb885cbSTobias Grosser     isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc);
87*edb885cbSTobias Grosser     isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA);
88*edb885cbSTobias Grosser     MPA = isl_multi_pw_aff_coalesce(MPA);
89*edb885cbSTobias Grosser     MPA = FunctionIndex(MPA, RefId, UserIndex);
90*edb885cbSTobias Grosser     isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA);
91*edb885cbSTobias Grosser     Access = FunctionExpr(Access, RefId, UserExpr);
92*edb885cbSTobias Grosser     RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access);
93*edb885cbSTobias Grosser   }
94*edb885cbSTobias Grosser 
95*edb885cbSTobias Grosser   return RefToExpr;
9660c60025STobias Grosser }
97f384594dSTobias Grosser 
9838fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
9938fc0aedSTobias Grosser ///
10038fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
10138fc0aedSTobias Grosser /// generates code for general-prupose AST nodes, with special functionality
10238fc0aedSTobias Grosser /// for generating GPU specific user nodes.
10338fc0aedSTobias Grosser ///
10438fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
10538fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
10638fc0aedSTobias Grosser public:
10738fc0aedSTobias Grosser   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P,
10838fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
10932837fe3STobias Grosser                  DominatorTree &DT, Scop &S, gpu_prog *Prog)
110*edb885cbSTobias Grosser       : IslNodeBuilder(Builder, Annotator, P, DL, LI, SE, DT, S), Prog(Prog) {
111*edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
112*edb885cbSTobias Grosser   }
11338fc0aedSTobias Grosser 
11438fc0aedSTobias Grosser private:
11532837fe3STobias Grosser   /// A module containing GPU code.
11632837fe3STobias Grosser   ///
11732837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
11832837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
11932837fe3STobias Grosser 
12032837fe3STobias Grosser   /// The GPU program we generate code for.
12132837fe3STobias Grosser   gpu_prog *Prog;
12232837fe3STobias Grosser 
123472f9654STobias Grosser   /// Class to free isl_ids.
124472f9654STobias Grosser   class IslIdDeleter {
125472f9654STobias Grosser   public:
126472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
127472f9654STobias Grosser   };
128472f9654STobias Grosser 
129472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
130472f9654STobias Grosser   ///
131472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
132472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
133472f9654STobias Grosser 
134*edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
135*edb885cbSTobias Grosser 
13638fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
13738fc0aedSTobias Grosser   ///
13838fc0aedSTobias Grosser   /// These AST nodes can be of type:
13938fc0aedSTobias Grosser   ///
14038fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
14138fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
14238fc0aedSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer (TODO)
1435260c041STobias Grosser   ///   - In-kernel synchronization
1445260c041STobias Grosser   ///   - In-kernel memory copy statement
14538fc0aedSTobias Grosser   ///
1461fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
1471fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
14832837fe3STobias Grosser 
149*edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
150*edb885cbSTobias Grosser   ///
151*edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
152*edb885cbSTobias Grosser   ///
153*edb885cbSTobias Grosser   /// @returns A set of values referenced by the kernel.
154*edb885cbSTobias Grosser   SetVector<Value *> getReferencesInKernel(ppcg_kernel *Kernel);
155*edb885cbSTobias Grosser 
15632837fe3STobias Grosser   /// Create GPU kernel.
15732837fe3STobias Grosser   ///
15832837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
15932837fe3STobias Grosser   ///
16032837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
16132837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
16232837fe3STobias Grosser 
16332837fe3STobias Grosser   /// Create kernel function.
16432837fe3STobias Grosser   ///
16532837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
16632837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
16732837fe3STobias Grosser   /// start block of this newly created function.
16832837fe3STobias Grosser   ///
16932837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
170*edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
171*edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
172*edb885cbSTobias Grosser                             SetVector<Value *> &SubtreeValues);
17332837fe3STobias Grosser 
17432837fe3STobias Grosser   /// Create the declaration of a kernel function.
17532837fe3STobias Grosser   ///
17632837fe3STobias Grosser   /// The kernel function takes as arguments:
17732837fe3STobias Grosser   ///
17832837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
179f6044bd0STobias Grosser   ///   - Host iterators
180c84a1995STobias Grosser   ///   - Parameters
18132837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
18232837fe3STobias Grosser   ///
18332837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
184*edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
185*edb885cbSTobias Grosser   ///
18632837fe3STobias Grosser   /// @returns The newly declared function.
187*edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
188*edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
18932837fe3STobias Grosser 
190472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
191472f9654STobias Grosser   ///
192472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
193472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
194472f9654STobias Grosser 
195*edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
196*edb885cbSTobias Grosser   ///
197*edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
198*edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
199*edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
200*edb885cbSTobias Grosser 
2015260c041STobias Grosser   /// Create an in-kernel synchronization call.
2025260c041STobias Grosser   void createKernelSync();
2035260c041STobias Grosser 
20432837fe3STobias Grosser   /// Finalize the generation of the kernel function.
20532837fe3STobias Grosser   ///
20632837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
20732837fe3STobias Grosser   /// dump its IR to stderr.
20832837fe3STobias Grosser   void finalizeKernelFunction();
2091fb9b64dSTobias Grosser };
2101fb9b64dSTobias Grosser 
2115260c041STobias Grosser /// Check if one string is a prefix of another.
2125260c041STobias Grosser ///
2135260c041STobias Grosser /// @param String The string in which to look for the prefix.
2145260c041STobias Grosser /// @param Prefix The prefix to look for.
2155260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
2165260c041STobias Grosser   return String.find(Prefix) == 0;
2175260c041STobias Grosser }
2185260c041STobias Grosser 
2191fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
22032837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
22132837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
22232837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
22332837fe3STobias Grosser   isl_id_free(Id);
22432837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
22532837fe3STobias Grosser 
22632837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
22732837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
22832837fe3STobias Grosser     createKernel(UserStmt);
22932837fe3STobias Grosser     isl_ast_expr_free(Expr);
23032837fe3STobias Grosser     return;
23132837fe3STobias Grosser   }
23232837fe3STobias Grosser 
2335260c041STobias Grosser   if (isPrefix(Str, "to_device") || isPrefix(Str, "from_device")) {
2345260c041STobias Grosser     // TODO: Insert memory copies
23532837fe3STobias Grosser     isl_ast_expr_free(Expr);
2361fb9b64dSTobias Grosser     isl_ast_node_free(UserStmt);
23738fc0aedSTobias Grosser     return;
23838fc0aedSTobias Grosser   }
23938fc0aedSTobias Grosser 
2405260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
2415260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
2425260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
2435260c041STobias Grosser   isl_id_free(Anno);
2445260c041STobias Grosser 
2455260c041STobias Grosser   switch (KernelStmt->type) {
2465260c041STobias Grosser   case ppcg_kernel_domain:
247*edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
2485260c041STobias Grosser     isl_ast_node_free(UserStmt);
2495260c041STobias Grosser     return;
2505260c041STobias Grosser   case ppcg_kernel_copy:
2515260c041STobias Grosser     // TODO: Create kernel copy stmt
2525260c041STobias Grosser     isl_ast_expr_free(Expr);
2535260c041STobias Grosser     isl_ast_node_free(UserStmt);
2545260c041STobias Grosser     return;
2555260c041STobias Grosser   case ppcg_kernel_sync:
2565260c041STobias Grosser     createKernelSync();
2575260c041STobias Grosser     isl_ast_expr_free(Expr);
2585260c041STobias Grosser     isl_ast_node_free(UserStmt);
2595260c041STobias Grosser     return;
2605260c041STobias Grosser   }
2615260c041STobias Grosser 
2625260c041STobias Grosser   isl_ast_expr_free(Expr);
2635260c041STobias Grosser   isl_ast_node_free(UserStmt);
2645260c041STobias Grosser   return;
2655260c041STobias Grosser }
2665260c041STobias Grosser 
267*edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
268*edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
269*edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
270*edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
271*edb885cbSTobias Grosser 
272*edb885cbSTobias Grosser   LoopToScevMapT LTS;
273*edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
274*edb885cbSTobias Grosser 
275*edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
276*edb885cbSTobias Grosser 
277*edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
278*edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
279*edb885cbSTobias Grosser   else
280*edb885cbSTobias Grosser     assert(0 && "Region statement not supported\n");
281*edb885cbSTobias Grosser }
282*edb885cbSTobias Grosser 
2835260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
2845260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
2855260c041STobias Grosser   auto *Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
2865260c041STobias Grosser   Builder.CreateCall(Sync, {});
2875260c041STobias Grosser }
2885260c041STobias Grosser 
289*edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
290*edb885cbSTobias Grosser ///
291*edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
292*edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
293*edb885cbSTobias Grosser ///
294*edb885cbSTobias Grosser /// @param Node The node to collect references for.
295*edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
296*edb885cbSTobias Grosser ///
297*edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
298*edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
299*edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
300*edb885cbSTobias Grosser     return isl_bool_true;
301*edb885cbSTobias Grosser 
302*edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
303*edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
304*edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
305*edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
306*edb885cbSTobias Grosser   isl_id_free(Id);
307*edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
308*edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
309*edb885cbSTobias Grosser 
310*edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
311*edb885cbSTobias Grosser     return isl_bool_true;
312*edb885cbSTobias Grosser 
313*edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
314*edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
315*edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
316*edb885cbSTobias Grosser   isl_id_free(Id);
317*edb885cbSTobias Grosser 
318*edb885cbSTobias Grosser   addReferencesFromStmt(Stmt, User);
319*edb885cbSTobias Grosser 
320*edb885cbSTobias Grosser   return isl_bool_true;
321*edb885cbSTobias Grosser }
322*edb885cbSTobias Grosser 
323*edb885cbSTobias Grosser SetVector<Value *> GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
324*edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
325*edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
326*edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
327*edb885cbSTobias Grosser   SubtreeReferences References = {
328*edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
329*edb885cbSTobias Grosser 
330*edb885cbSTobias Grosser   for (const auto &I : IDToValue)
331*edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
332*edb885cbSTobias Grosser 
333*edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
334*edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
335*edb885cbSTobias Grosser 
336*edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
337*edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
338*edb885cbSTobias Grosser 
339*edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
340*edb885cbSTobias Grosser     SubtreeValues.remove(SAI.second->getBasePtr());
341*edb885cbSTobias Grosser 
342*edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
343*edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
344*edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
345*edb885cbSTobias Grosser     assert(IDToValue.count(Id));
346*edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
347*edb885cbSTobias Grosser     SubtreeValues.remove(Val);
348*edb885cbSTobias Grosser     isl_id_free(Id);
349*edb885cbSTobias Grosser   }
350*edb885cbSTobias Grosser   isl_space_free(Space);
351*edb885cbSTobias Grosser 
352*edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
353*edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
354*edb885cbSTobias Grosser     assert(IDToValue.count(Id));
355*edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
356*edb885cbSTobias Grosser     SubtreeValues.remove(Val);
357*edb885cbSTobias Grosser     isl_id_free(Id);
358*edb885cbSTobias Grosser   }
359*edb885cbSTobias Grosser 
360*edb885cbSTobias Grosser   return SubtreeValues;
361*edb885cbSTobias Grosser }
362*edb885cbSTobias Grosser 
36332837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
36432837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
36532837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
36632837fe3STobias Grosser   isl_id_free(Id);
36732837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
36832837fe3STobias Grosser 
369*edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel);
370*edb885cbSTobias Grosser 
37132837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
37232837fe3STobias Grosser 
37332837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
374472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
375*edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
37632837fe3STobias Grosser 
377*edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
378*edb885cbSTobias Grosser 
379*edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
380*edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
381*edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
382*edb885cbSTobias Grosser   for (const Loop *L : Loops) {
383*edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
384*edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
385*edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
386*edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
387*edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
388*edb885cbSTobias Grosser     SubtreeValues.insert(V);
389*edb885cbSTobias Grosser   }
390*edb885cbSTobias Grosser 
391*edb885cbSTobias Grosser   createKernelFunction(Kernel, SubtreeValues);
39232837fe3STobias Grosser 
39359ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
39459ab0705STobias Grosser 
39532837fe3STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
396472f9654STobias Grosser   IDToValue = HostIDs;
39732837fe3STobias Grosser 
398*edb885cbSTobias Grosser   ValueMap = HostValueMap;
399*edb885cbSTobias Grosser   ScalarMap.clear();
400*edb885cbSTobias Grosser   PHIOpMap.clear();
401*edb885cbSTobias Grosser   EscapeMap.clear();
402*edb885cbSTobias Grosser   IDToSAI.clear();
403*edb885cbSTobias Grosser 
40432837fe3STobias Grosser   finalizeKernelFunction();
40532837fe3STobias Grosser }
40632837fe3STobias Grosser 
40732837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
40832837fe3STobias Grosser ///
40932837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
41032837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
41132837fe3STobias Grosser   std::string Ret = "e";
41232837fe3STobias Grosser 
41332837fe3STobias Grosser   if (!is64Bit)
41432837fe3STobias Grosser     Ret += "-p:32:32";
41532837fe3STobias Grosser 
41632837fe3STobias Grosser   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
41732837fe3STobias Grosser 
41832837fe3STobias Grosser   return Ret;
41932837fe3STobias Grosser }
42032837fe3STobias Grosser 
421*edb885cbSTobias Grosser Function *
422*edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
423*edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
42432837fe3STobias Grosser   std::vector<Type *> Args;
42532837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
42632837fe3STobias Grosser 
42732837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
42832837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
42932837fe3STobias Grosser       continue;
43032837fe3STobias Grosser 
43132837fe3STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
43232837fe3STobias Grosser   }
43332837fe3STobias Grosser 
434f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
435f6044bd0STobias Grosser 
436f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++)
437f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
438f6044bd0STobias Grosser 
439c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
440c84a1995STobias Grosser 
441c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++)
442c84a1995STobias Grosser     Args.push_back(Builder.getInt64Ty());
443c84a1995STobias Grosser 
444*edb885cbSTobias Grosser   for (auto *V : SubtreeValues)
445*edb885cbSTobias Grosser     Args.push_back(V->getType());
446*edb885cbSTobias Grosser 
44732837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
44832837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
44932837fe3STobias Grosser                               GPUModule.get());
45032837fe3STobias Grosser   FN->setCallingConv(CallingConv::PTX_Kernel);
45132837fe3STobias Grosser 
45232837fe3STobias Grosser   auto Arg = FN->arg_begin();
45332837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
45432837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
45532837fe3STobias Grosser       continue;
45632837fe3STobias Grosser 
457*edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
458*edb885cbSTobias Grosser 
459*edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
460*edb885cbSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
461*edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
462*edb885cbSTobias Grosser     Value *Val = &*Arg;
463*edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
464*edb885cbSTobias Grosser     isl_ast_build *Build =
465*edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
466*edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
467*edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
468*edb885cbSTobias Grosser           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
469*edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
470*edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
471*edb885cbSTobias Grosser     }
472*edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
473*edb885cbSTobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, ScopArrayInfo::MK_Array);
474*edb885cbSTobias Grosser 
475*edb885cbSTobias Grosser     isl_ast_build_free(Build);
476*edb885cbSTobias Grosser     isl_id_free(Id);
477*edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
47832837fe3STobias Grosser     Arg++;
47932837fe3STobias Grosser   }
48032837fe3STobias Grosser 
481f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
482f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
483f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
484f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
485f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
486f6044bd0STobias Grosser     Arg++;
487f6044bd0STobias Grosser   }
488f6044bd0STobias Grosser 
489c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
490c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
491c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
492c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
493c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
494c84a1995STobias Grosser     Arg++;
495c84a1995STobias Grosser   }
496c84a1995STobias Grosser 
497*edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
498*edb885cbSTobias Grosser     Arg->setName(V->getName());
499*edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
500*edb885cbSTobias Grosser     Arg++;
501*edb885cbSTobias Grosser   }
502*edb885cbSTobias Grosser 
50332837fe3STobias Grosser   return FN;
50432837fe3STobias Grosser }
50532837fe3STobias Grosser 
506472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
507472f9654STobias Grosser   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
508472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
509472f9654STobias Grosser 
510472f9654STobias Grosser   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
511472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
512472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
513472f9654STobias Grosser 
514472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
515472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
516472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
517472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
518472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
519472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
520472f9654STobias Grosser     IDToValue[Id] = Val;
521472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
522472f9654STobias Grosser   };
523472f9654STobias Grosser 
524472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
525472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
526472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
527472f9654STobias Grosser   }
528472f9654STobias Grosser 
529472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
530472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
531472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
532472f9654STobias Grosser   }
533472f9654STobias Grosser }
534472f9654STobias Grosser 
535*edb885cbSTobias Grosser void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel,
536*edb885cbSTobias Grosser                                           SetVector<Value *> &SubtreeValues) {
53732837fe3STobias Grosser 
53832837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
53932837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
54032837fe3STobias Grosser   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
54132837fe3STobias Grosser   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
54232837fe3STobias Grosser 
543*edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
54432837fe3STobias Grosser 
54559ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
54632837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
54732837fe3STobias Grosser 
54859ab0705STobias Grosser   DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
54959ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
55059ab0705STobias Grosser 
55132837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
55232837fe3STobias Grosser   Builder.CreateRetVoid();
55332837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
554472f9654STobias Grosser 
555472f9654STobias Grosser   insertKernelIntrinsics(Kernel);
55632837fe3STobias Grosser }
55732837fe3STobias Grosser 
55832837fe3STobias Grosser void GPUNodeBuilder::finalizeKernelFunction() {
55932837fe3STobias Grosser 
56032837fe3STobias Grosser   if (DumpKernelIR)
56132837fe3STobias Grosser     outs() << *GPUModule << "\n";
56232837fe3STobias Grosser 
56332837fe3STobias Grosser   GPUModule.release();
564472f9654STobias Grosser   KernelIDs.clear();
56532837fe3STobias Grosser }
56632837fe3STobias Grosser 
5679dfe4e7cSTobias Grosser namespace {
5689dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
5699dfe4e7cSTobias Grosser public:
5709dfe4e7cSTobias Grosser   static char ID;
5719dfe4e7cSTobias Grosser 
572e938517eSTobias Grosser   /// The scop that is currently processed.
573e938517eSTobias Grosser   Scop *S;
574e938517eSTobias Grosser 
57538fc0aedSTobias Grosser   LoopInfo *LI;
57638fc0aedSTobias Grosser   DominatorTree *DT;
57738fc0aedSTobias Grosser   ScalarEvolution *SE;
57838fc0aedSTobias Grosser   const DataLayout *DL;
57938fc0aedSTobias Grosser   RegionInfo *RI;
58038fc0aedSTobias Grosser 
5819dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
5829dfe4e7cSTobias Grosser 
583e938517eSTobias Grosser   /// Construct compilation options for PPCG.
584e938517eSTobias Grosser   ///
585e938517eSTobias Grosser   /// @returns The compilation options.
586e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
587e938517eSTobias Grosser     auto DebugOptions =
588e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
589e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
590e938517eSTobias Grosser 
591e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
592e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
593e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
594e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
595e938517eSTobias Grosser 
596e938517eSTobias Grosser     Options->debug = DebugOptions;
597e938517eSTobias Grosser 
598e938517eSTobias Grosser     Options->reschedule = true;
599e938517eSTobias Grosser     Options->scale_tile_loops = false;
600e938517eSTobias Grosser     Options->wrap = false;
601e938517eSTobias Grosser 
602e938517eSTobias Grosser     Options->non_negative_parameters = false;
603e938517eSTobias Grosser     Options->ctx = nullptr;
604e938517eSTobias Grosser     Options->sizes = nullptr;
605e938517eSTobias Grosser 
6064eaedde5STobias Grosser     Options->tile_size = 32;
6074eaedde5STobias Grosser 
608e938517eSTobias Grosser     Options->use_private_memory = false;
609e938517eSTobias Grosser     Options->use_shared_memory = false;
610e938517eSTobias Grosser     Options->max_shared_memory = 0;
611e938517eSTobias Grosser 
612e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
613e938517eSTobias Grosser     Options->openmp = false;
614e938517eSTobias Grosser     Options->linearize_device_arrays = true;
615e938517eSTobias Grosser     Options->live_range_reordering = false;
616e938517eSTobias Grosser 
617e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
618e938517eSTobias Grosser     Options->opencl_use_gpu = false;
619e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
620e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
621e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
622e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
623e938517eSTobias Grosser 
624e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
625e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
626e938517eSTobias Grosser 
627e938517eSTobias Grosser     return Options;
628e938517eSTobias Grosser   }
629e938517eSTobias Grosser 
630f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
631f384594dSTobias Grosser   ///
632f384594dSTobias Grosser   /// Instead of a normal access of the form:
633f384594dSTobias Grosser   ///
634f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
635f384594dSTobias Grosser   ///
636f384594dSTobias Grosser   /// a tagged access has the form
637f384594dSTobias Grosser   ///
638f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
639f384594dSTobias Grosser   ///
640f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
641f384594dSTobias Grosser   /// triggered the access.
642f384594dSTobias Grosser   ///
643f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
644f384594dSTobias Grosser   ///
645f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
646f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
647f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
648f384594dSTobias Grosser 
649f384594dSTobias Grosser     for (auto &Stmt : *S)
650f384594dSTobias Grosser       for (auto &Acc : Stmt)
651f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
652f384594dSTobias Grosser           isl_map *Relation = Acc->getAccessRelation();
653f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
654f384594dSTobias Grosser 
655f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
656f384594dSTobias Grosser           Space = isl_space_range(Space);
657f384594dSTobias Grosser           Space = isl_space_from_range(Space);
6586293ba69STobias Grosser           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
659f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
660f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
661f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
662f384594dSTobias Grosser         }
663f384594dSTobias Grosser 
664f384594dSTobias Grosser     return Accesses;
665f384594dSTobias Grosser   }
666f384594dSTobias Grosser 
667f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
668f384594dSTobias Grosser   ///
669f384594dSTobias Grosser   /// @see getTaggedAccesses
670f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
671f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
672f384594dSTobias Grosser   }
673f384594dSTobias Grosser 
674f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
675f384594dSTobias Grosser   ///
676f384594dSTobias Grosser   /// @see getTaggedAccesses
677f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
678f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
679f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
680f384594dSTobias Grosser   }
681f384594dSTobias Grosser 
682f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
683f384594dSTobias Grosser   ///
684f384594dSTobias Grosser   /// @see getTaggedAccesses
685f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
686f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
687f384594dSTobias Grosser   }
688f384594dSTobias Grosser 
689aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
690aef5196fSTobias Grosser   ///
691aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
692aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
693aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
694aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
695aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
696aef5196fSTobias Grosser   /// the data format that ppcg expects.
697aef5196fSTobias Grosser   ///
698aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
699aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
700aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
701bd81a7eeSTobias Grosser         S->getIslCtx(),
702bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
703aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
704aef5196fSTobias Grosser     auto *Space = S->getParamSpace();
705aef5196fSTobias Grosser 
706aef5196fSTobias Grosser     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
707aef5196fSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
708aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
709aef5196fSTobias Grosser     }
710aef5196fSTobias Grosser 
711aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
712aef5196fSTobias Grosser       auto Id = Array.second->getBasePtrId();
713aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
714aef5196fSTobias Grosser     }
715aef5196fSTobias Grosser 
716aef5196fSTobias Grosser     isl_space_free(Space);
717aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
718aef5196fSTobias Grosser 
719aef5196fSTobias Grosser     return Names;
720aef5196fSTobias Grosser   }
721aef5196fSTobias Grosser 
722e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
723e938517eSTobias Grosser   ///
724f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
725f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
726f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
727f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
728e938517eSTobias Grosser   ///
729e938517eSTobias Grosser   /// @returns A new ppcg scop.
730e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
731e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
732e938517eSTobias Grosser 
733e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
734e938517eSTobias Grosser 
735e938517eSTobias Grosser     PPCGScop->start = 0;
736e938517eSTobias Grosser     PPCGScop->end = 0;
737e938517eSTobias Grosser 
738f384594dSTobias Grosser     PPCGScop->context = S->getContext();
739f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
740e938517eSTobias Grosser     PPCGScop->call = nullptr;
741f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
742f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
743e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
744f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
745f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
746f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
747f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
748e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
749f384594dSTobias Grosser     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
750e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
751e938517eSTobias Grosser 
752e938517eSTobias Grosser     PPCGScop->independence = nullptr;
753e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
754e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
755e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
756e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
757e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
758e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
759e938517eSTobias Grosser 
760f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
761aef5196fSTobias Grosser     PPCGScop->names = getNames();
762e938517eSTobias Grosser 
763e938517eSTobias Grosser     PPCGScop->pet = nullptr;
764e938517eSTobias Grosser 
765f384594dSTobias Grosser     compute_tagger(PPCGScop);
766f384594dSTobias Grosser     compute_dependences(PPCGScop);
767f384594dSTobias Grosser 
768e938517eSTobias Grosser     return PPCGScop;
769e938517eSTobias Grosser   }
770e938517eSTobias Grosser 
77160f63b49STobias Grosser   /// Collect the array acesses in a statement.
77260f63b49STobias Grosser   ///
77360f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
77460f63b49STobias Grosser   ///
77560f63b49STobias Grosser   /// @returns A list of array accesses.
77660f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
77760f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
77860f63b49STobias Grosser 
77960f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
78060f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
78160f63b49STobias Grosser       Access->read = Acc->isRead();
78260f63b49STobias Grosser       Access->write = Acc->isWrite();
78360f63b49STobias Grosser       Access->access = Acc->getAccessRelation();
78460f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
78560f63b49STobias Grosser       Space = isl_space_range(Space);
78660f63b49STobias Grosser       Space = isl_space_from_range(Space);
7876293ba69STobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
78860f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
78960f63b49STobias Grosser       Access->tagged_access =
79060f63b49STobias Grosser           isl_map_domain_product(Acc->getAccessRelation(), Universe);
79160f63b49STobias Grosser       Access->exact_write = Acc->isWrite();
79260f63b49STobias Grosser       Access->ref_id = Acc->getId();
79360f63b49STobias Grosser       Access->next = Accesses;
79460f63b49STobias Grosser       Accesses = Access;
79560f63b49STobias Grosser     }
79660f63b49STobias Grosser 
79760f63b49STobias Grosser     return Accesses;
79860f63b49STobias Grosser   }
79960f63b49STobias Grosser 
80069b46751STobias Grosser   /// Collect the list of GPU statements.
80169b46751STobias Grosser   ///
80269b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
80369b46751STobias Grosser   /// as well as a list with all memory accesses.
80469b46751STobias Grosser   ///
80569b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
80669b46751STobias Grosser   ///
80769b46751STobias Grosser   /// @returns A linked-list of statements.
80869b46751STobias Grosser   gpu_stmt *getStatements() {
80969b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
81069b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
81169b46751STobias Grosser 
81269b46751STobias Grosser     int i = 0;
81369b46751STobias Grosser     for (auto &Stmt : *S) {
81469b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
81569b46751STobias Grosser 
81669b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
81769b46751STobias Grosser 
81869b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
81969b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
82060f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
82169b46751STobias Grosser       i++;
82269b46751STobias Grosser     }
82369b46751STobias Grosser 
82469b46751STobias Grosser     return Stmts;
82569b46751STobias Grosser   }
82669b46751STobias Grosser 
82760f63b49STobias Grosser   /// Derive the extent of an array.
82860f63b49STobias Grosser   ///
82960f63b49STobias Grosser   /// The extent of an array is defined by the set of memory locations for
83060f63b49STobias Grosser   /// which a memory access in the iteration domain exists.
83160f63b49STobias Grosser   ///
83260f63b49STobias Grosser   /// @param Array The array to derive the extent for.
83360f63b49STobias Grosser   ///
83460f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
83560f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
83660f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
83760f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
83860f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
83960f63b49STobias Grosser     isl_set *AccessSet =
84060f63b49STobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace());
84160f63b49STobias Grosser     isl_union_set_free(AccessUSet);
84260f63b49STobias Grosser 
84360f63b49STobias Grosser     return AccessSet;
84460f63b49STobias Grosser   }
84560f63b49STobias Grosser 
84660f63b49STobias Grosser   /// Derive the bounds of an array.
84760f63b49STobias Grosser   ///
84860f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
84960f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
85060f63b49STobias Grosser   /// ScopArrayInfo.
85160f63b49STobias Grosser   ///
85260f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
85360f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
85460f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
85560f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
85660f63b49STobias Grosser       isl_set *Dom = isl_set_copy(PPCGArray.extent);
85760f63b49STobias Grosser       Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
85860f63b49STobias Grosser       isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
85960f63b49STobias Grosser       isl_set_free(Dom);
86060f63b49STobias Grosser       Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
86160f63b49STobias Grosser       isl_local_space *LS = isl_local_space_from_space(isl_set_get_space(Dom));
86260f63b49STobias Grosser       isl_aff *One = isl_aff_zero_on_domain(LS);
86360f63b49STobias Grosser       One = isl_aff_add_constant_si(One, 1);
86460f63b49STobias Grosser       Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
86560f63b49STobias Grosser       Bound = isl_pw_aff_gist(Bound, S->getContext());
86660f63b49STobias Grosser       PPCGArray.bound[0] = Bound;
86760f63b49STobias Grosser     }
86860f63b49STobias Grosser 
86960f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
87060f63b49STobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
87160f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
87260f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
87360f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
87460f63b49STobias Grosser       PPCGArray.bound[i] = Bound;
87560f63b49STobias Grosser     }
87660f63b49STobias Grosser   }
87760f63b49STobias Grosser 
87860f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
87960f63b49STobias Grosser   ///
88060f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
88160f63b49STobias Grosser   void createArrays(gpu_prog *PPCGProg) {
88260f63b49STobias Grosser     int i = 0;
88360f63b49STobias Grosser     for (auto &Element : S->arrays()) {
88460f63b49STobias Grosser       ScopArrayInfo *Array = Element.second.get();
88560f63b49STobias Grosser 
88660f63b49STobias Grosser       std::string TypeName;
88760f63b49STobias Grosser       raw_string_ostream OS(TypeName);
88860f63b49STobias Grosser 
88960f63b49STobias Grosser       OS << *Array->getElementType();
89060f63b49STobias Grosser       TypeName = OS.str();
89160f63b49STobias Grosser 
89260f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
89360f63b49STobias Grosser 
89460f63b49STobias Grosser       PPCGArray.space = Array->getSpace();
89560f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
89660f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
89760f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
89860f63b49STobias Grosser       PPCGArray.extent = nullptr;
89960f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
90060f63b49STobias Grosser       PPCGArray.bound =
90160f63b49STobias Grosser           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
90260f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
90360f63b49STobias Grosser       PPCGArray.n_ref = 0;
90460f63b49STobias Grosser       PPCGArray.refs = nullptr;
90560f63b49STobias Grosser       PPCGArray.accessed = true;
90660f63b49STobias Grosser       PPCGArray.read_only_scalar = false;
90760f63b49STobias Grosser       PPCGArray.has_compound_element = false;
90860f63b49STobias Grosser       PPCGArray.local = false;
90960f63b49STobias Grosser       PPCGArray.declare_local = false;
91060f63b49STobias Grosser       PPCGArray.global = false;
91160f63b49STobias Grosser       PPCGArray.linearize = false;
91260f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
91360f63b49STobias Grosser 
91460f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
9152d010dafSTobias Grosser       i++;
916b9fc860aSTobias Grosser 
917b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
91860f63b49STobias Grosser     }
91960f63b49STobias Grosser   }
92060f63b49STobias Grosser 
92160f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
92260f63b49STobias Grosser   ///
92360f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
92460f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
92560f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
92660f63b49STobias Grosser 
92760f63b49STobias Grosser     for (auto &Item : S->arrays()) {
92860f63b49STobias Grosser       ScopArrayInfo *Array = Item.second.get();
92960f63b49STobias Grosser       isl_space *Space = Array->getSpace();
93060f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
93160f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
93260f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
93360f63b49STobias Grosser     }
93460f63b49STobias Grosser 
93560f63b49STobias Grosser     return Maps;
93660f63b49STobias Grosser   }
93760f63b49STobias Grosser 
938e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
939e938517eSTobias Grosser   ///
940e938517eSTobias Grosser   /// @returns A new gpu grogram description.
941e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
942e938517eSTobias Grosser 
943e938517eSTobias Grosser     if (!PPCGScop)
944e938517eSTobias Grosser       return nullptr;
945e938517eSTobias Grosser 
946e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
947e938517eSTobias Grosser 
948e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
949e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
950aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
95160f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
95260f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
95360f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
95460f63b49STobias Grosser     PPCGProg->tagged_must_kill =
95560f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
95660f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
95760f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
95860f63b49STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
959e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
960e938517eSTobias Grosser     PPCGProg->array_order = nullptr;
96169b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
96269b46751STobias Grosser     PPCGProg->stmts = getStatements();
96360f63b49STobias Grosser     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
96460f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
96560f63b49STobias Grosser                                        PPCGProg->n_array);
96660f63b49STobias Grosser 
96760f63b49STobias Grosser     createArrays(PPCGProg);
968e938517eSTobias Grosser 
969e938517eSTobias Grosser     return PPCGProg;
970e938517eSTobias Grosser   }
971e938517eSTobias Grosser 
97269b46751STobias Grosser   struct PrintGPUUserData {
97369b46751STobias Grosser     struct cuda_info *CudaInfo;
97469b46751STobias Grosser     struct gpu_prog *PPCGProg;
97569b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
97669b46751STobias Grosser   };
97769b46751STobias Grosser 
97869b46751STobias Grosser   /// Print a user statement node in the host code.
97969b46751STobias Grosser   ///
98069b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
98169b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
98269b46751STobias Grosser   /// host ast.
98369b46751STobias Grosser   ///
98469b46751STobias Grosser   /// @param P The printer to print to
98569b46751STobias Grosser   /// @param Options The printing options to use
98669b46751STobias Grosser   /// @param Node The node to print
98769b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
98869b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
98969b46751STobias Grosser   ///
99069b46751STobias Grosser   /// @returns A printer to which the output has been printed.
99169b46751STobias Grosser   static __isl_give isl_printer *
99269b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
99369b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
99469b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
99569b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
99669b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
99769b46751STobias Grosser 
99869b46751STobias Grosser     if (Id) {
99920251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
100020251734STobias Grosser 
100120251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
100220251734STobias Grosser       // otherwise try to call pet functionality that is not available in
100320251734STobias Grosser       // Polly.
100420251734STobias Grosser       if (IsUser) {
100520251734STobias Grosser         P = isl_printer_start_line(P);
100620251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
100720251734STobias Grosser         P = isl_printer_end_line(P);
100820251734STobias Grosser         isl_id_free(Id);
100920251734STobias Grosser         isl_ast_print_options_free(Options);
101020251734STobias Grosser         return P;
101120251734STobias Grosser       }
101220251734STobias Grosser 
101369b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
101469b46751STobias Grosser       isl_id_free(Id);
101569b46751STobias Grosser       Data->Kernels.push_back(Kernel);
101669b46751STobias Grosser     }
101769b46751STobias Grosser 
101869b46751STobias Grosser     return print_host_user(P, Options, Node, User);
101969b46751STobias Grosser   }
102069b46751STobias Grosser 
102169b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
102269b46751STobias Grosser   ///
102369b46751STobias Grosser   /// @param Kernel The kernel to print
102469b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
102569b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
102669b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
102769b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
102869b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
102969b46751STobias Grosser     char *String = isl_printer_get_str(P);
103069b46751STobias Grosser     printf("%s\n", String);
103169b46751STobias Grosser     free(String);
103269b46751STobias Grosser     isl_printer_free(P);
103369b46751STobias Grosser   }
103469b46751STobias Grosser 
103569b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
103669b46751STobias Grosser   ///
103769b46751STobias Grosser   /// @param Tree An AST describing GPU code
103869b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
103969b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
104069b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
104169b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
104269b46751STobias Grosser 
104369b46751STobias Grosser     PrintGPUUserData Data;
104469b46751STobias Grosser     Data.PPCGProg = PPCGProg;
104569b46751STobias Grosser 
104669b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
104769b46751STobias Grosser     Options =
104869b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
104969b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
105069b46751STobias Grosser     char *String = isl_printer_get_str(P);
105169b46751STobias Grosser     printf("# host\n");
105269b46751STobias Grosser     printf("%s\n", String);
105369b46751STobias Grosser     free(String);
105469b46751STobias Grosser     isl_printer_free(P);
105569b46751STobias Grosser 
105669b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
105769b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
105869b46751STobias Grosser       printKernel(Kernel);
105969b46751STobias Grosser     }
106069b46751STobias Grosser   }
106169b46751STobias Grosser 
1062f384594dSTobias Grosser   // Generate a GPU program using PPCG.
1063f384594dSTobias Grosser   //
1064f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
1065f384594dSTobias Grosser   //
1066f384594dSTobias Grosser   //  1) Compute new schedule for the program.
1067f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
1068f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
1069f384594dSTobias Grosser   //
1070f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
1071f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
1072f384594dSTobias Grosser   // strategy directly from this pass.
1073f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
1074f384594dSTobias Grosser 
1075f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
1076f384594dSTobias Grosser 
1077f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
1078f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
1079f384594dSTobias Grosser     PPCGGen->print = nullptr;
1080f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
108160c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
1082f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
1083f384594dSTobias Grosser     PPCGGen->tree = nullptr;
1084f384594dSTobias Grosser     PPCGGen->types.n = 0;
1085f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
1086f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
1087f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
1088f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
1089f384594dSTobias Grosser 
1090f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
1091f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
1092f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
10932341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
1094f384594dSTobias Grosser 
1095f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
1096f384594dSTobias Grosser 
1097aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
1098aef5196fSTobias Grosser 
109969b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
1100aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
110169b46751STobias Grosser     } else {
1102aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
110369b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
110469b46751STobias Grosser     }
1105aef5196fSTobias Grosser 
1106f384594dSTobias Grosser     if (DumpSchedule) {
1107f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
1108f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
1109f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
1110f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
1111f384594dSTobias Grosser       if (Schedule)
1112f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
1113f384594dSTobias Grosser       else
1114f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
1115f384594dSTobias Grosser 
1116f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
1117f384594dSTobias Grosser       isl_printer_free(P);
1118f384594dSTobias Grosser     }
1119f384594dSTobias Grosser 
112069b46751STobias Grosser     if (DumpCode) {
112169b46751STobias Grosser       printf("Code\n");
112269b46751STobias Grosser       printf("====\n");
112369b46751STobias Grosser       if (PPCGGen->tree)
112469b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
112569b46751STobias Grosser       else
112669b46751STobias Grosser         printf("No code generated\n");
112769b46751STobias Grosser     }
112869b46751STobias Grosser 
1129f384594dSTobias Grosser     isl_schedule_free(Schedule);
1130f384594dSTobias Grosser 
1131f384594dSTobias Grosser     return PPCGGen;
1132f384594dSTobias Grosser   }
1133f384594dSTobias Grosser 
1134f384594dSTobias Grosser   /// Free gpu_gen structure.
1135f384594dSTobias Grosser   ///
1136f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
1137f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
1138f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
1139f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
1140f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
1141f384594dSTobias Grosser     free(PPCGGen);
1142f384594dSTobias Grosser   }
1143f384594dSTobias Grosser 
1144b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
1145b307ed4dSTobias Grosser   ///
1146b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
1147b307ed4dSTobias Grosser   /// ourselves.
1148b307ed4dSTobias Grosser   ///
1149b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
1150b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
1151b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
1152b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
1153b307ed4dSTobias Grosser     free(PPCGScop->options);
1154b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
1155b307ed4dSTobias Grosser   }
1156b307ed4dSTobias Grosser 
115738fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
115838fc0aedSTobias Grosser   ///
115932837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
116032837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
116132837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
116238fc0aedSTobias Grosser     ScopAnnotator Annotator;
116338fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
116438fc0aedSTobias Grosser 
116538fc0aedSTobias Grosser     Region *R = &S->getRegion();
116638fc0aedSTobias Grosser 
116738fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
116838fc0aedSTobias Grosser 
116938fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
117038fc0aedSTobias Grosser 
117138fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
117238fc0aedSTobias Grosser 
117332837fe3STobias Grosser     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S,
117432837fe3STobias Grosser                                Prog);
117538fc0aedSTobias Grosser 
117638fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
117738fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
117838fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
117938fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
118038fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
118138fc0aedSTobias Grosser     // code generating this scop.
118238fc0aedSTobias Grosser     BasicBlock *StartBlock =
118338fc0aedSTobias Grosser         executeScopConditionally(*S, this, Builder.getTrue());
118438fc0aedSTobias Grosser 
118538fc0aedSTobias Grosser     // TODO: Handle LICM
118638fc0aedSTobias Grosser     // TODO: Verify run-time checks
118738fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
118838fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
118938fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
119038fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
119138fc0aedSTobias Grosser     NodeBuilder.create(Root);
119238fc0aedSTobias Grosser     NodeBuilder.finalizeSCoP(*S);
119338fc0aedSTobias Grosser   }
119438fc0aedSTobias Grosser 
1195e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
1196e938517eSTobias Grosser     S = &CurrentScop;
119738fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
119838fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
119938fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
120038fc0aedSTobias Grosser     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
120138fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
1202e938517eSTobias Grosser 
12032d58a64eSTobias Grosser     // We currently do not support scops with invariant loads.
12042d58a64eSTobias Grosser     if (S->hasInvariantAccesses())
12052d58a64eSTobias Grosser       return false;
12062d58a64eSTobias Grosser 
1207e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
1208e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
1209f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
121038fc0aedSTobias Grosser 
121138fc0aedSTobias Grosser     if (PPCGGen->tree)
121232837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
121338fc0aedSTobias Grosser 
1214b307ed4dSTobias Grosser     freeOptions(PPCGScop);
1215f384594dSTobias Grosser     freePPCGGen(PPCGGen);
1216e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
1217e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
1218e938517eSTobias Grosser 
1219e938517eSTobias Grosser     return true;
1220e938517eSTobias Grosser   }
12219dfe4e7cSTobias Grosser 
12229dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
12239dfe4e7cSTobias Grosser 
12249dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
12259dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
12269dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
12279dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
12289dfe4e7cSTobias Grosser     AU.addRequired<ScopDetection>();
12299dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
12309dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
12319dfe4e7cSTobias Grosser 
12329dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
12339dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
12349dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
12359dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
12369dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
12379dfe4e7cSTobias Grosser     AU.addPreserved<PostDominatorTreeWrapperPass>();
12389dfe4e7cSTobias Grosser     AU.addPreserved<ScopDetection>();
12399dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
12409dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
12419dfe4e7cSTobias Grosser 
12429dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
12439dfe4e7cSTobias Grosser     //        region tree.
12449dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
12459dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
12469dfe4e7cSTobias Grosser   }
12479dfe4e7cSTobias Grosser };
12489dfe4e7cSTobias Grosser }
12499dfe4e7cSTobias Grosser 
12509dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
12519dfe4e7cSTobias Grosser 
12529dfe4e7cSTobias Grosser Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
12539dfe4e7cSTobias Grosser 
12549dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
12559dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
12569dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
12579dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
12589dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
12599dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
12609dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
12619dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScopDetection);
12629dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
12639dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
1264