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 
15*cb1aef8dSTobias Grosser #include "polly/CodeGen/IslAst.h"
169dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h"
1738fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h"
189dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h"
199dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h"
20f384594dSTobias Grosser #include "polly/Options.h"
21629109b6STobias Grosser #include "polly/ScopDetection.h"
229dfe4e7cSTobias Grosser #include "polly/ScopInfo.h"
23edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h"
2474dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h"
259dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h"
269dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h"
279dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h"
289dfe4e7cSTobias Grosser #include "llvm/Analysis/PostDominators.h"
299dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
3074dc3cb4STobias Grosser #include "llvm/Analysis/TargetLibraryInfo.h"
3174dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h"
3274dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h"
33e1a98343STobias Grosser #include "llvm/IR/Verifier.h"
3474dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h"
3574dc3cb4STobias Grosser #include "llvm/Support/TargetSelect.h"
3674dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h"
379a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h"
389dfe4e7cSTobias Grosser 
39f384594dSTobias Grosser #include "isl/union_map.h"
40f384594dSTobias Grosser 
41e938517eSTobias Grosser extern "C" {
42a56f8f8eSTobias Grosser #include "ppcg/cuda.h"
43a56f8f8eSTobias Grosser #include "ppcg/gpu.h"
44a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h"
45a56f8f8eSTobias Grosser #include "ppcg/ppcg.h"
46a56f8f8eSTobias Grosser #include "ppcg/schedule.h"
47e938517eSTobias Grosser }
48e938517eSTobias Grosser 
499dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h"
509dfe4e7cSTobias Grosser 
519dfe4e7cSTobias Grosser using namespace polly;
529dfe4e7cSTobias Grosser using namespace llvm;
539dfe4e7cSTobias Grosser 
549dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg"
559dfe4e7cSTobias Grosser 
56f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
57f384594dSTobias Grosser                                   cl::desc("Dump the computed GPU Schedule"),
58681bd568STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
59f384594dSTobias Grosser                                   cl::cat(PollyCategory));
6069b46751STobias Grosser 
6169b46751STobias Grosser static cl::opt<bool>
6269b46751STobias Grosser     DumpCode("polly-acc-dump-code",
6369b46751STobias Grosser              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
6469b46751STobias Grosser              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
6569b46751STobias Grosser 
6632837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
6732837fe3STobias Grosser                                   cl::desc("Dump the kernel LLVM-IR"),
6832837fe3STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
6932837fe3STobias Grosser                                   cl::cat(PollyCategory));
7032837fe3STobias Grosser 
7174dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
7274dc3cb4STobias Grosser                                    cl::desc("Dump the kernel assembly code"),
7374dc3cb4STobias Grosser                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
7474dc3cb4STobias Grosser                                    cl::cat(PollyCategory));
7574dc3cb4STobias Grosser 
7674dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath",
7774dc3cb4STobias Grosser                               cl::desc("Allow unsafe math optimizations"),
7874dc3cb4STobias Grosser                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
7974dc3cb4STobias Grosser                               cl::cat(PollyCategory));
80b513b491STobias Grosser static cl::opt<bool> SharedMemory("polly-acc-use-shared",
81b513b491STobias Grosser                                   cl::desc("Use shared memory"), cl::Hidden,
82b513b491STobias Grosser                                   cl::init(false), cl::ZeroOrMore,
83b513b491STobias Grosser                                   cl::cat(PollyCategory));
84130ca30fSTobias Grosser static cl::opt<bool> PrivateMemory("polly-acc-use-private",
85130ca30fSTobias Grosser                                    cl::desc("Use private memory"), cl::Hidden,
86130ca30fSTobias Grosser                                    cl::init(false), cl::ZeroOrMore,
87130ca30fSTobias Grosser                                    cl::cat(PollyCategory));
8874dc3cb4STobias Grosser 
8974dc3cb4STobias Grosser static cl::opt<std::string>
9074dc3cb4STobias Grosser     CudaVersion("polly-acc-cuda-version",
9174dc3cb4STobias Grosser                 cl::desc("The CUDA version to compile for"), cl::Hidden,
9274dc3cb4STobias Grosser                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
9374dc3cb4STobias Grosser 
9460c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
9560c60025STobias Grosser ///
9660c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
9760c60025STobias Grosser /// of the scheduled ScopStmts.
9860c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
99edb885cbSTobias Grosser     void *StmtT, isl_ast_build *Build,
10060c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
10160c60025STobias Grosser                                        isl_id *Id, void *User),
10260c60025STobias Grosser     void *UserIndex,
10360c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
104edb885cbSTobias Grosser     void *UserExpr) {
10560c60025STobias Grosser 
106edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
10760c60025STobias Grosser 
108edb885cbSTobias Grosser   isl_ctx *Ctx;
109edb885cbSTobias Grosser 
110edb885cbSTobias Grosser   if (!Stmt || !Build)
111edb885cbSTobias Grosser     return NULL;
112edb885cbSTobias Grosser 
113edb885cbSTobias Grosser   Ctx = isl_ast_build_get_ctx(Build);
114edb885cbSTobias Grosser   isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0);
115edb885cbSTobias Grosser 
116edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
117edb885cbSTobias Grosser     isl_map *AddrFunc = Acc->getAddressFunction();
118edb885cbSTobias Grosser     AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain());
119edb885cbSTobias Grosser     isl_id *RefId = Acc->getId();
120edb885cbSTobias Grosser     isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc);
121edb885cbSTobias Grosser     isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA);
122edb885cbSTobias Grosser     MPA = isl_multi_pw_aff_coalesce(MPA);
123edb885cbSTobias Grosser     MPA = FunctionIndex(MPA, RefId, UserIndex);
124edb885cbSTobias Grosser     isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA);
125edb885cbSTobias Grosser     Access = FunctionExpr(Access, RefId, UserExpr);
126edb885cbSTobias Grosser     RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access);
127edb885cbSTobias Grosser   }
128edb885cbSTobias Grosser 
129edb885cbSTobias Grosser   return RefToExpr;
13060c60025STobias Grosser }
131f384594dSTobias Grosser 
13238fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
13338fc0aedSTobias Grosser ///
13438fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
13538fc0aedSTobias Grosser /// generates code for general-prupose AST nodes, with special functionality
13638fc0aedSTobias Grosser /// for generating GPU specific user nodes.
13738fc0aedSTobias Grosser ///
13838fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
13938fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
14038fc0aedSTobias Grosser public:
14138fc0aedSTobias Grosser   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P,
14238fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
14332837fe3STobias Grosser                  DominatorTree &DT, Scop &S, gpu_prog *Prog)
144edb885cbSTobias Grosser       : IslNodeBuilder(Builder, Annotator, P, DL, LI, SE, DT, S), Prog(Prog) {
145edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
146edb885cbSTobias Grosser   }
14738fc0aedSTobias Grosser 
148fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
149fa7b0802STobias Grosser   void initializeAfterRTH();
150fa7b0802STobias Grosser 
151fa7b0802STobias Grosser   /// Finalize the generated scop.
152fa7b0802STobias Grosser   virtual void finalize();
153fa7b0802STobias Grosser 
15438fc0aedSTobias Grosser private:
15574dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
15674dc3cb4STobias Grosser   ///
15774dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
15874dc3cb4STobias Grosser   /// more.
15974dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
16074dc3cb4STobias Grosser 
16113c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
16213c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
1637287aeddSTobias Grosser 
164fa7b0802STobias Grosser   /// The current GPU context.
165fa7b0802STobias Grosser   Value *GPUContext;
166fa7b0802STobias Grosser 
167b513b491STobias Grosser   /// The set of isl_ids allocated in the kernel
168b513b491STobias Grosser   std::vector<isl_id *> KernelIds;
169b513b491STobias Grosser 
17032837fe3STobias Grosser   /// A module containing GPU code.
17132837fe3STobias Grosser   ///
17232837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
17332837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
17432837fe3STobias Grosser 
17532837fe3STobias Grosser   /// The GPU program we generate code for.
17632837fe3STobias Grosser   gpu_prog *Prog;
17732837fe3STobias Grosser 
178472f9654STobias Grosser   /// Class to free isl_ids.
179472f9654STobias Grosser   class IslIdDeleter {
180472f9654STobias Grosser   public:
181472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
182472f9654STobias Grosser   };
183472f9654STobias Grosser 
184472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
185472f9654STobias Grosser   ///
186472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
187472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
188472f9654STobias Grosser 
189edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
190edb885cbSTobias Grosser 
19138fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
19238fc0aedSTobias Grosser   ///
19338fc0aedSTobias Grosser   /// These AST nodes can be of type:
19438fc0aedSTobias Grosser   ///
19538fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
19638fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
19713c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
1985260c041STobias Grosser   ///   - In-kernel synchronization
1995260c041STobias Grosser   ///   - In-kernel memory copy statement
20038fc0aedSTobias Grosser   ///
2011fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
2021fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
20332837fe3STobias Grosser 
20413c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
20513c78e4dSTobias Grosser 
20613c78e4dSTobias Grosser   /// Create code for a data transfer statement
20713c78e4dSTobias Grosser   ///
20813c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
20913c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
21013c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
21113c78e4dSTobias Grosser                           enum DataDirection Direction);
21213c78e4dSTobias Grosser 
213edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
214edb885cbSTobias Grosser   ///
215edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
216edb885cbSTobias Grosser   ///
217edb885cbSTobias Grosser   /// @returns A set of values referenced by the kernel.
218edb885cbSTobias Grosser   SetVector<Value *> getReferencesInKernel(ppcg_kernel *Kernel);
219edb885cbSTobias Grosser 
22079a947c2STobias Grosser   /// Compute the sizes of the execution grid for a given kernel.
22179a947c2STobias Grosser   ///
22279a947c2STobias Grosser   /// @param Kernel The kernel to compute grid sizes for.
22379a947c2STobias Grosser   ///
22479a947c2STobias Grosser   /// @returns A tuple with grid sizes for X and Y dimension
22579a947c2STobias Grosser   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
22679a947c2STobias Grosser 
22779a947c2STobias Grosser   /// Compute the sizes of the thread blocks for a given kernel.
22879a947c2STobias Grosser   ///
22979a947c2STobias Grosser   /// @param Kernel The kernel to compute thread block sizes for.
23079a947c2STobias Grosser   ///
23179a947c2STobias Grosser   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
23279a947c2STobias Grosser   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
23379a947c2STobias Grosser 
23479a947c2STobias Grosser   /// Create kernel launch parameters.
23579a947c2STobias Grosser   ///
23679a947c2STobias Grosser   /// @param Kernel        The kernel to create parameters for.
23779a947c2STobias Grosser   /// @param F             The kernel function that has been created.
23857693272STobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
23979a947c2STobias Grosser   ///
24079a947c2STobias Grosser   /// @returns A stack allocated array with pointers to the parameter
24179a947c2STobias Grosser   ///          values that are passed to the kernel.
24257693272STobias Grosser   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
24357693272STobias Grosser                                 SetVector<Value *> SubtreeValues);
24479a947c2STobias Grosser 
245b513b491STobias Grosser   /// Create declarations for kernel variable.
246b513b491STobias Grosser   ///
247b513b491STobias Grosser   /// This includes shared memory declarations.
248b513b491STobias Grosser   ///
249b513b491STobias Grosser   /// @param Kernel        The kernel definition to create variables for.
250b513b491STobias Grosser   /// @param FN            The function into which to generate the variables.
251b513b491STobias Grosser   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
252b513b491STobias Grosser 
253c1c6a2a6STobias Grosser   /// Add CUDA annotations to module.
254c1c6a2a6STobias Grosser   ///
255c1c6a2a6STobias Grosser   /// Add a set of CUDA annotations that declares the maximal block dimensions
256c1c6a2a6STobias Grosser   /// that will be used to execute the CUDA kernel. This allows the NVIDIA
257c1c6a2a6STobias Grosser   /// PTX compiler to bound the number of allocated registers to ensure the
258c1c6a2a6STobias Grosser   /// resulting kernel is known to run with up to as many block dimensions
259c1c6a2a6STobias Grosser   /// as specified here.
260c1c6a2a6STobias Grosser   ///
261c1c6a2a6STobias Grosser   /// @param M         The module to add the annotations to.
262c1c6a2a6STobias Grosser   /// @param BlockDimX The size of block dimension X.
263c1c6a2a6STobias Grosser   /// @param BlockDimY The size of block dimension Y.
264c1c6a2a6STobias Grosser   /// @param BlockDimZ The size of block dimension Z.
265c1c6a2a6STobias Grosser   void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY,
266c1c6a2a6STobias Grosser                           Value *BlockDimZ);
267c1c6a2a6STobias Grosser 
26832837fe3STobias Grosser   /// Create GPU kernel.
26932837fe3STobias Grosser   ///
27032837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
27132837fe3STobias Grosser   ///
27232837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
27332837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
27432837fe3STobias Grosser 
27513c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
27613c78e4dSTobias Grosser   ///
27713c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
27813c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
27913c78e4dSTobias Grosser 
28000bb5a99STobias Grosser   /// Prepare the kernel arguments for kernel code generation
28100bb5a99STobias Grosser   ///
28200bb5a99STobias Grosser   /// @param Kernel The kernel to generate code for.
28300bb5a99STobias Grosser   /// @param FN     The function created for the kernel.
28400bb5a99STobias Grosser   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
28500bb5a99STobias Grosser 
28632837fe3STobias Grosser   /// Create kernel function.
28732837fe3STobias Grosser   ///
28832837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
28932837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
29032837fe3STobias Grosser   /// start block of this newly created function.
29132837fe3STobias Grosser   ///
29232837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
293edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
294edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
295edb885cbSTobias Grosser                             SetVector<Value *> &SubtreeValues);
29632837fe3STobias Grosser 
29732837fe3STobias Grosser   /// Create the declaration of a kernel function.
29832837fe3STobias Grosser   ///
29932837fe3STobias Grosser   /// The kernel function takes as arguments:
30032837fe3STobias Grosser   ///
30132837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
302f6044bd0STobias Grosser   ///   - Host iterators
303c84a1995STobias Grosser   ///   - Parameters
30432837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
30532837fe3STobias Grosser   ///
30632837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
307edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
308edb885cbSTobias Grosser   ///
30932837fe3STobias Grosser   /// @returns The newly declared function.
310edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
311edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
31232837fe3STobias Grosser 
313472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
314472f9654STobias Grosser   ///
315472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
316472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
317472f9654STobias Grosser 
318b513b491STobias Grosser   /// Create a global-to-shared or shared-to-global copy statement.
319b513b491STobias Grosser   ///
320b513b491STobias Grosser   /// @param CopyStmt The copy statement to generate code for
321b513b491STobias Grosser   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
322b513b491STobias Grosser 
323edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
324edb885cbSTobias Grosser   ///
325edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
326edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
327edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
328edb885cbSTobias Grosser 
3295260c041STobias Grosser   /// Create an in-kernel synchronization call.
3305260c041STobias Grosser   void createKernelSync();
3315260c041STobias Grosser 
33274dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
33374dc3cb4STobias Grosser   ///
33474dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
33574dc3cb4STobias Grosser   std::string createKernelASM();
33674dc3cb4STobias Grosser 
33774dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
33874dc3cb4STobias Grosser   ///
33974dc3cb4STobias Grosser   /// @param F The function to remove references to.
34074dc3cb4STobias Grosser   void clearDominators(Function *F);
34174dc3cb4STobias Grosser 
34274dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
34374dc3cb4STobias Grosser   ///
34474dc3cb4STobias Grosser   /// @param F The function to remove references to.
34574dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
34674dc3cb4STobias Grosser 
34774dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
34874dc3cb4STobias Grosser   ///
34974dc3cb4STobias Grosser   /// @param F The function to remove references to.
35074dc3cb4STobias Grosser   void clearLoops(Function *F);
35174dc3cb4STobias Grosser 
35232837fe3STobias Grosser   /// Finalize the generation of the kernel function.
35332837fe3STobias Grosser   ///
35432837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
35532837fe3STobias Grosser   /// dump its IR to stderr.
35657793596STobias Grosser   ///
35757793596STobias Grosser   /// @returns The Assembly string of the kernel.
35857793596STobias Grosser   std::string finalizeKernelFunction();
359fa7b0802STobias Grosser 
3607287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
361fa7b0802STobias Grosser   void allocateDeviceArrays();
362fa7b0802STobias Grosser 
3637287aeddSTobias Grosser   /// Free all allocated device arrays.
3647287aeddSTobias Grosser   void freeDeviceArrays();
3657287aeddSTobias Grosser 
366fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
367fa7b0802STobias Grosser   ///
368fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
369fa7b0802STobias Grosser   Value *createCallInitContext();
370fa7b0802STobias Grosser 
37179a947c2STobias Grosser   /// Create a call to get the device pointer for a kernel allocation.
37279a947c2STobias Grosser   ///
37379a947c2STobias Grosser   /// @param Allocation The Polly GPU allocation
37479a947c2STobias Grosser   ///
37579a947c2STobias Grosser   /// @returns The device parameter corresponding to this allocation.
37679a947c2STobias Grosser   Value *createCallGetDevicePtr(Value *Allocation);
37779a947c2STobias Grosser 
378fa7b0802STobias Grosser   /// Create a call to free the GPU context.
379fa7b0802STobias Grosser   ///
380fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
381fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
382fa7b0802STobias Grosser 
3837287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
3847287aeddSTobias Grosser   ///
3857287aeddSTobias Grosser   /// @param Size The size of memory to allocate
3867287aeddSTobias Grosser   ///
3877287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
388fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
3897287aeddSTobias Grosser 
3907287aeddSTobias Grosser   /// Create a call to free a device array.
3917287aeddSTobias Grosser   ///
3927287aeddSTobias Grosser   /// @param Array The device array to free.
3937287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
39413c78e4dSTobias Grosser 
39513c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
39613c78e4dSTobias Grosser   ///
39713c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
39813c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
39913c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
40013c78e4dSTobias Grosser                                       Value *Size);
40113c78e4dSTobias Grosser 
40213c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
40313c78e4dSTobias Grosser   ///
40413c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
40513c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
40613c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
40713c78e4dSTobias Grosser                                       Value *Size);
40857793596STobias Grosser 
40957793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
41057793596STobias Grosser   ///
41157793596STobias Grosser   /// @param Buffer The string describing the kernel.
41257793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
41357793596STobias Grosser   ///
41457793596STobias Grosser   /// @returns A pointer to a kernel object
41557793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
41657793596STobias Grosser 
41757793596STobias Grosser   /// Create a call to free a GPU kernel.
41857793596STobias Grosser   ///
41957793596STobias Grosser   /// @param GPUKernel THe kernel to free.
42057793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
42179a947c2STobias Grosser 
42279a947c2STobias Grosser   /// Create a call to launch a GPU kernel.
42379a947c2STobias Grosser   ///
42479a947c2STobias Grosser   /// @param GPUKernel  The kernel to launch.
42579a947c2STobias Grosser   /// @param GridDimX   The size of the first grid dimension.
42679a947c2STobias Grosser   /// @param GridDimY   The size of the second grid dimension.
42779a947c2STobias Grosser   /// @param GridBlockX The size of the first block dimension.
42879a947c2STobias Grosser   /// @param GridBlockY The size of the second block dimension.
42979a947c2STobias Grosser   /// @param GridBlockZ The size of the third block dimension.
43079a947c2STobias Grosser   /// @param Paramters  A pointer to an array that contains itself pointers to
43179a947c2STobias Grosser   ///                   the parameter values passed for each kernel argument.
43279a947c2STobias Grosser   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
43379a947c2STobias Grosser                               Value *GridDimY, Value *BlockDimX,
43479a947c2STobias Grosser                               Value *BlockDimY, Value *BlockDimZ,
43579a947c2STobias Grosser                               Value *Parameters);
4361fb9b64dSTobias Grosser };
4371fb9b64dSTobias Grosser 
438fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
439fa7b0802STobias Grosser   GPUContext = createCallInitContext();
440fa7b0802STobias Grosser   allocateDeviceArrays();
441fa7b0802STobias Grosser }
442fa7b0802STobias Grosser 
443fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
4447287aeddSTobias Grosser   freeDeviceArrays();
445fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
446fa7b0802STobias Grosser   IslNodeBuilder::finalize();
447fa7b0802STobias Grosser }
448fa7b0802STobias Grosser 
449fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
450fa7b0802STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
451fa7b0802STobias Grosser 
452fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
453fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
45413c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
4557287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
4567287aeddSTobias Grosser     DevArrayName.append(Array->name);
457fa7b0802STobias Grosser 
45813c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
4597287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
4607287aeddSTobias Grosser     DevArray->setName(DevArrayName);
46113c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
462fa7b0802STobias Grosser   }
463fa7b0802STobias Grosser 
464fa7b0802STobias Grosser   isl_ast_build_free(Build);
465fa7b0802STobias Grosser }
466fa7b0802STobias Grosser 
467c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX,
468c1c6a2a6STobias Grosser                                         Value *BlockDimY, Value *BlockDimZ) {
469c1c6a2a6STobias Grosser   auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations");
470c1c6a2a6STobias Grosser 
471c1c6a2a6STobias Grosser   for (auto &F : *M) {
472c1c6a2a6STobias Grosser     if (F.getCallingConv() != CallingConv::PTX_Kernel)
473c1c6a2a6STobias Grosser       continue;
474c1c6a2a6STobias Grosser 
475c1c6a2a6STobias Grosser     Value *V[] = {BlockDimX, BlockDimY, BlockDimZ};
476c1c6a2a6STobias Grosser 
477c1c6a2a6STobias Grosser     Metadata *Elements[] = {
478c1c6a2a6STobias Grosser         ValueAsMetadata::get(&F),   MDString::get(M->getContext(), "maxntidx"),
479c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"),
480c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"),
481c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[2]),
482c1c6a2a6STobias Grosser     };
483c1c6a2a6STobias Grosser     MDNode *Node = MDNode::get(M->getContext(), Elements);
484c1c6a2a6STobias Grosser     AnnotationNode->addOperand(Node);
485c1c6a2a6STobias Grosser   }
486c1c6a2a6STobias Grosser }
487c1c6a2a6STobias Grosser 
4887287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
48913c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
49013c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
4917287aeddSTobias Grosser }
4927287aeddSTobias Grosser 
49357793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
49457793596STobias Grosser   const char *Name = "polly_getKernel";
49557793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
49657793596STobias Grosser   Function *F = M->getFunction(Name);
49757793596STobias Grosser 
49857793596STobias Grosser   // If F is not available, declare it.
49957793596STobias Grosser   if (!F) {
50057793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
50157793596STobias Grosser     std::vector<Type *> Args;
50257793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
50357793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
50457793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
50557793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
50657793596STobias Grosser   }
50757793596STobias Grosser 
50857793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
50957793596STobias Grosser }
51057793596STobias Grosser 
51179a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
51279a947c2STobias Grosser   const char *Name = "polly_getDevicePtr";
51379a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
51479a947c2STobias Grosser   Function *F = M->getFunction(Name);
51579a947c2STobias Grosser 
51679a947c2STobias Grosser   // If F is not available, declare it.
51779a947c2STobias Grosser   if (!F) {
51879a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
51979a947c2STobias Grosser     std::vector<Type *> Args;
52079a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
52179a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
52279a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
52379a947c2STobias Grosser   }
52479a947c2STobias Grosser 
52579a947c2STobias Grosser   return Builder.CreateCall(F, {Allocation});
52679a947c2STobias Grosser }
52779a947c2STobias Grosser 
52879a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
52979a947c2STobias Grosser                                             Value *GridDimY, Value *BlockDimX,
53079a947c2STobias Grosser                                             Value *BlockDimY, Value *BlockDimZ,
53179a947c2STobias Grosser                                             Value *Parameters) {
53279a947c2STobias Grosser   const char *Name = "polly_launchKernel";
53379a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
53479a947c2STobias Grosser   Function *F = M->getFunction(Name);
53579a947c2STobias Grosser 
53679a947c2STobias Grosser   // If F is not available, declare it.
53779a947c2STobias Grosser   if (!F) {
53879a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
53979a947c2STobias Grosser     std::vector<Type *> Args;
54079a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
54179a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
54279a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
54379a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
54479a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
54579a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
54679a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
54779a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
54879a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
54979a947c2STobias Grosser   }
55079a947c2STobias Grosser 
55179a947c2STobias Grosser   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
55279a947c2STobias Grosser                          BlockDimZ, Parameters});
55379a947c2STobias Grosser }
55479a947c2STobias Grosser 
55557793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
55657793596STobias Grosser   const char *Name = "polly_freeKernel";
55757793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
55857793596STobias Grosser   Function *F = M->getFunction(Name);
55957793596STobias Grosser 
56057793596STobias Grosser   // If F is not available, declare it.
56157793596STobias Grosser   if (!F) {
56257793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
56357793596STobias Grosser     std::vector<Type *> Args;
56457793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
56557793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
56657793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
56757793596STobias Grosser   }
56857793596STobias Grosser 
56957793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
57057793596STobias Grosser }
57157793596STobias Grosser 
5727287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
5737287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
5747287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
5757287aeddSTobias Grosser   Function *F = M->getFunction(Name);
5767287aeddSTobias Grosser 
5777287aeddSTobias Grosser   // If F is not available, declare it.
5787287aeddSTobias Grosser   if (!F) {
5797287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
5807287aeddSTobias Grosser     std::vector<Type *> Args;
5817287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
5827287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
5837287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
5847287aeddSTobias Grosser   }
5857287aeddSTobias Grosser 
5867287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
5877287aeddSTobias Grosser }
5887287aeddSTobias Grosser 
589fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
590fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
591fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
592fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
593fa7b0802STobias Grosser 
594fa7b0802STobias Grosser   // If F is not available, declare it.
595fa7b0802STobias Grosser   if (!F) {
596fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
597fa7b0802STobias Grosser     std::vector<Type *> Args;
598fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
599fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
600fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
601fa7b0802STobias Grosser   }
602fa7b0802STobias Grosser 
603fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
604fa7b0802STobias Grosser }
605fa7b0802STobias Grosser 
60613c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
60713c78e4dSTobias Grosser                                                     Value *DeviceData,
60813c78e4dSTobias Grosser                                                     Value *Size) {
60913c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
61013c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
61113c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
61213c78e4dSTobias Grosser 
61313c78e4dSTobias Grosser   // If F is not available, declare it.
61413c78e4dSTobias Grosser   if (!F) {
61513c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
61613c78e4dSTobias Grosser     std::vector<Type *> Args;
61713c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
61813c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
61913c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
62013c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
62113c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
62213c78e4dSTobias Grosser   }
62313c78e4dSTobias Grosser 
62413c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
62513c78e4dSTobias Grosser }
62613c78e4dSTobias Grosser 
62713c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
62813c78e4dSTobias Grosser                                                     Value *HostData,
62913c78e4dSTobias Grosser                                                     Value *Size) {
63013c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
63113c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
63213c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
63313c78e4dSTobias Grosser 
63413c78e4dSTobias Grosser   // If F is not available, declare it.
63513c78e4dSTobias Grosser   if (!F) {
63613c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
63713c78e4dSTobias Grosser     std::vector<Type *> Args;
63813c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
63913c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
64013c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
64113c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
64213c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
64313c78e4dSTobias Grosser   }
64413c78e4dSTobias Grosser 
64513c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
64613c78e4dSTobias Grosser }
64713c78e4dSTobias Grosser 
648fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
649fa7b0802STobias Grosser   const char *Name = "polly_initContext";
650fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
651fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
652fa7b0802STobias Grosser 
653fa7b0802STobias Grosser   // If F is not available, declare it.
654fa7b0802STobias Grosser   if (!F) {
655fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
656fa7b0802STobias Grosser     std::vector<Type *> Args;
657fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
658fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
659fa7b0802STobias Grosser   }
660fa7b0802STobias Grosser 
661fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
662fa7b0802STobias Grosser }
663fa7b0802STobias Grosser 
664fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
665fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
666fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
667fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
668fa7b0802STobias Grosser 
669fa7b0802STobias Grosser   // If F is not available, declare it.
670fa7b0802STobias Grosser   if (!F) {
671fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
672fa7b0802STobias Grosser     std::vector<Type *> Args;
673fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
674fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
675fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
676fa7b0802STobias Grosser   }
677fa7b0802STobias Grosser 
678fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
679fa7b0802STobias Grosser }
680fa7b0802STobias Grosser 
6815260c041STobias Grosser /// Check if one string is a prefix of another.
6825260c041STobias Grosser ///
6835260c041STobias Grosser /// @param String The string in which to look for the prefix.
6845260c041STobias Grosser /// @param Prefix The prefix to look for.
6855260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
6865260c041STobias Grosser   return String.find(Prefix) == 0;
6875260c041STobias Grosser }
6885260c041STobias Grosser 
68913c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
69013c78e4dSTobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
69113c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
69213c78e4dSTobias Grosser 
69313c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
69413c78e4dSTobias Grosser     auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]);
69513c78e4dSTobias Grosser     isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero);
69613c78e4dSTobias Grosser 
69713c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
69813c78e4dSTobias Grosser       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]);
69913c78e4dSTobias Grosser       isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
70013c78e4dSTobias Grosser       Res = isl_ast_expr_mul(Res, Expr);
70113c78e4dSTobias Grosser     }
70213c78e4dSTobias Grosser 
70313c78e4dSTobias Grosser     Value *NumElements = ExprBuilder.create(Res);
70413c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
70513c78e4dSTobias Grosser   }
70613c78e4dSTobias Grosser   isl_ast_build_free(Build);
70713c78e4dSTobias Grosser   return ArraySize;
70813c78e4dSTobias Grosser }
70913c78e4dSTobias Grosser 
71013c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
71113c78e4dSTobias Grosser                                         enum DataDirection Direction) {
71213c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
71313c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
71413c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
71513c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
71613c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
71713c78e4dSTobias Grosser 
71813c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
71913c78e4dSTobias Grosser   Value *HostPtr = ScopArray->getBasePtr();
72013c78e4dSTobias Grosser 
72113c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
72213c78e4dSTobias Grosser 
72313c78e4dSTobias Grosser   if (gpu_array_is_scalar(Array)) {
72413c78e4dSTobias Grosser     HostPtr = Builder.CreateAlloca(ScopArray->getElementType());
72513c78e4dSTobias Grosser     Builder.CreateStore(ScopArray->getBasePtr(), HostPtr);
72613c78e4dSTobias Grosser   }
72713c78e4dSTobias Grosser 
72813c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
72913c78e4dSTobias Grosser 
73013c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
73113c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
73213c78e4dSTobias Grosser   else
73313c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
73413c78e4dSTobias Grosser 
73513c78e4dSTobias Grosser   isl_id_free(Id);
73613c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
73713c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
73813c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
73913c78e4dSTobias Grosser }
74013c78e4dSTobias Grosser 
7411fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
74232837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
74332837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
74432837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
74532837fe3STobias Grosser   isl_id_free(Id);
74632837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
74732837fe3STobias Grosser 
74832837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
74932837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
75032837fe3STobias Grosser     createKernel(UserStmt);
75132837fe3STobias Grosser     isl_ast_expr_free(Expr);
75232837fe3STobias Grosser     return;
75332837fe3STobias Grosser   }
75432837fe3STobias Grosser 
75513c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
75613c78e4dSTobias Grosser     createDataTransfer(UserStmt, HOST_TO_DEVICE);
75732837fe3STobias Grosser     isl_ast_expr_free(Expr);
75813c78e4dSTobias Grosser     return;
75913c78e4dSTobias Grosser   }
76013c78e4dSTobias Grosser 
76113c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
76213c78e4dSTobias Grosser     createDataTransfer(UserStmt, DEVICE_TO_HOST);
76313c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
76438fc0aedSTobias Grosser     return;
76538fc0aedSTobias Grosser   }
76638fc0aedSTobias Grosser 
7675260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
7685260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
7695260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
7705260c041STobias Grosser   isl_id_free(Anno);
7715260c041STobias Grosser 
7725260c041STobias Grosser   switch (KernelStmt->type) {
7735260c041STobias Grosser   case ppcg_kernel_domain:
774edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
7755260c041STobias Grosser     isl_ast_node_free(UserStmt);
7765260c041STobias Grosser     return;
7775260c041STobias Grosser   case ppcg_kernel_copy:
778b513b491STobias Grosser     createKernelCopy(KernelStmt);
7795260c041STobias Grosser     isl_ast_expr_free(Expr);
7805260c041STobias Grosser     isl_ast_node_free(UserStmt);
7815260c041STobias Grosser     return;
7825260c041STobias Grosser   case ppcg_kernel_sync:
7835260c041STobias Grosser     createKernelSync();
7845260c041STobias Grosser     isl_ast_expr_free(Expr);
7855260c041STobias Grosser     isl_ast_node_free(UserStmt);
7865260c041STobias Grosser     return;
7875260c041STobias Grosser   }
7885260c041STobias Grosser 
7895260c041STobias Grosser   isl_ast_expr_free(Expr);
7905260c041STobias Grosser   isl_ast_node_free(UserStmt);
7915260c041STobias Grosser   return;
7925260c041STobias Grosser }
793b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
794b513b491STobias Grosser   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
795b513b491STobias Grosser   LocalIndex = isl_ast_expr_address_of(LocalIndex);
796b513b491STobias Grosser   Value *LocalAddr = ExprBuilder.create(LocalIndex);
797b513b491STobias Grosser   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
798b513b491STobias Grosser   Index = isl_ast_expr_address_of(Index);
799b513b491STobias Grosser   Value *GlobalAddr = ExprBuilder.create(Index);
800b513b491STobias Grosser 
801b513b491STobias Grosser   if (KernelStmt->u.c.read) {
802b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read");
803b513b491STobias Grosser     Builder.CreateStore(Load, LocalAddr);
804b513b491STobias Grosser   } else {
805b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write");
806b513b491STobias Grosser     Builder.CreateStore(Load, GlobalAddr);
807b513b491STobias Grosser   }
808b513b491STobias Grosser }
8095260c041STobias Grosser 
810edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
811edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
812edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
813edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
814edb885cbSTobias Grosser 
815edb885cbSTobias Grosser   LoopToScevMapT LTS;
816edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
817edb885cbSTobias Grosser 
818edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
819edb885cbSTobias Grosser 
820edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
821edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
822edb885cbSTobias Grosser   else
823edb885cbSTobias Grosser     assert(0 && "Region statement not supported\n");
824edb885cbSTobias Grosser }
825edb885cbSTobias Grosser 
8265260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
8275260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8285260c041STobias Grosser   auto *Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
8295260c041STobias Grosser   Builder.CreateCall(Sync, {});
8305260c041STobias Grosser }
8315260c041STobias Grosser 
832edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
833edb885cbSTobias Grosser ///
834edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
835edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
836edb885cbSTobias Grosser ///
837edb885cbSTobias Grosser /// @param Node The node to collect references for.
838edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
839edb885cbSTobias Grosser ///
840edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
841edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
842edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
843edb885cbSTobias Grosser     return isl_bool_true;
844edb885cbSTobias Grosser 
845edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
846edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
847edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
848edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
849edb885cbSTobias Grosser   isl_id_free(Id);
850edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
851edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
852edb885cbSTobias Grosser 
853edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
854edb885cbSTobias Grosser     return isl_bool_true;
855edb885cbSTobias Grosser 
856edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
857edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
858edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
859edb885cbSTobias Grosser   isl_id_free(Id);
860edb885cbSTobias Grosser 
86100bb5a99STobias Grosser   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
862edb885cbSTobias Grosser 
863edb885cbSTobias Grosser   return isl_bool_true;
864edb885cbSTobias Grosser }
865edb885cbSTobias Grosser 
866edb885cbSTobias Grosser SetVector<Value *> GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
867edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
868edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
869edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
870edb885cbSTobias Grosser   SubtreeReferences References = {
871edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
872edb885cbSTobias Grosser 
873edb885cbSTobias Grosser   for (const auto &I : IDToValue)
874edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
875edb885cbSTobias Grosser 
876edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
877edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
878edb885cbSTobias Grosser 
879edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
880edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
881edb885cbSTobias Grosser 
882edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
883d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
884edb885cbSTobias Grosser 
885edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
886edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
887edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
888edb885cbSTobias Grosser     assert(IDToValue.count(Id));
889edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
890edb885cbSTobias Grosser     SubtreeValues.remove(Val);
891edb885cbSTobias Grosser     isl_id_free(Id);
892edb885cbSTobias Grosser   }
893edb885cbSTobias Grosser   isl_space_free(Space);
894edb885cbSTobias Grosser 
895edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
896edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
897edb885cbSTobias Grosser     assert(IDToValue.count(Id));
898edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
899edb885cbSTobias Grosser     SubtreeValues.remove(Val);
900edb885cbSTobias Grosser     isl_id_free(Id);
901edb885cbSTobias Grosser   }
902edb885cbSTobias Grosser 
903edb885cbSTobias Grosser   return SubtreeValues;
904edb885cbSTobias Grosser }
905edb885cbSTobias Grosser 
90674dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
90774dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
90874dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
90974dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
91074dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
91174dc3cb4STobias Grosser 
91274dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
91374dc3cb4STobias Grosser     DT.eraseNode(BB);
91474dc3cb4STobias Grosser }
91574dc3cb4STobias Grosser 
91674dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
91774dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
91874dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
91974dc3cb4STobias Grosser     if (L)
92074dc3cb4STobias Grosser       SE.forgetLoop(L);
92174dc3cb4STobias Grosser   }
92274dc3cb4STobias Grosser }
92374dc3cb4STobias Grosser 
92474dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
92574dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
92674dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
92774dc3cb4STobias Grosser     if (L)
92874dc3cb4STobias Grosser       SE.forgetLoop(L);
92974dc3cb4STobias Grosser     LI.removeBlock(&BB);
93074dc3cb4STobias Grosser   }
93174dc3cb4STobias Grosser }
93274dc3cb4STobias Grosser 
93379a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
93479a947c2STobias Grosser   std::vector<Value *> Sizes;
93579a947c2STobias Grosser   isl_ast_build *Context = isl_ast_build_from_context(S.getContext());
93679a947c2STobias Grosser 
93779a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
93879a947c2STobias Grosser     isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i);
93979a947c2STobias Grosser     isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size);
94079a947c2STobias Grosser     Value *Res = ExprBuilder.create(GridSize);
94179a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
94279a947c2STobias Grosser     Sizes.push_back(Res);
94379a947c2STobias Grosser   }
94479a947c2STobias Grosser   isl_ast_build_free(Context);
94579a947c2STobias Grosser 
94679a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
94779a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
94879a947c2STobias Grosser 
94979a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
95079a947c2STobias Grosser }
95179a947c2STobias Grosser 
95279a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
95379a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
95479a947c2STobias Grosser   std::vector<Value *> Sizes;
95579a947c2STobias Grosser 
95679a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
95779a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
95879a947c2STobias Grosser     Sizes.push_back(Res);
95979a947c2STobias Grosser   }
96079a947c2STobias Grosser 
96179a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
96279a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
96379a947c2STobias Grosser 
96479a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
96579a947c2STobias Grosser }
96679a947c2STobias Grosser 
96757693272STobias Grosser Value *
96857693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
96957693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
9704e18d71cSTobias Grosser   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(),
9714e18d71cSTobias Grosser                                  std::distance(F->arg_begin(), F->arg_end()));
97279a947c2STobias Grosser 
97379a947c2STobias Grosser   BasicBlock *EntryBlock =
97479a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
97579a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
97679a947c2STobias Grosser   Instruction *Parameters =
97779a947c2STobias Grosser       new AllocaInst(ArrayTy, Launch + "_params", EntryBlock->getTerminator());
97879a947c2STobias Grosser 
97979a947c2STobias Grosser   int Index = 0;
98079a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
98179a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
98279a947c2STobias Grosser       continue;
98379a947c2STobias Grosser 
98479a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
98579a947c2STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
98679a947c2STobias Grosser 
98779a947c2STobias Grosser     Value *DevArray = DeviceAllocations[(ScopArrayInfo *)SAI];
98879a947c2STobias Grosser     DevArray = createCallGetDevicePtr(DevArray);
98979a947c2STobias Grosser     Instruction *Param = new AllocaInst(
99079a947c2STobias Grosser         Builder.getInt8PtrTy(), Launch + "_param_" + std::to_string(Index),
99179a947c2STobias Grosser         EntryBlock->getTerminator());
99279a947c2STobias Grosser     Builder.CreateStore(DevArray, Param);
99344143bb9STobias Grosser     Value *Slot = Builder.CreateGEP(
99444143bb9STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
99579a947c2STobias Grosser     Value *ParamTyped =
99679a947c2STobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
99779a947c2STobias Grosser     Builder.CreateStore(ParamTyped, Slot);
99879a947c2STobias Grosser     Index++;
99979a947c2STobias Grosser   }
100079a947c2STobias Grosser 
1001a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1002a490147cSTobias Grosser 
1003a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1004a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1005a490147cSTobias Grosser     Value *Val = IDToValue[Id];
1006a490147cSTobias Grosser     isl_id_free(Id);
1007a490147cSTobias Grosser     Instruction *Param = new AllocaInst(
1008a490147cSTobias Grosser         Val->getType(), Launch + "_param_" + std::to_string(Index),
1009a490147cSTobias Grosser         EntryBlock->getTerminator());
1010a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
1011a490147cSTobias Grosser     Value *Slot = Builder.CreateGEP(
1012a490147cSTobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1013a490147cSTobias Grosser     Value *ParamTyped =
1014a490147cSTobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1015a490147cSTobias Grosser     Builder.CreateStore(ParamTyped, Slot);
1016a490147cSTobias Grosser     Index++;
1017a490147cSTobias Grosser   }
1018a490147cSTobias Grosser 
1019d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1020d8b94bcaSTobias Grosser 
1021d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
1022d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1023d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
1024d8b94bcaSTobias Grosser     isl_id_free(Id);
1025d8b94bcaSTobias Grosser     Instruction *Param = new AllocaInst(
1026d8b94bcaSTobias Grosser         Val->getType(), Launch + "_param_" + std::to_string(Index),
1027d8b94bcaSTobias Grosser         EntryBlock->getTerminator());
1028d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
1029d8b94bcaSTobias Grosser     Value *Slot = Builder.CreateGEP(
1030d8b94bcaSTobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1031d8b94bcaSTobias Grosser     Value *ParamTyped =
1032d8b94bcaSTobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1033d8b94bcaSTobias Grosser     Builder.CreateStore(ParamTyped, Slot);
1034d8b94bcaSTobias Grosser     Index++;
1035d8b94bcaSTobias Grosser   }
1036d8b94bcaSTobias Grosser 
103757693272STobias Grosser   for (auto Val : SubtreeValues) {
103857693272STobias Grosser     Instruction *Param = new AllocaInst(
103957693272STobias Grosser         Val->getType(), Launch + "_param_" + std::to_string(Index),
104057693272STobias Grosser         EntryBlock->getTerminator());
104157693272STobias Grosser     Builder.CreateStore(Val, Param);
104257693272STobias Grosser     Value *Slot = Builder.CreateGEP(
104357693272STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
104457693272STobias Grosser     Value *ParamTyped =
104557693272STobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
104657693272STobias Grosser     Builder.CreateStore(ParamTyped, Slot);
104757693272STobias Grosser     Index++;
104857693272STobias Grosser   }
104957693272STobias Grosser 
105079a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
105179a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
105279a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
105379a947c2STobias Grosser }
105479a947c2STobias Grosser 
105532837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
105632837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
105732837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
105832837fe3STobias Grosser   isl_id_free(Id);
105932837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
106032837fe3STobias Grosser 
1061c1c6a2a6STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1062c1c6a2a6STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1063c1c6a2a6STobias Grosser 
1064edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel);
1065edb885cbSTobias Grosser 
106632837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
106732837fe3STobias Grosser 
106832837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1069472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1070edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
107132837fe3STobias Grosser 
1072edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1073edb885cbSTobias Grosser 
1074edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
1075edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
1076edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
1077edb885cbSTobias Grosser   for (const Loop *L : Loops) {
1078edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1079edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1080edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1081edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1082edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1083edb885cbSTobias Grosser     SubtreeValues.insert(V);
1084edb885cbSTobias Grosser   }
1085edb885cbSTobias Grosser 
1086edb885cbSTobias Grosser   createKernelFunction(Kernel, SubtreeValues);
108732837fe3STobias Grosser 
108859ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
108959ab0705STobias Grosser 
109074dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
1091c1c6a2a6STobias Grosser   addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
109274dc3cb4STobias Grosser   clearDominators(F);
109374dc3cb4STobias Grosser   clearScalarEvolution(F);
109474dc3cb4STobias Grosser   clearLoops(F);
109574dc3cb4STobias Grosser 
109632837fe3STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
1097472f9654STobias Grosser   IDToValue = HostIDs;
109832837fe3STobias Grosser 
1099edb885cbSTobias Grosser   ValueMap = HostValueMap;
1100edb885cbSTobias Grosser   ScalarMap.clear();
1101edb885cbSTobias Grosser   PHIOpMap.clear();
1102edb885cbSTobias Grosser   EscapeMap.clear();
1103edb885cbSTobias Grosser   IDToSAI.clear();
110474dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
110574dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
110674dc3cb4STobias Grosser     S.invalidateScopArrayInfo(BasePtr, ScopArrayInfo::MK_Array);
110774dc3cb4STobias Grosser   LocalArrays.clear();
1108edb885cbSTobias Grosser 
110957693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
111079a947c2STobias Grosser 
111157793596STobias Grosser   std::string ASMString = finalizeKernelFunction();
111257793596STobias Grosser   std::string Name = "kernel_" + std::to_string(Kernel->id);
111357793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
111457793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
111557793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
111679a947c2STobias Grosser 
111779a947c2STobias Grosser   Value *GridDimX, *GridDimY;
111879a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
111979a947c2STobias Grosser 
112079a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
112179a947c2STobias Grosser                          BlockDimZ, Parameters);
112257793596STobias Grosser   createCallFreeKernel(GPUKernel);
1123b513b491STobias Grosser 
1124b513b491STobias Grosser   for (auto Id : KernelIds)
1125b513b491STobias Grosser     isl_id_free(Id);
1126b513b491STobias Grosser 
1127b513b491STobias Grosser   KernelIds.clear();
112832837fe3STobias Grosser }
112932837fe3STobias Grosser 
113032837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
113132837fe3STobias Grosser ///
113232837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
113332837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
113432837fe3STobias Grosser   std::string Ret = "e";
113532837fe3STobias Grosser 
113632837fe3STobias Grosser   if (!is64Bit)
113732837fe3STobias Grosser     Ret += "-p:32:32";
113832837fe3STobias Grosser 
113932837fe3STobias Grosser   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
114032837fe3STobias Grosser 
114132837fe3STobias Grosser   return Ret;
114232837fe3STobias Grosser }
114332837fe3STobias Grosser 
1144edb885cbSTobias Grosser Function *
1145edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1146edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
114732837fe3STobias Grosser   std::vector<Type *> Args;
114832837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
114932837fe3STobias Grosser 
115032837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
115132837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
115232837fe3STobias Grosser       continue;
115332837fe3STobias Grosser 
115432837fe3STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
115532837fe3STobias Grosser   }
115632837fe3STobias Grosser 
1157f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1158f6044bd0STobias Grosser 
1159f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++)
1160f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
1161f6044bd0STobias Grosser 
1162c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1163c84a1995STobias Grosser 
1164c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++)
1165c84a1995STobias Grosser     Args.push_back(Builder.getInt64Ty());
1166c84a1995STobias Grosser 
1167edb885cbSTobias Grosser   for (auto *V : SubtreeValues)
1168edb885cbSTobias Grosser     Args.push_back(V->getType());
1169edb885cbSTobias Grosser 
117032837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
117132837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
117232837fe3STobias Grosser                               GPUModule.get());
117332837fe3STobias Grosser   FN->setCallingConv(CallingConv::PTX_Kernel);
117432837fe3STobias Grosser 
117532837fe3STobias Grosser   auto Arg = FN->arg_begin();
117632837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
117732837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
117832837fe3STobias Grosser       continue;
117932837fe3STobias Grosser 
1180edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
1181edb885cbSTobias Grosser 
1182edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1183edb885cbSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1184edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
1185edb885cbSTobias Grosser     Value *Val = &*Arg;
1186edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1187edb885cbSTobias Grosser     isl_ast_build *Build =
1188edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
1189edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1190edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
1191edb885cbSTobias Grosser           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
1192edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
1193edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
1194edb885cbSTobias Grosser     }
1195edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
1196edb885cbSTobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, ScopArrayInfo::MK_Array);
119774dc3cb4STobias Grosser     LocalArrays.push_back(Val);
1198edb885cbSTobias Grosser 
1199edb885cbSTobias Grosser     isl_ast_build_free(Build);
1200b513b491STobias Grosser     KernelIds.push_back(Id);
1201edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
120232837fe3STobias Grosser     Arg++;
120332837fe3STobias Grosser   }
120432837fe3STobias Grosser 
1205f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1206f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1207f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
1208f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
1209f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1210f6044bd0STobias Grosser     Arg++;
1211f6044bd0STobias Grosser   }
1212f6044bd0STobias Grosser 
1213c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
1214c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1215c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
1216c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
1217c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1218c84a1995STobias Grosser     Arg++;
1219c84a1995STobias Grosser   }
1220c84a1995STobias Grosser 
1221edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
1222edb885cbSTobias Grosser     Arg->setName(V->getName());
1223edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
1224edb885cbSTobias Grosser     Arg++;
1225edb885cbSTobias Grosser   }
1226edb885cbSTobias Grosser 
122732837fe3STobias Grosser   return FN;
122832837fe3STobias Grosser }
122932837fe3STobias Grosser 
1230472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
1231472f9654STobias Grosser   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
1232472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
1233472f9654STobias Grosser 
1234472f9654STobias Grosser   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
1235472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
1236472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
1237472f9654STobias Grosser 
1238472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1239472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
1240472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1241472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1242472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1243472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1244472f9654STobias Grosser     IDToValue[Id] = Val;
1245472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1246472f9654STobias Grosser   };
1247472f9654STobias Grosser 
1248472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
1249472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1250472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
1251472f9654STobias Grosser   }
1252472f9654STobias Grosser 
1253472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
1254472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1255472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
1256472f9654STobias Grosser   }
1257472f9654STobias Grosser }
1258472f9654STobias Grosser 
125900bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
126000bb5a99STobias Grosser   auto Arg = FN->arg_begin();
126100bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
126200bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
126300bb5a99STobias Grosser       continue;
126400bb5a99STobias Grosser 
126500bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
126600bb5a99STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
126700bb5a99STobias Grosser     isl_id_free(Id);
126800bb5a99STobias Grosser 
126900bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
127000bb5a99STobias Grosser       Arg++;
127100bb5a99STobias Grosser       continue;
127200bb5a99STobias Grosser     }
127300bb5a99STobias Grosser 
127400bb5a99STobias Grosser     Value *Alloca = BlockGen.getOrCreateScalarAlloca(SAI->getBasePtr());
127500bb5a99STobias Grosser     Value *ArgPtr = &*Arg;
127600bb5a99STobias Grosser     Type *TypePtr = SAI->getElementType()->getPointerTo();
127700bb5a99STobias Grosser     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
127800bb5a99STobias Grosser     Value *Val = Builder.CreateLoad(TypedArgPtr);
127900bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
128000bb5a99STobias Grosser 
128100bb5a99STobias Grosser     Arg++;
128200bb5a99STobias Grosser   }
128300bb5a99STobias Grosser }
128400bb5a99STobias Grosser 
1285b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
1286b513b491STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1287b513b491STobias Grosser 
1288b513b491STobias Grosser   for (int i = 0; i < Kernel->n_var; ++i) {
1289b513b491STobias Grosser     struct ppcg_kernel_var &Var = Kernel->var[i];
1290b513b491STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
1291b513b491STobias Grosser     Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType();
1292b513b491STobias Grosser 
1293f919d8b3STobias Grosser     Type *ArrayTy = EleTy;
1294b513b491STobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1295b513b491STobias Grosser 
1296928d7573STobias Grosser     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
1297b513b491STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1298f919d8b3STobias Grosser       long Bound = isl_val_get_num_si(Val);
1299b513b491STobias Grosser       isl_val_free(Val);
1300b513b491STobias Grosser       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
1301928d7573STobias Grosser     }
1302928d7573STobias Grosser 
1303928d7573STobias Grosser     for (int j = Var.array->n_index - 1; j >= 0; --j) {
1304928d7573STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1305928d7573STobias Grosser       long Bound = isl_val_get_num_si(Val);
1306928d7573STobias Grosser       isl_val_free(Val);
1307b513b491STobias Grosser       ArrayTy = ArrayType::get(ArrayTy, Bound);
1308b513b491STobias Grosser     }
1309b513b491STobias Grosser 
1310130ca30fSTobias Grosser     const ScopArrayInfo *SAI;
1311130ca30fSTobias Grosser     Value *Allocation;
1312130ca30fSTobias Grosser     if (Var.type == ppcg_access_shared) {
1313130ca30fSTobias Grosser       auto GlobalVar = new GlobalVariable(
1314130ca30fSTobias Grosser           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
1315130ca30fSTobias Grosser           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
1316130ca30fSTobias Grosser       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
1317f919d8b3STobias Grosser       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
1318f919d8b3STobias Grosser 
1319130ca30fSTobias Grosser       Allocation = GlobalVar;
1320130ca30fSTobias Grosser     } else if (Var.type == ppcg_access_private) {
1321130ca30fSTobias Grosser       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
1322130ca30fSTobias Grosser     } else {
1323130ca30fSTobias Grosser       llvm_unreachable("unknown variable type");
1324130ca30fSTobias Grosser     }
1325130ca30fSTobias Grosser     SAI = S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes,
1326130ca30fSTobias Grosser                                      ScopArrayInfo::MK_Array);
1327b513b491STobias Grosser     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
1328130ca30fSTobias Grosser     IDToValue[Id] = Allocation;
1329130ca30fSTobias Grosser     LocalArrays.push_back(Allocation);
1330b513b491STobias Grosser     KernelIds.push_back(Id);
1331b513b491STobias Grosser     IDToSAI[Id] = SAI;
1332b513b491STobias Grosser   }
1333b513b491STobias Grosser }
1334b513b491STobias Grosser 
1335edb885cbSTobias Grosser void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel,
1336edb885cbSTobias Grosser                                           SetVector<Value *> &SubtreeValues) {
133732837fe3STobias Grosser 
133832837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
133932837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
134032837fe3STobias Grosser   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
134132837fe3STobias Grosser   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
134232837fe3STobias Grosser 
1343edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
134432837fe3STobias Grosser 
134559ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
134632837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
134732837fe3STobias Grosser 
134859ab0705STobias Grosser   DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
134959ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
135059ab0705STobias Grosser 
135132837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
135232837fe3STobias Grosser   Builder.CreateRetVoid();
135332837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
1354472f9654STobias Grosser 
1355629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
1356629109b6STobias Grosser 
135700bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
1358b513b491STobias Grosser   createKernelVariables(Kernel, FN);
1359472f9654STobias Grosser   insertKernelIntrinsics(Kernel);
136032837fe3STobias Grosser }
136132837fe3STobias Grosser 
136274dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
136374dc3cb4STobias Grosser   llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda"));
136474dc3cb4STobias Grosser   std::string ErrMsg;
136574dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
136674dc3cb4STobias Grosser 
136774dc3cb4STobias Grosser   if (!GPUTarget) {
136874dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
136974dc3cb4STobias Grosser     return "";
137074dc3cb4STobias Grosser   }
137174dc3cb4STobias Grosser 
137274dc3cb4STobias Grosser   TargetOptions Options;
137374dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
137474dc3cb4STobias Grosser   std::unique_ptr<TargetMachine> TargetM(
137574dc3cb4STobias Grosser       GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "",
137674dc3cb4STobias Grosser                                      Options, Optional<Reloc::Model>()));
137774dc3cb4STobias Grosser 
137874dc3cb4STobias Grosser   SmallString<0> ASMString;
137974dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
138074dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
138174dc3cb4STobias Grosser 
138274dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
138374dc3cb4STobias Grosser 
138474dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
138574dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
138674dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
138774dc3cb4STobias Grosser     return "";
138874dc3cb4STobias Grosser   }
138974dc3cb4STobias Grosser 
139074dc3cb4STobias Grosser   PM.run(*GPUModule);
139174dc3cb4STobias Grosser 
139274dc3cb4STobias Grosser   return ASMStream.str();
139374dc3cb4STobias Grosser }
139474dc3cb4STobias Grosser 
139557793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
1396e1a98343STobias Grosser   // Verify module.
1397e1a98343STobias Grosser   llvm::legacy::PassManager Passes;
1398e1a98343STobias Grosser   Passes.add(createVerifierPass());
1399e1a98343STobias Grosser   Passes.run(*GPUModule);
140032837fe3STobias Grosser 
140132837fe3STobias Grosser   if (DumpKernelIR)
140232837fe3STobias Grosser     outs() << *GPUModule << "\n";
140332837fe3STobias Grosser 
14049a18d559STobias Grosser   // Optimize module.
14059a18d559STobias Grosser   llvm::legacy::PassManager OptPasses;
14069a18d559STobias Grosser   PassManagerBuilder PassBuilder;
14079a18d559STobias Grosser   PassBuilder.OptLevel = 3;
14089a18d559STobias Grosser   PassBuilder.SizeLevel = 0;
14099a18d559STobias Grosser   PassBuilder.populateModulePassManager(OptPasses);
14109a18d559STobias Grosser   OptPasses.run(*GPUModule);
14119a18d559STobias Grosser 
141274dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
141374dc3cb4STobias Grosser 
141474dc3cb4STobias Grosser   if (DumpKernelASM)
141574dc3cb4STobias Grosser     outs() << Assembly << "\n";
141674dc3cb4STobias Grosser 
141732837fe3STobias Grosser   GPUModule.release();
1418472f9654STobias Grosser   KernelIDs.clear();
141957793596STobias Grosser 
142057793596STobias Grosser   return Assembly;
142132837fe3STobias Grosser }
142232837fe3STobias Grosser 
14239dfe4e7cSTobias Grosser namespace {
14249dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
14259dfe4e7cSTobias Grosser public:
14269dfe4e7cSTobias Grosser   static char ID;
14279dfe4e7cSTobias Grosser 
1428e938517eSTobias Grosser   /// The scop that is currently processed.
1429e938517eSTobias Grosser   Scop *S;
1430e938517eSTobias Grosser 
143138fc0aedSTobias Grosser   LoopInfo *LI;
143238fc0aedSTobias Grosser   DominatorTree *DT;
143338fc0aedSTobias Grosser   ScalarEvolution *SE;
143438fc0aedSTobias Grosser   const DataLayout *DL;
143538fc0aedSTobias Grosser   RegionInfo *RI;
143638fc0aedSTobias Grosser 
14379dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
14389dfe4e7cSTobias Grosser 
1439e938517eSTobias Grosser   /// Construct compilation options for PPCG.
1440e938517eSTobias Grosser   ///
1441e938517eSTobias Grosser   /// @returns The compilation options.
1442e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
1443e938517eSTobias Grosser     auto DebugOptions =
1444e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
1445e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
1446e938517eSTobias Grosser 
1447e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
1448e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
1449e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
1450e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
14518950ceadSTobias Grosser     DebugOptions->verbose = false;
1452e938517eSTobias Grosser 
1453e938517eSTobias Grosser     Options->debug = DebugOptions;
1454e938517eSTobias Grosser 
1455e938517eSTobias Grosser     Options->reschedule = true;
1456e938517eSTobias Grosser     Options->scale_tile_loops = false;
1457e938517eSTobias Grosser     Options->wrap = false;
1458e938517eSTobias Grosser 
1459e938517eSTobias Grosser     Options->non_negative_parameters = false;
1460e938517eSTobias Grosser     Options->ctx = nullptr;
1461e938517eSTobias Grosser     Options->sizes = nullptr;
1462e938517eSTobias Grosser 
14634eaedde5STobias Grosser     Options->tile_size = 32;
14644eaedde5STobias Grosser 
1465130ca30fSTobias Grosser     Options->use_private_memory = PrivateMemory;
1466b513b491STobias Grosser     Options->use_shared_memory = SharedMemory;
1467b513b491STobias Grosser     Options->max_shared_memory = 48 * 1024;
1468e938517eSTobias Grosser 
1469e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
1470e938517eSTobias Grosser     Options->openmp = false;
1471e938517eSTobias Grosser     Options->linearize_device_arrays = true;
1472e938517eSTobias Grosser     Options->live_range_reordering = false;
1473e938517eSTobias Grosser 
1474e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
1475e938517eSTobias Grosser     Options->opencl_use_gpu = false;
1476e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
1477e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
1478e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
1479e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
1480e938517eSTobias Grosser 
1481e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
1482e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
1483e938517eSTobias Grosser 
1484e938517eSTobias Grosser     return Options;
1485e938517eSTobias Grosser   }
1486e938517eSTobias Grosser 
1487f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
1488f384594dSTobias Grosser   ///
1489f384594dSTobias Grosser   /// Instead of a normal access of the form:
1490f384594dSTobias Grosser   ///
1491f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
1492f384594dSTobias Grosser   ///
1493f384594dSTobias Grosser   /// a tagged access has the form
1494f384594dSTobias Grosser   ///
1495f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
1496f384594dSTobias Grosser   ///
1497f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
1498f384594dSTobias Grosser   /// triggered the access.
1499f384594dSTobias Grosser   ///
1500f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
1501f384594dSTobias Grosser   ///
1502f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
1503f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
1504f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
1505f384594dSTobias Grosser 
1506f384594dSTobias Grosser     for (auto &Stmt : *S)
1507f384594dSTobias Grosser       for (auto &Acc : Stmt)
1508f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
1509f384594dSTobias Grosser           isl_map *Relation = Acc->getAccessRelation();
1510f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
1511f384594dSTobias Grosser 
1512f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
1513f384594dSTobias Grosser           Space = isl_space_range(Space);
1514f384594dSTobias Grosser           Space = isl_space_from_range(Space);
15156293ba69STobias Grosser           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1516f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
1517f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
1518f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
1519f384594dSTobias Grosser         }
1520f384594dSTobias Grosser 
1521f384594dSTobias Grosser     return Accesses;
1522f384594dSTobias Grosser   }
1523f384594dSTobias Grosser 
1524f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
1525f384594dSTobias Grosser   ///
1526f384594dSTobias Grosser   /// @see getTaggedAccesses
1527f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
1528f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
1529f384594dSTobias Grosser   }
1530f384594dSTobias Grosser 
1531f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
1532f384594dSTobias Grosser   ///
1533f384594dSTobias Grosser   /// @see getTaggedAccesses
1534f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
1535f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
1536f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
1537f384594dSTobias Grosser   }
1538f384594dSTobias Grosser 
1539f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
1540f384594dSTobias Grosser   ///
1541f384594dSTobias Grosser   /// @see getTaggedAccesses
1542f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
1543f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
1544f384594dSTobias Grosser   }
1545f384594dSTobias Grosser 
1546aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
1547aef5196fSTobias Grosser   ///
1548aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
1549aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
1550aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
1551aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
1552aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
1553aef5196fSTobias Grosser   /// the data format that ppcg expects.
1554aef5196fSTobias Grosser   ///
1555aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
1556aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
1557aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
1558bd81a7eeSTobias Grosser         S->getIslCtx(),
1559bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
1560aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
1561aef5196fSTobias Grosser     auto *Space = S->getParamSpace();
1562aef5196fSTobias Grosser 
1563aef5196fSTobias Grosser     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
1564aef5196fSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
1565aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1566aef5196fSTobias Grosser     }
1567aef5196fSTobias Grosser 
1568aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
1569d7754a12SRoman Gareev       auto Id = Array->getBasePtrId();
1570aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1571aef5196fSTobias Grosser     }
1572aef5196fSTobias Grosser 
1573aef5196fSTobias Grosser     isl_space_free(Space);
1574aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
1575aef5196fSTobias Grosser 
1576aef5196fSTobias Grosser     return Names;
1577aef5196fSTobias Grosser   }
1578aef5196fSTobias Grosser 
1579e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
1580e938517eSTobias Grosser   ///
1581f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
1582f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
1583f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
1584f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
1585e938517eSTobias Grosser   ///
1586e938517eSTobias Grosser   /// @returns A new ppcg scop.
1587e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
1588e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
1589e938517eSTobias Grosser 
1590e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
1591e938517eSTobias Grosser 
1592e938517eSTobias Grosser     PPCGScop->start = 0;
1593e938517eSTobias Grosser     PPCGScop->end = 0;
1594e938517eSTobias Grosser 
1595f384594dSTobias Grosser     PPCGScop->context = S->getContext();
1596f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
1597e938517eSTobias Grosser     PPCGScop->call = nullptr;
1598f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
1599f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
1600e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
1601f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
1602f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
1603f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
1604f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
1605e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
1606f384594dSTobias Grosser     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
1607e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
1608e938517eSTobias Grosser 
1609e938517eSTobias Grosser     PPCGScop->independence = nullptr;
1610e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
1611e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
1612e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
1613e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
1614e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
1615e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
1616e938517eSTobias Grosser 
1617f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
1618aef5196fSTobias Grosser     PPCGScop->names = getNames();
1619e938517eSTobias Grosser 
1620e938517eSTobias Grosser     PPCGScop->pet = nullptr;
1621e938517eSTobias Grosser 
1622f384594dSTobias Grosser     compute_tagger(PPCGScop);
1623f384594dSTobias Grosser     compute_dependences(PPCGScop);
1624f384594dSTobias Grosser 
1625e938517eSTobias Grosser     return PPCGScop;
1626e938517eSTobias Grosser   }
1627e938517eSTobias Grosser 
162860f63b49STobias Grosser   /// Collect the array acesses in a statement.
162960f63b49STobias Grosser   ///
163060f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
163160f63b49STobias Grosser   ///
163260f63b49STobias Grosser   /// @returns A list of array accesses.
163360f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
163460f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
163560f63b49STobias Grosser 
163660f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
163760f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
163860f63b49STobias Grosser       Access->read = Acc->isRead();
163960f63b49STobias Grosser       Access->write = Acc->isWrite();
164060f63b49STobias Grosser       Access->access = Acc->getAccessRelation();
164160f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
164260f63b49STobias Grosser       Space = isl_space_range(Space);
164360f63b49STobias Grosser       Space = isl_space_from_range(Space);
16446293ba69STobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
164560f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
164660f63b49STobias Grosser       Access->tagged_access =
164760f63b49STobias Grosser           isl_map_domain_product(Acc->getAccessRelation(), Universe);
1648b513b491STobias Grosser       Access->exact_write = !Acc->isMayWrite();
164960f63b49STobias Grosser       Access->ref_id = Acc->getId();
165060f63b49STobias Grosser       Access->next = Accesses;
1651b513b491STobias Grosser       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
165260f63b49STobias Grosser       Accesses = Access;
165360f63b49STobias Grosser     }
165460f63b49STobias Grosser 
165560f63b49STobias Grosser     return Accesses;
165660f63b49STobias Grosser   }
165760f63b49STobias Grosser 
165869b46751STobias Grosser   /// Collect the list of GPU statements.
165969b46751STobias Grosser   ///
166069b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
166169b46751STobias Grosser   /// as well as a list with all memory accesses.
166269b46751STobias Grosser   ///
166369b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
166469b46751STobias Grosser   ///
166569b46751STobias Grosser   /// @returns A linked-list of statements.
166669b46751STobias Grosser   gpu_stmt *getStatements() {
166769b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
166869b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
166969b46751STobias Grosser 
167069b46751STobias Grosser     int i = 0;
167169b46751STobias Grosser     for (auto &Stmt : *S) {
167269b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
167369b46751STobias Grosser 
167469b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
167569b46751STobias Grosser 
167669b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
167769b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
167860f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
167969b46751STobias Grosser       i++;
168069b46751STobias Grosser     }
168169b46751STobias Grosser 
168269b46751STobias Grosser     return Stmts;
168369b46751STobias Grosser   }
168469b46751STobias Grosser 
168560f63b49STobias Grosser   /// Derive the extent of an array.
168660f63b49STobias Grosser   ///
168760f63b49STobias Grosser   /// The extent of an array is defined by the set of memory locations for
168860f63b49STobias Grosser   /// which a memory access in the iteration domain exists.
168960f63b49STobias Grosser   ///
169060f63b49STobias Grosser   /// @param Array The array to derive the extent for.
169160f63b49STobias Grosser   ///
169260f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
169360f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
169460f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
169560f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
169660f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
169760f63b49STobias Grosser     isl_set *AccessSet =
169860f63b49STobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace());
169960f63b49STobias Grosser     isl_union_set_free(AccessUSet);
170060f63b49STobias Grosser 
170160f63b49STobias Grosser     return AccessSet;
170260f63b49STobias Grosser   }
170360f63b49STobias Grosser 
170460f63b49STobias Grosser   /// Derive the bounds of an array.
170560f63b49STobias Grosser   ///
170660f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
170760f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
170860f63b49STobias Grosser   /// ScopArrayInfo.
170960f63b49STobias Grosser   ///
171060f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
171160f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
171260f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
171360f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
171460f63b49STobias Grosser       isl_set *Dom = isl_set_copy(PPCGArray.extent);
171560f63b49STobias Grosser       Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
171660f63b49STobias Grosser       isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
171760f63b49STobias Grosser       isl_set_free(Dom);
171860f63b49STobias Grosser       Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
171960f63b49STobias Grosser       isl_local_space *LS = isl_local_space_from_space(isl_set_get_space(Dom));
172060f63b49STobias Grosser       isl_aff *One = isl_aff_zero_on_domain(LS);
172160f63b49STobias Grosser       One = isl_aff_add_constant_si(One, 1);
172260f63b49STobias Grosser       Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
172360f63b49STobias Grosser       Bound = isl_pw_aff_gist(Bound, S->getContext());
172460f63b49STobias Grosser       PPCGArray.bound[0] = Bound;
172560f63b49STobias Grosser     }
172660f63b49STobias Grosser 
172760f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
172860f63b49STobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
172960f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
173060f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
173160f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
173260f63b49STobias Grosser       PPCGArray.bound[i] = Bound;
173360f63b49STobias Grosser     }
173460f63b49STobias Grosser   }
173560f63b49STobias Grosser 
173660f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
173760f63b49STobias Grosser   ///
173860f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
173960f63b49STobias Grosser   void createArrays(gpu_prog *PPCGProg) {
174060f63b49STobias Grosser     int i = 0;
1741d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
174260f63b49STobias Grosser       std::string TypeName;
174360f63b49STobias Grosser       raw_string_ostream OS(TypeName);
174460f63b49STobias Grosser 
174560f63b49STobias Grosser       OS << *Array->getElementType();
174660f63b49STobias Grosser       TypeName = OS.str();
174760f63b49STobias Grosser 
174860f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
174960f63b49STobias Grosser 
175060f63b49STobias Grosser       PPCGArray.space = Array->getSpace();
175160f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
175260f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
175360f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
175460f63b49STobias Grosser       PPCGArray.extent = nullptr;
175560f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
175660f63b49STobias Grosser       PPCGArray.bound =
175760f63b49STobias Grosser           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
175860f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
175960f63b49STobias Grosser       PPCGArray.n_ref = 0;
176060f63b49STobias Grosser       PPCGArray.refs = nullptr;
176160f63b49STobias Grosser       PPCGArray.accessed = true;
176260f63b49STobias Grosser       PPCGArray.read_only_scalar = false;
176360f63b49STobias Grosser       PPCGArray.has_compound_element = false;
176460f63b49STobias Grosser       PPCGArray.local = false;
176560f63b49STobias Grosser       PPCGArray.declare_local = false;
176660f63b49STobias Grosser       PPCGArray.global = false;
176760f63b49STobias Grosser       PPCGArray.linearize = false;
176860f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
176913c78e4dSTobias Grosser       PPCGArray.user = Array;
177060f63b49STobias Grosser 
177160f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
17722d010dafSTobias Grosser       i++;
1773b9fc860aSTobias Grosser 
1774b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
177560f63b49STobias Grosser     }
177660f63b49STobias Grosser   }
177760f63b49STobias Grosser 
177860f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
177960f63b49STobias Grosser   ///
178060f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
178160f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
178260f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
178360f63b49STobias Grosser 
1784d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
178560f63b49STobias Grosser       isl_space *Space = Array->getSpace();
178660f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
178760f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
178860f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
178960f63b49STobias Grosser     }
179060f63b49STobias Grosser 
179160f63b49STobias Grosser     return Maps;
179260f63b49STobias Grosser   }
179360f63b49STobias Grosser 
1794e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
1795e938517eSTobias Grosser   ///
1796e938517eSTobias Grosser   /// @returns A new gpu grogram description.
1797e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
1798e938517eSTobias Grosser 
1799e938517eSTobias Grosser     if (!PPCGScop)
1800e938517eSTobias Grosser       return nullptr;
1801e938517eSTobias Grosser 
1802e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
1803e938517eSTobias Grosser 
1804e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
1805e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
1806aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
180760f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
180860f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
180960f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
181060f63b49STobias Grosser     PPCGProg->tagged_must_kill =
181160f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
181260f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
181360f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
181460f63b49STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
1815e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
1816e938517eSTobias Grosser     PPCGProg->array_order = nullptr;
181769b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
181869b46751STobias Grosser     PPCGProg->stmts = getStatements();
181960f63b49STobias Grosser     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
182060f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
182160f63b49STobias Grosser                                        PPCGProg->n_array);
182260f63b49STobias Grosser 
182360f63b49STobias Grosser     createArrays(PPCGProg);
1824e938517eSTobias Grosser 
1825e938517eSTobias Grosser     return PPCGProg;
1826e938517eSTobias Grosser   }
1827e938517eSTobias Grosser 
182869b46751STobias Grosser   struct PrintGPUUserData {
182969b46751STobias Grosser     struct cuda_info *CudaInfo;
183069b46751STobias Grosser     struct gpu_prog *PPCGProg;
183169b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
183269b46751STobias Grosser   };
183369b46751STobias Grosser 
183469b46751STobias Grosser   /// Print a user statement node in the host code.
183569b46751STobias Grosser   ///
183669b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
183769b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
183869b46751STobias Grosser   /// host ast.
183969b46751STobias Grosser   ///
184069b46751STobias Grosser   /// @param P The printer to print to
184169b46751STobias Grosser   /// @param Options The printing options to use
184269b46751STobias Grosser   /// @param Node The node to print
184369b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
184469b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
184569b46751STobias Grosser   ///
184669b46751STobias Grosser   /// @returns A printer to which the output has been printed.
184769b46751STobias Grosser   static __isl_give isl_printer *
184869b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
184969b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
185069b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
185169b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
185269b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
185369b46751STobias Grosser 
185469b46751STobias Grosser     if (Id) {
185520251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
185620251734STobias Grosser 
185720251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
185820251734STobias Grosser       // otherwise try to call pet functionality that is not available in
185920251734STobias Grosser       // Polly.
186020251734STobias Grosser       if (IsUser) {
186120251734STobias Grosser         P = isl_printer_start_line(P);
186220251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
186320251734STobias Grosser         P = isl_printer_end_line(P);
186420251734STobias Grosser         isl_id_free(Id);
186520251734STobias Grosser         isl_ast_print_options_free(Options);
186620251734STobias Grosser         return P;
186720251734STobias Grosser       }
186820251734STobias Grosser 
186969b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
187069b46751STobias Grosser       isl_id_free(Id);
187169b46751STobias Grosser       Data->Kernels.push_back(Kernel);
187269b46751STobias Grosser     }
187369b46751STobias Grosser 
187469b46751STobias Grosser     return print_host_user(P, Options, Node, User);
187569b46751STobias Grosser   }
187669b46751STobias Grosser 
187769b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
187869b46751STobias Grosser   ///
187969b46751STobias Grosser   /// @param Kernel The kernel to print
188069b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
188169b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
188269b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
188369b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
188469b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
188569b46751STobias Grosser     char *String = isl_printer_get_str(P);
188669b46751STobias Grosser     printf("%s\n", String);
188769b46751STobias Grosser     free(String);
188869b46751STobias Grosser     isl_printer_free(P);
188969b46751STobias Grosser   }
189069b46751STobias Grosser 
189169b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
189269b46751STobias Grosser   ///
189369b46751STobias Grosser   /// @param Tree An AST describing GPU code
189469b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
189569b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
189669b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
189769b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
189869b46751STobias Grosser 
189969b46751STobias Grosser     PrintGPUUserData Data;
190069b46751STobias Grosser     Data.PPCGProg = PPCGProg;
190169b46751STobias Grosser 
190269b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
190369b46751STobias Grosser     Options =
190469b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
190569b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
190669b46751STobias Grosser     char *String = isl_printer_get_str(P);
190769b46751STobias Grosser     printf("# host\n");
190869b46751STobias Grosser     printf("%s\n", String);
190969b46751STobias Grosser     free(String);
191069b46751STobias Grosser     isl_printer_free(P);
191169b46751STobias Grosser 
191269b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
191369b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
191469b46751STobias Grosser       printKernel(Kernel);
191569b46751STobias Grosser     }
191669b46751STobias Grosser   }
191769b46751STobias Grosser 
1918f384594dSTobias Grosser   // Generate a GPU program using PPCG.
1919f384594dSTobias Grosser   //
1920f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
1921f384594dSTobias Grosser   //
1922f384594dSTobias Grosser   //  1) Compute new schedule for the program.
1923f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
1924f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
1925f384594dSTobias Grosser   //
1926f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
1927f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
1928f384594dSTobias Grosser   // strategy directly from this pass.
1929f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
1930f384594dSTobias Grosser 
1931f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
1932f384594dSTobias Grosser 
1933f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
1934f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
1935f384594dSTobias Grosser     PPCGGen->print = nullptr;
1936f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
193760c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
1938f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
1939f384594dSTobias Grosser     PPCGGen->tree = nullptr;
1940f384594dSTobias Grosser     PPCGGen->types.n = 0;
1941f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
1942f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
1943f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
1944f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
1945f384594dSTobias Grosser 
1946f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
1947f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
1948f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
19492341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
1950f384594dSTobias Grosser 
1951f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
1952f384594dSTobias Grosser 
1953aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
1954aef5196fSTobias Grosser 
195569b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
1956aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
195769b46751STobias Grosser     } else {
1958aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
195969b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
196069b46751STobias Grosser     }
1961aef5196fSTobias Grosser 
1962f384594dSTobias Grosser     if (DumpSchedule) {
1963f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
1964f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
1965f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
1966f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
1967f384594dSTobias Grosser       if (Schedule)
1968f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
1969f384594dSTobias Grosser       else
1970f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
1971f384594dSTobias Grosser 
1972f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
1973f384594dSTobias Grosser       isl_printer_free(P);
1974f384594dSTobias Grosser     }
1975f384594dSTobias Grosser 
197669b46751STobias Grosser     if (DumpCode) {
197769b46751STobias Grosser       printf("Code\n");
197869b46751STobias Grosser       printf("====\n");
197969b46751STobias Grosser       if (PPCGGen->tree)
198069b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
198169b46751STobias Grosser       else
198269b46751STobias Grosser         printf("No code generated\n");
198369b46751STobias Grosser     }
198469b46751STobias Grosser 
1985f384594dSTobias Grosser     isl_schedule_free(Schedule);
1986f384594dSTobias Grosser 
1987f384594dSTobias Grosser     return PPCGGen;
1988f384594dSTobias Grosser   }
1989f384594dSTobias Grosser 
1990f384594dSTobias Grosser   /// Free gpu_gen structure.
1991f384594dSTobias Grosser   ///
1992f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
1993f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
1994f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
1995f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
1996f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
1997f384594dSTobias Grosser     free(PPCGGen);
1998f384594dSTobias Grosser   }
1999f384594dSTobias Grosser 
2000b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
2001b307ed4dSTobias Grosser   ///
2002b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
2003b307ed4dSTobias Grosser   /// ourselves.
2004b307ed4dSTobias Grosser   ///
2005b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
2006b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
2007b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
2008b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
2009b307ed4dSTobias Grosser     free(PPCGScop->options);
2010b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
2011b307ed4dSTobias Grosser   }
2012b307ed4dSTobias Grosser 
201338fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
201438fc0aedSTobias Grosser   ///
201532837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
201632837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
201732837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
201838fc0aedSTobias Grosser     ScopAnnotator Annotator;
201938fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
202038fc0aedSTobias Grosser 
202138fc0aedSTobias Grosser     Region *R = &S->getRegion();
202238fc0aedSTobias Grosser 
202338fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
202438fc0aedSTobias Grosser 
202538fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
202638fc0aedSTobias Grosser 
202738fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
202838fc0aedSTobias Grosser 
202932837fe3STobias Grosser     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S,
203032837fe3STobias Grosser                                Prog);
203138fc0aedSTobias Grosser 
203238fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
203338fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
203438fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
203538fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
203638fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
203738fc0aedSTobias Grosser     // code generating this scop.
203838fc0aedSTobias Grosser     BasicBlock *StartBlock =
203938fc0aedSTobias Grosser         executeScopConditionally(*S, this, Builder.getTrue());
204038fc0aedSTobias Grosser 
204138fc0aedSTobias Grosser     // TODO: Handle LICM
204238fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
204338fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
204438fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
2045*cb1aef8dSTobias Grosser 
2046*cb1aef8dSTobias Grosser     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx());
2047*cb1aef8dSTobias Grosser     isl_ast_expr *Condition = IslAst::buildRunCondition(S, Build);
2048*cb1aef8dSTobias Grosser     isl_ast_build_free(Build);
2049*cb1aef8dSTobias Grosser 
2050*cb1aef8dSTobias Grosser     Value *RTC = NodeBuilder.createRTC(Condition);
2051*cb1aef8dSTobias Grosser     Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
2052*cb1aef8dSTobias Grosser 
205338fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
2054fa7b0802STobias Grosser 
2055fa7b0802STobias Grosser     NodeBuilder.initializeAfterRTH();
205638fc0aedSTobias Grosser     NodeBuilder.create(Root);
20578ed5e599STobias Grosser     NodeBuilder.finalize();
205838fc0aedSTobias Grosser   }
205938fc0aedSTobias Grosser 
2060e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
2061e938517eSTobias Grosser     S = &CurrentScop;
206238fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
206338fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
206438fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
206538fc0aedSTobias Grosser     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
206638fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
2067e938517eSTobias Grosser 
20682d58a64eSTobias Grosser     // We currently do not support scops with invariant loads.
20692d58a64eSTobias Grosser     if (S->hasInvariantAccesses())
20702d58a64eSTobias Grosser       return false;
20712d58a64eSTobias Grosser 
2072e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
2073e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
2074f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
207538fc0aedSTobias Grosser 
207638fc0aedSTobias Grosser     if (PPCGGen->tree)
207732837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
207838fc0aedSTobias Grosser 
2079b307ed4dSTobias Grosser     freeOptions(PPCGScop);
2080f384594dSTobias Grosser     freePPCGGen(PPCGGen);
2081e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
2082e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
2083e938517eSTobias Grosser 
2084e938517eSTobias Grosser     return true;
2085e938517eSTobias Grosser   }
20869dfe4e7cSTobias Grosser 
20879dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
20889dfe4e7cSTobias Grosser 
20899dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
20909dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
20919dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
20929dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
20939dfe4e7cSTobias Grosser     AU.addRequired<ScopDetection>();
20949dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
20959dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
20969dfe4e7cSTobias Grosser 
20979dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
20989dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
20999dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
21009dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
21019dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
21029dfe4e7cSTobias Grosser     AU.addPreserved<PostDominatorTreeWrapperPass>();
21039dfe4e7cSTobias Grosser     AU.addPreserved<ScopDetection>();
21049dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
21059dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
21069dfe4e7cSTobias Grosser 
21079dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
21089dfe4e7cSTobias Grosser     //        region tree.
21099dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
21109dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
21119dfe4e7cSTobias Grosser   }
21129dfe4e7cSTobias Grosser };
21139dfe4e7cSTobias Grosser }
21149dfe4e7cSTobias Grosser 
21159dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
21169dfe4e7cSTobias Grosser 
21179dfe4e7cSTobias Grosser Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
21189dfe4e7cSTobias Grosser 
21199dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
21209dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
21219dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
21229dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
21239dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
21249dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
21259dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
21269dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScopDetection);
21279dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
21289dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
2129