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"
21edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h"
2274dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h"
239dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h"
249dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h"
259dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h"
269dfe4e7cSTobias Grosser #include "llvm/Analysis/PostDominators.h"
279dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
2874dc3cb4STobias Grosser #include "llvm/Analysis/TargetLibraryInfo.h"
2974dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h"
3074dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h"
31e1a98343STobias Grosser #include "llvm/IR/Verifier.h"
3274dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h"
3374dc3cb4STobias Grosser #include "llvm/Support/TargetSelect.h"
3474dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h"
359a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h"
369dfe4e7cSTobias Grosser 
37f384594dSTobias Grosser #include "isl/union_map.h"
38f384594dSTobias Grosser 
39e938517eSTobias Grosser extern "C" {
40a56f8f8eSTobias Grosser #include "ppcg/cuda.h"
41a56f8f8eSTobias Grosser #include "ppcg/gpu.h"
42a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h"
43a56f8f8eSTobias Grosser #include "ppcg/ppcg.h"
44a56f8f8eSTobias Grosser #include "ppcg/schedule.h"
45e938517eSTobias Grosser }
46e938517eSTobias Grosser 
479dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h"
489dfe4e7cSTobias Grosser 
499dfe4e7cSTobias Grosser using namespace polly;
509dfe4e7cSTobias Grosser using namespace llvm;
519dfe4e7cSTobias Grosser 
529dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg"
539dfe4e7cSTobias Grosser 
54f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
55f384594dSTobias Grosser                                   cl::desc("Dump the computed GPU Schedule"),
56681bd568STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
57f384594dSTobias Grosser                                   cl::cat(PollyCategory));
5869b46751STobias Grosser 
5969b46751STobias Grosser static cl::opt<bool>
6069b46751STobias Grosser     DumpCode("polly-acc-dump-code",
6169b46751STobias Grosser              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
6269b46751STobias Grosser              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
6369b46751STobias Grosser 
6432837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
6532837fe3STobias Grosser                                   cl::desc("Dump the kernel LLVM-IR"),
6632837fe3STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
6732837fe3STobias Grosser                                   cl::cat(PollyCategory));
6832837fe3STobias Grosser 
6974dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
7074dc3cb4STobias Grosser                                    cl::desc("Dump the kernel assembly code"),
7174dc3cb4STobias Grosser                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
7274dc3cb4STobias Grosser                                    cl::cat(PollyCategory));
7374dc3cb4STobias Grosser 
7474dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath",
7574dc3cb4STobias Grosser                               cl::desc("Allow unsafe math optimizations"),
7674dc3cb4STobias Grosser                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
7774dc3cb4STobias Grosser                               cl::cat(PollyCategory));
7874dc3cb4STobias Grosser 
7974dc3cb4STobias Grosser static cl::opt<std::string>
8074dc3cb4STobias Grosser     CudaVersion("polly-acc-cuda-version",
8174dc3cb4STobias Grosser                 cl::desc("The CUDA version to compile for"), cl::Hidden,
8274dc3cb4STobias Grosser                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
8374dc3cb4STobias Grosser 
8460c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
8560c60025STobias Grosser ///
8660c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
8760c60025STobias Grosser /// of the scheduled ScopStmts.
8860c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
89edb885cbSTobias Grosser     void *StmtT, isl_ast_build *Build,
9060c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
9160c60025STobias Grosser                                        isl_id *Id, void *User),
9260c60025STobias Grosser     void *UserIndex,
9360c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
94edb885cbSTobias Grosser     void *UserExpr) {
9560c60025STobias Grosser 
96edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
9760c60025STobias Grosser 
98edb885cbSTobias Grosser   isl_ctx *Ctx;
99edb885cbSTobias Grosser 
100edb885cbSTobias Grosser   if (!Stmt || !Build)
101edb885cbSTobias Grosser     return NULL;
102edb885cbSTobias Grosser 
103edb885cbSTobias Grosser   Ctx = isl_ast_build_get_ctx(Build);
104edb885cbSTobias Grosser   isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0);
105edb885cbSTobias Grosser 
106edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
107edb885cbSTobias Grosser     isl_map *AddrFunc = Acc->getAddressFunction();
108edb885cbSTobias Grosser     AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain());
109edb885cbSTobias Grosser     isl_id *RefId = Acc->getId();
110edb885cbSTobias Grosser     isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc);
111edb885cbSTobias Grosser     isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA);
112edb885cbSTobias Grosser     MPA = isl_multi_pw_aff_coalesce(MPA);
113edb885cbSTobias Grosser     MPA = FunctionIndex(MPA, RefId, UserIndex);
114edb885cbSTobias Grosser     isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA);
115edb885cbSTobias Grosser     Access = FunctionExpr(Access, RefId, UserExpr);
116edb885cbSTobias Grosser     RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access);
117edb885cbSTobias Grosser   }
118edb885cbSTobias Grosser 
119edb885cbSTobias Grosser   return RefToExpr;
12060c60025STobias Grosser }
121f384594dSTobias Grosser 
12238fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
12338fc0aedSTobias Grosser ///
12438fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
12538fc0aedSTobias Grosser /// generates code for general-prupose AST nodes, with special functionality
12638fc0aedSTobias Grosser /// for generating GPU specific user nodes.
12738fc0aedSTobias Grosser ///
12838fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
12938fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
13038fc0aedSTobias Grosser public:
13138fc0aedSTobias Grosser   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P,
13238fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
13332837fe3STobias Grosser                  DominatorTree &DT, Scop &S, gpu_prog *Prog)
134edb885cbSTobias Grosser       : IslNodeBuilder(Builder, Annotator, P, DL, LI, SE, DT, S), Prog(Prog) {
135edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
136edb885cbSTobias Grosser   }
13738fc0aedSTobias Grosser 
138fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
139fa7b0802STobias Grosser   void initializeAfterRTH();
140fa7b0802STobias Grosser 
141fa7b0802STobias Grosser   /// Finalize the generated scop.
142fa7b0802STobias Grosser   virtual void finalize();
143fa7b0802STobias Grosser 
14438fc0aedSTobias Grosser private:
14574dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
14674dc3cb4STobias Grosser   ///
14774dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
14874dc3cb4STobias Grosser   /// more.
14974dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
15074dc3cb4STobias Grosser 
15113c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
15213c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
1537287aeddSTobias Grosser 
154fa7b0802STobias Grosser   /// The current GPU context.
155fa7b0802STobias Grosser   Value *GPUContext;
156fa7b0802STobias Grosser 
15732837fe3STobias Grosser   /// A module containing GPU code.
15832837fe3STobias Grosser   ///
15932837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
16032837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
16132837fe3STobias Grosser 
16232837fe3STobias Grosser   /// The GPU program we generate code for.
16332837fe3STobias Grosser   gpu_prog *Prog;
16432837fe3STobias Grosser 
165472f9654STobias Grosser   /// Class to free isl_ids.
166472f9654STobias Grosser   class IslIdDeleter {
167472f9654STobias Grosser   public:
168472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
169472f9654STobias Grosser   };
170472f9654STobias Grosser 
171472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
172472f9654STobias Grosser   ///
173472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
174472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
175472f9654STobias Grosser 
176edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
177edb885cbSTobias Grosser 
17838fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
17938fc0aedSTobias Grosser   ///
18038fc0aedSTobias Grosser   /// These AST nodes can be of type:
18138fc0aedSTobias Grosser   ///
18238fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
18338fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
18413c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
1855260c041STobias Grosser   ///   - In-kernel synchronization
1865260c041STobias Grosser   ///   - In-kernel memory copy statement
18738fc0aedSTobias Grosser   ///
1881fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
1891fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
19032837fe3STobias Grosser 
19113c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
19213c78e4dSTobias Grosser 
19313c78e4dSTobias Grosser   /// Create code for a data transfer statement
19413c78e4dSTobias Grosser   ///
19513c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
19613c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
19713c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
19813c78e4dSTobias Grosser                           enum DataDirection Direction);
19913c78e4dSTobias Grosser 
200edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
201edb885cbSTobias Grosser   ///
202edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
203edb885cbSTobias Grosser   ///
204edb885cbSTobias Grosser   /// @returns A set of values referenced by the kernel.
205edb885cbSTobias Grosser   SetVector<Value *> getReferencesInKernel(ppcg_kernel *Kernel);
206edb885cbSTobias Grosser 
20779a947c2STobias Grosser   /// Compute the sizes of the execution grid for a given kernel.
20879a947c2STobias Grosser   ///
20979a947c2STobias Grosser   /// @param Kernel The kernel to compute grid sizes for.
21079a947c2STobias Grosser   ///
21179a947c2STobias Grosser   /// @returns A tuple with grid sizes for X and Y dimension
21279a947c2STobias Grosser   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
21379a947c2STobias Grosser 
21479a947c2STobias Grosser   /// Compute the sizes of the thread blocks for a given kernel.
21579a947c2STobias Grosser   ///
21679a947c2STobias Grosser   /// @param Kernel The kernel to compute thread block sizes for.
21779a947c2STobias Grosser   ///
21879a947c2STobias Grosser   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
21979a947c2STobias Grosser   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
22079a947c2STobias Grosser 
22179a947c2STobias Grosser   /// Create kernel launch parameters.
22279a947c2STobias Grosser   ///
22379a947c2STobias Grosser   /// @param Kernel The kernel to create parameters for.
22479a947c2STobias Grosser   /// @param F      The kernel function that has been created.
22579a947c2STobias Grosser   ///
22679a947c2STobias Grosser   /// @returns A stack allocated array with pointers to the parameter
22779a947c2STobias Grosser   ///          values that are passed to the kernel.
22879a947c2STobias Grosser   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F);
22979a947c2STobias Grosser 
23032837fe3STobias Grosser   /// Create GPU kernel.
23132837fe3STobias Grosser   ///
23232837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
23332837fe3STobias Grosser   ///
23432837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
23532837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
23632837fe3STobias Grosser 
23713c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
23813c78e4dSTobias Grosser   ///
23913c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
24013c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
24113c78e4dSTobias Grosser 
24232837fe3STobias Grosser   /// Create kernel function.
24332837fe3STobias Grosser   ///
24432837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
24532837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
24632837fe3STobias Grosser   /// start block of this newly created function.
24732837fe3STobias Grosser   ///
24832837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
249edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
250edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
251edb885cbSTobias Grosser                             SetVector<Value *> &SubtreeValues);
25232837fe3STobias Grosser 
25332837fe3STobias Grosser   /// Create the declaration of a kernel function.
25432837fe3STobias Grosser   ///
25532837fe3STobias Grosser   /// The kernel function takes as arguments:
25632837fe3STobias Grosser   ///
25732837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
258f6044bd0STobias Grosser   ///   - Host iterators
259c84a1995STobias Grosser   ///   - Parameters
26032837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
26132837fe3STobias Grosser   ///
26232837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
263edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
264edb885cbSTobias Grosser   ///
26532837fe3STobias Grosser   /// @returns The newly declared function.
266edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
267edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
26832837fe3STobias Grosser 
269472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
270472f9654STobias Grosser   ///
271472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
272472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
273472f9654STobias Grosser 
274edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
275edb885cbSTobias Grosser   ///
276edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
277edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
278edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
279edb885cbSTobias Grosser 
2805260c041STobias Grosser   /// Create an in-kernel synchronization call.
2815260c041STobias Grosser   void createKernelSync();
2825260c041STobias Grosser 
28374dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
28474dc3cb4STobias Grosser   ///
28574dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
28674dc3cb4STobias Grosser   std::string createKernelASM();
28774dc3cb4STobias Grosser 
28874dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
28974dc3cb4STobias Grosser   ///
29074dc3cb4STobias Grosser   /// @param F The function to remove references to.
29174dc3cb4STobias Grosser   void clearDominators(Function *F);
29274dc3cb4STobias Grosser 
29374dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
29474dc3cb4STobias Grosser   ///
29574dc3cb4STobias Grosser   /// @param F The function to remove references to.
29674dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
29774dc3cb4STobias Grosser 
29874dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
29974dc3cb4STobias Grosser   ///
30074dc3cb4STobias Grosser   /// @param F The function to remove references to.
30174dc3cb4STobias Grosser   void clearLoops(Function *F);
30274dc3cb4STobias Grosser 
30332837fe3STobias Grosser   /// Finalize the generation of the kernel function.
30432837fe3STobias Grosser   ///
30532837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
30632837fe3STobias Grosser   /// dump its IR to stderr.
30757793596STobias Grosser   ///
30857793596STobias Grosser   /// @returns The Assembly string of the kernel.
30957793596STobias Grosser   std::string finalizeKernelFunction();
310fa7b0802STobias Grosser 
3117287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
312fa7b0802STobias Grosser   void allocateDeviceArrays();
313fa7b0802STobias Grosser 
3147287aeddSTobias Grosser   /// Free all allocated device arrays.
3157287aeddSTobias Grosser   void freeDeviceArrays();
3167287aeddSTobias Grosser 
317fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
318fa7b0802STobias Grosser   ///
319fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
320fa7b0802STobias Grosser   Value *createCallInitContext();
321fa7b0802STobias Grosser 
32279a947c2STobias Grosser   /// Create a call to get the device pointer for a kernel allocation.
32379a947c2STobias Grosser   ///
32479a947c2STobias Grosser   /// @param Allocation The Polly GPU allocation
32579a947c2STobias Grosser   ///
32679a947c2STobias Grosser   /// @returns The device parameter corresponding to this allocation.
32779a947c2STobias Grosser   Value *createCallGetDevicePtr(Value *Allocation);
32879a947c2STobias Grosser 
329fa7b0802STobias Grosser   /// Create a call to free the GPU context.
330fa7b0802STobias Grosser   ///
331fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
332fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
333fa7b0802STobias Grosser 
3347287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
3357287aeddSTobias Grosser   ///
3367287aeddSTobias Grosser   /// @param Size The size of memory to allocate
3377287aeddSTobias Grosser   ///
3387287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
339fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
3407287aeddSTobias Grosser 
3417287aeddSTobias Grosser   /// Create a call to free a device array.
3427287aeddSTobias Grosser   ///
3437287aeddSTobias Grosser   /// @param Array The device array to free.
3447287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
34513c78e4dSTobias Grosser 
34613c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
34713c78e4dSTobias Grosser   ///
34813c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
34913c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
35013c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
35113c78e4dSTobias Grosser                                       Value *Size);
35213c78e4dSTobias Grosser 
35313c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
35413c78e4dSTobias Grosser   ///
35513c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
35613c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
35713c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
35813c78e4dSTobias Grosser                                       Value *Size);
35957793596STobias Grosser 
36057793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
36157793596STobias Grosser   ///
36257793596STobias Grosser   /// @param Buffer The string describing the kernel.
36357793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
36457793596STobias Grosser   ///
36557793596STobias Grosser   /// @returns A pointer to a kernel object
36657793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
36757793596STobias Grosser 
36857793596STobias Grosser   /// Create a call to free a GPU kernel.
36957793596STobias Grosser   ///
37057793596STobias Grosser   /// @param GPUKernel THe kernel to free.
37157793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
37279a947c2STobias Grosser 
37379a947c2STobias Grosser   /// Create a call to launch a GPU kernel.
37479a947c2STobias Grosser   ///
37579a947c2STobias Grosser   /// @param GPUKernel  The kernel to launch.
37679a947c2STobias Grosser   /// @param GridDimX   The size of the first grid dimension.
37779a947c2STobias Grosser   /// @param GridDimY   The size of the second grid dimension.
37879a947c2STobias Grosser   /// @param GridBlockX The size of the first block dimension.
37979a947c2STobias Grosser   /// @param GridBlockY The size of the second block dimension.
38079a947c2STobias Grosser   /// @param GridBlockZ The size of the third block dimension.
38179a947c2STobias Grosser   /// @param Paramters  A pointer to an array that contains itself pointers to
38279a947c2STobias Grosser   ///                   the parameter values passed for each kernel argument.
38379a947c2STobias Grosser   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
38479a947c2STobias Grosser                               Value *GridDimY, Value *BlockDimX,
38579a947c2STobias Grosser                               Value *BlockDimY, Value *BlockDimZ,
38679a947c2STobias Grosser                               Value *Parameters);
3871fb9b64dSTobias Grosser };
3881fb9b64dSTobias Grosser 
389fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
390fa7b0802STobias Grosser   GPUContext = createCallInitContext();
391fa7b0802STobias Grosser   allocateDeviceArrays();
392fa7b0802STobias Grosser }
393fa7b0802STobias Grosser 
394fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
3957287aeddSTobias Grosser   freeDeviceArrays();
396fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
397fa7b0802STobias Grosser   IslNodeBuilder::finalize();
398fa7b0802STobias Grosser }
399fa7b0802STobias Grosser 
400fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
401fa7b0802STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
402fa7b0802STobias Grosser 
403fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
404fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
40513c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
4067287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
4077287aeddSTobias Grosser     DevArrayName.append(Array->name);
408fa7b0802STobias Grosser 
40913c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
4107287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
4117287aeddSTobias Grosser     DevArray->setName(DevArrayName);
41213c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
413fa7b0802STobias Grosser   }
414fa7b0802STobias Grosser 
415fa7b0802STobias Grosser   isl_ast_build_free(Build);
416fa7b0802STobias Grosser }
417fa7b0802STobias Grosser 
4187287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
41913c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
42013c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
4217287aeddSTobias Grosser }
4227287aeddSTobias Grosser 
42357793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
42457793596STobias Grosser   const char *Name = "polly_getKernel";
42557793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
42657793596STobias Grosser   Function *F = M->getFunction(Name);
42757793596STobias Grosser 
42857793596STobias Grosser   // If F is not available, declare it.
42957793596STobias Grosser   if (!F) {
43057793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
43157793596STobias Grosser     std::vector<Type *> Args;
43257793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
43357793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
43457793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
43557793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
43657793596STobias Grosser   }
43757793596STobias Grosser 
43857793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
43957793596STobias Grosser }
44057793596STobias Grosser 
44179a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
44279a947c2STobias Grosser   const char *Name = "polly_getDevicePtr";
44379a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
44479a947c2STobias Grosser   Function *F = M->getFunction(Name);
44579a947c2STobias Grosser 
44679a947c2STobias Grosser   // If F is not available, declare it.
44779a947c2STobias Grosser   if (!F) {
44879a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
44979a947c2STobias Grosser     std::vector<Type *> Args;
45079a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
45179a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
45279a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
45379a947c2STobias Grosser   }
45479a947c2STobias Grosser 
45579a947c2STobias Grosser   return Builder.CreateCall(F, {Allocation});
45679a947c2STobias Grosser }
45779a947c2STobias Grosser 
45879a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
45979a947c2STobias Grosser                                             Value *GridDimY, Value *BlockDimX,
46079a947c2STobias Grosser                                             Value *BlockDimY, Value *BlockDimZ,
46179a947c2STobias Grosser                                             Value *Parameters) {
46279a947c2STobias Grosser   const char *Name = "polly_launchKernel";
46379a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
46479a947c2STobias Grosser   Function *F = M->getFunction(Name);
46579a947c2STobias Grosser 
46679a947c2STobias Grosser   // If F is not available, declare it.
46779a947c2STobias Grosser   if (!F) {
46879a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
46979a947c2STobias Grosser     std::vector<Type *> Args;
47079a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
47179a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
47279a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
47379a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
47479a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
47579a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
47679a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
47779a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
47879a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
47979a947c2STobias Grosser   }
48079a947c2STobias Grosser 
48179a947c2STobias Grosser   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
48279a947c2STobias Grosser                          BlockDimZ, Parameters});
48379a947c2STobias Grosser }
48479a947c2STobias Grosser 
48557793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
48657793596STobias Grosser   const char *Name = "polly_freeKernel";
48757793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
48857793596STobias Grosser   Function *F = M->getFunction(Name);
48957793596STobias Grosser 
49057793596STobias Grosser   // If F is not available, declare it.
49157793596STobias Grosser   if (!F) {
49257793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
49357793596STobias Grosser     std::vector<Type *> Args;
49457793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
49557793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
49657793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
49757793596STobias Grosser   }
49857793596STobias Grosser 
49957793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
50057793596STobias Grosser }
50157793596STobias Grosser 
5027287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
5037287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
5047287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
5057287aeddSTobias Grosser   Function *F = M->getFunction(Name);
5067287aeddSTobias Grosser 
5077287aeddSTobias Grosser   // If F is not available, declare it.
5087287aeddSTobias Grosser   if (!F) {
5097287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
5107287aeddSTobias Grosser     std::vector<Type *> Args;
5117287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
5127287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
5137287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
5147287aeddSTobias Grosser   }
5157287aeddSTobias Grosser 
5167287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
5177287aeddSTobias Grosser }
5187287aeddSTobias Grosser 
519fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
520fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
521fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
522fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
523fa7b0802STobias Grosser 
524fa7b0802STobias Grosser   // If F is not available, declare it.
525fa7b0802STobias Grosser   if (!F) {
526fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
527fa7b0802STobias Grosser     std::vector<Type *> Args;
528fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
529fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
530fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
531fa7b0802STobias Grosser   }
532fa7b0802STobias Grosser 
533fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
534fa7b0802STobias Grosser }
535fa7b0802STobias Grosser 
53613c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
53713c78e4dSTobias Grosser                                                     Value *DeviceData,
53813c78e4dSTobias Grosser                                                     Value *Size) {
53913c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
54013c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
54113c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
54213c78e4dSTobias Grosser 
54313c78e4dSTobias Grosser   // If F is not available, declare it.
54413c78e4dSTobias Grosser   if (!F) {
54513c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
54613c78e4dSTobias Grosser     std::vector<Type *> Args;
54713c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
54813c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
54913c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
55013c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
55113c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
55213c78e4dSTobias Grosser   }
55313c78e4dSTobias Grosser 
55413c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
55513c78e4dSTobias Grosser }
55613c78e4dSTobias Grosser 
55713c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
55813c78e4dSTobias Grosser                                                     Value *HostData,
55913c78e4dSTobias Grosser                                                     Value *Size) {
56013c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
56113c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
56213c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
56313c78e4dSTobias Grosser 
56413c78e4dSTobias Grosser   // If F is not available, declare it.
56513c78e4dSTobias Grosser   if (!F) {
56613c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
56713c78e4dSTobias Grosser     std::vector<Type *> Args;
56813c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
56913c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
57013c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
57113c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
57213c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
57313c78e4dSTobias Grosser   }
57413c78e4dSTobias Grosser 
57513c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
57613c78e4dSTobias Grosser }
57713c78e4dSTobias Grosser 
578fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
579fa7b0802STobias Grosser   const char *Name = "polly_initContext";
580fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
581fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
582fa7b0802STobias Grosser 
583fa7b0802STobias Grosser   // If F is not available, declare it.
584fa7b0802STobias Grosser   if (!F) {
585fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
586fa7b0802STobias Grosser     std::vector<Type *> Args;
587fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
588fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
589fa7b0802STobias Grosser   }
590fa7b0802STobias Grosser 
591fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
592fa7b0802STobias Grosser }
593fa7b0802STobias Grosser 
594fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
595fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
596fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
597fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
598fa7b0802STobias Grosser 
599fa7b0802STobias Grosser   // If F is not available, declare it.
600fa7b0802STobias Grosser   if (!F) {
601fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
602fa7b0802STobias Grosser     std::vector<Type *> Args;
603fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
604fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
605fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
606fa7b0802STobias Grosser   }
607fa7b0802STobias Grosser 
608fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
609fa7b0802STobias Grosser }
610fa7b0802STobias Grosser 
6115260c041STobias Grosser /// Check if one string is a prefix of another.
6125260c041STobias Grosser ///
6135260c041STobias Grosser /// @param String The string in which to look for the prefix.
6145260c041STobias Grosser /// @param Prefix The prefix to look for.
6155260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
6165260c041STobias Grosser   return String.find(Prefix) == 0;
6175260c041STobias Grosser }
6185260c041STobias Grosser 
61913c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
62013c78e4dSTobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
62113c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
62213c78e4dSTobias Grosser 
62313c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
62413c78e4dSTobias Grosser     auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]);
62513c78e4dSTobias Grosser     isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero);
62613c78e4dSTobias Grosser 
62713c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
62813c78e4dSTobias Grosser       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]);
62913c78e4dSTobias Grosser       isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
63013c78e4dSTobias Grosser       Res = isl_ast_expr_mul(Res, Expr);
63113c78e4dSTobias Grosser     }
63213c78e4dSTobias Grosser 
63313c78e4dSTobias Grosser     Value *NumElements = ExprBuilder.create(Res);
63413c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
63513c78e4dSTobias Grosser   }
63613c78e4dSTobias Grosser   isl_ast_build_free(Build);
63713c78e4dSTobias Grosser   return ArraySize;
63813c78e4dSTobias Grosser }
63913c78e4dSTobias Grosser 
64013c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
64113c78e4dSTobias Grosser                                         enum DataDirection Direction) {
64213c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
64313c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
64413c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
64513c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
64613c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
64713c78e4dSTobias Grosser 
64813c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
64913c78e4dSTobias Grosser   Value *HostPtr = ScopArray->getBasePtr();
65013c78e4dSTobias Grosser 
65113c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
65213c78e4dSTobias Grosser 
65313c78e4dSTobias Grosser   if (gpu_array_is_scalar(Array)) {
65413c78e4dSTobias Grosser     HostPtr = Builder.CreateAlloca(ScopArray->getElementType());
65513c78e4dSTobias Grosser     Builder.CreateStore(ScopArray->getBasePtr(), HostPtr);
65613c78e4dSTobias Grosser   }
65713c78e4dSTobias Grosser 
65813c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
65913c78e4dSTobias Grosser 
66013c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
66113c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
66213c78e4dSTobias Grosser   else
66313c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
66413c78e4dSTobias Grosser 
66513c78e4dSTobias Grosser   isl_id_free(Id);
66613c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
66713c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
66813c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
66913c78e4dSTobias Grosser }
67013c78e4dSTobias Grosser 
6711fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
67232837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
67332837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
67432837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
67532837fe3STobias Grosser   isl_id_free(Id);
67632837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
67732837fe3STobias Grosser 
67832837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
67932837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
68032837fe3STobias Grosser     createKernel(UserStmt);
68132837fe3STobias Grosser     isl_ast_expr_free(Expr);
68232837fe3STobias Grosser     return;
68332837fe3STobias Grosser   }
68432837fe3STobias Grosser 
68513c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
68613c78e4dSTobias Grosser     createDataTransfer(UserStmt, HOST_TO_DEVICE);
68732837fe3STobias Grosser     isl_ast_expr_free(Expr);
68813c78e4dSTobias Grosser     return;
68913c78e4dSTobias Grosser   }
69013c78e4dSTobias Grosser 
69113c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
69213c78e4dSTobias Grosser     createDataTransfer(UserStmt, DEVICE_TO_HOST);
69313c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
69438fc0aedSTobias Grosser     return;
69538fc0aedSTobias Grosser   }
69638fc0aedSTobias Grosser 
6975260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
6985260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
6995260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
7005260c041STobias Grosser   isl_id_free(Anno);
7015260c041STobias Grosser 
7025260c041STobias Grosser   switch (KernelStmt->type) {
7035260c041STobias Grosser   case ppcg_kernel_domain:
704edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
7055260c041STobias Grosser     isl_ast_node_free(UserStmt);
7065260c041STobias Grosser     return;
7075260c041STobias Grosser   case ppcg_kernel_copy:
7085260c041STobias Grosser     // TODO: Create kernel copy stmt
7095260c041STobias Grosser     isl_ast_expr_free(Expr);
7105260c041STobias Grosser     isl_ast_node_free(UserStmt);
7115260c041STobias Grosser     return;
7125260c041STobias Grosser   case ppcg_kernel_sync:
7135260c041STobias Grosser     createKernelSync();
7145260c041STobias Grosser     isl_ast_expr_free(Expr);
7155260c041STobias Grosser     isl_ast_node_free(UserStmt);
7165260c041STobias Grosser     return;
7175260c041STobias Grosser   }
7185260c041STobias Grosser 
7195260c041STobias Grosser   isl_ast_expr_free(Expr);
7205260c041STobias Grosser   isl_ast_node_free(UserStmt);
7215260c041STobias Grosser   return;
7225260c041STobias Grosser }
7235260c041STobias Grosser 
724edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
725edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
726edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
727edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
728edb885cbSTobias Grosser 
729edb885cbSTobias Grosser   LoopToScevMapT LTS;
730edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
731edb885cbSTobias Grosser 
732edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
733edb885cbSTobias Grosser 
734edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
735edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
736edb885cbSTobias Grosser   else
737edb885cbSTobias Grosser     assert(0 && "Region statement not supported\n");
738edb885cbSTobias Grosser }
739edb885cbSTobias Grosser 
7405260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
7415260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7425260c041STobias Grosser   auto *Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
7435260c041STobias Grosser   Builder.CreateCall(Sync, {});
7445260c041STobias Grosser }
7455260c041STobias Grosser 
746edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
747edb885cbSTobias Grosser ///
748edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
749edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
750edb885cbSTobias Grosser ///
751edb885cbSTobias Grosser /// @param Node The node to collect references for.
752edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
753edb885cbSTobias Grosser ///
754edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
755edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
756edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
757edb885cbSTobias Grosser     return isl_bool_true;
758edb885cbSTobias Grosser 
759edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
760edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
761edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
762edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
763edb885cbSTobias Grosser   isl_id_free(Id);
764edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
765edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
766edb885cbSTobias Grosser 
767edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
768edb885cbSTobias Grosser     return isl_bool_true;
769edb885cbSTobias Grosser 
770edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
771edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
772edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
773edb885cbSTobias Grosser   isl_id_free(Id);
774edb885cbSTobias Grosser 
775edb885cbSTobias Grosser   addReferencesFromStmt(Stmt, User);
776edb885cbSTobias Grosser 
777edb885cbSTobias Grosser   return isl_bool_true;
778edb885cbSTobias Grosser }
779edb885cbSTobias Grosser 
780edb885cbSTobias Grosser SetVector<Value *> GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
781edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
782edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
783edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
784edb885cbSTobias Grosser   SubtreeReferences References = {
785edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
786edb885cbSTobias Grosser 
787edb885cbSTobias Grosser   for (const auto &I : IDToValue)
788edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
789edb885cbSTobias Grosser 
790edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
791edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
792edb885cbSTobias Grosser 
793edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
794edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
795edb885cbSTobias Grosser 
796edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
797edb885cbSTobias Grosser     SubtreeValues.remove(SAI.second->getBasePtr());
798edb885cbSTobias Grosser 
799edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
800edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
801edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
802edb885cbSTobias Grosser     assert(IDToValue.count(Id));
803edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
804edb885cbSTobias Grosser     SubtreeValues.remove(Val);
805edb885cbSTobias Grosser     isl_id_free(Id);
806edb885cbSTobias Grosser   }
807edb885cbSTobias Grosser   isl_space_free(Space);
808edb885cbSTobias Grosser 
809edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
810edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
811edb885cbSTobias Grosser     assert(IDToValue.count(Id));
812edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
813edb885cbSTobias Grosser     SubtreeValues.remove(Val);
814edb885cbSTobias Grosser     isl_id_free(Id);
815edb885cbSTobias Grosser   }
816edb885cbSTobias Grosser 
817edb885cbSTobias Grosser   return SubtreeValues;
818edb885cbSTobias Grosser }
819edb885cbSTobias Grosser 
82074dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
82174dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
82274dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
82374dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
82474dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
82574dc3cb4STobias Grosser 
82674dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
82774dc3cb4STobias Grosser     DT.eraseNode(BB);
82874dc3cb4STobias Grosser }
82974dc3cb4STobias Grosser 
83074dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
83174dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
83274dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
83374dc3cb4STobias Grosser     if (L)
83474dc3cb4STobias Grosser       SE.forgetLoop(L);
83574dc3cb4STobias Grosser   }
83674dc3cb4STobias Grosser }
83774dc3cb4STobias Grosser 
83874dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
83974dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
84074dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
84174dc3cb4STobias Grosser     if (L)
84274dc3cb4STobias Grosser       SE.forgetLoop(L);
84374dc3cb4STobias Grosser     LI.removeBlock(&BB);
84474dc3cb4STobias Grosser   }
84574dc3cb4STobias Grosser }
84674dc3cb4STobias Grosser 
84779a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
84879a947c2STobias Grosser   std::vector<Value *> Sizes;
84979a947c2STobias Grosser   isl_ast_build *Context = isl_ast_build_from_context(S.getContext());
85079a947c2STobias Grosser 
85179a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
85279a947c2STobias Grosser     isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i);
85379a947c2STobias Grosser     isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size);
85479a947c2STobias Grosser     Value *Res = ExprBuilder.create(GridSize);
85579a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
85679a947c2STobias Grosser     Sizes.push_back(Res);
85779a947c2STobias Grosser   }
85879a947c2STobias Grosser   isl_ast_build_free(Context);
85979a947c2STobias Grosser 
86079a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
86179a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
86279a947c2STobias Grosser 
86379a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
86479a947c2STobias Grosser }
86579a947c2STobias Grosser 
86679a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
86779a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
86879a947c2STobias Grosser   std::vector<Value *> Sizes;
86979a947c2STobias Grosser 
87079a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
87179a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
87279a947c2STobias Grosser     Sizes.push_back(Res);
87379a947c2STobias Grosser   }
87479a947c2STobias Grosser 
87579a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
87679a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
87779a947c2STobias Grosser 
87879a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
87979a947c2STobias Grosser }
88079a947c2STobias Grosser 
88179a947c2STobias Grosser Value *GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel,
88279a947c2STobias Grosser                                               Function *F) {
8834e18d71cSTobias Grosser   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(),
8844e18d71cSTobias Grosser                                  std::distance(F->arg_begin(), F->arg_end()));
88579a947c2STobias Grosser 
88679a947c2STobias Grosser   BasicBlock *EntryBlock =
88779a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
88879a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
88979a947c2STobias Grosser   Instruction *Parameters =
89079a947c2STobias Grosser       new AllocaInst(ArrayTy, Launch + "_params", EntryBlock->getTerminator());
89179a947c2STobias Grosser 
89279a947c2STobias Grosser   int Index = 0;
89379a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
89479a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
89579a947c2STobias Grosser       continue;
89679a947c2STobias Grosser 
89779a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
89879a947c2STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
89979a947c2STobias Grosser 
90079a947c2STobias Grosser     Value *DevArray = DeviceAllocations[(ScopArrayInfo *)SAI];
90179a947c2STobias Grosser     DevArray = createCallGetDevicePtr(DevArray);
90279a947c2STobias Grosser     Instruction *Param = new AllocaInst(
90379a947c2STobias Grosser         Builder.getInt8PtrTy(), Launch + "_param_" + std::to_string(Index),
90479a947c2STobias Grosser         EntryBlock->getTerminator());
90579a947c2STobias Grosser     Builder.CreateStore(DevArray, Param);
90644143bb9STobias Grosser     Value *Slot = Builder.CreateGEP(
90744143bb9STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
90879a947c2STobias Grosser     Value *ParamTyped =
90979a947c2STobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
91079a947c2STobias Grosser     Builder.CreateStore(ParamTyped, Slot);
91179a947c2STobias Grosser     Index++;
91279a947c2STobias Grosser   }
91379a947c2STobias Grosser 
914*a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
915*a490147cSTobias Grosser 
916*a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
917*a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
918*a490147cSTobias Grosser     Value *Val = IDToValue[Id];
919*a490147cSTobias Grosser     isl_id_free(Id);
920*a490147cSTobias Grosser     Instruction *Param = new AllocaInst(
921*a490147cSTobias Grosser         Val->getType(), Launch + "_param_" + std::to_string(Index),
922*a490147cSTobias Grosser         EntryBlock->getTerminator());
923*a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
924*a490147cSTobias Grosser     Value *Slot = Builder.CreateGEP(
925*a490147cSTobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
926*a490147cSTobias Grosser     Value *ParamTyped =
927*a490147cSTobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
928*a490147cSTobias Grosser     Builder.CreateStore(ParamTyped, Slot);
929*a490147cSTobias Grosser     Index++;
930*a490147cSTobias Grosser   }
931*a490147cSTobias Grosser 
93279a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
93379a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
93479a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
93579a947c2STobias Grosser }
93679a947c2STobias Grosser 
93732837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
93832837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
93932837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
94032837fe3STobias Grosser   isl_id_free(Id);
94132837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
94232837fe3STobias Grosser 
943edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel);
944edb885cbSTobias Grosser 
94532837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
94632837fe3STobias Grosser 
94732837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
948472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
949edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
95032837fe3STobias Grosser 
951edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
952edb885cbSTobias Grosser 
953edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
954edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
955edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
956edb885cbSTobias Grosser   for (const Loop *L : Loops) {
957edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
958edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
959edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
960edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
961edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
962edb885cbSTobias Grosser     SubtreeValues.insert(V);
963edb885cbSTobias Grosser   }
964edb885cbSTobias Grosser 
965edb885cbSTobias Grosser   createKernelFunction(Kernel, SubtreeValues);
96632837fe3STobias Grosser 
96759ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
96859ab0705STobias Grosser 
96974dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
97074dc3cb4STobias Grosser   clearDominators(F);
97174dc3cb4STobias Grosser   clearScalarEvolution(F);
97274dc3cb4STobias Grosser   clearLoops(F);
97374dc3cb4STobias Grosser 
97432837fe3STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
975472f9654STobias Grosser   IDToValue = HostIDs;
97632837fe3STobias Grosser 
977edb885cbSTobias Grosser   ValueMap = HostValueMap;
978edb885cbSTobias Grosser   ScalarMap.clear();
979edb885cbSTobias Grosser   PHIOpMap.clear();
980edb885cbSTobias Grosser   EscapeMap.clear();
981edb885cbSTobias Grosser   IDToSAI.clear();
98274dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
98374dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
98474dc3cb4STobias Grosser     S.invalidateScopArrayInfo(BasePtr, ScopArrayInfo::MK_Array);
98574dc3cb4STobias Grosser   LocalArrays.clear();
986edb885cbSTobias Grosser 
98779a947c2STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F);
98879a947c2STobias Grosser 
98957793596STobias Grosser   std::string ASMString = finalizeKernelFunction();
99057793596STobias Grosser   std::string Name = "kernel_" + std::to_string(Kernel->id);
99157793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
99257793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
99357793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
99479a947c2STobias Grosser 
99579a947c2STobias Grosser   Value *GridDimX, *GridDimY;
99679a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
99779a947c2STobias Grosser 
99879a947c2STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
99979a947c2STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
100079a947c2STobias Grosser 
100179a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
100279a947c2STobias Grosser                          BlockDimZ, Parameters);
100357793596STobias Grosser   createCallFreeKernel(GPUKernel);
100432837fe3STobias Grosser }
100532837fe3STobias Grosser 
100632837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
100732837fe3STobias Grosser ///
100832837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
100932837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
101032837fe3STobias Grosser   std::string Ret = "e";
101132837fe3STobias Grosser 
101232837fe3STobias Grosser   if (!is64Bit)
101332837fe3STobias Grosser     Ret += "-p:32:32";
101432837fe3STobias Grosser 
101532837fe3STobias Grosser   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
101632837fe3STobias Grosser 
101732837fe3STobias Grosser   return Ret;
101832837fe3STobias Grosser }
101932837fe3STobias Grosser 
1020edb885cbSTobias Grosser Function *
1021edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1022edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
102332837fe3STobias Grosser   std::vector<Type *> Args;
102432837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
102532837fe3STobias Grosser 
102632837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
102732837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
102832837fe3STobias Grosser       continue;
102932837fe3STobias Grosser 
103032837fe3STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
103132837fe3STobias Grosser   }
103232837fe3STobias Grosser 
1033f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1034f6044bd0STobias Grosser 
1035f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++)
1036f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
1037f6044bd0STobias Grosser 
1038c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1039c84a1995STobias Grosser 
1040c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++)
1041c84a1995STobias Grosser     Args.push_back(Builder.getInt64Ty());
1042c84a1995STobias Grosser 
1043edb885cbSTobias Grosser   for (auto *V : SubtreeValues)
1044edb885cbSTobias Grosser     Args.push_back(V->getType());
1045edb885cbSTobias Grosser 
104632837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
104732837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
104832837fe3STobias Grosser                               GPUModule.get());
104932837fe3STobias Grosser   FN->setCallingConv(CallingConv::PTX_Kernel);
105032837fe3STobias Grosser 
105132837fe3STobias Grosser   auto Arg = FN->arg_begin();
105232837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
105332837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
105432837fe3STobias Grosser       continue;
105532837fe3STobias Grosser 
1056edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
1057edb885cbSTobias Grosser 
1058edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1059edb885cbSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1060edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
1061edb885cbSTobias Grosser     Value *Val = &*Arg;
1062edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1063edb885cbSTobias Grosser     isl_ast_build *Build =
1064edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
1065edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1066edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
1067edb885cbSTobias Grosser           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
1068edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
1069edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
1070edb885cbSTobias Grosser     }
1071edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
1072edb885cbSTobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, ScopArrayInfo::MK_Array);
107374dc3cb4STobias Grosser     LocalArrays.push_back(Val);
1074edb885cbSTobias Grosser 
1075edb885cbSTobias Grosser     isl_ast_build_free(Build);
1076edb885cbSTobias Grosser     isl_id_free(Id);
1077edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
107832837fe3STobias Grosser     Arg++;
107932837fe3STobias Grosser   }
108032837fe3STobias Grosser 
1081f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1082f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1083f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
1084f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
1085f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1086f6044bd0STobias Grosser     Arg++;
1087f6044bd0STobias Grosser   }
1088f6044bd0STobias Grosser 
1089c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
1090c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1091c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
1092c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
1093c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1094c84a1995STobias Grosser     Arg++;
1095c84a1995STobias Grosser   }
1096c84a1995STobias Grosser 
1097edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
1098edb885cbSTobias Grosser     Arg->setName(V->getName());
1099edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
1100edb885cbSTobias Grosser     Arg++;
1101edb885cbSTobias Grosser   }
1102edb885cbSTobias Grosser 
110332837fe3STobias Grosser   return FN;
110432837fe3STobias Grosser }
110532837fe3STobias Grosser 
1106472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
1107472f9654STobias Grosser   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
1108472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
1109472f9654STobias Grosser 
1110472f9654STobias Grosser   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
1111472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
1112472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
1113472f9654STobias Grosser 
1114472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1115472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
1116472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1117472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1118472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1119472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1120472f9654STobias Grosser     IDToValue[Id] = Val;
1121472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1122472f9654STobias Grosser   };
1123472f9654STobias Grosser 
1124472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
1125472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1126472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
1127472f9654STobias Grosser   }
1128472f9654STobias Grosser 
1129472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
1130472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1131472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
1132472f9654STobias Grosser   }
1133472f9654STobias Grosser }
1134472f9654STobias Grosser 
1135edb885cbSTobias Grosser void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel,
1136edb885cbSTobias Grosser                                           SetVector<Value *> &SubtreeValues) {
113732837fe3STobias Grosser 
113832837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
113932837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
114032837fe3STobias Grosser   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
114132837fe3STobias Grosser   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
114232837fe3STobias Grosser 
1143edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
114432837fe3STobias Grosser 
114559ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
114632837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
114732837fe3STobias Grosser 
114859ab0705STobias Grosser   DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
114959ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
115059ab0705STobias Grosser 
115132837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
115232837fe3STobias Grosser   Builder.CreateRetVoid();
115332837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
1154472f9654STobias Grosser 
1155472f9654STobias Grosser   insertKernelIntrinsics(Kernel);
115632837fe3STobias Grosser }
115732837fe3STobias Grosser 
115874dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
115974dc3cb4STobias Grosser   llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda"));
116074dc3cb4STobias Grosser   std::string ErrMsg;
116174dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
116274dc3cb4STobias Grosser 
116374dc3cb4STobias Grosser   if (!GPUTarget) {
116474dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
116574dc3cb4STobias Grosser     return "";
116674dc3cb4STobias Grosser   }
116774dc3cb4STobias Grosser 
116874dc3cb4STobias Grosser   TargetOptions Options;
116974dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
117074dc3cb4STobias Grosser   std::unique_ptr<TargetMachine> TargetM(
117174dc3cb4STobias Grosser       GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "",
117274dc3cb4STobias Grosser                                      Options, Optional<Reloc::Model>()));
117374dc3cb4STobias Grosser 
117474dc3cb4STobias Grosser   SmallString<0> ASMString;
117574dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
117674dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
117774dc3cb4STobias Grosser 
117874dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
117974dc3cb4STobias Grosser 
118074dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
118174dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
118274dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
118374dc3cb4STobias Grosser     return "";
118474dc3cb4STobias Grosser   }
118574dc3cb4STobias Grosser 
118674dc3cb4STobias Grosser   PM.run(*GPUModule);
118774dc3cb4STobias Grosser 
118874dc3cb4STobias Grosser   return ASMStream.str();
118974dc3cb4STobias Grosser }
119074dc3cb4STobias Grosser 
119157793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
1192e1a98343STobias Grosser   // Verify module.
1193e1a98343STobias Grosser   llvm::legacy::PassManager Passes;
1194e1a98343STobias Grosser   Passes.add(createVerifierPass());
1195e1a98343STobias Grosser   Passes.run(*GPUModule);
119632837fe3STobias Grosser 
119732837fe3STobias Grosser   if (DumpKernelIR)
119832837fe3STobias Grosser     outs() << *GPUModule << "\n";
119932837fe3STobias Grosser 
12009a18d559STobias Grosser   // Optimize module.
12019a18d559STobias Grosser   llvm::legacy::PassManager OptPasses;
12029a18d559STobias Grosser   PassManagerBuilder PassBuilder;
12039a18d559STobias Grosser   PassBuilder.OptLevel = 3;
12049a18d559STobias Grosser   PassBuilder.SizeLevel = 0;
12059a18d559STobias Grosser   PassBuilder.populateModulePassManager(OptPasses);
12069a18d559STobias Grosser   OptPasses.run(*GPUModule);
12079a18d559STobias Grosser 
120874dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
120974dc3cb4STobias Grosser 
121074dc3cb4STobias Grosser   if (DumpKernelASM)
121174dc3cb4STobias Grosser     outs() << Assembly << "\n";
121274dc3cb4STobias Grosser 
121332837fe3STobias Grosser   GPUModule.release();
1214472f9654STobias Grosser   KernelIDs.clear();
121557793596STobias Grosser 
121657793596STobias Grosser   return Assembly;
121732837fe3STobias Grosser }
121832837fe3STobias Grosser 
12199dfe4e7cSTobias Grosser namespace {
12209dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
12219dfe4e7cSTobias Grosser public:
12229dfe4e7cSTobias Grosser   static char ID;
12239dfe4e7cSTobias Grosser 
1224e938517eSTobias Grosser   /// The scop that is currently processed.
1225e938517eSTobias Grosser   Scop *S;
1226e938517eSTobias Grosser 
122738fc0aedSTobias Grosser   LoopInfo *LI;
122838fc0aedSTobias Grosser   DominatorTree *DT;
122938fc0aedSTobias Grosser   ScalarEvolution *SE;
123038fc0aedSTobias Grosser   const DataLayout *DL;
123138fc0aedSTobias Grosser   RegionInfo *RI;
123238fc0aedSTobias Grosser 
12339dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
12349dfe4e7cSTobias Grosser 
1235e938517eSTobias Grosser   /// Construct compilation options for PPCG.
1236e938517eSTobias Grosser   ///
1237e938517eSTobias Grosser   /// @returns The compilation options.
1238e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
1239e938517eSTobias Grosser     auto DebugOptions =
1240e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
1241e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
1242e938517eSTobias Grosser 
1243e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
1244e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
1245e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
1246e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
1247e938517eSTobias Grosser 
1248e938517eSTobias Grosser     Options->debug = DebugOptions;
1249e938517eSTobias Grosser 
1250e938517eSTobias Grosser     Options->reschedule = true;
1251e938517eSTobias Grosser     Options->scale_tile_loops = false;
1252e938517eSTobias Grosser     Options->wrap = false;
1253e938517eSTobias Grosser 
1254e938517eSTobias Grosser     Options->non_negative_parameters = false;
1255e938517eSTobias Grosser     Options->ctx = nullptr;
1256e938517eSTobias Grosser     Options->sizes = nullptr;
1257e938517eSTobias Grosser 
12584eaedde5STobias Grosser     Options->tile_size = 32;
12594eaedde5STobias Grosser 
1260e938517eSTobias Grosser     Options->use_private_memory = false;
1261e938517eSTobias Grosser     Options->use_shared_memory = false;
1262e938517eSTobias Grosser     Options->max_shared_memory = 0;
1263e938517eSTobias Grosser 
1264e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
1265e938517eSTobias Grosser     Options->openmp = false;
1266e938517eSTobias Grosser     Options->linearize_device_arrays = true;
1267e938517eSTobias Grosser     Options->live_range_reordering = false;
1268e938517eSTobias Grosser 
1269e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
1270e938517eSTobias Grosser     Options->opencl_use_gpu = false;
1271e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
1272e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
1273e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
1274e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
1275e938517eSTobias Grosser 
1276e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
1277e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
1278e938517eSTobias Grosser 
1279e938517eSTobias Grosser     return Options;
1280e938517eSTobias Grosser   }
1281e938517eSTobias Grosser 
1282f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
1283f384594dSTobias Grosser   ///
1284f384594dSTobias Grosser   /// Instead of a normal access of the form:
1285f384594dSTobias Grosser   ///
1286f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
1287f384594dSTobias Grosser   ///
1288f384594dSTobias Grosser   /// a tagged access has the form
1289f384594dSTobias Grosser   ///
1290f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
1291f384594dSTobias Grosser   ///
1292f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
1293f384594dSTobias Grosser   /// triggered the access.
1294f384594dSTobias Grosser   ///
1295f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
1296f384594dSTobias Grosser   ///
1297f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
1298f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
1299f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
1300f384594dSTobias Grosser 
1301f384594dSTobias Grosser     for (auto &Stmt : *S)
1302f384594dSTobias Grosser       for (auto &Acc : Stmt)
1303f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
1304f384594dSTobias Grosser           isl_map *Relation = Acc->getAccessRelation();
1305f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
1306f384594dSTobias Grosser 
1307f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
1308f384594dSTobias Grosser           Space = isl_space_range(Space);
1309f384594dSTobias Grosser           Space = isl_space_from_range(Space);
13106293ba69STobias Grosser           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1311f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
1312f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
1313f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
1314f384594dSTobias Grosser         }
1315f384594dSTobias Grosser 
1316f384594dSTobias Grosser     return Accesses;
1317f384594dSTobias Grosser   }
1318f384594dSTobias Grosser 
1319f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
1320f384594dSTobias Grosser   ///
1321f384594dSTobias Grosser   /// @see getTaggedAccesses
1322f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
1323f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
1324f384594dSTobias Grosser   }
1325f384594dSTobias Grosser 
1326f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
1327f384594dSTobias Grosser   ///
1328f384594dSTobias Grosser   /// @see getTaggedAccesses
1329f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
1330f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
1331f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
1332f384594dSTobias Grosser   }
1333f384594dSTobias Grosser 
1334f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
1335f384594dSTobias Grosser   ///
1336f384594dSTobias Grosser   /// @see getTaggedAccesses
1337f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
1338f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
1339f384594dSTobias Grosser   }
1340f384594dSTobias Grosser 
1341aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
1342aef5196fSTobias Grosser   ///
1343aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
1344aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
1345aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
1346aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
1347aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
1348aef5196fSTobias Grosser   /// the data format that ppcg expects.
1349aef5196fSTobias Grosser   ///
1350aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
1351aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
1352aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
1353bd81a7eeSTobias Grosser         S->getIslCtx(),
1354bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
1355aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
1356aef5196fSTobias Grosser     auto *Space = S->getParamSpace();
1357aef5196fSTobias Grosser 
1358aef5196fSTobias Grosser     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
1359aef5196fSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
1360aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1361aef5196fSTobias Grosser     }
1362aef5196fSTobias Grosser 
1363aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
1364aef5196fSTobias Grosser       auto Id = Array.second->getBasePtrId();
1365aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1366aef5196fSTobias Grosser     }
1367aef5196fSTobias Grosser 
1368aef5196fSTobias Grosser     isl_space_free(Space);
1369aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
1370aef5196fSTobias Grosser 
1371aef5196fSTobias Grosser     return Names;
1372aef5196fSTobias Grosser   }
1373aef5196fSTobias Grosser 
1374e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
1375e938517eSTobias Grosser   ///
1376f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
1377f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
1378f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
1379f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
1380e938517eSTobias Grosser   ///
1381e938517eSTobias Grosser   /// @returns A new ppcg scop.
1382e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
1383e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
1384e938517eSTobias Grosser 
1385e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
1386e938517eSTobias Grosser 
1387e938517eSTobias Grosser     PPCGScop->start = 0;
1388e938517eSTobias Grosser     PPCGScop->end = 0;
1389e938517eSTobias Grosser 
1390f384594dSTobias Grosser     PPCGScop->context = S->getContext();
1391f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
1392e938517eSTobias Grosser     PPCGScop->call = nullptr;
1393f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
1394f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
1395e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
1396f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
1397f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
1398f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
1399f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
1400e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
1401f384594dSTobias Grosser     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
1402e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
1403e938517eSTobias Grosser 
1404e938517eSTobias Grosser     PPCGScop->independence = nullptr;
1405e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
1406e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
1407e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
1408e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
1409e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
1410e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
1411e938517eSTobias Grosser 
1412f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
1413aef5196fSTobias Grosser     PPCGScop->names = getNames();
1414e938517eSTobias Grosser 
1415e938517eSTobias Grosser     PPCGScop->pet = nullptr;
1416e938517eSTobias Grosser 
1417f384594dSTobias Grosser     compute_tagger(PPCGScop);
1418f384594dSTobias Grosser     compute_dependences(PPCGScop);
1419f384594dSTobias Grosser 
1420e938517eSTobias Grosser     return PPCGScop;
1421e938517eSTobias Grosser   }
1422e938517eSTobias Grosser 
142360f63b49STobias Grosser   /// Collect the array acesses in a statement.
142460f63b49STobias Grosser   ///
142560f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
142660f63b49STobias Grosser   ///
142760f63b49STobias Grosser   /// @returns A list of array accesses.
142860f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
142960f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
143060f63b49STobias Grosser 
143160f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
143260f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
143360f63b49STobias Grosser       Access->read = Acc->isRead();
143460f63b49STobias Grosser       Access->write = Acc->isWrite();
143560f63b49STobias Grosser       Access->access = Acc->getAccessRelation();
143660f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
143760f63b49STobias Grosser       Space = isl_space_range(Space);
143860f63b49STobias Grosser       Space = isl_space_from_range(Space);
14396293ba69STobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
144060f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
144160f63b49STobias Grosser       Access->tagged_access =
144260f63b49STobias Grosser           isl_map_domain_product(Acc->getAccessRelation(), Universe);
144360f63b49STobias Grosser       Access->exact_write = Acc->isWrite();
144460f63b49STobias Grosser       Access->ref_id = Acc->getId();
144560f63b49STobias Grosser       Access->next = Accesses;
144660f63b49STobias Grosser       Accesses = Access;
144760f63b49STobias Grosser     }
144860f63b49STobias Grosser 
144960f63b49STobias Grosser     return Accesses;
145060f63b49STobias Grosser   }
145160f63b49STobias Grosser 
145269b46751STobias Grosser   /// Collect the list of GPU statements.
145369b46751STobias Grosser   ///
145469b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
145569b46751STobias Grosser   /// as well as a list with all memory accesses.
145669b46751STobias Grosser   ///
145769b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
145869b46751STobias Grosser   ///
145969b46751STobias Grosser   /// @returns A linked-list of statements.
146069b46751STobias Grosser   gpu_stmt *getStatements() {
146169b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
146269b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
146369b46751STobias Grosser 
146469b46751STobias Grosser     int i = 0;
146569b46751STobias Grosser     for (auto &Stmt : *S) {
146669b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
146769b46751STobias Grosser 
146869b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
146969b46751STobias Grosser 
147069b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
147169b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
147260f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
147369b46751STobias Grosser       i++;
147469b46751STobias Grosser     }
147569b46751STobias Grosser 
147669b46751STobias Grosser     return Stmts;
147769b46751STobias Grosser   }
147869b46751STobias Grosser 
147960f63b49STobias Grosser   /// Derive the extent of an array.
148060f63b49STobias Grosser   ///
148160f63b49STobias Grosser   /// The extent of an array is defined by the set of memory locations for
148260f63b49STobias Grosser   /// which a memory access in the iteration domain exists.
148360f63b49STobias Grosser   ///
148460f63b49STobias Grosser   /// @param Array The array to derive the extent for.
148560f63b49STobias Grosser   ///
148660f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
148760f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
148860f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
148960f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
149060f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
149160f63b49STobias Grosser     isl_set *AccessSet =
149260f63b49STobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace());
149360f63b49STobias Grosser     isl_union_set_free(AccessUSet);
149460f63b49STobias Grosser 
149560f63b49STobias Grosser     return AccessSet;
149660f63b49STobias Grosser   }
149760f63b49STobias Grosser 
149860f63b49STobias Grosser   /// Derive the bounds of an array.
149960f63b49STobias Grosser   ///
150060f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
150160f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
150260f63b49STobias Grosser   /// ScopArrayInfo.
150360f63b49STobias Grosser   ///
150460f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
150560f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
150660f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
150760f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
150860f63b49STobias Grosser       isl_set *Dom = isl_set_copy(PPCGArray.extent);
150960f63b49STobias Grosser       Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
151060f63b49STobias Grosser       isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
151160f63b49STobias Grosser       isl_set_free(Dom);
151260f63b49STobias Grosser       Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
151360f63b49STobias Grosser       isl_local_space *LS = isl_local_space_from_space(isl_set_get_space(Dom));
151460f63b49STobias Grosser       isl_aff *One = isl_aff_zero_on_domain(LS);
151560f63b49STobias Grosser       One = isl_aff_add_constant_si(One, 1);
151660f63b49STobias Grosser       Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
151760f63b49STobias Grosser       Bound = isl_pw_aff_gist(Bound, S->getContext());
151860f63b49STobias Grosser       PPCGArray.bound[0] = Bound;
151960f63b49STobias Grosser     }
152060f63b49STobias Grosser 
152160f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
152260f63b49STobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
152360f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
152460f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
152560f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
152660f63b49STobias Grosser       PPCGArray.bound[i] = Bound;
152760f63b49STobias Grosser     }
152860f63b49STobias Grosser   }
152960f63b49STobias Grosser 
153060f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
153160f63b49STobias Grosser   ///
153260f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
153360f63b49STobias Grosser   void createArrays(gpu_prog *PPCGProg) {
153460f63b49STobias Grosser     int i = 0;
153560f63b49STobias Grosser     for (auto &Element : S->arrays()) {
153660f63b49STobias Grosser       ScopArrayInfo *Array = Element.second.get();
153760f63b49STobias Grosser 
153860f63b49STobias Grosser       std::string TypeName;
153960f63b49STobias Grosser       raw_string_ostream OS(TypeName);
154060f63b49STobias Grosser 
154160f63b49STobias Grosser       OS << *Array->getElementType();
154260f63b49STobias Grosser       TypeName = OS.str();
154360f63b49STobias Grosser 
154460f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
154560f63b49STobias Grosser 
154660f63b49STobias Grosser       PPCGArray.space = Array->getSpace();
154760f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
154860f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
154960f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
155060f63b49STobias Grosser       PPCGArray.extent = nullptr;
155160f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
155260f63b49STobias Grosser       PPCGArray.bound =
155360f63b49STobias Grosser           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
155460f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
155560f63b49STobias Grosser       PPCGArray.n_ref = 0;
155660f63b49STobias Grosser       PPCGArray.refs = nullptr;
155760f63b49STobias Grosser       PPCGArray.accessed = true;
155860f63b49STobias Grosser       PPCGArray.read_only_scalar = false;
155960f63b49STobias Grosser       PPCGArray.has_compound_element = false;
156060f63b49STobias Grosser       PPCGArray.local = false;
156160f63b49STobias Grosser       PPCGArray.declare_local = false;
156260f63b49STobias Grosser       PPCGArray.global = false;
156360f63b49STobias Grosser       PPCGArray.linearize = false;
156460f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
156513c78e4dSTobias Grosser       PPCGArray.user = Array;
156660f63b49STobias Grosser 
156760f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
15682d010dafSTobias Grosser       i++;
1569b9fc860aSTobias Grosser 
1570b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
157160f63b49STobias Grosser     }
157260f63b49STobias Grosser   }
157360f63b49STobias Grosser 
157460f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
157560f63b49STobias Grosser   ///
157660f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
157760f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
157860f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
157960f63b49STobias Grosser 
158060f63b49STobias Grosser     for (auto &Item : S->arrays()) {
158160f63b49STobias Grosser       ScopArrayInfo *Array = Item.second.get();
158260f63b49STobias Grosser       isl_space *Space = Array->getSpace();
158360f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
158460f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
158560f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
158660f63b49STobias Grosser     }
158760f63b49STobias Grosser 
158860f63b49STobias Grosser     return Maps;
158960f63b49STobias Grosser   }
159060f63b49STobias Grosser 
1591e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
1592e938517eSTobias Grosser   ///
1593e938517eSTobias Grosser   /// @returns A new gpu grogram description.
1594e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
1595e938517eSTobias Grosser 
1596e938517eSTobias Grosser     if (!PPCGScop)
1597e938517eSTobias Grosser       return nullptr;
1598e938517eSTobias Grosser 
1599e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
1600e938517eSTobias Grosser 
1601e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
1602e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
1603aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
160460f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
160560f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
160660f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
160760f63b49STobias Grosser     PPCGProg->tagged_must_kill =
160860f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
160960f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
161060f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
161160f63b49STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
1612e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
1613e938517eSTobias Grosser     PPCGProg->array_order = nullptr;
161469b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
161569b46751STobias Grosser     PPCGProg->stmts = getStatements();
161660f63b49STobias Grosser     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
161760f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
161860f63b49STobias Grosser                                        PPCGProg->n_array);
161960f63b49STobias Grosser 
162060f63b49STobias Grosser     createArrays(PPCGProg);
1621e938517eSTobias Grosser 
1622e938517eSTobias Grosser     return PPCGProg;
1623e938517eSTobias Grosser   }
1624e938517eSTobias Grosser 
162569b46751STobias Grosser   struct PrintGPUUserData {
162669b46751STobias Grosser     struct cuda_info *CudaInfo;
162769b46751STobias Grosser     struct gpu_prog *PPCGProg;
162869b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
162969b46751STobias Grosser   };
163069b46751STobias Grosser 
163169b46751STobias Grosser   /// Print a user statement node in the host code.
163269b46751STobias Grosser   ///
163369b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
163469b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
163569b46751STobias Grosser   /// host ast.
163669b46751STobias Grosser   ///
163769b46751STobias Grosser   /// @param P The printer to print to
163869b46751STobias Grosser   /// @param Options The printing options to use
163969b46751STobias Grosser   /// @param Node The node to print
164069b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
164169b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
164269b46751STobias Grosser   ///
164369b46751STobias Grosser   /// @returns A printer to which the output has been printed.
164469b46751STobias Grosser   static __isl_give isl_printer *
164569b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
164669b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
164769b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
164869b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
164969b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
165069b46751STobias Grosser 
165169b46751STobias Grosser     if (Id) {
165220251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
165320251734STobias Grosser 
165420251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
165520251734STobias Grosser       // otherwise try to call pet functionality that is not available in
165620251734STobias Grosser       // Polly.
165720251734STobias Grosser       if (IsUser) {
165820251734STobias Grosser         P = isl_printer_start_line(P);
165920251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
166020251734STobias Grosser         P = isl_printer_end_line(P);
166120251734STobias Grosser         isl_id_free(Id);
166220251734STobias Grosser         isl_ast_print_options_free(Options);
166320251734STobias Grosser         return P;
166420251734STobias Grosser       }
166520251734STobias Grosser 
166669b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
166769b46751STobias Grosser       isl_id_free(Id);
166869b46751STobias Grosser       Data->Kernels.push_back(Kernel);
166969b46751STobias Grosser     }
167069b46751STobias Grosser 
167169b46751STobias Grosser     return print_host_user(P, Options, Node, User);
167269b46751STobias Grosser   }
167369b46751STobias Grosser 
167469b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
167569b46751STobias Grosser   ///
167669b46751STobias Grosser   /// @param Kernel The kernel to print
167769b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
167869b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
167969b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
168069b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
168169b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
168269b46751STobias Grosser     char *String = isl_printer_get_str(P);
168369b46751STobias Grosser     printf("%s\n", String);
168469b46751STobias Grosser     free(String);
168569b46751STobias Grosser     isl_printer_free(P);
168669b46751STobias Grosser   }
168769b46751STobias Grosser 
168869b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
168969b46751STobias Grosser   ///
169069b46751STobias Grosser   /// @param Tree An AST describing GPU code
169169b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
169269b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
169369b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
169469b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
169569b46751STobias Grosser 
169669b46751STobias Grosser     PrintGPUUserData Data;
169769b46751STobias Grosser     Data.PPCGProg = PPCGProg;
169869b46751STobias Grosser 
169969b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
170069b46751STobias Grosser     Options =
170169b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
170269b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
170369b46751STobias Grosser     char *String = isl_printer_get_str(P);
170469b46751STobias Grosser     printf("# host\n");
170569b46751STobias Grosser     printf("%s\n", String);
170669b46751STobias Grosser     free(String);
170769b46751STobias Grosser     isl_printer_free(P);
170869b46751STobias Grosser 
170969b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
171069b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
171169b46751STobias Grosser       printKernel(Kernel);
171269b46751STobias Grosser     }
171369b46751STobias Grosser   }
171469b46751STobias Grosser 
1715f384594dSTobias Grosser   // Generate a GPU program using PPCG.
1716f384594dSTobias Grosser   //
1717f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
1718f384594dSTobias Grosser   //
1719f384594dSTobias Grosser   //  1) Compute new schedule for the program.
1720f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
1721f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
1722f384594dSTobias Grosser   //
1723f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
1724f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
1725f384594dSTobias Grosser   // strategy directly from this pass.
1726f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
1727f384594dSTobias Grosser 
1728f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
1729f384594dSTobias Grosser 
1730f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
1731f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
1732f384594dSTobias Grosser     PPCGGen->print = nullptr;
1733f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
173460c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
1735f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
1736f384594dSTobias Grosser     PPCGGen->tree = nullptr;
1737f384594dSTobias Grosser     PPCGGen->types.n = 0;
1738f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
1739f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
1740f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
1741f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
1742f384594dSTobias Grosser 
1743f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
1744f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
1745f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
17462341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
1747f384594dSTobias Grosser 
1748f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
1749f384594dSTobias Grosser 
1750aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
1751aef5196fSTobias Grosser 
175269b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
1753aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
175469b46751STobias Grosser     } else {
1755aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
175669b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
175769b46751STobias Grosser     }
1758aef5196fSTobias Grosser 
1759f384594dSTobias Grosser     if (DumpSchedule) {
1760f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
1761f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
1762f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
1763f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
1764f384594dSTobias Grosser       if (Schedule)
1765f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
1766f384594dSTobias Grosser       else
1767f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
1768f384594dSTobias Grosser 
1769f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
1770f384594dSTobias Grosser       isl_printer_free(P);
1771f384594dSTobias Grosser     }
1772f384594dSTobias Grosser 
177369b46751STobias Grosser     if (DumpCode) {
177469b46751STobias Grosser       printf("Code\n");
177569b46751STobias Grosser       printf("====\n");
177669b46751STobias Grosser       if (PPCGGen->tree)
177769b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
177869b46751STobias Grosser       else
177969b46751STobias Grosser         printf("No code generated\n");
178069b46751STobias Grosser     }
178169b46751STobias Grosser 
1782f384594dSTobias Grosser     isl_schedule_free(Schedule);
1783f384594dSTobias Grosser 
1784f384594dSTobias Grosser     return PPCGGen;
1785f384594dSTobias Grosser   }
1786f384594dSTobias Grosser 
1787f384594dSTobias Grosser   /// Free gpu_gen structure.
1788f384594dSTobias Grosser   ///
1789f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
1790f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
1791f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
1792f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
1793f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
1794f384594dSTobias Grosser     free(PPCGGen);
1795f384594dSTobias Grosser   }
1796f384594dSTobias Grosser 
1797b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
1798b307ed4dSTobias Grosser   ///
1799b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
1800b307ed4dSTobias Grosser   /// ourselves.
1801b307ed4dSTobias Grosser   ///
1802b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
1803b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
1804b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
1805b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
1806b307ed4dSTobias Grosser     free(PPCGScop->options);
1807b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
1808b307ed4dSTobias Grosser   }
1809b307ed4dSTobias Grosser 
181038fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
181138fc0aedSTobias Grosser   ///
181232837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
181332837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
181432837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
181538fc0aedSTobias Grosser     ScopAnnotator Annotator;
181638fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
181738fc0aedSTobias Grosser 
181838fc0aedSTobias Grosser     Region *R = &S->getRegion();
181938fc0aedSTobias Grosser 
182038fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
182138fc0aedSTobias Grosser 
182238fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
182338fc0aedSTobias Grosser 
182438fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
182538fc0aedSTobias Grosser 
182632837fe3STobias Grosser     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S,
182732837fe3STobias Grosser                                Prog);
182838fc0aedSTobias Grosser 
182938fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
183038fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
183138fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
183238fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
183338fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
183438fc0aedSTobias Grosser     // code generating this scop.
183538fc0aedSTobias Grosser     BasicBlock *StartBlock =
183638fc0aedSTobias Grosser         executeScopConditionally(*S, this, Builder.getTrue());
183738fc0aedSTobias Grosser 
183838fc0aedSTobias Grosser     // TODO: Handle LICM
183938fc0aedSTobias Grosser     // TODO: Verify run-time checks
184038fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
184138fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
184238fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
184338fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
1844fa7b0802STobias Grosser 
1845fa7b0802STobias Grosser     NodeBuilder.initializeAfterRTH();
184638fc0aedSTobias Grosser     NodeBuilder.create(Root);
18478ed5e599STobias Grosser     NodeBuilder.finalize();
184838fc0aedSTobias Grosser   }
184938fc0aedSTobias Grosser 
1850e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
1851e938517eSTobias Grosser     S = &CurrentScop;
185238fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
185338fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
185438fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
185538fc0aedSTobias Grosser     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
185638fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
1857e938517eSTobias Grosser 
18582d58a64eSTobias Grosser     // We currently do not support scops with invariant loads.
18592d58a64eSTobias Grosser     if (S->hasInvariantAccesses())
18602d58a64eSTobias Grosser       return false;
18612d58a64eSTobias Grosser 
1862e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
1863e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
1864f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
186538fc0aedSTobias Grosser 
186638fc0aedSTobias Grosser     if (PPCGGen->tree)
186732837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
186838fc0aedSTobias Grosser 
1869b307ed4dSTobias Grosser     freeOptions(PPCGScop);
1870f384594dSTobias Grosser     freePPCGGen(PPCGGen);
1871e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
1872e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
1873e938517eSTobias Grosser 
1874e938517eSTobias Grosser     return true;
1875e938517eSTobias Grosser   }
18769dfe4e7cSTobias Grosser 
18779dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
18789dfe4e7cSTobias Grosser 
18799dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
18809dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
18819dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
18829dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
18839dfe4e7cSTobias Grosser     AU.addRequired<ScopDetection>();
18849dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
18859dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
18869dfe4e7cSTobias Grosser 
18879dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
18889dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
18899dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
18909dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
18919dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
18929dfe4e7cSTobias Grosser     AU.addPreserved<PostDominatorTreeWrapperPass>();
18939dfe4e7cSTobias Grosser     AU.addPreserved<ScopDetection>();
18949dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
18959dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
18969dfe4e7cSTobias Grosser 
18979dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
18989dfe4e7cSTobias Grosser     //        region tree.
18999dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
19009dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
19019dfe4e7cSTobias Grosser   }
19029dfe4e7cSTobias Grosser };
19039dfe4e7cSTobias Grosser }
19049dfe4e7cSTobias Grosser 
19059dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
19069dfe4e7cSTobias Grosser 
19079dfe4e7cSTobias Grosser Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
19089dfe4e7cSTobias Grosser 
19099dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
19109dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
19119dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
19129dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
19139dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
19149dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
19159dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
19169dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScopDetection);
19179dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
19189dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
1919