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 
151*7287aeddSTobias Grosser   /// A list of device arrays that has been allocated.
152*7287aeddSTobias Grosser   std::vector<Value *> AllocatedDevArrays;
153*7287aeddSTobias 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)
18438fc0aedSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer (TODO)
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 
191edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
192edb885cbSTobias Grosser   ///
193edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
194edb885cbSTobias Grosser   ///
195edb885cbSTobias Grosser   /// @returns A set of values referenced by the kernel.
196edb885cbSTobias Grosser   SetVector<Value *> getReferencesInKernel(ppcg_kernel *Kernel);
197edb885cbSTobias Grosser 
19832837fe3STobias Grosser   /// Create GPU kernel.
19932837fe3STobias Grosser   ///
20032837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
20132837fe3STobias Grosser   ///
20232837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
20332837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
20432837fe3STobias Grosser 
20532837fe3STobias Grosser   /// Create kernel function.
20632837fe3STobias Grosser   ///
20732837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
20832837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
20932837fe3STobias Grosser   /// start block of this newly created function.
21032837fe3STobias Grosser   ///
21132837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
212edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
213edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
214edb885cbSTobias Grosser                             SetVector<Value *> &SubtreeValues);
21532837fe3STobias Grosser 
21632837fe3STobias Grosser   /// Create the declaration of a kernel function.
21732837fe3STobias Grosser   ///
21832837fe3STobias Grosser   /// The kernel function takes as arguments:
21932837fe3STobias Grosser   ///
22032837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
221f6044bd0STobias Grosser   ///   - Host iterators
222c84a1995STobias Grosser   ///   - Parameters
22332837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
22432837fe3STobias Grosser   ///
22532837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
226edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
227edb885cbSTobias Grosser   ///
22832837fe3STobias Grosser   /// @returns The newly declared function.
229edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
230edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
23132837fe3STobias Grosser 
232472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
233472f9654STobias Grosser   ///
234472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
235472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
236472f9654STobias Grosser 
237edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
238edb885cbSTobias Grosser   ///
239edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
240edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
241edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
242edb885cbSTobias Grosser 
2435260c041STobias Grosser   /// Create an in-kernel synchronization call.
2445260c041STobias Grosser   void createKernelSync();
2455260c041STobias Grosser 
24674dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
24774dc3cb4STobias Grosser   ///
24874dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
24974dc3cb4STobias Grosser   std::string createKernelASM();
25074dc3cb4STobias Grosser 
25174dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
25274dc3cb4STobias Grosser   ///
25374dc3cb4STobias Grosser   /// @param F The function to remove references to.
25474dc3cb4STobias Grosser   void clearDominators(Function *F);
25574dc3cb4STobias Grosser 
25674dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
25774dc3cb4STobias Grosser   ///
25874dc3cb4STobias Grosser   /// @param F The function to remove references to.
25974dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
26074dc3cb4STobias Grosser 
26174dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
26274dc3cb4STobias Grosser   ///
26374dc3cb4STobias Grosser   /// @param F The function to remove references to.
26474dc3cb4STobias Grosser   void clearLoops(Function *F);
26574dc3cb4STobias Grosser 
26632837fe3STobias Grosser   /// Finalize the generation of the kernel function.
26732837fe3STobias Grosser   ///
26832837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
26932837fe3STobias Grosser   /// dump its IR to stderr.
27032837fe3STobias Grosser   void finalizeKernelFunction();
271fa7b0802STobias Grosser 
272*7287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
273fa7b0802STobias Grosser   void allocateDeviceArrays();
274fa7b0802STobias Grosser 
275*7287aeddSTobias Grosser   /// Free all allocated device arrays.
276*7287aeddSTobias Grosser   void freeDeviceArrays();
277*7287aeddSTobias Grosser 
278fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
279fa7b0802STobias Grosser   ///
280fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
281fa7b0802STobias Grosser   Value *createCallInitContext();
282fa7b0802STobias Grosser 
283fa7b0802STobias Grosser   /// Create a call to free the GPU context.
284fa7b0802STobias Grosser   ///
285fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
286fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
287fa7b0802STobias Grosser 
288*7287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
289*7287aeddSTobias Grosser   ///
290*7287aeddSTobias Grosser   /// @param Size The size of memory to allocate
291*7287aeddSTobias Grosser   ///
292*7287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
293fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
294*7287aeddSTobias Grosser 
295*7287aeddSTobias Grosser   /// Create a call to free a device array.
296*7287aeddSTobias Grosser   ///
297*7287aeddSTobias Grosser   /// @param Array The device array to free.
298*7287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
2991fb9b64dSTobias Grosser };
3001fb9b64dSTobias Grosser 
301fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
302fa7b0802STobias Grosser   GPUContext = createCallInitContext();
303fa7b0802STobias Grosser   allocateDeviceArrays();
304fa7b0802STobias Grosser }
305fa7b0802STobias Grosser 
306fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
307*7287aeddSTobias Grosser   freeDeviceArrays();
308fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
309fa7b0802STobias Grosser   IslNodeBuilder::finalize();
310fa7b0802STobias Grosser }
311fa7b0802STobias Grosser 
312fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
313fa7b0802STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
314fa7b0802STobias Grosser 
315fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
316fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
317*7287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
318*7287aeddSTobias Grosser     DevArrayName.append(Array->name);
319fa7b0802STobias Grosser 
320fa7b0802STobias Grosser     Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
321fa7b0802STobias Grosser 
322fa7b0802STobias Grosser     if (!gpu_array_is_scalar(Array)) {
323fa7b0802STobias Grosser       auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]);
324fa7b0802STobias Grosser       isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero);
325fa7b0802STobias Grosser 
326fa7b0802STobias Grosser       for (unsigned int i = 1; i < Array->n_index; i++) {
327fa7b0802STobias Grosser         isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]);
328fa7b0802STobias Grosser         isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
329fa7b0802STobias Grosser         Res = isl_ast_expr_mul(Res, Expr);
330fa7b0802STobias Grosser       }
331fa7b0802STobias Grosser 
332fa7b0802STobias Grosser       Value *NumElements = ExprBuilder.create(Res);
333fa7b0802STobias Grosser       ArraySize = Builder.CreateMul(ArraySize, NumElements);
334fa7b0802STobias Grosser     }
335fa7b0802STobias Grosser 
336*7287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
337*7287aeddSTobias Grosser     DevArray->setName(DevArrayName);
338*7287aeddSTobias Grosser     AllocatedDevArrays.push_back(DevArray);
339fa7b0802STobias Grosser   }
340fa7b0802STobias Grosser 
341fa7b0802STobias Grosser   isl_ast_build_free(Build);
342fa7b0802STobias Grosser }
343fa7b0802STobias Grosser 
344*7287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
345*7287aeddSTobias Grosser   for (auto &Array : AllocatedDevArrays)
346*7287aeddSTobias Grosser     createCallFreeDeviceMemory(Array);
347*7287aeddSTobias Grosser }
348*7287aeddSTobias Grosser 
349*7287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
350*7287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
351*7287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
352*7287aeddSTobias Grosser   Function *F = M->getFunction(Name);
353*7287aeddSTobias Grosser 
354*7287aeddSTobias Grosser   // If F is not available, declare it.
355*7287aeddSTobias Grosser   if (!F) {
356*7287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
357*7287aeddSTobias Grosser     std::vector<Type *> Args;
358*7287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
359*7287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
360*7287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
361*7287aeddSTobias Grosser   }
362*7287aeddSTobias Grosser 
363*7287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
364*7287aeddSTobias Grosser }
365*7287aeddSTobias Grosser 
366fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
367fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
368fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
369fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
370fa7b0802STobias Grosser 
371fa7b0802STobias Grosser   // If F is not available, declare it.
372fa7b0802STobias Grosser   if (!F) {
373fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
374fa7b0802STobias Grosser     std::vector<Type *> Args;
375fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
376fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
377fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
378fa7b0802STobias Grosser   }
379fa7b0802STobias Grosser 
380fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
381fa7b0802STobias Grosser }
382fa7b0802STobias Grosser 
383fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
384fa7b0802STobias Grosser   const char *Name = "polly_initContext";
385fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
386fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
387fa7b0802STobias Grosser 
388fa7b0802STobias Grosser   // If F is not available, declare it.
389fa7b0802STobias Grosser   if (!F) {
390fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
391fa7b0802STobias Grosser     std::vector<Type *> Args;
392fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
393fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
394fa7b0802STobias Grosser   }
395fa7b0802STobias Grosser 
396fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
397fa7b0802STobias Grosser }
398fa7b0802STobias Grosser 
399fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
400fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
401fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
402fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
403fa7b0802STobias Grosser 
404fa7b0802STobias Grosser   // If F is not available, declare it.
405fa7b0802STobias Grosser   if (!F) {
406fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
407fa7b0802STobias Grosser     std::vector<Type *> Args;
408fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
409fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
410fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
411fa7b0802STobias Grosser   }
412fa7b0802STobias Grosser 
413fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
414fa7b0802STobias Grosser }
415fa7b0802STobias Grosser 
4165260c041STobias Grosser /// Check if one string is a prefix of another.
4175260c041STobias Grosser ///
4185260c041STobias Grosser /// @param String The string in which to look for the prefix.
4195260c041STobias Grosser /// @param Prefix The prefix to look for.
4205260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
4215260c041STobias Grosser   return String.find(Prefix) == 0;
4225260c041STobias Grosser }
4235260c041STobias Grosser 
4241fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
42532837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
42632837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
42732837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
42832837fe3STobias Grosser   isl_id_free(Id);
42932837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
43032837fe3STobias Grosser 
43132837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
43232837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
43332837fe3STobias Grosser     createKernel(UserStmt);
43432837fe3STobias Grosser     isl_ast_expr_free(Expr);
43532837fe3STobias Grosser     return;
43632837fe3STobias Grosser   }
43732837fe3STobias Grosser 
4385260c041STobias Grosser   if (isPrefix(Str, "to_device") || isPrefix(Str, "from_device")) {
4395260c041STobias Grosser     // TODO: Insert memory copies
44032837fe3STobias Grosser     isl_ast_expr_free(Expr);
4411fb9b64dSTobias Grosser     isl_ast_node_free(UserStmt);
44238fc0aedSTobias Grosser     return;
44338fc0aedSTobias Grosser   }
44438fc0aedSTobias Grosser 
4455260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
4465260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
4475260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
4485260c041STobias Grosser   isl_id_free(Anno);
4495260c041STobias Grosser 
4505260c041STobias Grosser   switch (KernelStmt->type) {
4515260c041STobias Grosser   case ppcg_kernel_domain:
452edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
4535260c041STobias Grosser     isl_ast_node_free(UserStmt);
4545260c041STobias Grosser     return;
4555260c041STobias Grosser   case ppcg_kernel_copy:
4565260c041STobias Grosser     // TODO: Create kernel copy stmt
4575260c041STobias Grosser     isl_ast_expr_free(Expr);
4585260c041STobias Grosser     isl_ast_node_free(UserStmt);
4595260c041STobias Grosser     return;
4605260c041STobias Grosser   case ppcg_kernel_sync:
4615260c041STobias Grosser     createKernelSync();
4625260c041STobias Grosser     isl_ast_expr_free(Expr);
4635260c041STobias Grosser     isl_ast_node_free(UserStmt);
4645260c041STobias Grosser     return;
4655260c041STobias Grosser   }
4665260c041STobias Grosser 
4675260c041STobias Grosser   isl_ast_expr_free(Expr);
4685260c041STobias Grosser   isl_ast_node_free(UserStmt);
4695260c041STobias Grosser   return;
4705260c041STobias Grosser }
4715260c041STobias Grosser 
472edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
473edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
474edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
475edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
476edb885cbSTobias Grosser 
477edb885cbSTobias Grosser   LoopToScevMapT LTS;
478edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
479edb885cbSTobias Grosser 
480edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
481edb885cbSTobias Grosser 
482edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
483edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
484edb885cbSTobias Grosser   else
485edb885cbSTobias Grosser     assert(0 && "Region statement not supported\n");
486edb885cbSTobias Grosser }
487edb885cbSTobias Grosser 
4885260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
4895260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
4905260c041STobias Grosser   auto *Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
4915260c041STobias Grosser   Builder.CreateCall(Sync, {});
4925260c041STobias Grosser }
4935260c041STobias Grosser 
494edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
495edb885cbSTobias Grosser ///
496edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
497edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
498edb885cbSTobias Grosser ///
499edb885cbSTobias Grosser /// @param Node The node to collect references for.
500edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
501edb885cbSTobias Grosser ///
502edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
503edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
504edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
505edb885cbSTobias Grosser     return isl_bool_true;
506edb885cbSTobias Grosser 
507edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
508edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
509edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
510edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
511edb885cbSTobias Grosser   isl_id_free(Id);
512edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
513edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
514edb885cbSTobias Grosser 
515edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
516edb885cbSTobias Grosser     return isl_bool_true;
517edb885cbSTobias Grosser 
518edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
519edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
520edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
521edb885cbSTobias Grosser   isl_id_free(Id);
522edb885cbSTobias Grosser 
523edb885cbSTobias Grosser   addReferencesFromStmt(Stmt, User);
524edb885cbSTobias Grosser 
525edb885cbSTobias Grosser   return isl_bool_true;
526edb885cbSTobias Grosser }
527edb885cbSTobias Grosser 
528edb885cbSTobias Grosser SetVector<Value *> GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
529edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
530edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
531edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
532edb885cbSTobias Grosser   SubtreeReferences References = {
533edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
534edb885cbSTobias Grosser 
535edb885cbSTobias Grosser   for (const auto &I : IDToValue)
536edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
537edb885cbSTobias Grosser 
538edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
539edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
540edb885cbSTobias Grosser 
541edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
542edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
543edb885cbSTobias Grosser 
544edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
545edb885cbSTobias Grosser     SubtreeValues.remove(SAI.second->getBasePtr());
546edb885cbSTobias Grosser 
547edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
548edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
549edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
550edb885cbSTobias Grosser     assert(IDToValue.count(Id));
551edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
552edb885cbSTobias Grosser     SubtreeValues.remove(Val);
553edb885cbSTobias Grosser     isl_id_free(Id);
554edb885cbSTobias Grosser   }
555edb885cbSTobias Grosser   isl_space_free(Space);
556edb885cbSTobias Grosser 
557edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
558edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
559edb885cbSTobias Grosser     assert(IDToValue.count(Id));
560edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
561edb885cbSTobias Grosser     SubtreeValues.remove(Val);
562edb885cbSTobias Grosser     isl_id_free(Id);
563edb885cbSTobias Grosser   }
564edb885cbSTobias Grosser 
565edb885cbSTobias Grosser   return SubtreeValues;
566edb885cbSTobias Grosser }
567edb885cbSTobias Grosser 
56874dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
56974dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
57074dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
57174dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
57274dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
57374dc3cb4STobias Grosser 
57474dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
57574dc3cb4STobias Grosser     DT.eraseNode(BB);
57674dc3cb4STobias Grosser }
57774dc3cb4STobias Grosser 
57874dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
57974dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
58074dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
58174dc3cb4STobias Grosser     if (L)
58274dc3cb4STobias Grosser       SE.forgetLoop(L);
58374dc3cb4STobias Grosser   }
58474dc3cb4STobias Grosser }
58574dc3cb4STobias Grosser 
58674dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
58774dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
58874dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
58974dc3cb4STobias Grosser     if (L)
59074dc3cb4STobias Grosser       SE.forgetLoop(L);
59174dc3cb4STobias Grosser     LI.removeBlock(&BB);
59274dc3cb4STobias Grosser   }
59374dc3cb4STobias Grosser }
59474dc3cb4STobias Grosser 
59532837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
59632837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
59732837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
59832837fe3STobias Grosser   isl_id_free(Id);
59932837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
60032837fe3STobias Grosser 
601edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel);
602edb885cbSTobias Grosser 
60332837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
60432837fe3STobias Grosser 
60532837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
606472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
607edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
60832837fe3STobias Grosser 
609edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
610edb885cbSTobias Grosser 
611edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
612edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
613edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
614edb885cbSTobias Grosser   for (const Loop *L : Loops) {
615edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
616edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
617edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
618edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
619edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
620edb885cbSTobias Grosser     SubtreeValues.insert(V);
621edb885cbSTobias Grosser   }
622edb885cbSTobias Grosser 
623edb885cbSTobias Grosser   createKernelFunction(Kernel, SubtreeValues);
62432837fe3STobias Grosser 
62559ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
62659ab0705STobias Grosser 
62774dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
62874dc3cb4STobias Grosser   clearDominators(F);
62974dc3cb4STobias Grosser   clearScalarEvolution(F);
63074dc3cb4STobias Grosser   clearLoops(F);
63174dc3cb4STobias Grosser 
63232837fe3STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
633472f9654STobias Grosser   IDToValue = HostIDs;
63432837fe3STobias Grosser 
635edb885cbSTobias Grosser   ValueMap = HostValueMap;
636edb885cbSTobias Grosser   ScalarMap.clear();
637edb885cbSTobias Grosser   PHIOpMap.clear();
638edb885cbSTobias Grosser   EscapeMap.clear();
639edb885cbSTobias Grosser   IDToSAI.clear();
64074dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
64174dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
64274dc3cb4STobias Grosser     S.invalidateScopArrayInfo(BasePtr, ScopArrayInfo::MK_Array);
64374dc3cb4STobias Grosser   LocalArrays.clear();
644edb885cbSTobias Grosser 
64532837fe3STobias Grosser   finalizeKernelFunction();
64632837fe3STobias Grosser }
64732837fe3STobias Grosser 
64832837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
64932837fe3STobias Grosser ///
65032837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
65132837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
65232837fe3STobias Grosser   std::string Ret = "e";
65332837fe3STobias Grosser 
65432837fe3STobias Grosser   if (!is64Bit)
65532837fe3STobias Grosser     Ret += "-p:32:32";
65632837fe3STobias Grosser 
65732837fe3STobias Grosser   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
65832837fe3STobias Grosser 
65932837fe3STobias Grosser   return Ret;
66032837fe3STobias Grosser }
66132837fe3STobias Grosser 
662edb885cbSTobias Grosser Function *
663edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
664edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
66532837fe3STobias Grosser   std::vector<Type *> Args;
66632837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
66732837fe3STobias Grosser 
66832837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
66932837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
67032837fe3STobias Grosser       continue;
67132837fe3STobias Grosser 
67232837fe3STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
67332837fe3STobias Grosser   }
67432837fe3STobias Grosser 
675f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
676f6044bd0STobias Grosser 
677f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++)
678f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
679f6044bd0STobias Grosser 
680c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
681c84a1995STobias Grosser 
682c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++)
683c84a1995STobias Grosser     Args.push_back(Builder.getInt64Ty());
684c84a1995STobias Grosser 
685edb885cbSTobias Grosser   for (auto *V : SubtreeValues)
686edb885cbSTobias Grosser     Args.push_back(V->getType());
687edb885cbSTobias Grosser 
68832837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
68932837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
69032837fe3STobias Grosser                               GPUModule.get());
69132837fe3STobias Grosser   FN->setCallingConv(CallingConv::PTX_Kernel);
69232837fe3STobias Grosser 
69332837fe3STobias Grosser   auto Arg = FN->arg_begin();
69432837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
69532837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
69632837fe3STobias Grosser       continue;
69732837fe3STobias Grosser 
698edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
699edb885cbSTobias Grosser 
700edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
701edb885cbSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
702edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
703edb885cbSTobias Grosser     Value *Val = &*Arg;
704edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
705edb885cbSTobias Grosser     isl_ast_build *Build =
706edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
707edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
708edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
709edb885cbSTobias Grosser           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
710edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
711edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
712edb885cbSTobias Grosser     }
713edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
714edb885cbSTobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, ScopArrayInfo::MK_Array);
71574dc3cb4STobias Grosser     LocalArrays.push_back(Val);
716edb885cbSTobias Grosser 
717edb885cbSTobias Grosser     isl_ast_build_free(Build);
718edb885cbSTobias Grosser     isl_id_free(Id);
719edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
72032837fe3STobias Grosser     Arg++;
72132837fe3STobias Grosser   }
72232837fe3STobias Grosser 
723f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
724f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
725f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
726f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
727f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
728f6044bd0STobias Grosser     Arg++;
729f6044bd0STobias Grosser   }
730f6044bd0STobias Grosser 
731c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
732c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
733c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
734c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
735c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
736c84a1995STobias Grosser     Arg++;
737c84a1995STobias Grosser   }
738c84a1995STobias Grosser 
739edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
740edb885cbSTobias Grosser     Arg->setName(V->getName());
741edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
742edb885cbSTobias Grosser     Arg++;
743edb885cbSTobias Grosser   }
744edb885cbSTobias Grosser 
74532837fe3STobias Grosser   return FN;
74632837fe3STobias Grosser }
74732837fe3STobias Grosser 
748472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
749472f9654STobias Grosser   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
750472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
751472f9654STobias Grosser 
752472f9654STobias Grosser   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
753472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
754472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
755472f9654STobias Grosser 
756472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
757472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
758472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
759472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
760472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
761472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
762472f9654STobias Grosser     IDToValue[Id] = Val;
763472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
764472f9654STobias Grosser   };
765472f9654STobias Grosser 
766472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
767472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
768472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
769472f9654STobias Grosser   }
770472f9654STobias Grosser 
771472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
772472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
773472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
774472f9654STobias Grosser   }
775472f9654STobias Grosser }
776472f9654STobias Grosser 
777edb885cbSTobias Grosser void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel,
778edb885cbSTobias Grosser                                           SetVector<Value *> &SubtreeValues) {
77932837fe3STobias Grosser 
78032837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
78132837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
78232837fe3STobias Grosser   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
78332837fe3STobias Grosser   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
78432837fe3STobias Grosser 
785edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
78632837fe3STobias Grosser 
78759ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
78832837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
78932837fe3STobias Grosser 
79059ab0705STobias Grosser   DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
79159ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
79259ab0705STobias Grosser 
79332837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
79432837fe3STobias Grosser   Builder.CreateRetVoid();
79532837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
796472f9654STobias Grosser 
797472f9654STobias Grosser   insertKernelIntrinsics(Kernel);
79832837fe3STobias Grosser }
79932837fe3STobias Grosser 
80074dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
80174dc3cb4STobias Grosser   llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda"));
80274dc3cb4STobias Grosser   std::string ErrMsg;
80374dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
80474dc3cb4STobias Grosser 
80574dc3cb4STobias Grosser   if (!GPUTarget) {
80674dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
80774dc3cb4STobias Grosser     return "";
80874dc3cb4STobias Grosser   }
80974dc3cb4STobias Grosser 
81074dc3cb4STobias Grosser   TargetOptions Options;
81174dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
81274dc3cb4STobias Grosser   std::unique_ptr<TargetMachine> TargetM(
81374dc3cb4STobias Grosser       GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "",
81474dc3cb4STobias Grosser                                      Options, Optional<Reloc::Model>()));
81574dc3cb4STobias Grosser 
81674dc3cb4STobias Grosser   SmallString<0> ASMString;
81774dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
81874dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
81974dc3cb4STobias Grosser 
82074dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
82174dc3cb4STobias Grosser 
82274dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
82374dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
82474dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
82574dc3cb4STobias Grosser     return "";
82674dc3cb4STobias Grosser   }
82774dc3cb4STobias Grosser 
82874dc3cb4STobias Grosser   PM.run(*GPUModule);
82974dc3cb4STobias Grosser 
83074dc3cb4STobias Grosser   return ASMStream.str();
83174dc3cb4STobias Grosser }
83274dc3cb4STobias Grosser 
83332837fe3STobias Grosser void GPUNodeBuilder::finalizeKernelFunction() {
834e1a98343STobias Grosser   // Verify module.
835e1a98343STobias Grosser   llvm::legacy::PassManager Passes;
836e1a98343STobias Grosser   Passes.add(createVerifierPass());
837e1a98343STobias Grosser   Passes.run(*GPUModule);
83832837fe3STobias Grosser 
83932837fe3STobias Grosser   if (DumpKernelIR)
84032837fe3STobias Grosser     outs() << *GPUModule << "\n";
84132837fe3STobias Grosser 
8429a18d559STobias Grosser   // Optimize module.
8439a18d559STobias Grosser   llvm::legacy::PassManager OptPasses;
8449a18d559STobias Grosser   PassManagerBuilder PassBuilder;
8459a18d559STobias Grosser   PassBuilder.OptLevel = 3;
8469a18d559STobias Grosser   PassBuilder.SizeLevel = 0;
8479a18d559STobias Grosser   PassBuilder.populateModulePassManager(OptPasses);
8489a18d559STobias Grosser   OptPasses.run(*GPUModule);
8499a18d559STobias Grosser 
85074dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
85174dc3cb4STobias Grosser 
85274dc3cb4STobias Grosser   if (DumpKernelASM)
85374dc3cb4STobias Grosser     outs() << Assembly << "\n";
85474dc3cb4STobias Grosser 
85532837fe3STobias Grosser   GPUModule.release();
856472f9654STobias Grosser   KernelIDs.clear();
85732837fe3STobias Grosser }
85832837fe3STobias Grosser 
8599dfe4e7cSTobias Grosser namespace {
8609dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
8619dfe4e7cSTobias Grosser public:
8629dfe4e7cSTobias Grosser   static char ID;
8639dfe4e7cSTobias Grosser 
864e938517eSTobias Grosser   /// The scop that is currently processed.
865e938517eSTobias Grosser   Scop *S;
866e938517eSTobias Grosser 
86738fc0aedSTobias Grosser   LoopInfo *LI;
86838fc0aedSTobias Grosser   DominatorTree *DT;
86938fc0aedSTobias Grosser   ScalarEvolution *SE;
87038fc0aedSTobias Grosser   const DataLayout *DL;
87138fc0aedSTobias Grosser   RegionInfo *RI;
87238fc0aedSTobias Grosser 
8739dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
8749dfe4e7cSTobias Grosser 
875e938517eSTobias Grosser   /// Construct compilation options for PPCG.
876e938517eSTobias Grosser   ///
877e938517eSTobias Grosser   /// @returns The compilation options.
878e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
879e938517eSTobias Grosser     auto DebugOptions =
880e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
881e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
882e938517eSTobias Grosser 
883e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
884e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
885e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
886e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
887e938517eSTobias Grosser 
888e938517eSTobias Grosser     Options->debug = DebugOptions;
889e938517eSTobias Grosser 
890e938517eSTobias Grosser     Options->reschedule = true;
891e938517eSTobias Grosser     Options->scale_tile_loops = false;
892e938517eSTobias Grosser     Options->wrap = false;
893e938517eSTobias Grosser 
894e938517eSTobias Grosser     Options->non_negative_parameters = false;
895e938517eSTobias Grosser     Options->ctx = nullptr;
896e938517eSTobias Grosser     Options->sizes = nullptr;
897e938517eSTobias Grosser 
8984eaedde5STobias Grosser     Options->tile_size = 32;
8994eaedde5STobias Grosser 
900e938517eSTobias Grosser     Options->use_private_memory = false;
901e938517eSTobias Grosser     Options->use_shared_memory = false;
902e938517eSTobias Grosser     Options->max_shared_memory = 0;
903e938517eSTobias Grosser 
904e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
905e938517eSTobias Grosser     Options->openmp = false;
906e938517eSTobias Grosser     Options->linearize_device_arrays = true;
907e938517eSTobias Grosser     Options->live_range_reordering = false;
908e938517eSTobias Grosser 
909e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
910e938517eSTobias Grosser     Options->opencl_use_gpu = false;
911e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
912e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
913e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
914e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
915e938517eSTobias Grosser 
916e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
917e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
918e938517eSTobias Grosser 
919e938517eSTobias Grosser     return Options;
920e938517eSTobias Grosser   }
921e938517eSTobias Grosser 
922f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
923f384594dSTobias Grosser   ///
924f384594dSTobias Grosser   /// Instead of a normal access of the form:
925f384594dSTobias Grosser   ///
926f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
927f384594dSTobias Grosser   ///
928f384594dSTobias Grosser   /// a tagged access has the form
929f384594dSTobias Grosser   ///
930f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
931f384594dSTobias Grosser   ///
932f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
933f384594dSTobias Grosser   /// triggered the access.
934f384594dSTobias Grosser   ///
935f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
936f384594dSTobias Grosser   ///
937f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
938f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
939f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
940f384594dSTobias Grosser 
941f384594dSTobias Grosser     for (auto &Stmt : *S)
942f384594dSTobias Grosser       for (auto &Acc : Stmt)
943f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
944f384594dSTobias Grosser           isl_map *Relation = Acc->getAccessRelation();
945f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
946f384594dSTobias Grosser 
947f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
948f384594dSTobias Grosser           Space = isl_space_range(Space);
949f384594dSTobias Grosser           Space = isl_space_from_range(Space);
9506293ba69STobias Grosser           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
951f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
952f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
953f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
954f384594dSTobias Grosser         }
955f384594dSTobias Grosser 
956f384594dSTobias Grosser     return Accesses;
957f384594dSTobias Grosser   }
958f384594dSTobias Grosser 
959f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
960f384594dSTobias Grosser   ///
961f384594dSTobias Grosser   /// @see getTaggedAccesses
962f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
963f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
964f384594dSTobias Grosser   }
965f384594dSTobias Grosser 
966f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
967f384594dSTobias Grosser   ///
968f384594dSTobias Grosser   /// @see getTaggedAccesses
969f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
970f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
971f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
972f384594dSTobias Grosser   }
973f384594dSTobias Grosser 
974f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
975f384594dSTobias Grosser   ///
976f384594dSTobias Grosser   /// @see getTaggedAccesses
977f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
978f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
979f384594dSTobias Grosser   }
980f384594dSTobias Grosser 
981aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
982aef5196fSTobias Grosser   ///
983aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
984aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
985aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
986aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
987aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
988aef5196fSTobias Grosser   /// the data format that ppcg expects.
989aef5196fSTobias Grosser   ///
990aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
991aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
992aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
993bd81a7eeSTobias Grosser         S->getIslCtx(),
994bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
995aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
996aef5196fSTobias Grosser     auto *Space = S->getParamSpace();
997aef5196fSTobias Grosser 
998aef5196fSTobias Grosser     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
999aef5196fSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
1000aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1001aef5196fSTobias Grosser     }
1002aef5196fSTobias Grosser 
1003aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
1004aef5196fSTobias Grosser       auto Id = Array.second->getBasePtrId();
1005aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1006aef5196fSTobias Grosser     }
1007aef5196fSTobias Grosser 
1008aef5196fSTobias Grosser     isl_space_free(Space);
1009aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
1010aef5196fSTobias Grosser 
1011aef5196fSTobias Grosser     return Names;
1012aef5196fSTobias Grosser   }
1013aef5196fSTobias Grosser 
1014e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
1015e938517eSTobias Grosser   ///
1016f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
1017f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
1018f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
1019f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
1020e938517eSTobias Grosser   ///
1021e938517eSTobias Grosser   /// @returns A new ppcg scop.
1022e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
1023e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
1024e938517eSTobias Grosser 
1025e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
1026e938517eSTobias Grosser 
1027e938517eSTobias Grosser     PPCGScop->start = 0;
1028e938517eSTobias Grosser     PPCGScop->end = 0;
1029e938517eSTobias Grosser 
1030f384594dSTobias Grosser     PPCGScop->context = S->getContext();
1031f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
1032e938517eSTobias Grosser     PPCGScop->call = nullptr;
1033f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
1034f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
1035e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
1036f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
1037f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
1038f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
1039f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
1040e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
1041f384594dSTobias Grosser     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
1042e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
1043e938517eSTobias Grosser 
1044e938517eSTobias Grosser     PPCGScop->independence = nullptr;
1045e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
1046e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
1047e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
1048e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
1049e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
1050e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
1051e938517eSTobias Grosser 
1052f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
1053aef5196fSTobias Grosser     PPCGScop->names = getNames();
1054e938517eSTobias Grosser 
1055e938517eSTobias Grosser     PPCGScop->pet = nullptr;
1056e938517eSTobias Grosser 
1057f384594dSTobias Grosser     compute_tagger(PPCGScop);
1058f384594dSTobias Grosser     compute_dependences(PPCGScop);
1059f384594dSTobias Grosser 
1060e938517eSTobias Grosser     return PPCGScop;
1061e938517eSTobias Grosser   }
1062e938517eSTobias Grosser 
106360f63b49STobias Grosser   /// Collect the array acesses in a statement.
106460f63b49STobias Grosser   ///
106560f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
106660f63b49STobias Grosser   ///
106760f63b49STobias Grosser   /// @returns A list of array accesses.
106860f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
106960f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
107060f63b49STobias Grosser 
107160f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
107260f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
107360f63b49STobias Grosser       Access->read = Acc->isRead();
107460f63b49STobias Grosser       Access->write = Acc->isWrite();
107560f63b49STobias Grosser       Access->access = Acc->getAccessRelation();
107660f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
107760f63b49STobias Grosser       Space = isl_space_range(Space);
107860f63b49STobias Grosser       Space = isl_space_from_range(Space);
10796293ba69STobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
108060f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
108160f63b49STobias Grosser       Access->tagged_access =
108260f63b49STobias Grosser           isl_map_domain_product(Acc->getAccessRelation(), Universe);
108360f63b49STobias Grosser       Access->exact_write = Acc->isWrite();
108460f63b49STobias Grosser       Access->ref_id = Acc->getId();
108560f63b49STobias Grosser       Access->next = Accesses;
108660f63b49STobias Grosser       Accesses = Access;
108760f63b49STobias Grosser     }
108860f63b49STobias Grosser 
108960f63b49STobias Grosser     return Accesses;
109060f63b49STobias Grosser   }
109160f63b49STobias Grosser 
109269b46751STobias Grosser   /// Collect the list of GPU statements.
109369b46751STobias Grosser   ///
109469b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
109569b46751STobias Grosser   /// as well as a list with all memory accesses.
109669b46751STobias Grosser   ///
109769b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
109869b46751STobias Grosser   ///
109969b46751STobias Grosser   /// @returns A linked-list of statements.
110069b46751STobias Grosser   gpu_stmt *getStatements() {
110169b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
110269b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
110369b46751STobias Grosser 
110469b46751STobias Grosser     int i = 0;
110569b46751STobias Grosser     for (auto &Stmt : *S) {
110669b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
110769b46751STobias Grosser 
110869b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
110969b46751STobias Grosser 
111069b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
111169b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
111260f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
111369b46751STobias Grosser       i++;
111469b46751STobias Grosser     }
111569b46751STobias Grosser 
111669b46751STobias Grosser     return Stmts;
111769b46751STobias Grosser   }
111869b46751STobias Grosser 
111960f63b49STobias Grosser   /// Derive the extent of an array.
112060f63b49STobias Grosser   ///
112160f63b49STobias Grosser   /// The extent of an array is defined by the set of memory locations for
112260f63b49STobias Grosser   /// which a memory access in the iteration domain exists.
112360f63b49STobias Grosser   ///
112460f63b49STobias Grosser   /// @param Array The array to derive the extent for.
112560f63b49STobias Grosser   ///
112660f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
112760f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
112860f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
112960f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
113060f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
113160f63b49STobias Grosser     isl_set *AccessSet =
113260f63b49STobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace());
113360f63b49STobias Grosser     isl_union_set_free(AccessUSet);
113460f63b49STobias Grosser 
113560f63b49STobias Grosser     return AccessSet;
113660f63b49STobias Grosser   }
113760f63b49STobias Grosser 
113860f63b49STobias Grosser   /// Derive the bounds of an array.
113960f63b49STobias Grosser   ///
114060f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
114160f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
114260f63b49STobias Grosser   /// ScopArrayInfo.
114360f63b49STobias Grosser   ///
114460f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
114560f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
114660f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
114760f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
114860f63b49STobias Grosser       isl_set *Dom = isl_set_copy(PPCGArray.extent);
114960f63b49STobias Grosser       Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
115060f63b49STobias Grosser       isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
115160f63b49STobias Grosser       isl_set_free(Dom);
115260f63b49STobias Grosser       Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
115360f63b49STobias Grosser       isl_local_space *LS = isl_local_space_from_space(isl_set_get_space(Dom));
115460f63b49STobias Grosser       isl_aff *One = isl_aff_zero_on_domain(LS);
115560f63b49STobias Grosser       One = isl_aff_add_constant_si(One, 1);
115660f63b49STobias Grosser       Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
115760f63b49STobias Grosser       Bound = isl_pw_aff_gist(Bound, S->getContext());
115860f63b49STobias Grosser       PPCGArray.bound[0] = Bound;
115960f63b49STobias Grosser     }
116060f63b49STobias Grosser 
116160f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
116260f63b49STobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
116360f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
116460f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
116560f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
116660f63b49STobias Grosser       PPCGArray.bound[i] = Bound;
116760f63b49STobias Grosser     }
116860f63b49STobias Grosser   }
116960f63b49STobias Grosser 
117060f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
117160f63b49STobias Grosser   ///
117260f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
117360f63b49STobias Grosser   void createArrays(gpu_prog *PPCGProg) {
117460f63b49STobias Grosser     int i = 0;
117560f63b49STobias Grosser     for (auto &Element : S->arrays()) {
117660f63b49STobias Grosser       ScopArrayInfo *Array = Element.second.get();
117760f63b49STobias Grosser 
117860f63b49STobias Grosser       std::string TypeName;
117960f63b49STobias Grosser       raw_string_ostream OS(TypeName);
118060f63b49STobias Grosser 
118160f63b49STobias Grosser       OS << *Array->getElementType();
118260f63b49STobias Grosser       TypeName = OS.str();
118360f63b49STobias Grosser 
118460f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
118560f63b49STobias Grosser 
118660f63b49STobias Grosser       PPCGArray.space = Array->getSpace();
118760f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
118860f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
118960f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
119060f63b49STobias Grosser       PPCGArray.extent = nullptr;
119160f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
119260f63b49STobias Grosser       PPCGArray.bound =
119360f63b49STobias Grosser           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
119460f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
119560f63b49STobias Grosser       PPCGArray.n_ref = 0;
119660f63b49STobias Grosser       PPCGArray.refs = nullptr;
119760f63b49STobias Grosser       PPCGArray.accessed = true;
119860f63b49STobias Grosser       PPCGArray.read_only_scalar = false;
119960f63b49STobias Grosser       PPCGArray.has_compound_element = false;
120060f63b49STobias Grosser       PPCGArray.local = false;
120160f63b49STobias Grosser       PPCGArray.declare_local = false;
120260f63b49STobias Grosser       PPCGArray.global = false;
120360f63b49STobias Grosser       PPCGArray.linearize = false;
120460f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
120560f63b49STobias Grosser 
120660f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
12072d010dafSTobias Grosser       i++;
1208b9fc860aSTobias Grosser 
1209b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
121060f63b49STobias Grosser     }
121160f63b49STobias Grosser   }
121260f63b49STobias Grosser 
121360f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
121460f63b49STobias Grosser   ///
121560f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
121660f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
121760f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
121860f63b49STobias Grosser 
121960f63b49STobias Grosser     for (auto &Item : S->arrays()) {
122060f63b49STobias Grosser       ScopArrayInfo *Array = Item.second.get();
122160f63b49STobias Grosser       isl_space *Space = Array->getSpace();
122260f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
122360f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
122460f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
122560f63b49STobias Grosser     }
122660f63b49STobias Grosser 
122760f63b49STobias Grosser     return Maps;
122860f63b49STobias Grosser   }
122960f63b49STobias Grosser 
1230e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
1231e938517eSTobias Grosser   ///
1232e938517eSTobias Grosser   /// @returns A new gpu grogram description.
1233e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
1234e938517eSTobias Grosser 
1235e938517eSTobias Grosser     if (!PPCGScop)
1236e938517eSTobias Grosser       return nullptr;
1237e938517eSTobias Grosser 
1238e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
1239e938517eSTobias Grosser 
1240e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
1241e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
1242aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
124360f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
124460f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
124560f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
124660f63b49STobias Grosser     PPCGProg->tagged_must_kill =
124760f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
124860f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
124960f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
125060f63b49STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
1251e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
1252e938517eSTobias Grosser     PPCGProg->array_order = nullptr;
125369b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
125469b46751STobias Grosser     PPCGProg->stmts = getStatements();
125560f63b49STobias Grosser     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
125660f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
125760f63b49STobias Grosser                                        PPCGProg->n_array);
125860f63b49STobias Grosser 
125960f63b49STobias Grosser     createArrays(PPCGProg);
1260e938517eSTobias Grosser 
1261e938517eSTobias Grosser     return PPCGProg;
1262e938517eSTobias Grosser   }
1263e938517eSTobias Grosser 
126469b46751STobias Grosser   struct PrintGPUUserData {
126569b46751STobias Grosser     struct cuda_info *CudaInfo;
126669b46751STobias Grosser     struct gpu_prog *PPCGProg;
126769b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
126869b46751STobias Grosser   };
126969b46751STobias Grosser 
127069b46751STobias Grosser   /// Print a user statement node in the host code.
127169b46751STobias Grosser   ///
127269b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
127369b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
127469b46751STobias Grosser   /// host ast.
127569b46751STobias Grosser   ///
127669b46751STobias Grosser   /// @param P The printer to print to
127769b46751STobias Grosser   /// @param Options The printing options to use
127869b46751STobias Grosser   /// @param Node The node to print
127969b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
128069b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
128169b46751STobias Grosser   ///
128269b46751STobias Grosser   /// @returns A printer to which the output has been printed.
128369b46751STobias Grosser   static __isl_give isl_printer *
128469b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
128569b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
128669b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
128769b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
128869b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
128969b46751STobias Grosser 
129069b46751STobias Grosser     if (Id) {
129120251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
129220251734STobias Grosser 
129320251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
129420251734STobias Grosser       // otherwise try to call pet functionality that is not available in
129520251734STobias Grosser       // Polly.
129620251734STobias Grosser       if (IsUser) {
129720251734STobias Grosser         P = isl_printer_start_line(P);
129820251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
129920251734STobias Grosser         P = isl_printer_end_line(P);
130020251734STobias Grosser         isl_id_free(Id);
130120251734STobias Grosser         isl_ast_print_options_free(Options);
130220251734STobias Grosser         return P;
130320251734STobias Grosser       }
130420251734STobias Grosser 
130569b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
130669b46751STobias Grosser       isl_id_free(Id);
130769b46751STobias Grosser       Data->Kernels.push_back(Kernel);
130869b46751STobias Grosser     }
130969b46751STobias Grosser 
131069b46751STobias Grosser     return print_host_user(P, Options, Node, User);
131169b46751STobias Grosser   }
131269b46751STobias Grosser 
131369b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
131469b46751STobias Grosser   ///
131569b46751STobias Grosser   /// @param Kernel The kernel to print
131669b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
131769b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
131869b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
131969b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
132069b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
132169b46751STobias Grosser     char *String = isl_printer_get_str(P);
132269b46751STobias Grosser     printf("%s\n", String);
132369b46751STobias Grosser     free(String);
132469b46751STobias Grosser     isl_printer_free(P);
132569b46751STobias Grosser   }
132669b46751STobias Grosser 
132769b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
132869b46751STobias Grosser   ///
132969b46751STobias Grosser   /// @param Tree An AST describing GPU code
133069b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
133169b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
133269b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
133369b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
133469b46751STobias Grosser 
133569b46751STobias Grosser     PrintGPUUserData Data;
133669b46751STobias Grosser     Data.PPCGProg = PPCGProg;
133769b46751STobias Grosser 
133869b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
133969b46751STobias Grosser     Options =
134069b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
134169b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
134269b46751STobias Grosser     char *String = isl_printer_get_str(P);
134369b46751STobias Grosser     printf("# host\n");
134469b46751STobias Grosser     printf("%s\n", String);
134569b46751STobias Grosser     free(String);
134669b46751STobias Grosser     isl_printer_free(P);
134769b46751STobias Grosser 
134869b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
134969b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
135069b46751STobias Grosser       printKernel(Kernel);
135169b46751STobias Grosser     }
135269b46751STobias Grosser   }
135369b46751STobias Grosser 
1354f384594dSTobias Grosser   // Generate a GPU program using PPCG.
1355f384594dSTobias Grosser   //
1356f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
1357f384594dSTobias Grosser   //
1358f384594dSTobias Grosser   //  1) Compute new schedule for the program.
1359f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
1360f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
1361f384594dSTobias Grosser   //
1362f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
1363f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
1364f384594dSTobias Grosser   // strategy directly from this pass.
1365f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
1366f384594dSTobias Grosser 
1367f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
1368f384594dSTobias Grosser 
1369f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
1370f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
1371f384594dSTobias Grosser     PPCGGen->print = nullptr;
1372f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
137360c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
1374f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
1375f384594dSTobias Grosser     PPCGGen->tree = nullptr;
1376f384594dSTobias Grosser     PPCGGen->types.n = 0;
1377f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
1378f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
1379f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
1380f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
1381f384594dSTobias Grosser 
1382f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
1383f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
1384f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
13852341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
1386f384594dSTobias Grosser 
1387f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
1388f384594dSTobias Grosser 
1389aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
1390aef5196fSTobias Grosser 
139169b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
1392aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
139369b46751STobias Grosser     } else {
1394aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
139569b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
139669b46751STobias Grosser     }
1397aef5196fSTobias Grosser 
1398f384594dSTobias Grosser     if (DumpSchedule) {
1399f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
1400f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
1401f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
1402f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
1403f384594dSTobias Grosser       if (Schedule)
1404f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
1405f384594dSTobias Grosser       else
1406f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
1407f384594dSTobias Grosser 
1408f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
1409f384594dSTobias Grosser       isl_printer_free(P);
1410f384594dSTobias Grosser     }
1411f384594dSTobias Grosser 
141269b46751STobias Grosser     if (DumpCode) {
141369b46751STobias Grosser       printf("Code\n");
141469b46751STobias Grosser       printf("====\n");
141569b46751STobias Grosser       if (PPCGGen->tree)
141669b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
141769b46751STobias Grosser       else
141869b46751STobias Grosser         printf("No code generated\n");
141969b46751STobias Grosser     }
142069b46751STobias Grosser 
1421f384594dSTobias Grosser     isl_schedule_free(Schedule);
1422f384594dSTobias Grosser 
1423f384594dSTobias Grosser     return PPCGGen;
1424f384594dSTobias Grosser   }
1425f384594dSTobias Grosser 
1426f384594dSTobias Grosser   /// Free gpu_gen structure.
1427f384594dSTobias Grosser   ///
1428f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
1429f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
1430f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
1431f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
1432f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
1433f384594dSTobias Grosser     free(PPCGGen);
1434f384594dSTobias Grosser   }
1435f384594dSTobias Grosser 
1436b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
1437b307ed4dSTobias Grosser   ///
1438b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
1439b307ed4dSTobias Grosser   /// ourselves.
1440b307ed4dSTobias Grosser   ///
1441b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
1442b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
1443b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
1444b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
1445b307ed4dSTobias Grosser     free(PPCGScop->options);
1446b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
1447b307ed4dSTobias Grosser   }
1448b307ed4dSTobias Grosser 
144938fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
145038fc0aedSTobias Grosser   ///
145132837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
145232837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
145332837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
145438fc0aedSTobias Grosser     ScopAnnotator Annotator;
145538fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
145638fc0aedSTobias Grosser 
145738fc0aedSTobias Grosser     Region *R = &S->getRegion();
145838fc0aedSTobias Grosser 
145938fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
146038fc0aedSTobias Grosser 
146138fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
146238fc0aedSTobias Grosser 
146338fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
146438fc0aedSTobias Grosser 
146532837fe3STobias Grosser     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S,
146632837fe3STobias Grosser                                Prog);
146738fc0aedSTobias Grosser 
146838fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
146938fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
147038fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
147138fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
147238fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
147338fc0aedSTobias Grosser     // code generating this scop.
147438fc0aedSTobias Grosser     BasicBlock *StartBlock =
147538fc0aedSTobias Grosser         executeScopConditionally(*S, this, Builder.getTrue());
147638fc0aedSTobias Grosser 
147738fc0aedSTobias Grosser     // TODO: Handle LICM
147838fc0aedSTobias Grosser     // TODO: Verify run-time checks
147938fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
148038fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
148138fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
148238fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
1483fa7b0802STobias Grosser 
1484fa7b0802STobias Grosser     NodeBuilder.initializeAfterRTH();
148538fc0aedSTobias Grosser     NodeBuilder.create(Root);
14868ed5e599STobias Grosser     NodeBuilder.finalize();
148738fc0aedSTobias Grosser   }
148838fc0aedSTobias Grosser 
1489e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
1490e938517eSTobias Grosser     S = &CurrentScop;
149138fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
149238fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
149338fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
149438fc0aedSTobias Grosser     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
149538fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
1496e938517eSTobias Grosser 
14972d58a64eSTobias Grosser     // We currently do not support scops with invariant loads.
14982d58a64eSTobias Grosser     if (S->hasInvariantAccesses())
14992d58a64eSTobias Grosser       return false;
15002d58a64eSTobias Grosser 
1501e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
1502e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
1503f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
150438fc0aedSTobias Grosser 
150538fc0aedSTobias Grosser     if (PPCGGen->tree)
150632837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
150738fc0aedSTobias Grosser 
1508b307ed4dSTobias Grosser     freeOptions(PPCGScop);
1509f384594dSTobias Grosser     freePPCGGen(PPCGGen);
1510e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
1511e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
1512e938517eSTobias Grosser 
1513e938517eSTobias Grosser     return true;
1514e938517eSTobias Grosser   }
15159dfe4e7cSTobias Grosser 
15169dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
15179dfe4e7cSTobias Grosser 
15189dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
15199dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
15209dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
15219dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
15229dfe4e7cSTobias Grosser     AU.addRequired<ScopDetection>();
15239dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
15249dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
15259dfe4e7cSTobias Grosser 
15269dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
15279dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
15289dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
15299dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
15309dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
15319dfe4e7cSTobias Grosser     AU.addPreserved<PostDominatorTreeWrapperPass>();
15329dfe4e7cSTobias Grosser     AU.addPreserved<ScopDetection>();
15339dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
15349dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
15359dfe4e7cSTobias Grosser 
15369dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
15379dfe4e7cSTobias Grosser     //        region tree.
15389dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
15399dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
15409dfe4e7cSTobias Grosser   }
15419dfe4e7cSTobias Grosser };
15429dfe4e7cSTobias Grosser }
15439dfe4e7cSTobias Grosser 
15449dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
15459dfe4e7cSTobias Grosser 
15469dfe4e7cSTobias Grosser Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
15479dfe4e7cSTobias Grosser 
15489dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
15499dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
15509dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
15519dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
15529dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
15539dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
15549dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
15559dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScopDetection);
15569dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
15579dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
1558