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 
5432837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
5532837fe3STobias Grosser                                   cl::desc("Dump the kernel LLVM-IR"),
5632837fe3STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
5732837fe3STobias Grosser                                   cl::cat(PollyCategory));
5832837fe3STobias 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,
8832837fe3STobias Grosser                  DominatorTree &DT, Scop &S, gpu_prog *Prog)
8932837fe3STobias Grosser       : IslNodeBuilder(Builder, Annotator, P, DL, LI, SE, DT, S), Prog(Prog) {}
9038fc0aedSTobias Grosser 
9138fc0aedSTobias Grosser private:
9232837fe3STobias Grosser   /// A module containing GPU code.
9332837fe3STobias Grosser   ///
9432837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
9532837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
9632837fe3STobias Grosser 
9732837fe3STobias Grosser   /// The GPU program we generate code for.
9832837fe3STobias Grosser   gpu_prog *Prog;
9932837fe3STobias Grosser 
100472f9654STobias Grosser   /// Class to free isl_ids.
101472f9654STobias Grosser   class IslIdDeleter {
102472f9654STobias Grosser   public:
103472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
104472f9654STobias Grosser   };
105472f9654STobias Grosser 
106472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
107472f9654STobias Grosser   ///
108472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
109472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
110472f9654STobias Grosser 
11138fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
11238fc0aedSTobias Grosser   ///
11338fc0aedSTobias Grosser   /// These AST nodes can be of type:
11438fc0aedSTobias Grosser   ///
11538fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
11638fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
11738fc0aedSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer (TODO)
11838fc0aedSTobias Grosser   ///
1191fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
1201fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
12132837fe3STobias Grosser 
12232837fe3STobias Grosser   /// Create GPU kernel.
12332837fe3STobias Grosser   ///
12432837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
12532837fe3STobias Grosser   ///
12632837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
12732837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
12832837fe3STobias Grosser 
12932837fe3STobias Grosser   /// Create kernel function.
13032837fe3STobias Grosser   ///
13132837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
13232837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
13332837fe3STobias Grosser   /// start block of this newly created function.
13432837fe3STobias Grosser   ///
13532837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
13632837fe3STobias Grosser   void createKernelFunction(ppcg_kernel *Kernel);
13732837fe3STobias Grosser 
13832837fe3STobias Grosser   /// Create the declaration of a kernel function.
13932837fe3STobias Grosser   ///
14032837fe3STobias Grosser   /// The kernel function takes as arguments:
14132837fe3STobias Grosser   ///
14232837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
143f6044bd0STobias Grosser   ///   - Host iterators
144*c84a1995STobias Grosser   ///   - Parameters
14532837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
14632837fe3STobias Grosser   ///
14732837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
14832837fe3STobias Grosser   /// @returns The newly declared function.
14932837fe3STobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel);
15032837fe3STobias Grosser 
151472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
152472f9654STobias Grosser   ///
153472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
154472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
155472f9654STobias Grosser 
15632837fe3STobias Grosser   /// Finalize the generation of the kernel function.
15732837fe3STobias Grosser   ///
15832837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
15932837fe3STobias Grosser   /// dump its IR to stderr.
16032837fe3STobias Grosser   void finalizeKernelFunction();
1611fb9b64dSTobias Grosser };
1621fb9b64dSTobias Grosser 
1631fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
16432837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
16532837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
16632837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
16732837fe3STobias Grosser   isl_id_free(Id);
16832837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
16932837fe3STobias Grosser 
17032837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
17132837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
17232837fe3STobias Grosser     createKernel(UserStmt);
17332837fe3STobias Grosser     isl_ast_expr_free(Expr);
17432837fe3STobias Grosser     return;
17532837fe3STobias Grosser   }
17632837fe3STobias Grosser 
17732837fe3STobias Grosser   isl_ast_expr_free(Expr);
1781fb9b64dSTobias Grosser   isl_ast_node_free(UserStmt);
17938fc0aedSTobias Grosser   return;
18038fc0aedSTobias Grosser }
18138fc0aedSTobias Grosser 
18232837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
18332837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
18432837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
18532837fe3STobias Grosser   isl_id_free(Id);
18632837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
18732837fe3STobias Grosser 
18832837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
18932837fe3STobias Grosser 
19032837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
191472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
19232837fe3STobias Grosser 
19332837fe3STobias Grosser   createKernelFunction(Kernel);
19432837fe3STobias Grosser 
19532837fe3STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
196472f9654STobias Grosser   IDToValue = HostIDs;
19732837fe3STobias Grosser 
19832837fe3STobias Grosser   finalizeKernelFunction();
19932837fe3STobias Grosser }
20032837fe3STobias Grosser 
20132837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
20232837fe3STobias Grosser ///
20332837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
20432837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
20532837fe3STobias Grosser   std::string Ret = "e";
20632837fe3STobias Grosser 
20732837fe3STobias Grosser   if (!is64Bit)
20832837fe3STobias Grosser     Ret += "-p:32:32";
20932837fe3STobias Grosser 
21032837fe3STobias Grosser   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
21132837fe3STobias Grosser 
21232837fe3STobias Grosser   return Ret;
21332837fe3STobias Grosser }
21432837fe3STobias Grosser 
21532837fe3STobias Grosser Function *GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel) {
21632837fe3STobias Grosser   std::vector<Type *> Args;
21732837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
21832837fe3STobias Grosser 
21932837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
22032837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
22132837fe3STobias Grosser       continue;
22232837fe3STobias Grosser 
22332837fe3STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
22432837fe3STobias Grosser   }
22532837fe3STobias Grosser 
226f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
227f6044bd0STobias Grosser 
228f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++)
229f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
230f6044bd0STobias Grosser 
231*c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
232*c84a1995STobias Grosser 
233*c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++)
234*c84a1995STobias Grosser     Args.push_back(Builder.getInt64Ty());
235*c84a1995STobias Grosser 
23632837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
23732837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
23832837fe3STobias Grosser                               GPUModule.get());
23932837fe3STobias Grosser   FN->setCallingConv(CallingConv::PTX_Kernel);
24032837fe3STobias Grosser 
24132837fe3STobias Grosser   auto Arg = FN->arg_begin();
24232837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
24332837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
24432837fe3STobias Grosser       continue;
24532837fe3STobias Grosser 
24632837fe3STobias Grosser     Arg->setName(Prog->array[i].name);
24732837fe3STobias Grosser     Arg++;
24832837fe3STobias Grosser   }
24932837fe3STobias Grosser 
250f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
251f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
252f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
253f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
254f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
255f6044bd0STobias Grosser     Arg++;
256f6044bd0STobias Grosser   }
257f6044bd0STobias Grosser 
258*c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
259*c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
260*c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
261*c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
262*c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
263*c84a1995STobias Grosser     Arg++;
264*c84a1995STobias Grosser   }
265*c84a1995STobias Grosser 
26632837fe3STobias Grosser   return FN;
26732837fe3STobias Grosser }
26832837fe3STobias Grosser 
269472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
270472f9654STobias Grosser   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
271472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
272472f9654STobias Grosser 
273472f9654STobias Grosser   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
274472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
275472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
276472f9654STobias Grosser 
277472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
278472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
279472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
280472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
281472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
282472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
283472f9654STobias Grosser     IDToValue[Id] = Val;
284472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
285472f9654STobias Grosser   };
286472f9654STobias Grosser 
287472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
288472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
289472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
290472f9654STobias Grosser   }
291472f9654STobias Grosser 
292472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
293472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
294472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
295472f9654STobias Grosser   }
296472f9654STobias Grosser }
297472f9654STobias Grosser 
29832837fe3STobias Grosser void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel) {
29932837fe3STobias Grosser 
30032837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
30132837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
30232837fe3STobias Grosser   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
30332837fe3STobias Grosser   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
30432837fe3STobias Grosser 
30532837fe3STobias Grosser   Function *FN = createKernelFunctionDecl(Kernel);
30632837fe3STobias Grosser 
30732837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
30832837fe3STobias Grosser 
30932837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
31032837fe3STobias Grosser   Builder.CreateRetVoid();
31132837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
312472f9654STobias Grosser 
313472f9654STobias Grosser   insertKernelIntrinsics(Kernel);
31432837fe3STobias Grosser }
31532837fe3STobias Grosser 
31632837fe3STobias Grosser void GPUNodeBuilder::finalizeKernelFunction() {
31732837fe3STobias Grosser 
31832837fe3STobias Grosser   if (DumpKernelIR)
31932837fe3STobias Grosser     outs() << *GPUModule << "\n";
32032837fe3STobias Grosser 
32132837fe3STobias Grosser   GPUModule.release();
322472f9654STobias Grosser   KernelIDs.clear();
32332837fe3STobias Grosser }
32432837fe3STobias Grosser 
3259dfe4e7cSTobias Grosser namespace {
3269dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
3279dfe4e7cSTobias Grosser public:
3289dfe4e7cSTobias Grosser   static char ID;
3299dfe4e7cSTobias Grosser 
330e938517eSTobias Grosser   /// The scop that is currently processed.
331e938517eSTobias Grosser   Scop *S;
332e938517eSTobias Grosser 
33338fc0aedSTobias Grosser   LoopInfo *LI;
33438fc0aedSTobias Grosser   DominatorTree *DT;
33538fc0aedSTobias Grosser   ScalarEvolution *SE;
33638fc0aedSTobias Grosser   const DataLayout *DL;
33738fc0aedSTobias Grosser   RegionInfo *RI;
33838fc0aedSTobias Grosser 
3399dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
3409dfe4e7cSTobias Grosser 
341e938517eSTobias Grosser   /// Construct compilation options for PPCG.
342e938517eSTobias Grosser   ///
343e938517eSTobias Grosser   /// @returns The compilation options.
344e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
345e938517eSTobias Grosser     auto DebugOptions =
346e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
347e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
348e938517eSTobias Grosser 
349e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
350e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
351e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
352e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
353e938517eSTobias Grosser 
354e938517eSTobias Grosser     Options->debug = DebugOptions;
355e938517eSTobias Grosser 
356e938517eSTobias Grosser     Options->reschedule = true;
357e938517eSTobias Grosser     Options->scale_tile_loops = false;
358e938517eSTobias Grosser     Options->wrap = false;
359e938517eSTobias Grosser 
360e938517eSTobias Grosser     Options->non_negative_parameters = false;
361e938517eSTobias Grosser     Options->ctx = nullptr;
362e938517eSTobias Grosser     Options->sizes = nullptr;
363e938517eSTobias Grosser 
3644eaedde5STobias Grosser     Options->tile_size = 32;
3654eaedde5STobias Grosser 
366e938517eSTobias Grosser     Options->use_private_memory = false;
367e938517eSTobias Grosser     Options->use_shared_memory = false;
368e938517eSTobias Grosser     Options->max_shared_memory = 0;
369e938517eSTobias Grosser 
370e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
371e938517eSTobias Grosser     Options->openmp = false;
372e938517eSTobias Grosser     Options->linearize_device_arrays = true;
373e938517eSTobias Grosser     Options->live_range_reordering = false;
374e938517eSTobias Grosser 
375e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
376e938517eSTobias Grosser     Options->opencl_use_gpu = false;
377e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
378e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
379e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
380e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
381e938517eSTobias Grosser 
382e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
383e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
384e938517eSTobias Grosser 
385e938517eSTobias Grosser     return Options;
386e938517eSTobias Grosser   }
387e938517eSTobias Grosser 
388f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
389f384594dSTobias Grosser   ///
390f384594dSTobias Grosser   /// Instead of a normal access of the form:
391f384594dSTobias Grosser   ///
392f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
393f384594dSTobias Grosser   ///
394f384594dSTobias Grosser   /// a tagged access has the form
395f384594dSTobias Grosser   ///
396f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
397f384594dSTobias Grosser   ///
398f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
399f384594dSTobias Grosser   /// triggered the access.
400f384594dSTobias Grosser   ///
401f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
402f384594dSTobias Grosser   ///
403f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
404f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
405f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
406f384594dSTobias Grosser 
407f384594dSTobias Grosser     for (auto &Stmt : *S)
408f384594dSTobias Grosser       for (auto &Acc : Stmt)
409f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
410f384594dSTobias Grosser           isl_map *Relation = Acc->getAccessRelation();
411f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
412f384594dSTobias Grosser 
413f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
414f384594dSTobias Grosser           Space = isl_space_range(Space);
415f384594dSTobias Grosser           Space = isl_space_from_range(Space);
4166293ba69STobias Grosser           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
417f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
418f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
419f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
420f384594dSTobias Grosser         }
421f384594dSTobias Grosser 
422f384594dSTobias Grosser     return Accesses;
423f384594dSTobias Grosser   }
424f384594dSTobias Grosser 
425f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
426f384594dSTobias Grosser   ///
427f384594dSTobias Grosser   /// @see getTaggedAccesses
428f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
429f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
430f384594dSTobias Grosser   }
431f384594dSTobias Grosser 
432f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
433f384594dSTobias Grosser   ///
434f384594dSTobias Grosser   /// @see getTaggedAccesses
435f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
436f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
437f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
438f384594dSTobias Grosser   }
439f384594dSTobias Grosser 
440f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
441f384594dSTobias Grosser   ///
442f384594dSTobias Grosser   /// @see getTaggedAccesses
443f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
444f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
445f384594dSTobias Grosser   }
446f384594dSTobias Grosser 
447aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
448aef5196fSTobias Grosser   ///
449aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
450aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
451aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
452aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
453aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
454aef5196fSTobias Grosser   /// the data format that ppcg expects.
455aef5196fSTobias Grosser   ///
456aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
457aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
458aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
459bd81a7eeSTobias Grosser         S->getIslCtx(),
460bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
461aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
462aef5196fSTobias Grosser     auto *Space = S->getParamSpace();
463aef5196fSTobias Grosser 
464aef5196fSTobias Grosser     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
465aef5196fSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
466aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
467aef5196fSTobias Grosser     }
468aef5196fSTobias Grosser 
469aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
470aef5196fSTobias Grosser       auto Id = Array.second->getBasePtrId();
471aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
472aef5196fSTobias Grosser     }
473aef5196fSTobias Grosser 
474aef5196fSTobias Grosser     isl_space_free(Space);
475aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
476aef5196fSTobias Grosser 
477aef5196fSTobias Grosser     return Names;
478aef5196fSTobias Grosser   }
479aef5196fSTobias Grosser 
480e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
481e938517eSTobias Grosser   ///
482f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
483f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
484f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
485f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
486e938517eSTobias Grosser   ///
487e938517eSTobias Grosser   /// @returns A new ppcg scop.
488e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
489e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
490e938517eSTobias Grosser 
491e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
492e938517eSTobias Grosser 
493e938517eSTobias Grosser     PPCGScop->start = 0;
494e938517eSTobias Grosser     PPCGScop->end = 0;
495e938517eSTobias Grosser 
496f384594dSTobias Grosser     PPCGScop->context = S->getContext();
497f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
498e938517eSTobias Grosser     PPCGScop->call = nullptr;
499f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
500f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
501e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
502f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
503f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
504f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
505f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
506e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
507f384594dSTobias Grosser     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
508e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
509e938517eSTobias Grosser 
510e938517eSTobias Grosser     PPCGScop->independence = nullptr;
511e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
512e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
513e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
514e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
515e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
516e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
517e938517eSTobias Grosser 
518f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
519aef5196fSTobias Grosser     PPCGScop->names = getNames();
520e938517eSTobias Grosser 
521e938517eSTobias Grosser     PPCGScop->pet = nullptr;
522e938517eSTobias Grosser 
523f384594dSTobias Grosser     compute_tagger(PPCGScop);
524f384594dSTobias Grosser     compute_dependences(PPCGScop);
525f384594dSTobias Grosser 
526e938517eSTobias Grosser     return PPCGScop;
527e938517eSTobias Grosser   }
528e938517eSTobias Grosser 
52960f63b49STobias Grosser   /// Collect the array acesses in a statement.
53060f63b49STobias Grosser   ///
53160f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
53260f63b49STobias Grosser   ///
53360f63b49STobias Grosser   /// @returns A list of array accesses.
53460f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
53560f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
53660f63b49STobias Grosser 
53760f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
53860f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
53960f63b49STobias Grosser       Access->read = Acc->isRead();
54060f63b49STobias Grosser       Access->write = Acc->isWrite();
54160f63b49STobias Grosser       Access->access = Acc->getAccessRelation();
54260f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
54360f63b49STobias Grosser       Space = isl_space_range(Space);
54460f63b49STobias Grosser       Space = isl_space_from_range(Space);
5456293ba69STobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
54660f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
54760f63b49STobias Grosser       Access->tagged_access =
54860f63b49STobias Grosser           isl_map_domain_product(Acc->getAccessRelation(), Universe);
54960f63b49STobias Grosser       Access->exact_write = Acc->isWrite();
55060f63b49STobias Grosser       Access->ref_id = Acc->getId();
55160f63b49STobias Grosser       Access->next = Accesses;
55260f63b49STobias Grosser       Accesses = Access;
55360f63b49STobias Grosser     }
55460f63b49STobias Grosser 
55560f63b49STobias Grosser     return Accesses;
55660f63b49STobias Grosser   }
55760f63b49STobias Grosser 
55869b46751STobias Grosser   /// Collect the list of GPU statements.
55969b46751STobias Grosser   ///
56069b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
56169b46751STobias Grosser   /// as well as a list with all memory accesses.
56269b46751STobias Grosser   ///
56369b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
56469b46751STobias Grosser   ///
56569b46751STobias Grosser   /// @returns A linked-list of statements.
56669b46751STobias Grosser   gpu_stmt *getStatements() {
56769b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
56869b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
56969b46751STobias Grosser 
57069b46751STobias Grosser     int i = 0;
57169b46751STobias Grosser     for (auto &Stmt : *S) {
57269b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
57369b46751STobias Grosser 
57469b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
57569b46751STobias Grosser 
57669b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
57769b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
57860f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
57969b46751STobias Grosser       i++;
58069b46751STobias Grosser     }
58169b46751STobias Grosser 
58269b46751STobias Grosser     return Stmts;
58369b46751STobias Grosser   }
58469b46751STobias Grosser 
58560f63b49STobias Grosser   /// Derive the extent of an array.
58660f63b49STobias Grosser   ///
58760f63b49STobias Grosser   /// The extent of an array is defined by the set of memory locations for
58860f63b49STobias Grosser   /// which a memory access in the iteration domain exists.
58960f63b49STobias Grosser   ///
59060f63b49STobias Grosser   /// @param Array The array to derive the extent for.
59160f63b49STobias Grosser   ///
59260f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
59360f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
59460f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
59560f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
59660f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
59760f63b49STobias Grosser     isl_set *AccessSet =
59860f63b49STobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace());
59960f63b49STobias Grosser     isl_union_set_free(AccessUSet);
60060f63b49STobias Grosser 
60160f63b49STobias Grosser     return AccessSet;
60260f63b49STobias Grosser   }
60360f63b49STobias Grosser 
60460f63b49STobias Grosser   /// Derive the bounds of an array.
60560f63b49STobias Grosser   ///
60660f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
60760f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
60860f63b49STobias Grosser   /// ScopArrayInfo.
60960f63b49STobias Grosser   ///
61060f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
61160f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
61260f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
61360f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
61460f63b49STobias Grosser       isl_set *Dom = isl_set_copy(PPCGArray.extent);
61560f63b49STobias Grosser       Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
61660f63b49STobias Grosser       isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
61760f63b49STobias Grosser       isl_set_free(Dom);
61860f63b49STobias Grosser       Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
61960f63b49STobias Grosser       isl_local_space *LS = isl_local_space_from_space(isl_set_get_space(Dom));
62060f63b49STobias Grosser       isl_aff *One = isl_aff_zero_on_domain(LS);
62160f63b49STobias Grosser       One = isl_aff_add_constant_si(One, 1);
62260f63b49STobias Grosser       Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
62360f63b49STobias Grosser       Bound = isl_pw_aff_gist(Bound, S->getContext());
62460f63b49STobias Grosser       PPCGArray.bound[0] = Bound;
62560f63b49STobias Grosser     }
62660f63b49STobias Grosser 
62760f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
62860f63b49STobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
62960f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
63060f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
63160f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
63260f63b49STobias Grosser       PPCGArray.bound[i] = Bound;
63360f63b49STobias Grosser     }
63460f63b49STobias Grosser   }
63560f63b49STobias Grosser 
63660f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
63760f63b49STobias Grosser   ///
63860f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
63960f63b49STobias Grosser   void createArrays(gpu_prog *PPCGProg) {
64060f63b49STobias Grosser     int i = 0;
64160f63b49STobias Grosser     for (auto &Element : S->arrays()) {
64260f63b49STobias Grosser       ScopArrayInfo *Array = Element.second.get();
64360f63b49STobias Grosser 
64460f63b49STobias Grosser       std::string TypeName;
64560f63b49STobias Grosser       raw_string_ostream OS(TypeName);
64660f63b49STobias Grosser 
64760f63b49STobias Grosser       OS << *Array->getElementType();
64860f63b49STobias Grosser       TypeName = OS.str();
64960f63b49STobias Grosser 
65060f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
65160f63b49STobias Grosser 
65260f63b49STobias Grosser       PPCGArray.space = Array->getSpace();
65360f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
65460f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
65560f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
65660f63b49STobias Grosser       PPCGArray.extent = nullptr;
65760f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
65860f63b49STobias Grosser       PPCGArray.bound =
65960f63b49STobias Grosser           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
66060f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
66160f63b49STobias Grosser       PPCGArray.n_ref = 0;
66260f63b49STobias Grosser       PPCGArray.refs = nullptr;
66360f63b49STobias Grosser       PPCGArray.accessed = true;
66460f63b49STobias Grosser       PPCGArray.read_only_scalar = false;
66560f63b49STobias Grosser       PPCGArray.has_compound_element = false;
66660f63b49STobias Grosser       PPCGArray.local = false;
66760f63b49STobias Grosser       PPCGArray.declare_local = false;
66860f63b49STobias Grosser       PPCGArray.global = false;
66960f63b49STobias Grosser       PPCGArray.linearize = false;
67060f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
67160f63b49STobias Grosser 
67260f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
6732d010dafSTobias Grosser       i++;
674b9fc860aSTobias Grosser 
675b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
67660f63b49STobias Grosser     }
67760f63b49STobias Grosser   }
67860f63b49STobias Grosser 
67960f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
68060f63b49STobias Grosser   ///
68160f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
68260f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
68360f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
68460f63b49STobias Grosser 
68560f63b49STobias Grosser     for (auto &Item : S->arrays()) {
68660f63b49STobias Grosser       ScopArrayInfo *Array = Item.second.get();
68760f63b49STobias Grosser       isl_space *Space = Array->getSpace();
68860f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
68960f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
69060f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
69160f63b49STobias Grosser     }
69260f63b49STobias Grosser 
69360f63b49STobias Grosser     return Maps;
69460f63b49STobias Grosser   }
69560f63b49STobias Grosser 
696e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
697e938517eSTobias Grosser   ///
698e938517eSTobias Grosser   /// @returns A new gpu grogram description.
699e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
700e938517eSTobias Grosser 
701e938517eSTobias Grosser     if (!PPCGScop)
702e938517eSTobias Grosser       return nullptr;
703e938517eSTobias Grosser 
704e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
705e938517eSTobias Grosser 
706e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
707e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
708aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
70960f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
71060f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
71160f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
71260f63b49STobias Grosser     PPCGProg->tagged_must_kill =
71360f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
71460f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
71560f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
71660f63b49STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
717e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
718e938517eSTobias Grosser     PPCGProg->array_order = nullptr;
71969b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
72069b46751STobias Grosser     PPCGProg->stmts = getStatements();
72160f63b49STobias Grosser     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
72260f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
72360f63b49STobias Grosser                                        PPCGProg->n_array);
72460f63b49STobias Grosser 
72560f63b49STobias Grosser     createArrays(PPCGProg);
726e938517eSTobias Grosser 
727e938517eSTobias Grosser     return PPCGProg;
728e938517eSTobias Grosser   }
729e938517eSTobias Grosser 
73069b46751STobias Grosser   struct PrintGPUUserData {
73169b46751STobias Grosser     struct cuda_info *CudaInfo;
73269b46751STobias Grosser     struct gpu_prog *PPCGProg;
73369b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
73469b46751STobias Grosser   };
73569b46751STobias Grosser 
73669b46751STobias Grosser   /// Print a user statement node in the host code.
73769b46751STobias Grosser   ///
73869b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
73969b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
74069b46751STobias Grosser   /// host ast.
74169b46751STobias Grosser   ///
74269b46751STobias Grosser   /// @param P The printer to print to
74369b46751STobias Grosser   /// @param Options The printing options to use
74469b46751STobias Grosser   /// @param Node The node to print
74569b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
74669b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
74769b46751STobias Grosser   ///
74869b46751STobias Grosser   /// @returns A printer to which the output has been printed.
74969b46751STobias Grosser   static __isl_give isl_printer *
75069b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
75169b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
75269b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
75369b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
75469b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
75569b46751STobias Grosser 
75669b46751STobias Grosser     if (Id) {
75720251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
75820251734STobias Grosser 
75920251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
76020251734STobias Grosser       // otherwise try to call pet functionality that is not available in
76120251734STobias Grosser       // Polly.
76220251734STobias Grosser       if (IsUser) {
76320251734STobias Grosser         P = isl_printer_start_line(P);
76420251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
76520251734STobias Grosser         P = isl_printer_end_line(P);
76620251734STobias Grosser         isl_id_free(Id);
76720251734STobias Grosser         isl_ast_print_options_free(Options);
76820251734STobias Grosser         return P;
76920251734STobias Grosser       }
77020251734STobias Grosser 
77169b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
77269b46751STobias Grosser       isl_id_free(Id);
77369b46751STobias Grosser       Data->Kernels.push_back(Kernel);
77469b46751STobias Grosser     }
77569b46751STobias Grosser 
77669b46751STobias Grosser     return print_host_user(P, Options, Node, User);
77769b46751STobias Grosser   }
77869b46751STobias Grosser 
77969b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
78069b46751STobias Grosser   ///
78169b46751STobias Grosser   /// @param Kernel The kernel to print
78269b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
78369b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
78469b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
78569b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
78669b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
78769b46751STobias Grosser     char *String = isl_printer_get_str(P);
78869b46751STobias Grosser     printf("%s\n", String);
78969b46751STobias Grosser     free(String);
79069b46751STobias Grosser     isl_printer_free(P);
79169b46751STobias Grosser   }
79269b46751STobias Grosser 
79369b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
79469b46751STobias Grosser   ///
79569b46751STobias Grosser   /// @param Tree An AST describing GPU code
79669b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
79769b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
79869b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
79969b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
80069b46751STobias Grosser 
80169b46751STobias Grosser     PrintGPUUserData Data;
80269b46751STobias Grosser     Data.PPCGProg = PPCGProg;
80369b46751STobias Grosser 
80469b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
80569b46751STobias Grosser     Options =
80669b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
80769b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
80869b46751STobias Grosser     char *String = isl_printer_get_str(P);
80969b46751STobias Grosser     printf("# host\n");
81069b46751STobias Grosser     printf("%s\n", String);
81169b46751STobias Grosser     free(String);
81269b46751STobias Grosser     isl_printer_free(P);
81369b46751STobias Grosser 
81469b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
81569b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
81669b46751STobias Grosser       printKernel(Kernel);
81769b46751STobias Grosser     }
81869b46751STobias Grosser   }
81969b46751STobias Grosser 
820f384594dSTobias Grosser   // Generate a GPU program using PPCG.
821f384594dSTobias Grosser   //
822f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
823f384594dSTobias Grosser   //
824f384594dSTobias Grosser   //  1) Compute new schedule for the program.
825f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
826f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
827f384594dSTobias Grosser   //
828f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
829f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
830f384594dSTobias Grosser   // strategy directly from this pass.
831f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
832f384594dSTobias Grosser 
833f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
834f384594dSTobias Grosser 
835f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
836f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
837f384594dSTobias Grosser     PPCGGen->print = nullptr;
838f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
83960c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
840f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
841f384594dSTobias Grosser     PPCGGen->tree = nullptr;
842f384594dSTobias Grosser     PPCGGen->types.n = 0;
843f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
844f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
845f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
846f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
847f384594dSTobias Grosser 
848f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
849f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
850f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
8512341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
852f384594dSTobias Grosser 
853f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
854f384594dSTobias Grosser 
855aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
856aef5196fSTobias Grosser 
85769b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
858aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
85969b46751STobias Grosser     } else {
860aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
86169b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
86269b46751STobias Grosser     }
863aef5196fSTobias Grosser 
864f384594dSTobias Grosser     if (DumpSchedule) {
865f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
866f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
867f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
868f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
869f384594dSTobias Grosser       if (Schedule)
870f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
871f384594dSTobias Grosser       else
872f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
873f384594dSTobias Grosser 
874f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
875f384594dSTobias Grosser       isl_printer_free(P);
876f384594dSTobias Grosser     }
877f384594dSTobias Grosser 
87869b46751STobias Grosser     if (DumpCode) {
87969b46751STobias Grosser       printf("Code\n");
88069b46751STobias Grosser       printf("====\n");
88169b46751STobias Grosser       if (PPCGGen->tree)
88269b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
88369b46751STobias Grosser       else
88469b46751STobias Grosser         printf("No code generated\n");
88569b46751STobias Grosser     }
88669b46751STobias Grosser 
887f384594dSTobias Grosser     isl_schedule_free(Schedule);
888f384594dSTobias Grosser 
889f384594dSTobias Grosser     return PPCGGen;
890f384594dSTobias Grosser   }
891f384594dSTobias Grosser 
892f384594dSTobias Grosser   /// Free gpu_gen structure.
893f384594dSTobias Grosser   ///
894f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
895f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
896f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
897f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
898f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
899f384594dSTobias Grosser     free(PPCGGen);
900f384594dSTobias Grosser   }
901f384594dSTobias Grosser 
902b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
903b307ed4dSTobias Grosser   ///
904b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
905b307ed4dSTobias Grosser   /// ourselves.
906b307ed4dSTobias Grosser   ///
907b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
908b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
909b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
910b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
911b307ed4dSTobias Grosser     free(PPCGScop->options);
912b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
913b307ed4dSTobias Grosser   }
914b307ed4dSTobias Grosser 
91538fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
91638fc0aedSTobias Grosser   ///
91732837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
91832837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
91932837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
92038fc0aedSTobias Grosser     ScopAnnotator Annotator;
92138fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
92238fc0aedSTobias Grosser 
92338fc0aedSTobias Grosser     Region *R = &S->getRegion();
92438fc0aedSTobias Grosser 
92538fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
92638fc0aedSTobias Grosser 
92738fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
92838fc0aedSTobias Grosser 
92938fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
93038fc0aedSTobias Grosser 
93132837fe3STobias Grosser     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S,
93232837fe3STobias Grosser                                Prog);
93338fc0aedSTobias Grosser 
93438fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
93538fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
93638fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
93738fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
93838fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
93938fc0aedSTobias Grosser     // code generating this scop.
94038fc0aedSTobias Grosser     BasicBlock *StartBlock =
94138fc0aedSTobias Grosser         executeScopConditionally(*S, this, Builder.getTrue());
94238fc0aedSTobias Grosser 
94338fc0aedSTobias Grosser     // TODO: Handle LICM
94438fc0aedSTobias Grosser     // TODO: Verify run-time checks
94538fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
94638fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
94738fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
94838fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
94938fc0aedSTobias Grosser     NodeBuilder.create(Root);
95038fc0aedSTobias Grosser     NodeBuilder.finalizeSCoP(*S);
95138fc0aedSTobias Grosser   }
95238fc0aedSTobias Grosser 
953e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
954e938517eSTobias Grosser     S = &CurrentScop;
95538fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
95638fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
95738fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
95838fc0aedSTobias Grosser     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
95938fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
960e938517eSTobias Grosser 
961e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
962e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
963f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
96438fc0aedSTobias Grosser 
96538fc0aedSTobias Grosser     if (PPCGGen->tree)
96632837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
96738fc0aedSTobias Grosser 
968b307ed4dSTobias Grosser     freeOptions(PPCGScop);
969f384594dSTobias Grosser     freePPCGGen(PPCGGen);
970e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
971e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
972e938517eSTobias Grosser 
973e938517eSTobias Grosser     return true;
974e938517eSTobias Grosser   }
9759dfe4e7cSTobias Grosser 
9769dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
9779dfe4e7cSTobias Grosser 
9789dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
9799dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
9809dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
9819dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
9829dfe4e7cSTobias Grosser     AU.addRequired<ScopDetection>();
9839dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
9849dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
9859dfe4e7cSTobias Grosser 
9869dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
9879dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
9889dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
9899dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
9909dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
9919dfe4e7cSTobias Grosser     AU.addPreserved<PostDominatorTreeWrapperPass>();
9929dfe4e7cSTobias Grosser     AU.addPreserved<ScopDetection>();
9939dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
9949dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
9959dfe4e7cSTobias Grosser 
9969dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
9979dfe4e7cSTobias Grosser     //        region tree.
9989dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
9999dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
10009dfe4e7cSTobias Grosser   }
10019dfe4e7cSTobias Grosser };
10029dfe4e7cSTobias Grosser }
10039dfe4e7cSTobias Grosser 
10049dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
10059dfe4e7cSTobias Grosser 
10069dfe4e7cSTobias Grosser Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
10079dfe4e7cSTobias Grosser 
10089dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
10099dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
10109dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
10119dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
10129dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
10139dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
10149dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
10159dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScopDetection);
10169dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
10179dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
1018