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 
138*fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
139*fa7b0802STobias Grosser   void initializeAfterRTH();
140*fa7b0802STobias Grosser 
141*fa7b0802STobias Grosser   /// Finalize the generated scop.
142*fa7b0802STobias Grosser   virtual void finalize();
143*fa7b0802STobias 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 
151*fa7b0802STobias Grosser   /// The current GPU context.
152*fa7b0802STobias Grosser   Value *GPUContext;
153*fa7b0802STobias Grosser 
15432837fe3STobias Grosser   /// A module containing GPU code.
15532837fe3STobias Grosser   ///
15632837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
15732837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
15832837fe3STobias Grosser 
15932837fe3STobias Grosser   /// The GPU program we generate code for.
16032837fe3STobias Grosser   gpu_prog *Prog;
16132837fe3STobias Grosser 
162472f9654STobias Grosser   /// Class to free isl_ids.
163472f9654STobias Grosser   class IslIdDeleter {
164472f9654STobias Grosser   public:
165472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
166472f9654STobias Grosser   };
167472f9654STobias Grosser 
168472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
169472f9654STobias Grosser   ///
170472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
171472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
172472f9654STobias Grosser 
173edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
174edb885cbSTobias Grosser 
17538fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
17638fc0aedSTobias Grosser   ///
17738fc0aedSTobias Grosser   /// These AST nodes can be of type:
17838fc0aedSTobias Grosser   ///
17938fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
18038fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
18138fc0aedSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer (TODO)
1825260c041STobias Grosser   ///   - In-kernel synchronization
1835260c041STobias Grosser   ///   - In-kernel memory copy statement
18438fc0aedSTobias Grosser   ///
1851fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
1861fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
18732837fe3STobias Grosser 
188edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
189edb885cbSTobias Grosser   ///
190edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
191edb885cbSTobias Grosser   ///
192edb885cbSTobias Grosser   /// @returns A set of values referenced by the kernel.
193edb885cbSTobias Grosser   SetVector<Value *> getReferencesInKernel(ppcg_kernel *Kernel);
194edb885cbSTobias Grosser 
19532837fe3STobias Grosser   /// Create GPU kernel.
19632837fe3STobias Grosser   ///
19732837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
19832837fe3STobias Grosser   ///
19932837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
20032837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
20132837fe3STobias Grosser 
20232837fe3STobias Grosser   /// Create kernel function.
20332837fe3STobias Grosser   ///
20432837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
20532837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
20632837fe3STobias Grosser   /// start block of this newly created function.
20732837fe3STobias Grosser   ///
20832837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
209edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
210edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
211edb885cbSTobias Grosser                             SetVector<Value *> &SubtreeValues);
21232837fe3STobias Grosser 
21332837fe3STobias Grosser   /// Create the declaration of a kernel function.
21432837fe3STobias Grosser   ///
21532837fe3STobias Grosser   /// The kernel function takes as arguments:
21632837fe3STobias Grosser   ///
21732837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
218f6044bd0STobias Grosser   ///   - Host iterators
219c84a1995STobias Grosser   ///   - Parameters
22032837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
22132837fe3STobias Grosser   ///
22232837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
223edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
224edb885cbSTobias Grosser   ///
22532837fe3STobias Grosser   /// @returns The newly declared function.
226edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
227edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
22832837fe3STobias Grosser 
229472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
230472f9654STobias Grosser   ///
231472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
232472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
233472f9654STobias Grosser 
234edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
235edb885cbSTobias Grosser   ///
236edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
237edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
238edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
239edb885cbSTobias Grosser 
2405260c041STobias Grosser   /// Create an in-kernel synchronization call.
2415260c041STobias Grosser   void createKernelSync();
2425260c041STobias Grosser 
24374dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
24474dc3cb4STobias Grosser   ///
24574dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
24674dc3cb4STobias Grosser   std::string createKernelASM();
24774dc3cb4STobias Grosser 
24874dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
24974dc3cb4STobias Grosser   ///
25074dc3cb4STobias Grosser   /// @param F The function to remove references to.
25174dc3cb4STobias Grosser   void clearDominators(Function *F);
25274dc3cb4STobias Grosser 
25374dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
25474dc3cb4STobias Grosser   ///
25574dc3cb4STobias Grosser   /// @param F The function to remove references to.
25674dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
25774dc3cb4STobias Grosser 
25874dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
25974dc3cb4STobias Grosser   ///
26074dc3cb4STobias Grosser   /// @param F The function to remove references to.
26174dc3cb4STobias Grosser   void clearLoops(Function *F);
26274dc3cb4STobias Grosser 
26332837fe3STobias Grosser   /// Finalize the generation of the kernel function.
26432837fe3STobias Grosser   ///
26532837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
26632837fe3STobias Grosser   /// dump its IR to stderr.
26732837fe3STobias Grosser   void finalizeKernelFunction();
268*fa7b0802STobias Grosser 
269*fa7b0802STobias Grosser   void allocateDeviceArrays();
270*fa7b0802STobias Grosser 
271*fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
272*fa7b0802STobias Grosser   ///
273*fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
274*fa7b0802STobias Grosser   Value *createCallInitContext();
275*fa7b0802STobias Grosser 
276*fa7b0802STobias Grosser   /// Create a call to free the GPU context.
277*fa7b0802STobias Grosser   ///
278*fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
279*fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
280*fa7b0802STobias Grosser 
281*fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
2821fb9b64dSTobias Grosser };
2831fb9b64dSTobias Grosser 
284*fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
285*fa7b0802STobias Grosser   GPUContext = createCallInitContext();
286*fa7b0802STobias Grosser   allocateDeviceArrays();
287*fa7b0802STobias Grosser }
288*fa7b0802STobias Grosser 
289*fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
290*fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
291*fa7b0802STobias Grosser   IslNodeBuilder::finalize();
292*fa7b0802STobias Grosser }
293*fa7b0802STobias Grosser 
294*fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
295*fa7b0802STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
296*fa7b0802STobias Grosser 
297*fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
298*fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
299*fa7b0802STobias Grosser     std::string DevPtrName("p_devptr_");
300*fa7b0802STobias Grosser     DevPtrName.append(Array->name);
301*fa7b0802STobias Grosser 
302*fa7b0802STobias Grosser     Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
303*fa7b0802STobias Grosser 
304*fa7b0802STobias Grosser     if (!gpu_array_is_scalar(Array)) {
305*fa7b0802STobias Grosser       auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]);
306*fa7b0802STobias Grosser       isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero);
307*fa7b0802STobias Grosser 
308*fa7b0802STobias Grosser       for (unsigned int i = 1; i < Array->n_index; i++) {
309*fa7b0802STobias Grosser         isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]);
310*fa7b0802STobias Grosser         isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
311*fa7b0802STobias Grosser         Res = isl_ast_expr_mul(Res, Expr);
312*fa7b0802STobias Grosser       }
313*fa7b0802STobias Grosser 
314*fa7b0802STobias Grosser       Value *NumElements = ExprBuilder.create(Res);
315*fa7b0802STobias Grosser       ArraySize = Builder.CreateMul(ArraySize, NumElements);
316*fa7b0802STobias Grosser     }
317*fa7b0802STobias Grosser 
318*fa7b0802STobias Grosser     Value *DevPtr = createCallAllocateMemoryForDevice(ArraySize);
319*fa7b0802STobias Grosser     DevPtr->setName(DevPtrName);
320*fa7b0802STobias Grosser   }
321*fa7b0802STobias Grosser 
322*fa7b0802STobias Grosser   isl_ast_build_free(Build);
323*fa7b0802STobias Grosser }
324*fa7b0802STobias Grosser 
325*fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
326*fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
327*fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
328*fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
329*fa7b0802STobias Grosser 
330*fa7b0802STobias Grosser   // If F is not available, declare it.
331*fa7b0802STobias Grosser   if (!F) {
332*fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
333*fa7b0802STobias Grosser     std::vector<Type *> Args;
334*fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
335*fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
336*fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
337*fa7b0802STobias Grosser   }
338*fa7b0802STobias Grosser 
339*fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
340*fa7b0802STobias Grosser }
341*fa7b0802STobias Grosser 
342*fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
343*fa7b0802STobias Grosser   const char *Name = "polly_initContext";
344*fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
345*fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
346*fa7b0802STobias Grosser 
347*fa7b0802STobias Grosser   // If F is not available, declare it.
348*fa7b0802STobias Grosser   if (!F) {
349*fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
350*fa7b0802STobias Grosser     std::vector<Type *> Args;
351*fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
352*fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
353*fa7b0802STobias Grosser   }
354*fa7b0802STobias Grosser 
355*fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
356*fa7b0802STobias Grosser }
357*fa7b0802STobias Grosser 
358*fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
359*fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
360*fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
361*fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
362*fa7b0802STobias Grosser 
363*fa7b0802STobias Grosser   // If F is not available, declare it.
364*fa7b0802STobias Grosser   if (!F) {
365*fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
366*fa7b0802STobias Grosser     std::vector<Type *> Args;
367*fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
368*fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
369*fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
370*fa7b0802STobias Grosser   }
371*fa7b0802STobias Grosser 
372*fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
373*fa7b0802STobias Grosser }
374*fa7b0802STobias Grosser 
3755260c041STobias Grosser /// Check if one string is a prefix of another.
3765260c041STobias Grosser ///
3775260c041STobias Grosser /// @param String The string in which to look for the prefix.
3785260c041STobias Grosser /// @param Prefix The prefix to look for.
3795260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
3805260c041STobias Grosser   return String.find(Prefix) == 0;
3815260c041STobias Grosser }
3825260c041STobias Grosser 
3831fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
38432837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
38532837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
38632837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
38732837fe3STobias Grosser   isl_id_free(Id);
38832837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
38932837fe3STobias Grosser 
39032837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
39132837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
39232837fe3STobias Grosser     createKernel(UserStmt);
39332837fe3STobias Grosser     isl_ast_expr_free(Expr);
39432837fe3STobias Grosser     return;
39532837fe3STobias Grosser   }
39632837fe3STobias Grosser 
3975260c041STobias Grosser   if (isPrefix(Str, "to_device") || isPrefix(Str, "from_device")) {
3985260c041STobias Grosser     // TODO: Insert memory copies
39932837fe3STobias Grosser     isl_ast_expr_free(Expr);
4001fb9b64dSTobias Grosser     isl_ast_node_free(UserStmt);
40138fc0aedSTobias Grosser     return;
40238fc0aedSTobias Grosser   }
40338fc0aedSTobias Grosser 
4045260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
4055260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
4065260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
4075260c041STobias Grosser   isl_id_free(Anno);
4085260c041STobias Grosser 
4095260c041STobias Grosser   switch (KernelStmt->type) {
4105260c041STobias Grosser   case ppcg_kernel_domain:
411edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
4125260c041STobias Grosser     isl_ast_node_free(UserStmt);
4135260c041STobias Grosser     return;
4145260c041STobias Grosser   case ppcg_kernel_copy:
4155260c041STobias Grosser     // TODO: Create kernel copy stmt
4165260c041STobias Grosser     isl_ast_expr_free(Expr);
4175260c041STobias Grosser     isl_ast_node_free(UserStmt);
4185260c041STobias Grosser     return;
4195260c041STobias Grosser   case ppcg_kernel_sync:
4205260c041STobias Grosser     createKernelSync();
4215260c041STobias Grosser     isl_ast_expr_free(Expr);
4225260c041STobias Grosser     isl_ast_node_free(UserStmt);
4235260c041STobias Grosser     return;
4245260c041STobias Grosser   }
4255260c041STobias Grosser 
4265260c041STobias Grosser   isl_ast_expr_free(Expr);
4275260c041STobias Grosser   isl_ast_node_free(UserStmt);
4285260c041STobias Grosser   return;
4295260c041STobias Grosser }
4305260c041STobias Grosser 
431edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
432edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
433edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
434edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
435edb885cbSTobias Grosser 
436edb885cbSTobias Grosser   LoopToScevMapT LTS;
437edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
438edb885cbSTobias Grosser 
439edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
440edb885cbSTobias Grosser 
441edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
442edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
443edb885cbSTobias Grosser   else
444edb885cbSTobias Grosser     assert(0 && "Region statement not supported\n");
445edb885cbSTobias Grosser }
446edb885cbSTobias Grosser 
4475260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
4485260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
4495260c041STobias Grosser   auto *Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
4505260c041STobias Grosser   Builder.CreateCall(Sync, {});
4515260c041STobias Grosser }
4525260c041STobias Grosser 
453edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
454edb885cbSTobias Grosser ///
455edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
456edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
457edb885cbSTobias Grosser ///
458edb885cbSTobias Grosser /// @param Node The node to collect references for.
459edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
460edb885cbSTobias Grosser ///
461edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
462edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
463edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
464edb885cbSTobias Grosser     return isl_bool_true;
465edb885cbSTobias Grosser 
466edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
467edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
468edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
469edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
470edb885cbSTobias Grosser   isl_id_free(Id);
471edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
472edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
473edb885cbSTobias Grosser 
474edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
475edb885cbSTobias Grosser     return isl_bool_true;
476edb885cbSTobias Grosser 
477edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
478edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
479edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
480edb885cbSTobias Grosser   isl_id_free(Id);
481edb885cbSTobias Grosser 
482edb885cbSTobias Grosser   addReferencesFromStmt(Stmt, User);
483edb885cbSTobias Grosser 
484edb885cbSTobias Grosser   return isl_bool_true;
485edb885cbSTobias Grosser }
486edb885cbSTobias Grosser 
487edb885cbSTobias Grosser SetVector<Value *> GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
488edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
489edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
490edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
491edb885cbSTobias Grosser   SubtreeReferences References = {
492edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
493edb885cbSTobias Grosser 
494edb885cbSTobias Grosser   for (const auto &I : IDToValue)
495edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
496edb885cbSTobias Grosser 
497edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
498edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
499edb885cbSTobias Grosser 
500edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
501edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
502edb885cbSTobias Grosser 
503edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
504edb885cbSTobias Grosser     SubtreeValues.remove(SAI.second->getBasePtr());
505edb885cbSTobias Grosser 
506edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
507edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
508edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
509edb885cbSTobias Grosser     assert(IDToValue.count(Id));
510edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
511edb885cbSTobias Grosser     SubtreeValues.remove(Val);
512edb885cbSTobias Grosser     isl_id_free(Id);
513edb885cbSTobias Grosser   }
514edb885cbSTobias Grosser   isl_space_free(Space);
515edb885cbSTobias Grosser 
516edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
517edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
518edb885cbSTobias Grosser     assert(IDToValue.count(Id));
519edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
520edb885cbSTobias Grosser     SubtreeValues.remove(Val);
521edb885cbSTobias Grosser     isl_id_free(Id);
522edb885cbSTobias Grosser   }
523edb885cbSTobias Grosser 
524edb885cbSTobias Grosser   return SubtreeValues;
525edb885cbSTobias Grosser }
526edb885cbSTobias Grosser 
52774dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
52874dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
52974dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
53074dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
53174dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
53274dc3cb4STobias Grosser 
53374dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
53474dc3cb4STobias Grosser     DT.eraseNode(BB);
53574dc3cb4STobias Grosser }
53674dc3cb4STobias Grosser 
53774dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
53874dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
53974dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
54074dc3cb4STobias Grosser     if (L)
54174dc3cb4STobias Grosser       SE.forgetLoop(L);
54274dc3cb4STobias Grosser   }
54374dc3cb4STobias Grosser }
54474dc3cb4STobias Grosser 
54574dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
54674dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
54774dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
54874dc3cb4STobias Grosser     if (L)
54974dc3cb4STobias Grosser       SE.forgetLoop(L);
55074dc3cb4STobias Grosser     LI.removeBlock(&BB);
55174dc3cb4STobias Grosser   }
55274dc3cb4STobias Grosser }
55374dc3cb4STobias Grosser 
55432837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
55532837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
55632837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
55732837fe3STobias Grosser   isl_id_free(Id);
55832837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
55932837fe3STobias Grosser 
560edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel);
561edb885cbSTobias Grosser 
56232837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
56332837fe3STobias Grosser 
56432837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
565472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
566edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
56732837fe3STobias Grosser 
568edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
569edb885cbSTobias Grosser 
570edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
571edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
572edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
573edb885cbSTobias Grosser   for (const Loop *L : Loops) {
574edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
575edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
576edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
577edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
578edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
579edb885cbSTobias Grosser     SubtreeValues.insert(V);
580edb885cbSTobias Grosser   }
581edb885cbSTobias Grosser 
582edb885cbSTobias Grosser   createKernelFunction(Kernel, SubtreeValues);
58332837fe3STobias Grosser 
58459ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
58559ab0705STobias Grosser 
58674dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
58774dc3cb4STobias Grosser   clearDominators(F);
58874dc3cb4STobias Grosser   clearScalarEvolution(F);
58974dc3cb4STobias Grosser   clearLoops(F);
59074dc3cb4STobias Grosser 
59132837fe3STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
592472f9654STobias Grosser   IDToValue = HostIDs;
59332837fe3STobias Grosser 
594edb885cbSTobias Grosser   ValueMap = HostValueMap;
595edb885cbSTobias Grosser   ScalarMap.clear();
596edb885cbSTobias Grosser   PHIOpMap.clear();
597edb885cbSTobias Grosser   EscapeMap.clear();
598edb885cbSTobias Grosser   IDToSAI.clear();
59974dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
60074dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
60174dc3cb4STobias Grosser     S.invalidateScopArrayInfo(BasePtr, ScopArrayInfo::MK_Array);
60274dc3cb4STobias Grosser   LocalArrays.clear();
603edb885cbSTobias Grosser 
60432837fe3STobias Grosser   finalizeKernelFunction();
60532837fe3STobias Grosser }
60632837fe3STobias Grosser 
60732837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
60832837fe3STobias Grosser ///
60932837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
61032837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
61132837fe3STobias Grosser   std::string Ret = "e";
61232837fe3STobias Grosser 
61332837fe3STobias Grosser   if (!is64Bit)
61432837fe3STobias Grosser     Ret += "-p:32:32";
61532837fe3STobias Grosser 
61632837fe3STobias Grosser   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
61732837fe3STobias Grosser 
61832837fe3STobias Grosser   return Ret;
61932837fe3STobias Grosser }
62032837fe3STobias Grosser 
621edb885cbSTobias Grosser Function *
622edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
623edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
62432837fe3STobias Grosser   std::vector<Type *> Args;
62532837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
62632837fe3STobias Grosser 
62732837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
62832837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
62932837fe3STobias Grosser       continue;
63032837fe3STobias Grosser 
63132837fe3STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
63232837fe3STobias Grosser   }
63332837fe3STobias Grosser 
634f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
635f6044bd0STobias Grosser 
636f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++)
637f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
638f6044bd0STobias Grosser 
639c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
640c84a1995STobias Grosser 
641c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++)
642c84a1995STobias Grosser     Args.push_back(Builder.getInt64Ty());
643c84a1995STobias Grosser 
644edb885cbSTobias Grosser   for (auto *V : SubtreeValues)
645edb885cbSTobias Grosser     Args.push_back(V->getType());
646edb885cbSTobias Grosser 
64732837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
64832837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
64932837fe3STobias Grosser                               GPUModule.get());
65032837fe3STobias Grosser   FN->setCallingConv(CallingConv::PTX_Kernel);
65132837fe3STobias Grosser 
65232837fe3STobias Grosser   auto Arg = FN->arg_begin();
65332837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
65432837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
65532837fe3STobias Grosser       continue;
65632837fe3STobias Grosser 
657edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
658edb885cbSTobias Grosser 
659edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
660edb885cbSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
661edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
662edb885cbSTobias Grosser     Value *Val = &*Arg;
663edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
664edb885cbSTobias Grosser     isl_ast_build *Build =
665edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
666edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
667edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
668edb885cbSTobias Grosser           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
669edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
670edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
671edb885cbSTobias Grosser     }
672edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
673edb885cbSTobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, ScopArrayInfo::MK_Array);
67474dc3cb4STobias Grosser     LocalArrays.push_back(Val);
675edb885cbSTobias Grosser 
676edb885cbSTobias Grosser     isl_ast_build_free(Build);
677edb885cbSTobias Grosser     isl_id_free(Id);
678edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
67932837fe3STobias Grosser     Arg++;
68032837fe3STobias Grosser   }
68132837fe3STobias Grosser 
682f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
683f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
684f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
685f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
686f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
687f6044bd0STobias Grosser     Arg++;
688f6044bd0STobias Grosser   }
689f6044bd0STobias Grosser 
690c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
691c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
692c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
693c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
694c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
695c84a1995STobias Grosser     Arg++;
696c84a1995STobias Grosser   }
697c84a1995STobias Grosser 
698edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
699edb885cbSTobias Grosser     Arg->setName(V->getName());
700edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
701edb885cbSTobias Grosser     Arg++;
702edb885cbSTobias Grosser   }
703edb885cbSTobias Grosser 
70432837fe3STobias Grosser   return FN;
70532837fe3STobias Grosser }
70632837fe3STobias Grosser 
707472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
708472f9654STobias Grosser   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
709472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
710472f9654STobias Grosser 
711472f9654STobias Grosser   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
712472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
713472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
714472f9654STobias Grosser 
715472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
716472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
717472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
718472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
719472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
720472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
721472f9654STobias Grosser     IDToValue[Id] = Val;
722472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
723472f9654STobias Grosser   };
724472f9654STobias Grosser 
725472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
726472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
727472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
728472f9654STobias Grosser   }
729472f9654STobias Grosser 
730472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
731472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
732472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
733472f9654STobias Grosser   }
734472f9654STobias Grosser }
735472f9654STobias Grosser 
736edb885cbSTobias Grosser void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel,
737edb885cbSTobias Grosser                                           SetVector<Value *> &SubtreeValues) {
73832837fe3STobias Grosser 
73932837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
74032837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
74132837fe3STobias Grosser   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
74232837fe3STobias Grosser   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
74332837fe3STobias Grosser 
744edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
74532837fe3STobias Grosser 
74659ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
74732837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
74832837fe3STobias Grosser 
74959ab0705STobias Grosser   DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
75059ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
75159ab0705STobias Grosser 
75232837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
75332837fe3STobias Grosser   Builder.CreateRetVoid();
75432837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
755472f9654STobias Grosser 
756472f9654STobias Grosser   insertKernelIntrinsics(Kernel);
75732837fe3STobias Grosser }
75832837fe3STobias Grosser 
75974dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
76074dc3cb4STobias Grosser   llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda"));
76174dc3cb4STobias Grosser   std::string ErrMsg;
76274dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
76374dc3cb4STobias Grosser 
76474dc3cb4STobias Grosser   if (!GPUTarget) {
76574dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
76674dc3cb4STobias Grosser     return "";
76774dc3cb4STobias Grosser   }
76874dc3cb4STobias Grosser 
76974dc3cb4STobias Grosser   TargetOptions Options;
77074dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
77174dc3cb4STobias Grosser   std::unique_ptr<TargetMachine> TargetM(
77274dc3cb4STobias Grosser       GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "",
77374dc3cb4STobias Grosser                                      Options, Optional<Reloc::Model>()));
77474dc3cb4STobias Grosser 
77574dc3cb4STobias Grosser   SmallString<0> ASMString;
77674dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
77774dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
77874dc3cb4STobias Grosser 
77974dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
78074dc3cb4STobias Grosser 
78174dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
78274dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
78374dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
78474dc3cb4STobias Grosser     return "";
78574dc3cb4STobias Grosser   }
78674dc3cb4STobias Grosser 
78774dc3cb4STobias Grosser   PM.run(*GPUModule);
78874dc3cb4STobias Grosser 
78974dc3cb4STobias Grosser   return ASMStream.str();
79074dc3cb4STobias Grosser }
79174dc3cb4STobias Grosser 
79232837fe3STobias Grosser void GPUNodeBuilder::finalizeKernelFunction() {
793e1a98343STobias Grosser   // Verify module.
794e1a98343STobias Grosser   llvm::legacy::PassManager Passes;
795e1a98343STobias Grosser   Passes.add(createVerifierPass());
796e1a98343STobias Grosser   Passes.run(*GPUModule);
79732837fe3STobias Grosser 
79832837fe3STobias Grosser   if (DumpKernelIR)
79932837fe3STobias Grosser     outs() << *GPUModule << "\n";
80032837fe3STobias Grosser 
8019a18d559STobias Grosser   // Optimize module.
8029a18d559STobias Grosser   llvm::legacy::PassManager OptPasses;
8039a18d559STobias Grosser   PassManagerBuilder PassBuilder;
8049a18d559STobias Grosser   PassBuilder.OptLevel = 3;
8059a18d559STobias Grosser   PassBuilder.SizeLevel = 0;
8069a18d559STobias Grosser   PassBuilder.populateModulePassManager(OptPasses);
8079a18d559STobias Grosser   OptPasses.run(*GPUModule);
8089a18d559STobias Grosser 
80974dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
81074dc3cb4STobias Grosser 
81174dc3cb4STobias Grosser   if (DumpKernelASM)
81274dc3cb4STobias Grosser     outs() << Assembly << "\n";
81374dc3cb4STobias Grosser 
81432837fe3STobias Grosser   GPUModule.release();
815472f9654STobias Grosser   KernelIDs.clear();
81632837fe3STobias Grosser }
81732837fe3STobias Grosser 
8189dfe4e7cSTobias Grosser namespace {
8199dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
8209dfe4e7cSTobias Grosser public:
8219dfe4e7cSTobias Grosser   static char ID;
8229dfe4e7cSTobias Grosser 
823e938517eSTobias Grosser   /// The scop that is currently processed.
824e938517eSTobias Grosser   Scop *S;
825e938517eSTobias Grosser 
82638fc0aedSTobias Grosser   LoopInfo *LI;
82738fc0aedSTobias Grosser   DominatorTree *DT;
82838fc0aedSTobias Grosser   ScalarEvolution *SE;
82938fc0aedSTobias Grosser   const DataLayout *DL;
83038fc0aedSTobias Grosser   RegionInfo *RI;
83138fc0aedSTobias Grosser 
8329dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
8339dfe4e7cSTobias Grosser 
834e938517eSTobias Grosser   /// Construct compilation options for PPCG.
835e938517eSTobias Grosser   ///
836e938517eSTobias Grosser   /// @returns The compilation options.
837e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
838e938517eSTobias Grosser     auto DebugOptions =
839e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
840e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
841e938517eSTobias Grosser 
842e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
843e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
844e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
845e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
846e938517eSTobias Grosser 
847e938517eSTobias Grosser     Options->debug = DebugOptions;
848e938517eSTobias Grosser 
849e938517eSTobias Grosser     Options->reschedule = true;
850e938517eSTobias Grosser     Options->scale_tile_loops = false;
851e938517eSTobias Grosser     Options->wrap = false;
852e938517eSTobias Grosser 
853e938517eSTobias Grosser     Options->non_negative_parameters = false;
854e938517eSTobias Grosser     Options->ctx = nullptr;
855e938517eSTobias Grosser     Options->sizes = nullptr;
856e938517eSTobias Grosser 
8574eaedde5STobias Grosser     Options->tile_size = 32;
8584eaedde5STobias Grosser 
859e938517eSTobias Grosser     Options->use_private_memory = false;
860e938517eSTobias Grosser     Options->use_shared_memory = false;
861e938517eSTobias Grosser     Options->max_shared_memory = 0;
862e938517eSTobias Grosser 
863e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
864e938517eSTobias Grosser     Options->openmp = false;
865e938517eSTobias Grosser     Options->linearize_device_arrays = true;
866e938517eSTobias Grosser     Options->live_range_reordering = false;
867e938517eSTobias Grosser 
868e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
869e938517eSTobias Grosser     Options->opencl_use_gpu = false;
870e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
871e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
872e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
873e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
874e938517eSTobias Grosser 
875e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
876e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
877e938517eSTobias Grosser 
878e938517eSTobias Grosser     return Options;
879e938517eSTobias Grosser   }
880e938517eSTobias Grosser 
881f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
882f384594dSTobias Grosser   ///
883f384594dSTobias Grosser   /// Instead of a normal access of the form:
884f384594dSTobias Grosser   ///
885f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
886f384594dSTobias Grosser   ///
887f384594dSTobias Grosser   /// a tagged access has the form
888f384594dSTobias Grosser   ///
889f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
890f384594dSTobias Grosser   ///
891f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
892f384594dSTobias Grosser   /// triggered the access.
893f384594dSTobias Grosser   ///
894f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
895f384594dSTobias Grosser   ///
896f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
897f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
898f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
899f384594dSTobias Grosser 
900f384594dSTobias Grosser     for (auto &Stmt : *S)
901f384594dSTobias Grosser       for (auto &Acc : Stmt)
902f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
903f384594dSTobias Grosser           isl_map *Relation = Acc->getAccessRelation();
904f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
905f384594dSTobias Grosser 
906f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
907f384594dSTobias Grosser           Space = isl_space_range(Space);
908f384594dSTobias Grosser           Space = isl_space_from_range(Space);
9096293ba69STobias Grosser           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
910f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
911f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
912f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
913f384594dSTobias Grosser         }
914f384594dSTobias Grosser 
915f384594dSTobias Grosser     return Accesses;
916f384594dSTobias Grosser   }
917f384594dSTobias Grosser 
918f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
919f384594dSTobias Grosser   ///
920f384594dSTobias Grosser   /// @see getTaggedAccesses
921f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
922f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
923f384594dSTobias Grosser   }
924f384594dSTobias Grosser 
925f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
926f384594dSTobias Grosser   ///
927f384594dSTobias Grosser   /// @see getTaggedAccesses
928f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
929f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
930f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
931f384594dSTobias Grosser   }
932f384594dSTobias Grosser 
933f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
934f384594dSTobias Grosser   ///
935f384594dSTobias Grosser   /// @see getTaggedAccesses
936f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
937f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
938f384594dSTobias Grosser   }
939f384594dSTobias Grosser 
940aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
941aef5196fSTobias Grosser   ///
942aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
943aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
944aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
945aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
946aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
947aef5196fSTobias Grosser   /// the data format that ppcg expects.
948aef5196fSTobias Grosser   ///
949aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
950aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
951aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
952bd81a7eeSTobias Grosser         S->getIslCtx(),
953bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
954aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
955aef5196fSTobias Grosser     auto *Space = S->getParamSpace();
956aef5196fSTobias Grosser 
957aef5196fSTobias Grosser     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
958aef5196fSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
959aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
960aef5196fSTobias Grosser     }
961aef5196fSTobias Grosser 
962aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
963aef5196fSTobias Grosser       auto Id = Array.second->getBasePtrId();
964aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
965aef5196fSTobias Grosser     }
966aef5196fSTobias Grosser 
967aef5196fSTobias Grosser     isl_space_free(Space);
968aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
969aef5196fSTobias Grosser 
970aef5196fSTobias Grosser     return Names;
971aef5196fSTobias Grosser   }
972aef5196fSTobias Grosser 
973e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
974e938517eSTobias Grosser   ///
975f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
976f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
977f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
978f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
979e938517eSTobias Grosser   ///
980e938517eSTobias Grosser   /// @returns A new ppcg scop.
981e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
982e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
983e938517eSTobias Grosser 
984e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
985e938517eSTobias Grosser 
986e938517eSTobias Grosser     PPCGScop->start = 0;
987e938517eSTobias Grosser     PPCGScop->end = 0;
988e938517eSTobias Grosser 
989f384594dSTobias Grosser     PPCGScop->context = S->getContext();
990f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
991e938517eSTobias Grosser     PPCGScop->call = nullptr;
992f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
993f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
994e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
995f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
996f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
997f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
998f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
999e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
1000f384594dSTobias Grosser     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
1001e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
1002e938517eSTobias Grosser 
1003e938517eSTobias Grosser     PPCGScop->independence = nullptr;
1004e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
1005e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
1006e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
1007e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
1008e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
1009e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
1010e938517eSTobias Grosser 
1011f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
1012aef5196fSTobias Grosser     PPCGScop->names = getNames();
1013e938517eSTobias Grosser 
1014e938517eSTobias Grosser     PPCGScop->pet = nullptr;
1015e938517eSTobias Grosser 
1016f384594dSTobias Grosser     compute_tagger(PPCGScop);
1017f384594dSTobias Grosser     compute_dependences(PPCGScop);
1018f384594dSTobias Grosser 
1019e938517eSTobias Grosser     return PPCGScop;
1020e938517eSTobias Grosser   }
1021e938517eSTobias Grosser 
102260f63b49STobias Grosser   /// Collect the array acesses in a statement.
102360f63b49STobias Grosser   ///
102460f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
102560f63b49STobias Grosser   ///
102660f63b49STobias Grosser   /// @returns A list of array accesses.
102760f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
102860f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
102960f63b49STobias Grosser 
103060f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
103160f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
103260f63b49STobias Grosser       Access->read = Acc->isRead();
103360f63b49STobias Grosser       Access->write = Acc->isWrite();
103460f63b49STobias Grosser       Access->access = Acc->getAccessRelation();
103560f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
103660f63b49STobias Grosser       Space = isl_space_range(Space);
103760f63b49STobias Grosser       Space = isl_space_from_range(Space);
10386293ba69STobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
103960f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
104060f63b49STobias Grosser       Access->tagged_access =
104160f63b49STobias Grosser           isl_map_domain_product(Acc->getAccessRelation(), Universe);
104260f63b49STobias Grosser       Access->exact_write = Acc->isWrite();
104360f63b49STobias Grosser       Access->ref_id = Acc->getId();
104460f63b49STobias Grosser       Access->next = Accesses;
104560f63b49STobias Grosser       Accesses = Access;
104660f63b49STobias Grosser     }
104760f63b49STobias Grosser 
104860f63b49STobias Grosser     return Accesses;
104960f63b49STobias Grosser   }
105060f63b49STobias Grosser 
105169b46751STobias Grosser   /// Collect the list of GPU statements.
105269b46751STobias Grosser   ///
105369b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
105469b46751STobias Grosser   /// as well as a list with all memory accesses.
105569b46751STobias Grosser   ///
105669b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
105769b46751STobias Grosser   ///
105869b46751STobias Grosser   /// @returns A linked-list of statements.
105969b46751STobias Grosser   gpu_stmt *getStatements() {
106069b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
106169b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
106269b46751STobias Grosser 
106369b46751STobias Grosser     int i = 0;
106469b46751STobias Grosser     for (auto &Stmt : *S) {
106569b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
106669b46751STobias Grosser 
106769b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
106869b46751STobias Grosser 
106969b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
107069b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
107160f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
107269b46751STobias Grosser       i++;
107369b46751STobias Grosser     }
107469b46751STobias Grosser 
107569b46751STobias Grosser     return Stmts;
107669b46751STobias Grosser   }
107769b46751STobias Grosser 
107860f63b49STobias Grosser   /// Derive the extent of an array.
107960f63b49STobias Grosser   ///
108060f63b49STobias Grosser   /// The extent of an array is defined by the set of memory locations for
108160f63b49STobias Grosser   /// which a memory access in the iteration domain exists.
108260f63b49STobias Grosser   ///
108360f63b49STobias Grosser   /// @param Array The array to derive the extent for.
108460f63b49STobias Grosser   ///
108560f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
108660f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
108760f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
108860f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
108960f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
109060f63b49STobias Grosser     isl_set *AccessSet =
109160f63b49STobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace());
109260f63b49STobias Grosser     isl_union_set_free(AccessUSet);
109360f63b49STobias Grosser 
109460f63b49STobias Grosser     return AccessSet;
109560f63b49STobias Grosser   }
109660f63b49STobias Grosser 
109760f63b49STobias Grosser   /// Derive the bounds of an array.
109860f63b49STobias Grosser   ///
109960f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
110060f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
110160f63b49STobias Grosser   /// ScopArrayInfo.
110260f63b49STobias Grosser   ///
110360f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
110460f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
110560f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
110660f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
110760f63b49STobias Grosser       isl_set *Dom = isl_set_copy(PPCGArray.extent);
110860f63b49STobias Grosser       Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
110960f63b49STobias Grosser       isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
111060f63b49STobias Grosser       isl_set_free(Dom);
111160f63b49STobias Grosser       Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
111260f63b49STobias Grosser       isl_local_space *LS = isl_local_space_from_space(isl_set_get_space(Dom));
111360f63b49STobias Grosser       isl_aff *One = isl_aff_zero_on_domain(LS);
111460f63b49STobias Grosser       One = isl_aff_add_constant_si(One, 1);
111560f63b49STobias Grosser       Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
111660f63b49STobias Grosser       Bound = isl_pw_aff_gist(Bound, S->getContext());
111760f63b49STobias Grosser       PPCGArray.bound[0] = Bound;
111860f63b49STobias Grosser     }
111960f63b49STobias Grosser 
112060f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
112160f63b49STobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
112260f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
112360f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
112460f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
112560f63b49STobias Grosser       PPCGArray.bound[i] = Bound;
112660f63b49STobias Grosser     }
112760f63b49STobias Grosser   }
112860f63b49STobias Grosser 
112960f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
113060f63b49STobias Grosser   ///
113160f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
113260f63b49STobias Grosser   void createArrays(gpu_prog *PPCGProg) {
113360f63b49STobias Grosser     int i = 0;
113460f63b49STobias Grosser     for (auto &Element : S->arrays()) {
113560f63b49STobias Grosser       ScopArrayInfo *Array = Element.second.get();
113660f63b49STobias Grosser 
113760f63b49STobias Grosser       std::string TypeName;
113860f63b49STobias Grosser       raw_string_ostream OS(TypeName);
113960f63b49STobias Grosser 
114060f63b49STobias Grosser       OS << *Array->getElementType();
114160f63b49STobias Grosser       TypeName = OS.str();
114260f63b49STobias Grosser 
114360f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
114460f63b49STobias Grosser 
114560f63b49STobias Grosser       PPCGArray.space = Array->getSpace();
114660f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
114760f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
114860f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
114960f63b49STobias Grosser       PPCGArray.extent = nullptr;
115060f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
115160f63b49STobias Grosser       PPCGArray.bound =
115260f63b49STobias Grosser           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
115360f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
115460f63b49STobias Grosser       PPCGArray.n_ref = 0;
115560f63b49STobias Grosser       PPCGArray.refs = nullptr;
115660f63b49STobias Grosser       PPCGArray.accessed = true;
115760f63b49STobias Grosser       PPCGArray.read_only_scalar = false;
115860f63b49STobias Grosser       PPCGArray.has_compound_element = false;
115960f63b49STobias Grosser       PPCGArray.local = false;
116060f63b49STobias Grosser       PPCGArray.declare_local = false;
116160f63b49STobias Grosser       PPCGArray.global = false;
116260f63b49STobias Grosser       PPCGArray.linearize = false;
116360f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
116460f63b49STobias Grosser 
116560f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
11662d010dafSTobias Grosser       i++;
1167b9fc860aSTobias Grosser 
1168b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
116960f63b49STobias Grosser     }
117060f63b49STobias Grosser   }
117160f63b49STobias Grosser 
117260f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
117360f63b49STobias Grosser   ///
117460f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
117560f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
117660f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
117760f63b49STobias Grosser 
117860f63b49STobias Grosser     for (auto &Item : S->arrays()) {
117960f63b49STobias Grosser       ScopArrayInfo *Array = Item.second.get();
118060f63b49STobias Grosser       isl_space *Space = Array->getSpace();
118160f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
118260f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
118360f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
118460f63b49STobias Grosser     }
118560f63b49STobias Grosser 
118660f63b49STobias Grosser     return Maps;
118760f63b49STobias Grosser   }
118860f63b49STobias Grosser 
1189e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
1190e938517eSTobias Grosser   ///
1191e938517eSTobias Grosser   /// @returns A new gpu grogram description.
1192e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
1193e938517eSTobias Grosser 
1194e938517eSTobias Grosser     if (!PPCGScop)
1195e938517eSTobias Grosser       return nullptr;
1196e938517eSTobias Grosser 
1197e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
1198e938517eSTobias Grosser 
1199e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
1200e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
1201aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
120260f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
120360f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
120460f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
120560f63b49STobias Grosser     PPCGProg->tagged_must_kill =
120660f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
120760f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
120860f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
120960f63b49STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
1210e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
1211e938517eSTobias Grosser     PPCGProg->array_order = nullptr;
121269b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
121369b46751STobias Grosser     PPCGProg->stmts = getStatements();
121460f63b49STobias Grosser     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
121560f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
121660f63b49STobias Grosser                                        PPCGProg->n_array);
121760f63b49STobias Grosser 
121860f63b49STobias Grosser     createArrays(PPCGProg);
1219e938517eSTobias Grosser 
1220e938517eSTobias Grosser     return PPCGProg;
1221e938517eSTobias Grosser   }
1222e938517eSTobias Grosser 
122369b46751STobias Grosser   struct PrintGPUUserData {
122469b46751STobias Grosser     struct cuda_info *CudaInfo;
122569b46751STobias Grosser     struct gpu_prog *PPCGProg;
122669b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
122769b46751STobias Grosser   };
122869b46751STobias Grosser 
122969b46751STobias Grosser   /// Print a user statement node in the host code.
123069b46751STobias Grosser   ///
123169b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
123269b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
123369b46751STobias Grosser   /// host ast.
123469b46751STobias Grosser   ///
123569b46751STobias Grosser   /// @param P The printer to print to
123669b46751STobias Grosser   /// @param Options The printing options to use
123769b46751STobias Grosser   /// @param Node The node to print
123869b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
123969b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
124069b46751STobias Grosser   ///
124169b46751STobias Grosser   /// @returns A printer to which the output has been printed.
124269b46751STobias Grosser   static __isl_give isl_printer *
124369b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
124469b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
124569b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
124669b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
124769b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
124869b46751STobias Grosser 
124969b46751STobias Grosser     if (Id) {
125020251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
125120251734STobias Grosser 
125220251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
125320251734STobias Grosser       // otherwise try to call pet functionality that is not available in
125420251734STobias Grosser       // Polly.
125520251734STobias Grosser       if (IsUser) {
125620251734STobias Grosser         P = isl_printer_start_line(P);
125720251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
125820251734STobias Grosser         P = isl_printer_end_line(P);
125920251734STobias Grosser         isl_id_free(Id);
126020251734STobias Grosser         isl_ast_print_options_free(Options);
126120251734STobias Grosser         return P;
126220251734STobias Grosser       }
126320251734STobias Grosser 
126469b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
126569b46751STobias Grosser       isl_id_free(Id);
126669b46751STobias Grosser       Data->Kernels.push_back(Kernel);
126769b46751STobias Grosser     }
126869b46751STobias Grosser 
126969b46751STobias Grosser     return print_host_user(P, Options, Node, User);
127069b46751STobias Grosser   }
127169b46751STobias Grosser 
127269b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
127369b46751STobias Grosser   ///
127469b46751STobias Grosser   /// @param Kernel The kernel to print
127569b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
127669b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
127769b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
127869b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
127969b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
128069b46751STobias Grosser     char *String = isl_printer_get_str(P);
128169b46751STobias Grosser     printf("%s\n", String);
128269b46751STobias Grosser     free(String);
128369b46751STobias Grosser     isl_printer_free(P);
128469b46751STobias Grosser   }
128569b46751STobias Grosser 
128669b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
128769b46751STobias Grosser   ///
128869b46751STobias Grosser   /// @param Tree An AST describing GPU code
128969b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
129069b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
129169b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
129269b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
129369b46751STobias Grosser 
129469b46751STobias Grosser     PrintGPUUserData Data;
129569b46751STobias Grosser     Data.PPCGProg = PPCGProg;
129669b46751STobias Grosser 
129769b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
129869b46751STobias Grosser     Options =
129969b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
130069b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
130169b46751STobias Grosser     char *String = isl_printer_get_str(P);
130269b46751STobias Grosser     printf("# host\n");
130369b46751STobias Grosser     printf("%s\n", String);
130469b46751STobias Grosser     free(String);
130569b46751STobias Grosser     isl_printer_free(P);
130669b46751STobias Grosser 
130769b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
130869b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
130969b46751STobias Grosser       printKernel(Kernel);
131069b46751STobias Grosser     }
131169b46751STobias Grosser   }
131269b46751STobias Grosser 
1313f384594dSTobias Grosser   // Generate a GPU program using PPCG.
1314f384594dSTobias Grosser   //
1315f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
1316f384594dSTobias Grosser   //
1317f384594dSTobias Grosser   //  1) Compute new schedule for the program.
1318f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
1319f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
1320f384594dSTobias Grosser   //
1321f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
1322f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
1323f384594dSTobias Grosser   // strategy directly from this pass.
1324f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
1325f384594dSTobias Grosser 
1326f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
1327f384594dSTobias Grosser 
1328f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
1329f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
1330f384594dSTobias Grosser     PPCGGen->print = nullptr;
1331f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
133260c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
1333f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
1334f384594dSTobias Grosser     PPCGGen->tree = nullptr;
1335f384594dSTobias Grosser     PPCGGen->types.n = 0;
1336f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
1337f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
1338f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
1339f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
1340f384594dSTobias Grosser 
1341f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
1342f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
1343f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
13442341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
1345f384594dSTobias Grosser 
1346f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
1347f384594dSTobias Grosser 
1348aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
1349aef5196fSTobias Grosser 
135069b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
1351aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
135269b46751STobias Grosser     } else {
1353aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
135469b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
135569b46751STobias Grosser     }
1356aef5196fSTobias Grosser 
1357f384594dSTobias Grosser     if (DumpSchedule) {
1358f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
1359f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
1360f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
1361f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
1362f384594dSTobias Grosser       if (Schedule)
1363f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
1364f384594dSTobias Grosser       else
1365f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
1366f384594dSTobias Grosser 
1367f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
1368f384594dSTobias Grosser       isl_printer_free(P);
1369f384594dSTobias Grosser     }
1370f384594dSTobias Grosser 
137169b46751STobias Grosser     if (DumpCode) {
137269b46751STobias Grosser       printf("Code\n");
137369b46751STobias Grosser       printf("====\n");
137469b46751STobias Grosser       if (PPCGGen->tree)
137569b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
137669b46751STobias Grosser       else
137769b46751STobias Grosser         printf("No code generated\n");
137869b46751STobias Grosser     }
137969b46751STobias Grosser 
1380f384594dSTobias Grosser     isl_schedule_free(Schedule);
1381f384594dSTobias Grosser 
1382f384594dSTobias Grosser     return PPCGGen;
1383f384594dSTobias Grosser   }
1384f384594dSTobias Grosser 
1385f384594dSTobias Grosser   /// Free gpu_gen structure.
1386f384594dSTobias Grosser   ///
1387f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
1388f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
1389f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
1390f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
1391f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
1392f384594dSTobias Grosser     free(PPCGGen);
1393f384594dSTobias Grosser   }
1394f384594dSTobias Grosser 
1395b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
1396b307ed4dSTobias Grosser   ///
1397b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
1398b307ed4dSTobias Grosser   /// ourselves.
1399b307ed4dSTobias Grosser   ///
1400b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
1401b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
1402b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
1403b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
1404b307ed4dSTobias Grosser     free(PPCGScop->options);
1405b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
1406b307ed4dSTobias Grosser   }
1407b307ed4dSTobias Grosser 
140838fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
140938fc0aedSTobias Grosser   ///
141032837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
141132837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
141232837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
141338fc0aedSTobias Grosser     ScopAnnotator Annotator;
141438fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
141538fc0aedSTobias Grosser 
141638fc0aedSTobias Grosser     Region *R = &S->getRegion();
141738fc0aedSTobias Grosser 
141838fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
141938fc0aedSTobias Grosser 
142038fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
142138fc0aedSTobias Grosser 
142238fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
142338fc0aedSTobias Grosser 
142432837fe3STobias Grosser     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S,
142532837fe3STobias Grosser                                Prog);
142638fc0aedSTobias Grosser 
142738fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
142838fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
142938fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
143038fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
143138fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
143238fc0aedSTobias Grosser     // code generating this scop.
143338fc0aedSTobias Grosser     BasicBlock *StartBlock =
143438fc0aedSTobias Grosser         executeScopConditionally(*S, this, Builder.getTrue());
143538fc0aedSTobias Grosser 
143638fc0aedSTobias Grosser     // TODO: Handle LICM
143738fc0aedSTobias Grosser     // TODO: Verify run-time checks
143838fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
143938fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
144038fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
144138fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
1442*fa7b0802STobias Grosser 
1443*fa7b0802STobias Grosser     NodeBuilder.initializeAfterRTH();
144438fc0aedSTobias Grosser     NodeBuilder.create(Root);
14458ed5e599STobias Grosser     NodeBuilder.finalize();
144638fc0aedSTobias Grosser   }
144738fc0aedSTobias Grosser 
1448e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
1449e938517eSTobias Grosser     S = &CurrentScop;
145038fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
145138fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
145238fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
145338fc0aedSTobias Grosser     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
145438fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
1455e938517eSTobias Grosser 
14562d58a64eSTobias Grosser     // We currently do not support scops with invariant loads.
14572d58a64eSTobias Grosser     if (S->hasInvariantAccesses())
14582d58a64eSTobias Grosser       return false;
14592d58a64eSTobias Grosser 
1460e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
1461e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
1462f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
146338fc0aedSTobias Grosser 
146438fc0aedSTobias Grosser     if (PPCGGen->tree)
146532837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
146638fc0aedSTobias Grosser 
1467b307ed4dSTobias Grosser     freeOptions(PPCGScop);
1468f384594dSTobias Grosser     freePPCGGen(PPCGGen);
1469e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
1470e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
1471e938517eSTobias Grosser 
1472e938517eSTobias Grosser     return true;
1473e938517eSTobias Grosser   }
14749dfe4e7cSTobias Grosser 
14759dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
14769dfe4e7cSTobias Grosser 
14779dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
14789dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
14799dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
14809dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
14819dfe4e7cSTobias Grosser     AU.addRequired<ScopDetection>();
14829dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
14839dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
14849dfe4e7cSTobias Grosser 
14859dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
14869dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
14879dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
14889dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
14899dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
14909dfe4e7cSTobias Grosser     AU.addPreserved<PostDominatorTreeWrapperPass>();
14919dfe4e7cSTobias Grosser     AU.addPreserved<ScopDetection>();
14929dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
14939dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
14949dfe4e7cSTobias Grosser 
14959dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
14969dfe4e7cSTobias Grosser     //        region tree.
14979dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
14989dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
14999dfe4e7cSTobias Grosser   }
15009dfe4e7cSTobias Grosser };
15019dfe4e7cSTobias Grosser }
15029dfe4e7cSTobias Grosser 
15039dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
15049dfe4e7cSTobias Grosser 
15059dfe4e7cSTobias Grosser Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
15069dfe4e7cSTobias Grosser 
15079dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
15089dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
15099dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
15109dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
15119dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
15129dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
15139dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
15149dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScopDetection);
15159dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
15169dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
1517