19dfe4e7cSTobias Grosser //===------ PPCGCodeGeneration.cpp - Polly Accelerator Code Generation. ---===//
29dfe4e7cSTobias Grosser //
39dfe4e7cSTobias Grosser //                     The LLVM Compiler Infrastructure
49dfe4e7cSTobias Grosser //
59dfe4e7cSTobias Grosser // This file is distributed under the University of Illinois Open Source
69dfe4e7cSTobias Grosser // License. See LICENSE.TXT for details.
79dfe4e7cSTobias Grosser //
89dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===//
99dfe4e7cSTobias Grosser //
109dfe4e7cSTobias Grosser // Take a scop created by ScopInfo and map it to GPU code using the ppcg
119dfe4e7cSTobias Grosser // GPU mapping strategy.
129dfe4e7cSTobias Grosser //
139dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===//
149dfe4e7cSTobias Grosser 
159dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h"
1638fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h"
179dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h"
189dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h"
19f384594dSTobias Grosser #include "polly/Options.h"
209dfe4e7cSTobias Grosser #include "polly/ScopInfo.h"
21edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h"
2274dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h"
239dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h"
249dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h"
259dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h"
269dfe4e7cSTobias Grosser #include "llvm/Analysis/PostDominators.h"
279dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
2874dc3cb4STobias Grosser #include "llvm/Analysis/TargetLibraryInfo.h"
2974dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h"
3074dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h"
31e1a98343STobias Grosser #include "llvm/IR/Verifier.h"
3274dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h"
3374dc3cb4STobias Grosser #include "llvm/Support/TargetSelect.h"
3474dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h"
359a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h"
369dfe4e7cSTobias Grosser 
37f384594dSTobias Grosser #include "isl/union_map.h"
38f384594dSTobias Grosser 
39e938517eSTobias Grosser extern "C" {
40a56f8f8eSTobias Grosser #include "ppcg/cuda.h"
41a56f8f8eSTobias Grosser #include "ppcg/gpu.h"
42a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h"
43a56f8f8eSTobias Grosser #include "ppcg/ppcg.h"
44a56f8f8eSTobias Grosser #include "ppcg/schedule.h"
45e938517eSTobias Grosser }
46e938517eSTobias Grosser 
479dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h"
489dfe4e7cSTobias Grosser 
499dfe4e7cSTobias Grosser using namespace polly;
509dfe4e7cSTobias Grosser using namespace llvm;
519dfe4e7cSTobias Grosser 
529dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg"
539dfe4e7cSTobias Grosser 
54f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
55f384594dSTobias Grosser                                   cl::desc("Dump the computed GPU Schedule"),
56681bd568STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
57f384594dSTobias Grosser                                   cl::cat(PollyCategory));
5869b46751STobias Grosser 
5969b46751STobias Grosser static cl::opt<bool>
6069b46751STobias Grosser     DumpCode("polly-acc-dump-code",
6169b46751STobias Grosser              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
6269b46751STobias Grosser              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
6369b46751STobias Grosser 
6432837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
6532837fe3STobias Grosser                                   cl::desc("Dump the kernel LLVM-IR"),
6632837fe3STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
6732837fe3STobias Grosser                                   cl::cat(PollyCategory));
6832837fe3STobias Grosser 
6974dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
7074dc3cb4STobias Grosser                                    cl::desc("Dump the kernel assembly code"),
7174dc3cb4STobias Grosser                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
7274dc3cb4STobias Grosser                                    cl::cat(PollyCategory));
7374dc3cb4STobias Grosser 
7474dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath",
7574dc3cb4STobias Grosser                               cl::desc("Allow unsafe math optimizations"),
7674dc3cb4STobias Grosser                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
7774dc3cb4STobias Grosser                               cl::cat(PollyCategory));
7874dc3cb4STobias Grosser 
7974dc3cb4STobias Grosser static cl::opt<std::string>
8074dc3cb4STobias Grosser     CudaVersion("polly-acc-cuda-version",
8174dc3cb4STobias Grosser                 cl::desc("The CUDA version to compile for"), cl::Hidden,
8274dc3cb4STobias Grosser                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
8374dc3cb4STobias Grosser 
8460c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
8560c60025STobias Grosser ///
8660c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
8760c60025STobias Grosser /// of the scheduled ScopStmts.
8860c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
89edb885cbSTobias Grosser     void *StmtT, isl_ast_build *Build,
9060c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
9160c60025STobias Grosser                                        isl_id *Id, void *User),
9260c60025STobias Grosser     void *UserIndex,
9360c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
94edb885cbSTobias Grosser     void *UserExpr) {
9560c60025STobias Grosser 
96edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
9760c60025STobias Grosser 
98edb885cbSTobias Grosser   isl_ctx *Ctx;
99edb885cbSTobias Grosser 
100edb885cbSTobias Grosser   if (!Stmt || !Build)
101edb885cbSTobias Grosser     return NULL;
102edb885cbSTobias Grosser 
103edb885cbSTobias Grosser   Ctx = isl_ast_build_get_ctx(Build);
104edb885cbSTobias Grosser   isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0);
105edb885cbSTobias Grosser 
106edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
107edb885cbSTobias Grosser     isl_map *AddrFunc = Acc->getAddressFunction();
108edb885cbSTobias Grosser     AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain());
109edb885cbSTobias Grosser     isl_id *RefId = Acc->getId();
110edb885cbSTobias Grosser     isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc);
111edb885cbSTobias Grosser     isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA);
112edb885cbSTobias Grosser     MPA = isl_multi_pw_aff_coalesce(MPA);
113edb885cbSTobias Grosser     MPA = FunctionIndex(MPA, RefId, UserIndex);
114edb885cbSTobias Grosser     isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA);
115edb885cbSTobias Grosser     Access = FunctionExpr(Access, RefId, UserExpr);
116edb885cbSTobias Grosser     RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access);
117edb885cbSTobias Grosser   }
118edb885cbSTobias Grosser 
119edb885cbSTobias Grosser   return RefToExpr;
12060c60025STobias Grosser }
121f384594dSTobias Grosser 
12238fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
12338fc0aedSTobias Grosser ///
12438fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
12538fc0aedSTobias Grosser /// generates code for general-prupose AST nodes, with special functionality
12638fc0aedSTobias Grosser /// for generating GPU specific user nodes.
12738fc0aedSTobias Grosser ///
12838fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
12938fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
13038fc0aedSTobias Grosser public:
13138fc0aedSTobias Grosser   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P,
13238fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
13332837fe3STobias Grosser                  DominatorTree &DT, Scop &S, gpu_prog *Prog)
134edb885cbSTobias Grosser       : IslNodeBuilder(Builder, Annotator, P, DL, LI, SE, DT, S), Prog(Prog) {
135edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
136edb885cbSTobias Grosser   }
13738fc0aedSTobias Grosser 
138fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
139fa7b0802STobias Grosser   void initializeAfterRTH();
140fa7b0802STobias Grosser 
141fa7b0802STobias Grosser   /// Finalize the generated scop.
142fa7b0802STobias Grosser   virtual void finalize();
143fa7b0802STobias Grosser 
14438fc0aedSTobias Grosser private:
14574dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
14674dc3cb4STobias Grosser   ///
14774dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
14874dc3cb4STobias Grosser   /// more.
14974dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
15074dc3cb4STobias Grosser 
151*13c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
152*13c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
1537287aeddSTobias Grosser 
154fa7b0802STobias Grosser   /// The current GPU context.
155fa7b0802STobias Grosser   Value *GPUContext;
156fa7b0802STobias Grosser 
15732837fe3STobias Grosser   /// A module containing GPU code.
15832837fe3STobias Grosser   ///
15932837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
16032837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
16132837fe3STobias Grosser 
16232837fe3STobias Grosser   /// The GPU program we generate code for.
16332837fe3STobias Grosser   gpu_prog *Prog;
16432837fe3STobias Grosser 
165472f9654STobias Grosser   /// Class to free isl_ids.
166472f9654STobias Grosser   class IslIdDeleter {
167472f9654STobias Grosser   public:
168472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
169472f9654STobias Grosser   };
170472f9654STobias Grosser 
171472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
172472f9654STobias Grosser   ///
173472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
174472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
175472f9654STobias Grosser 
176edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
177edb885cbSTobias Grosser 
17838fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
17938fc0aedSTobias Grosser   ///
18038fc0aedSTobias Grosser   /// These AST nodes can be of type:
18138fc0aedSTobias Grosser   ///
18238fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
18338fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
184*13c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
1855260c041STobias Grosser   ///   - In-kernel synchronization
1865260c041STobias Grosser   ///   - In-kernel memory copy statement
18738fc0aedSTobias Grosser   ///
1881fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
1891fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
19032837fe3STobias Grosser 
191*13c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
192*13c78e4dSTobias Grosser 
193*13c78e4dSTobias Grosser   /// Create code for a data transfer statement
194*13c78e4dSTobias Grosser   ///
195*13c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
196*13c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
197*13c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
198*13c78e4dSTobias Grosser                           enum DataDirection Direction);
199*13c78e4dSTobias Grosser 
200edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
201edb885cbSTobias Grosser   ///
202edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
203edb885cbSTobias Grosser   ///
204edb885cbSTobias Grosser   /// @returns A set of values referenced by the kernel.
205edb885cbSTobias Grosser   SetVector<Value *> getReferencesInKernel(ppcg_kernel *Kernel);
206edb885cbSTobias Grosser 
20732837fe3STobias Grosser   /// Create GPU kernel.
20832837fe3STobias Grosser   ///
20932837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
21032837fe3STobias Grosser   ///
21132837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
21232837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
21332837fe3STobias Grosser 
214*13c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
215*13c78e4dSTobias Grosser   ///
216*13c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
217*13c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
218*13c78e4dSTobias Grosser 
21932837fe3STobias Grosser   /// Create kernel function.
22032837fe3STobias Grosser   ///
22132837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
22232837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
22332837fe3STobias Grosser   /// start block of this newly created function.
22432837fe3STobias Grosser   ///
22532837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
226edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
227edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
228edb885cbSTobias Grosser                             SetVector<Value *> &SubtreeValues);
22932837fe3STobias Grosser 
23032837fe3STobias Grosser   /// Create the declaration of a kernel function.
23132837fe3STobias Grosser   ///
23232837fe3STobias Grosser   /// The kernel function takes as arguments:
23332837fe3STobias Grosser   ///
23432837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
235f6044bd0STobias Grosser   ///   - Host iterators
236c84a1995STobias Grosser   ///   - Parameters
23732837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
23832837fe3STobias Grosser   ///
23932837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
240edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
241edb885cbSTobias Grosser   ///
24232837fe3STobias Grosser   /// @returns The newly declared function.
243edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
244edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
24532837fe3STobias Grosser 
246472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
247472f9654STobias Grosser   ///
248472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
249472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
250472f9654STobias Grosser 
251edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
252edb885cbSTobias Grosser   ///
253edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
254edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
255edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
256edb885cbSTobias Grosser 
2575260c041STobias Grosser   /// Create an in-kernel synchronization call.
2585260c041STobias Grosser   void createKernelSync();
2595260c041STobias Grosser 
26074dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
26174dc3cb4STobias Grosser   ///
26274dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
26374dc3cb4STobias Grosser   std::string createKernelASM();
26474dc3cb4STobias Grosser 
26574dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
26674dc3cb4STobias Grosser   ///
26774dc3cb4STobias Grosser   /// @param F The function to remove references to.
26874dc3cb4STobias Grosser   void clearDominators(Function *F);
26974dc3cb4STobias Grosser 
27074dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
27174dc3cb4STobias Grosser   ///
27274dc3cb4STobias Grosser   /// @param F The function to remove references to.
27374dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
27474dc3cb4STobias Grosser 
27574dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
27674dc3cb4STobias Grosser   ///
27774dc3cb4STobias Grosser   /// @param F The function to remove references to.
27874dc3cb4STobias Grosser   void clearLoops(Function *F);
27974dc3cb4STobias Grosser 
28032837fe3STobias Grosser   /// Finalize the generation of the kernel function.
28132837fe3STobias Grosser   ///
28232837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
28332837fe3STobias Grosser   /// dump its IR to stderr.
28432837fe3STobias Grosser   void finalizeKernelFunction();
285fa7b0802STobias Grosser 
2867287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
287fa7b0802STobias Grosser   void allocateDeviceArrays();
288fa7b0802STobias Grosser 
2897287aeddSTobias Grosser   /// Free all allocated device arrays.
2907287aeddSTobias Grosser   void freeDeviceArrays();
2917287aeddSTobias Grosser 
292fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
293fa7b0802STobias Grosser   ///
294fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
295fa7b0802STobias Grosser   Value *createCallInitContext();
296fa7b0802STobias Grosser 
297fa7b0802STobias Grosser   /// Create a call to free the GPU context.
298fa7b0802STobias Grosser   ///
299fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
300fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
301fa7b0802STobias Grosser 
3027287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
3037287aeddSTobias Grosser   ///
3047287aeddSTobias Grosser   /// @param Size The size of memory to allocate
3057287aeddSTobias Grosser   ///
3067287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
307fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
3087287aeddSTobias Grosser 
3097287aeddSTobias Grosser   /// Create a call to free a device array.
3107287aeddSTobias Grosser   ///
3117287aeddSTobias Grosser   /// @param Array The device array to free.
3127287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
313*13c78e4dSTobias Grosser 
314*13c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
315*13c78e4dSTobias Grosser   ///
316*13c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
317*13c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
318*13c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
319*13c78e4dSTobias Grosser                                       Value *Size);
320*13c78e4dSTobias Grosser 
321*13c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
322*13c78e4dSTobias Grosser   ///
323*13c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
324*13c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
325*13c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
326*13c78e4dSTobias Grosser                                       Value *Size);
3271fb9b64dSTobias Grosser };
3281fb9b64dSTobias Grosser 
329fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
330fa7b0802STobias Grosser   GPUContext = createCallInitContext();
331fa7b0802STobias Grosser   allocateDeviceArrays();
332fa7b0802STobias Grosser }
333fa7b0802STobias Grosser 
334fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
3357287aeddSTobias Grosser   freeDeviceArrays();
336fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
337fa7b0802STobias Grosser   IslNodeBuilder::finalize();
338fa7b0802STobias Grosser }
339fa7b0802STobias Grosser 
340fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
341fa7b0802STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
342fa7b0802STobias Grosser 
343fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
344fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
345*13c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
3467287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
3477287aeddSTobias Grosser     DevArrayName.append(Array->name);
348fa7b0802STobias Grosser 
349*13c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
3507287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
3517287aeddSTobias Grosser     DevArray->setName(DevArrayName);
352*13c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
353fa7b0802STobias Grosser   }
354fa7b0802STobias Grosser 
355fa7b0802STobias Grosser   isl_ast_build_free(Build);
356fa7b0802STobias Grosser }
357fa7b0802STobias Grosser 
3587287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
359*13c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
360*13c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
3617287aeddSTobias Grosser }
3627287aeddSTobias Grosser 
3637287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
3647287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
3657287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
3667287aeddSTobias Grosser   Function *F = M->getFunction(Name);
3677287aeddSTobias Grosser 
3687287aeddSTobias Grosser   // If F is not available, declare it.
3697287aeddSTobias Grosser   if (!F) {
3707287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
3717287aeddSTobias Grosser     std::vector<Type *> Args;
3727287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
3737287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
3747287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
3757287aeddSTobias Grosser   }
3767287aeddSTobias Grosser 
3777287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
3787287aeddSTobias Grosser }
3797287aeddSTobias Grosser 
380fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
381fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
382fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
383fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
384fa7b0802STobias Grosser 
385fa7b0802STobias Grosser   // If F is not available, declare it.
386fa7b0802STobias Grosser   if (!F) {
387fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
388fa7b0802STobias Grosser     std::vector<Type *> Args;
389fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
390fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
391fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
392fa7b0802STobias Grosser   }
393fa7b0802STobias Grosser 
394fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
395fa7b0802STobias Grosser }
396fa7b0802STobias Grosser 
397*13c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
398*13c78e4dSTobias Grosser                                                     Value *DeviceData,
399*13c78e4dSTobias Grosser                                                     Value *Size) {
400*13c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
401*13c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
402*13c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
403*13c78e4dSTobias Grosser 
404*13c78e4dSTobias Grosser   // If F is not available, declare it.
405*13c78e4dSTobias Grosser   if (!F) {
406*13c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
407*13c78e4dSTobias Grosser     std::vector<Type *> Args;
408*13c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
409*13c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
410*13c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
411*13c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
412*13c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
413*13c78e4dSTobias Grosser   }
414*13c78e4dSTobias Grosser 
415*13c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
416*13c78e4dSTobias Grosser }
417*13c78e4dSTobias Grosser 
418*13c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
419*13c78e4dSTobias Grosser                                                     Value *HostData,
420*13c78e4dSTobias Grosser                                                     Value *Size) {
421*13c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
422*13c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
423*13c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
424*13c78e4dSTobias Grosser 
425*13c78e4dSTobias Grosser   // If F is not available, declare it.
426*13c78e4dSTobias Grosser   if (!F) {
427*13c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
428*13c78e4dSTobias Grosser     std::vector<Type *> Args;
429*13c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
430*13c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
431*13c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
432*13c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
433*13c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
434*13c78e4dSTobias Grosser   }
435*13c78e4dSTobias Grosser 
436*13c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
437*13c78e4dSTobias Grosser }
438*13c78e4dSTobias Grosser 
439fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
440fa7b0802STobias Grosser   const char *Name = "polly_initContext";
441fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
442fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
443fa7b0802STobias Grosser 
444fa7b0802STobias Grosser   // If F is not available, declare it.
445fa7b0802STobias Grosser   if (!F) {
446fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
447fa7b0802STobias Grosser     std::vector<Type *> Args;
448fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
449fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
450fa7b0802STobias Grosser   }
451fa7b0802STobias Grosser 
452fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
453fa7b0802STobias Grosser }
454fa7b0802STobias Grosser 
455fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
456fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
457fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
458fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
459fa7b0802STobias Grosser 
460fa7b0802STobias Grosser   // If F is not available, declare it.
461fa7b0802STobias Grosser   if (!F) {
462fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
463fa7b0802STobias Grosser     std::vector<Type *> Args;
464fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
465fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
466fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
467fa7b0802STobias Grosser   }
468fa7b0802STobias Grosser 
469fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
470fa7b0802STobias Grosser }
471fa7b0802STobias Grosser 
4725260c041STobias Grosser /// Check if one string is a prefix of another.
4735260c041STobias Grosser ///
4745260c041STobias Grosser /// @param String The string in which to look for the prefix.
4755260c041STobias Grosser /// @param Prefix The prefix to look for.
4765260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
4775260c041STobias Grosser   return String.find(Prefix) == 0;
4785260c041STobias Grosser }
4795260c041STobias Grosser 
480*13c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
481*13c78e4dSTobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
482*13c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
483*13c78e4dSTobias Grosser 
484*13c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
485*13c78e4dSTobias Grosser     auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]);
486*13c78e4dSTobias Grosser     isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero);
487*13c78e4dSTobias Grosser 
488*13c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
489*13c78e4dSTobias Grosser       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]);
490*13c78e4dSTobias Grosser       isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
491*13c78e4dSTobias Grosser       Res = isl_ast_expr_mul(Res, Expr);
492*13c78e4dSTobias Grosser     }
493*13c78e4dSTobias Grosser 
494*13c78e4dSTobias Grosser     Value *NumElements = ExprBuilder.create(Res);
495*13c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
496*13c78e4dSTobias Grosser   }
497*13c78e4dSTobias Grosser   isl_ast_build_free(Build);
498*13c78e4dSTobias Grosser   return ArraySize;
499*13c78e4dSTobias Grosser }
500*13c78e4dSTobias Grosser 
501*13c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
502*13c78e4dSTobias Grosser                                         enum DataDirection Direction) {
503*13c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
504*13c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
505*13c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
506*13c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
507*13c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
508*13c78e4dSTobias Grosser 
509*13c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
510*13c78e4dSTobias Grosser   Value *HostPtr = ScopArray->getBasePtr();
511*13c78e4dSTobias Grosser 
512*13c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
513*13c78e4dSTobias Grosser 
514*13c78e4dSTobias Grosser   if (gpu_array_is_scalar(Array)) {
515*13c78e4dSTobias Grosser     HostPtr = Builder.CreateAlloca(ScopArray->getElementType());
516*13c78e4dSTobias Grosser     Builder.CreateStore(ScopArray->getBasePtr(), HostPtr);
517*13c78e4dSTobias Grosser   }
518*13c78e4dSTobias Grosser 
519*13c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
520*13c78e4dSTobias Grosser 
521*13c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
522*13c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
523*13c78e4dSTobias Grosser   else
524*13c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
525*13c78e4dSTobias Grosser 
526*13c78e4dSTobias Grosser   isl_id_free(Id);
527*13c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
528*13c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
529*13c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
530*13c78e4dSTobias Grosser }
531*13c78e4dSTobias Grosser 
5321fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
53332837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
53432837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
53532837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
53632837fe3STobias Grosser   isl_id_free(Id);
53732837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
53832837fe3STobias Grosser 
53932837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
54032837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
54132837fe3STobias Grosser     createKernel(UserStmt);
54232837fe3STobias Grosser     isl_ast_expr_free(Expr);
54332837fe3STobias Grosser     return;
54432837fe3STobias Grosser   }
54532837fe3STobias Grosser 
546*13c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
547*13c78e4dSTobias Grosser     createDataTransfer(UserStmt, HOST_TO_DEVICE);
54832837fe3STobias Grosser     isl_ast_expr_free(Expr);
549*13c78e4dSTobias Grosser     return;
550*13c78e4dSTobias Grosser   }
551*13c78e4dSTobias Grosser 
552*13c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
553*13c78e4dSTobias Grosser     createDataTransfer(UserStmt, DEVICE_TO_HOST);
554*13c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
55538fc0aedSTobias Grosser     return;
55638fc0aedSTobias Grosser   }
55738fc0aedSTobias Grosser 
5585260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
5595260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
5605260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
5615260c041STobias Grosser   isl_id_free(Anno);
5625260c041STobias Grosser 
5635260c041STobias Grosser   switch (KernelStmt->type) {
5645260c041STobias Grosser   case ppcg_kernel_domain:
565edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
5665260c041STobias Grosser     isl_ast_node_free(UserStmt);
5675260c041STobias Grosser     return;
5685260c041STobias Grosser   case ppcg_kernel_copy:
5695260c041STobias Grosser     // TODO: Create kernel copy stmt
5705260c041STobias Grosser     isl_ast_expr_free(Expr);
5715260c041STobias Grosser     isl_ast_node_free(UserStmt);
5725260c041STobias Grosser     return;
5735260c041STobias Grosser   case ppcg_kernel_sync:
5745260c041STobias Grosser     createKernelSync();
5755260c041STobias Grosser     isl_ast_expr_free(Expr);
5765260c041STobias Grosser     isl_ast_node_free(UserStmt);
5775260c041STobias Grosser     return;
5785260c041STobias Grosser   }
5795260c041STobias Grosser 
5805260c041STobias Grosser   isl_ast_expr_free(Expr);
5815260c041STobias Grosser   isl_ast_node_free(UserStmt);
5825260c041STobias Grosser   return;
5835260c041STobias Grosser }
5845260c041STobias Grosser 
585edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
586edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
587edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
588edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
589edb885cbSTobias Grosser 
590edb885cbSTobias Grosser   LoopToScevMapT LTS;
591edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
592edb885cbSTobias Grosser 
593edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
594edb885cbSTobias Grosser 
595edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
596edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
597edb885cbSTobias Grosser   else
598edb885cbSTobias Grosser     assert(0 && "Region statement not supported\n");
599edb885cbSTobias Grosser }
600edb885cbSTobias Grosser 
6015260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
6025260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
6035260c041STobias Grosser   auto *Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
6045260c041STobias Grosser   Builder.CreateCall(Sync, {});
6055260c041STobias Grosser }
6065260c041STobias Grosser 
607edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
608edb885cbSTobias Grosser ///
609edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
610edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
611edb885cbSTobias Grosser ///
612edb885cbSTobias Grosser /// @param Node The node to collect references for.
613edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
614edb885cbSTobias Grosser ///
615edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
616edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
617edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
618edb885cbSTobias Grosser     return isl_bool_true;
619edb885cbSTobias Grosser 
620edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
621edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
622edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
623edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
624edb885cbSTobias Grosser   isl_id_free(Id);
625edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
626edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
627edb885cbSTobias Grosser 
628edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
629edb885cbSTobias Grosser     return isl_bool_true;
630edb885cbSTobias Grosser 
631edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
632edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
633edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
634edb885cbSTobias Grosser   isl_id_free(Id);
635edb885cbSTobias Grosser 
636edb885cbSTobias Grosser   addReferencesFromStmt(Stmt, User);
637edb885cbSTobias Grosser 
638edb885cbSTobias Grosser   return isl_bool_true;
639edb885cbSTobias Grosser }
640edb885cbSTobias Grosser 
641edb885cbSTobias Grosser SetVector<Value *> GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
642edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
643edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
644edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
645edb885cbSTobias Grosser   SubtreeReferences References = {
646edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
647edb885cbSTobias Grosser 
648edb885cbSTobias Grosser   for (const auto &I : IDToValue)
649edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
650edb885cbSTobias Grosser 
651edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
652edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
653edb885cbSTobias Grosser 
654edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
655edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
656edb885cbSTobias Grosser 
657edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
658edb885cbSTobias Grosser     SubtreeValues.remove(SAI.second->getBasePtr());
659edb885cbSTobias Grosser 
660edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
661edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
662edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
663edb885cbSTobias Grosser     assert(IDToValue.count(Id));
664edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
665edb885cbSTobias Grosser     SubtreeValues.remove(Val);
666edb885cbSTobias Grosser     isl_id_free(Id);
667edb885cbSTobias Grosser   }
668edb885cbSTobias Grosser   isl_space_free(Space);
669edb885cbSTobias Grosser 
670edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
671edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
672edb885cbSTobias Grosser     assert(IDToValue.count(Id));
673edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
674edb885cbSTobias Grosser     SubtreeValues.remove(Val);
675edb885cbSTobias Grosser     isl_id_free(Id);
676edb885cbSTobias Grosser   }
677edb885cbSTobias Grosser 
678edb885cbSTobias Grosser   return SubtreeValues;
679edb885cbSTobias Grosser }
680edb885cbSTobias Grosser 
68174dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
68274dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
68374dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
68474dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
68574dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
68674dc3cb4STobias Grosser 
68774dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
68874dc3cb4STobias Grosser     DT.eraseNode(BB);
68974dc3cb4STobias Grosser }
69074dc3cb4STobias Grosser 
69174dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
69274dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
69374dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
69474dc3cb4STobias Grosser     if (L)
69574dc3cb4STobias Grosser       SE.forgetLoop(L);
69674dc3cb4STobias Grosser   }
69774dc3cb4STobias Grosser }
69874dc3cb4STobias Grosser 
69974dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
70074dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
70174dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
70274dc3cb4STobias Grosser     if (L)
70374dc3cb4STobias Grosser       SE.forgetLoop(L);
70474dc3cb4STobias Grosser     LI.removeBlock(&BB);
70574dc3cb4STobias Grosser   }
70674dc3cb4STobias Grosser }
70774dc3cb4STobias Grosser 
70832837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
70932837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
71032837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
71132837fe3STobias Grosser   isl_id_free(Id);
71232837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
71332837fe3STobias Grosser 
714edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel);
715edb885cbSTobias Grosser 
71632837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
71732837fe3STobias Grosser 
71832837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
719472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
720edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
72132837fe3STobias Grosser 
722edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
723edb885cbSTobias Grosser 
724edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
725edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
726edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
727edb885cbSTobias Grosser   for (const Loop *L : Loops) {
728edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
729edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
730edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
731edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
732edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
733edb885cbSTobias Grosser     SubtreeValues.insert(V);
734edb885cbSTobias Grosser   }
735edb885cbSTobias Grosser 
736edb885cbSTobias Grosser   createKernelFunction(Kernel, SubtreeValues);
73732837fe3STobias Grosser 
73859ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
73959ab0705STobias Grosser 
74074dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
74174dc3cb4STobias Grosser   clearDominators(F);
74274dc3cb4STobias Grosser   clearScalarEvolution(F);
74374dc3cb4STobias Grosser   clearLoops(F);
74474dc3cb4STobias Grosser 
74532837fe3STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
746472f9654STobias Grosser   IDToValue = HostIDs;
74732837fe3STobias Grosser 
748edb885cbSTobias Grosser   ValueMap = HostValueMap;
749edb885cbSTobias Grosser   ScalarMap.clear();
750edb885cbSTobias Grosser   PHIOpMap.clear();
751edb885cbSTobias Grosser   EscapeMap.clear();
752edb885cbSTobias Grosser   IDToSAI.clear();
75374dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
75474dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
75574dc3cb4STobias Grosser     S.invalidateScopArrayInfo(BasePtr, ScopArrayInfo::MK_Array);
75674dc3cb4STobias Grosser   LocalArrays.clear();
757edb885cbSTobias Grosser 
75832837fe3STobias Grosser   finalizeKernelFunction();
75932837fe3STobias Grosser }
76032837fe3STobias Grosser 
76132837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
76232837fe3STobias Grosser ///
76332837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
76432837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
76532837fe3STobias Grosser   std::string Ret = "e";
76632837fe3STobias Grosser 
76732837fe3STobias Grosser   if (!is64Bit)
76832837fe3STobias Grosser     Ret += "-p:32:32";
76932837fe3STobias Grosser 
77032837fe3STobias Grosser   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
77132837fe3STobias Grosser 
77232837fe3STobias Grosser   return Ret;
77332837fe3STobias Grosser }
77432837fe3STobias Grosser 
775edb885cbSTobias Grosser Function *
776edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
777edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
77832837fe3STobias Grosser   std::vector<Type *> Args;
77932837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
78032837fe3STobias Grosser 
78132837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
78232837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
78332837fe3STobias Grosser       continue;
78432837fe3STobias Grosser 
78532837fe3STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
78632837fe3STobias Grosser   }
78732837fe3STobias Grosser 
788f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
789f6044bd0STobias Grosser 
790f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++)
791f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
792f6044bd0STobias Grosser 
793c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
794c84a1995STobias Grosser 
795c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++)
796c84a1995STobias Grosser     Args.push_back(Builder.getInt64Ty());
797c84a1995STobias Grosser 
798edb885cbSTobias Grosser   for (auto *V : SubtreeValues)
799edb885cbSTobias Grosser     Args.push_back(V->getType());
800edb885cbSTobias Grosser 
80132837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
80232837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
80332837fe3STobias Grosser                               GPUModule.get());
80432837fe3STobias Grosser   FN->setCallingConv(CallingConv::PTX_Kernel);
80532837fe3STobias Grosser 
80632837fe3STobias Grosser   auto Arg = FN->arg_begin();
80732837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
80832837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
80932837fe3STobias Grosser       continue;
81032837fe3STobias Grosser 
811edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
812edb885cbSTobias Grosser 
813edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
814edb885cbSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
815edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
816edb885cbSTobias Grosser     Value *Val = &*Arg;
817edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
818edb885cbSTobias Grosser     isl_ast_build *Build =
819edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
820edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
821edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
822edb885cbSTobias Grosser           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
823edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
824edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
825edb885cbSTobias Grosser     }
826edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
827edb885cbSTobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, ScopArrayInfo::MK_Array);
82874dc3cb4STobias Grosser     LocalArrays.push_back(Val);
829edb885cbSTobias Grosser 
830edb885cbSTobias Grosser     isl_ast_build_free(Build);
831edb885cbSTobias Grosser     isl_id_free(Id);
832edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
83332837fe3STobias Grosser     Arg++;
83432837fe3STobias Grosser   }
83532837fe3STobias Grosser 
836f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
837f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
838f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
839f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
840f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
841f6044bd0STobias Grosser     Arg++;
842f6044bd0STobias Grosser   }
843f6044bd0STobias Grosser 
844c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
845c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
846c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
847c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
848c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
849c84a1995STobias Grosser     Arg++;
850c84a1995STobias Grosser   }
851c84a1995STobias Grosser 
852edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
853edb885cbSTobias Grosser     Arg->setName(V->getName());
854edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
855edb885cbSTobias Grosser     Arg++;
856edb885cbSTobias Grosser   }
857edb885cbSTobias Grosser 
85832837fe3STobias Grosser   return FN;
85932837fe3STobias Grosser }
86032837fe3STobias Grosser 
861472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
862472f9654STobias Grosser   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
863472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
864472f9654STobias Grosser 
865472f9654STobias Grosser   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
866472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
867472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
868472f9654STobias Grosser 
869472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
870472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
871472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
872472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
873472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
874472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
875472f9654STobias Grosser     IDToValue[Id] = Val;
876472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
877472f9654STobias Grosser   };
878472f9654STobias Grosser 
879472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
880472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
881472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
882472f9654STobias Grosser   }
883472f9654STobias Grosser 
884472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
885472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
886472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
887472f9654STobias Grosser   }
888472f9654STobias Grosser }
889472f9654STobias Grosser 
890edb885cbSTobias Grosser void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel,
891edb885cbSTobias Grosser                                           SetVector<Value *> &SubtreeValues) {
89232837fe3STobias Grosser 
89332837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
89432837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
89532837fe3STobias Grosser   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
89632837fe3STobias Grosser   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
89732837fe3STobias Grosser 
898edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
89932837fe3STobias Grosser 
90059ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
90132837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
90232837fe3STobias Grosser 
90359ab0705STobias Grosser   DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
90459ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
90559ab0705STobias Grosser 
90632837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
90732837fe3STobias Grosser   Builder.CreateRetVoid();
90832837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
909472f9654STobias Grosser 
910472f9654STobias Grosser   insertKernelIntrinsics(Kernel);
91132837fe3STobias Grosser }
91232837fe3STobias Grosser 
91374dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
91474dc3cb4STobias Grosser   llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda"));
91574dc3cb4STobias Grosser   std::string ErrMsg;
91674dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
91774dc3cb4STobias Grosser 
91874dc3cb4STobias Grosser   if (!GPUTarget) {
91974dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
92074dc3cb4STobias Grosser     return "";
92174dc3cb4STobias Grosser   }
92274dc3cb4STobias Grosser 
92374dc3cb4STobias Grosser   TargetOptions Options;
92474dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
92574dc3cb4STobias Grosser   std::unique_ptr<TargetMachine> TargetM(
92674dc3cb4STobias Grosser       GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "",
92774dc3cb4STobias Grosser                                      Options, Optional<Reloc::Model>()));
92874dc3cb4STobias Grosser 
92974dc3cb4STobias Grosser   SmallString<0> ASMString;
93074dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
93174dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
93274dc3cb4STobias Grosser 
93374dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
93474dc3cb4STobias Grosser 
93574dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
93674dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
93774dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
93874dc3cb4STobias Grosser     return "";
93974dc3cb4STobias Grosser   }
94074dc3cb4STobias Grosser 
94174dc3cb4STobias Grosser   PM.run(*GPUModule);
94274dc3cb4STobias Grosser 
94374dc3cb4STobias Grosser   return ASMStream.str();
94474dc3cb4STobias Grosser }
94574dc3cb4STobias Grosser 
94632837fe3STobias Grosser void GPUNodeBuilder::finalizeKernelFunction() {
947e1a98343STobias Grosser   // Verify module.
948e1a98343STobias Grosser   llvm::legacy::PassManager Passes;
949e1a98343STobias Grosser   Passes.add(createVerifierPass());
950e1a98343STobias Grosser   Passes.run(*GPUModule);
95132837fe3STobias Grosser 
95232837fe3STobias Grosser   if (DumpKernelIR)
95332837fe3STobias Grosser     outs() << *GPUModule << "\n";
95432837fe3STobias Grosser 
9559a18d559STobias Grosser   // Optimize module.
9569a18d559STobias Grosser   llvm::legacy::PassManager OptPasses;
9579a18d559STobias Grosser   PassManagerBuilder PassBuilder;
9589a18d559STobias Grosser   PassBuilder.OptLevel = 3;
9599a18d559STobias Grosser   PassBuilder.SizeLevel = 0;
9609a18d559STobias Grosser   PassBuilder.populateModulePassManager(OptPasses);
9619a18d559STobias Grosser   OptPasses.run(*GPUModule);
9629a18d559STobias Grosser 
96374dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
96474dc3cb4STobias Grosser 
96574dc3cb4STobias Grosser   if (DumpKernelASM)
96674dc3cb4STobias Grosser     outs() << Assembly << "\n";
96774dc3cb4STobias Grosser 
96832837fe3STobias Grosser   GPUModule.release();
969472f9654STobias Grosser   KernelIDs.clear();
97032837fe3STobias Grosser }
97132837fe3STobias Grosser 
9729dfe4e7cSTobias Grosser namespace {
9739dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
9749dfe4e7cSTobias Grosser public:
9759dfe4e7cSTobias Grosser   static char ID;
9769dfe4e7cSTobias Grosser 
977e938517eSTobias Grosser   /// The scop that is currently processed.
978e938517eSTobias Grosser   Scop *S;
979e938517eSTobias Grosser 
98038fc0aedSTobias Grosser   LoopInfo *LI;
98138fc0aedSTobias Grosser   DominatorTree *DT;
98238fc0aedSTobias Grosser   ScalarEvolution *SE;
98338fc0aedSTobias Grosser   const DataLayout *DL;
98438fc0aedSTobias Grosser   RegionInfo *RI;
98538fc0aedSTobias Grosser 
9869dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
9879dfe4e7cSTobias Grosser 
988e938517eSTobias Grosser   /// Construct compilation options for PPCG.
989e938517eSTobias Grosser   ///
990e938517eSTobias Grosser   /// @returns The compilation options.
991e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
992e938517eSTobias Grosser     auto DebugOptions =
993e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
994e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
995e938517eSTobias Grosser 
996e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
997e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
998e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
999e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
1000e938517eSTobias Grosser 
1001e938517eSTobias Grosser     Options->debug = DebugOptions;
1002e938517eSTobias Grosser 
1003e938517eSTobias Grosser     Options->reschedule = true;
1004e938517eSTobias Grosser     Options->scale_tile_loops = false;
1005e938517eSTobias Grosser     Options->wrap = false;
1006e938517eSTobias Grosser 
1007e938517eSTobias Grosser     Options->non_negative_parameters = false;
1008e938517eSTobias Grosser     Options->ctx = nullptr;
1009e938517eSTobias Grosser     Options->sizes = nullptr;
1010e938517eSTobias Grosser 
10114eaedde5STobias Grosser     Options->tile_size = 32;
10124eaedde5STobias Grosser 
1013e938517eSTobias Grosser     Options->use_private_memory = false;
1014e938517eSTobias Grosser     Options->use_shared_memory = false;
1015e938517eSTobias Grosser     Options->max_shared_memory = 0;
1016e938517eSTobias Grosser 
1017e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
1018e938517eSTobias Grosser     Options->openmp = false;
1019e938517eSTobias Grosser     Options->linearize_device_arrays = true;
1020e938517eSTobias Grosser     Options->live_range_reordering = false;
1021e938517eSTobias Grosser 
1022e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
1023e938517eSTobias Grosser     Options->opencl_use_gpu = false;
1024e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
1025e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
1026e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
1027e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
1028e938517eSTobias Grosser 
1029e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
1030e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
1031e938517eSTobias Grosser 
1032e938517eSTobias Grosser     return Options;
1033e938517eSTobias Grosser   }
1034e938517eSTobias Grosser 
1035f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
1036f384594dSTobias Grosser   ///
1037f384594dSTobias Grosser   /// Instead of a normal access of the form:
1038f384594dSTobias Grosser   ///
1039f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
1040f384594dSTobias Grosser   ///
1041f384594dSTobias Grosser   /// a tagged access has the form
1042f384594dSTobias Grosser   ///
1043f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
1044f384594dSTobias Grosser   ///
1045f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
1046f384594dSTobias Grosser   /// triggered the access.
1047f384594dSTobias Grosser   ///
1048f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
1049f384594dSTobias Grosser   ///
1050f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
1051f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
1052f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
1053f384594dSTobias Grosser 
1054f384594dSTobias Grosser     for (auto &Stmt : *S)
1055f384594dSTobias Grosser       for (auto &Acc : Stmt)
1056f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
1057f384594dSTobias Grosser           isl_map *Relation = Acc->getAccessRelation();
1058f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
1059f384594dSTobias Grosser 
1060f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
1061f384594dSTobias Grosser           Space = isl_space_range(Space);
1062f384594dSTobias Grosser           Space = isl_space_from_range(Space);
10636293ba69STobias Grosser           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1064f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
1065f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
1066f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
1067f384594dSTobias Grosser         }
1068f384594dSTobias Grosser 
1069f384594dSTobias Grosser     return Accesses;
1070f384594dSTobias Grosser   }
1071f384594dSTobias Grosser 
1072f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
1073f384594dSTobias Grosser   ///
1074f384594dSTobias Grosser   /// @see getTaggedAccesses
1075f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
1076f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
1077f384594dSTobias Grosser   }
1078f384594dSTobias Grosser 
1079f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
1080f384594dSTobias Grosser   ///
1081f384594dSTobias Grosser   /// @see getTaggedAccesses
1082f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
1083f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
1084f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
1085f384594dSTobias Grosser   }
1086f384594dSTobias Grosser 
1087f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
1088f384594dSTobias Grosser   ///
1089f384594dSTobias Grosser   /// @see getTaggedAccesses
1090f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
1091f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
1092f384594dSTobias Grosser   }
1093f384594dSTobias Grosser 
1094aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
1095aef5196fSTobias Grosser   ///
1096aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
1097aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
1098aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
1099aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
1100aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
1101aef5196fSTobias Grosser   /// the data format that ppcg expects.
1102aef5196fSTobias Grosser   ///
1103aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
1104aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
1105aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
1106bd81a7eeSTobias Grosser         S->getIslCtx(),
1107bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
1108aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
1109aef5196fSTobias Grosser     auto *Space = S->getParamSpace();
1110aef5196fSTobias Grosser 
1111aef5196fSTobias Grosser     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
1112aef5196fSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
1113aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1114aef5196fSTobias Grosser     }
1115aef5196fSTobias Grosser 
1116aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
1117aef5196fSTobias Grosser       auto Id = Array.second->getBasePtrId();
1118aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1119aef5196fSTobias Grosser     }
1120aef5196fSTobias Grosser 
1121aef5196fSTobias Grosser     isl_space_free(Space);
1122aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
1123aef5196fSTobias Grosser 
1124aef5196fSTobias Grosser     return Names;
1125aef5196fSTobias Grosser   }
1126aef5196fSTobias Grosser 
1127e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
1128e938517eSTobias Grosser   ///
1129f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
1130f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
1131f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
1132f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
1133e938517eSTobias Grosser   ///
1134e938517eSTobias Grosser   /// @returns A new ppcg scop.
1135e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
1136e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
1137e938517eSTobias Grosser 
1138e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
1139e938517eSTobias Grosser 
1140e938517eSTobias Grosser     PPCGScop->start = 0;
1141e938517eSTobias Grosser     PPCGScop->end = 0;
1142e938517eSTobias Grosser 
1143f384594dSTobias Grosser     PPCGScop->context = S->getContext();
1144f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
1145e938517eSTobias Grosser     PPCGScop->call = nullptr;
1146f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
1147f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
1148e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
1149f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
1150f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
1151f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
1152f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
1153e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
1154f384594dSTobias Grosser     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
1155e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
1156e938517eSTobias Grosser 
1157e938517eSTobias Grosser     PPCGScop->independence = nullptr;
1158e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
1159e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
1160e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
1161e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
1162e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
1163e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
1164e938517eSTobias Grosser 
1165f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
1166aef5196fSTobias Grosser     PPCGScop->names = getNames();
1167e938517eSTobias Grosser 
1168e938517eSTobias Grosser     PPCGScop->pet = nullptr;
1169e938517eSTobias Grosser 
1170f384594dSTobias Grosser     compute_tagger(PPCGScop);
1171f384594dSTobias Grosser     compute_dependences(PPCGScop);
1172f384594dSTobias Grosser 
1173e938517eSTobias Grosser     return PPCGScop;
1174e938517eSTobias Grosser   }
1175e938517eSTobias Grosser 
117660f63b49STobias Grosser   /// Collect the array acesses in a statement.
117760f63b49STobias Grosser   ///
117860f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
117960f63b49STobias Grosser   ///
118060f63b49STobias Grosser   /// @returns A list of array accesses.
118160f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
118260f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
118360f63b49STobias Grosser 
118460f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
118560f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
118660f63b49STobias Grosser       Access->read = Acc->isRead();
118760f63b49STobias Grosser       Access->write = Acc->isWrite();
118860f63b49STobias Grosser       Access->access = Acc->getAccessRelation();
118960f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
119060f63b49STobias Grosser       Space = isl_space_range(Space);
119160f63b49STobias Grosser       Space = isl_space_from_range(Space);
11926293ba69STobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
119360f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
119460f63b49STobias Grosser       Access->tagged_access =
119560f63b49STobias Grosser           isl_map_domain_product(Acc->getAccessRelation(), Universe);
119660f63b49STobias Grosser       Access->exact_write = Acc->isWrite();
119760f63b49STobias Grosser       Access->ref_id = Acc->getId();
119860f63b49STobias Grosser       Access->next = Accesses;
119960f63b49STobias Grosser       Accesses = Access;
120060f63b49STobias Grosser     }
120160f63b49STobias Grosser 
120260f63b49STobias Grosser     return Accesses;
120360f63b49STobias Grosser   }
120460f63b49STobias Grosser 
120569b46751STobias Grosser   /// Collect the list of GPU statements.
120669b46751STobias Grosser   ///
120769b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
120869b46751STobias Grosser   /// as well as a list with all memory accesses.
120969b46751STobias Grosser   ///
121069b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
121169b46751STobias Grosser   ///
121269b46751STobias Grosser   /// @returns A linked-list of statements.
121369b46751STobias Grosser   gpu_stmt *getStatements() {
121469b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
121569b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
121669b46751STobias Grosser 
121769b46751STobias Grosser     int i = 0;
121869b46751STobias Grosser     for (auto &Stmt : *S) {
121969b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
122069b46751STobias Grosser 
122169b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
122269b46751STobias Grosser 
122369b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
122469b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
122560f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
122669b46751STobias Grosser       i++;
122769b46751STobias Grosser     }
122869b46751STobias Grosser 
122969b46751STobias Grosser     return Stmts;
123069b46751STobias Grosser   }
123169b46751STobias Grosser 
123260f63b49STobias Grosser   /// Derive the extent of an array.
123360f63b49STobias Grosser   ///
123460f63b49STobias Grosser   /// The extent of an array is defined by the set of memory locations for
123560f63b49STobias Grosser   /// which a memory access in the iteration domain exists.
123660f63b49STobias Grosser   ///
123760f63b49STobias Grosser   /// @param Array The array to derive the extent for.
123860f63b49STobias Grosser   ///
123960f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
124060f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
124160f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
124260f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
124360f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
124460f63b49STobias Grosser     isl_set *AccessSet =
124560f63b49STobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace());
124660f63b49STobias Grosser     isl_union_set_free(AccessUSet);
124760f63b49STobias Grosser 
124860f63b49STobias Grosser     return AccessSet;
124960f63b49STobias Grosser   }
125060f63b49STobias Grosser 
125160f63b49STobias Grosser   /// Derive the bounds of an array.
125260f63b49STobias Grosser   ///
125360f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
125460f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
125560f63b49STobias Grosser   /// ScopArrayInfo.
125660f63b49STobias Grosser   ///
125760f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
125860f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
125960f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
126060f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
126160f63b49STobias Grosser       isl_set *Dom = isl_set_copy(PPCGArray.extent);
126260f63b49STobias Grosser       Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
126360f63b49STobias Grosser       isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
126460f63b49STobias Grosser       isl_set_free(Dom);
126560f63b49STobias Grosser       Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
126660f63b49STobias Grosser       isl_local_space *LS = isl_local_space_from_space(isl_set_get_space(Dom));
126760f63b49STobias Grosser       isl_aff *One = isl_aff_zero_on_domain(LS);
126860f63b49STobias Grosser       One = isl_aff_add_constant_si(One, 1);
126960f63b49STobias Grosser       Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
127060f63b49STobias Grosser       Bound = isl_pw_aff_gist(Bound, S->getContext());
127160f63b49STobias Grosser       PPCGArray.bound[0] = Bound;
127260f63b49STobias Grosser     }
127360f63b49STobias Grosser 
127460f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
127560f63b49STobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
127660f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
127760f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
127860f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
127960f63b49STobias Grosser       PPCGArray.bound[i] = Bound;
128060f63b49STobias Grosser     }
128160f63b49STobias Grosser   }
128260f63b49STobias Grosser 
128360f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
128460f63b49STobias Grosser   ///
128560f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
128660f63b49STobias Grosser   void createArrays(gpu_prog *PPCGProg) {
128760f63b49STobias Grosser     int i = 0;
128860f63b49STobias Grosser     for (auto &Element : S->arrays()) {
128960f63b49STobias Grosser       ScopArrayInfo *Array = Element.second.get();
129060f63b49STobias Grosser 
129160f63b49STobias Grosser       std::string TypeName;
129260f63b49STobias Grosser       raw_string_ostream OS(TypeName);
129360f63b49STobias Grosser 
129460f63b49STobias Grosser       OS << *Array->getElementType();
129560f63b49STobias Grosser       TypeName = OS.str();
129660f63b49STobias Grosser 
129760f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
129860f63b49STobias Grosser 
129960f63b49STobias Grosser       PPCGArray.space = Array->getSpace();
130060f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
130160f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
130260f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
130360f63b49STobias Grosser       PPCGArray.extent = nullptr;
130460f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
130560f63b49STobias Grosser       PPCGArray.bound =
130660f63b49STobias Grosser           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
130760f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
130860f63b49STobias Grosser       PPCGArray.n_ref = 0;
130960f63b49STobias Grosser       PPCGArray.refs = nullptr;
131060f63b49STobias Grosser       PPCGArray.accessed = true;
131160f63b49STobias Grosser       PPCGArray.read_only_scalar = false;
131260f63b49STobias Grosser       PPCGArray.has_compound_element = false;
131360f63b49STobias Grosser       PPCGArray.local = false;
131460f63b49STobias Grosser       PPCGArray.declare_local = false;
131560f63b49STobias Grosser       PPCGArray.global = false;
131660f63b49STobias Grosser       PPCGArray.linearize = false;
131760f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
1318*13c78e4dSTobias Grosser       PPCGArray.user = Array;
131960f63b49STobias Grosser 
132060f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
13212d010dafSTobias Grosser       i++;
1322b9fc860aSTobias Grosser 
1323b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
132460f63b49STobias Grosser     }
132560f63b49STobias Grosser   }
132660f63b49STobias Grosser 
132760f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
132860f63b49STobias Grosser   ///
132960f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
133060f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
133160f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
133260f63b49STobias Grosser 
133360f63b49STobias Grosser     for (auto &Item : S->arrays()) {
133460f63b49STobias Grosser       ScopArrayInfo *Array = Item.second.get();
133560f63b49STobias Grosser       isl_space *Space = Array->getSpace();
133660f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
133760f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
133860f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
133960f63b49STobias Grosser     }
134060f63b49STobias Grosser 
134160f63b49STobias Grosser     return Maps;
134260f63b49STobias Grosser   }
134360f63b49STobias Grosser 
1344e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
1345e938517eSTobias Grosser   ///
1346e938517eSTobias Grosser   /// @returns A new gpu grogram description.
1347e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
1348e938517eSTobias Grosser 
1349e938517eSTobias Grosser     if (!PPCGScop)
1350e938517eSTobias Grosser       return nullptr;
1351e938517eSTobias Grosser 
1352e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
1353e938517eSTobias Grosser 
1354e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
1355e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
1356aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
135760f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
135860f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
135960f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
136060f63b49STobias Grosser     PPCGProg->tagged_must_kill =
136160f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
136260f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
136360f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
136460f63b49STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
1365e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
1366e938517eSTobias Grosser     PPCGProg->array_order = nullptr;
136769b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
136869b46751STobias Grosser     PPCGProg->stmts = getStatements();
136960f63b49STobias Grosser     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
137060f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
137160f63b49STobias Grosser                                        PPCGProg->n_array);
137260f63b49STobias Grosser 
137360f63b49STobias Grosser     createArrays(PPCGProg);
1374e938517eSTobias Grosser 
1375e938517eSTobias Grosser     return PPCGProg;
1376e938517eSTobias Grosser   }
1377e938517eSTobias Grosser 
137869b46751STobias Grosser   struct PrintGPUUserData {
137969b46751STobias Grosser     struct cuda_info *CudaInfo;
138069b46751STobias Grosser     struct gpu_prog *PPCGProg;
138169b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
138269b46751STobias Grosser   };
138369b46751STobias Grosser 
138469b46751STobias Grosser   /// Print a user statement node in the host code.
138569b46751STobias Grosser   ///
138669b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
138769b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
138869b46751STobias Grosser   /// host ast.
138969b46751STobias Grosser   ///
139069b46751STobias Grosser   /// @param P The printer to print to
139169b46751STobias Grosser   /// @param Options The printing options to use
139269b46751STobias Grosser   /// @param Node The node to print
139369b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
139469b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
139569b46751STobias Grosser   ///
139669b46751STobias Grosser   /// @returns A printer to which the output has been printed.
139769b46751STobias Grosser   static __isl_give isl_printer *
139869b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
139969b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
140069b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
140169b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
140269b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
140369b46751STobias Grosser 
140469b46751STobias Grosser     if (Id) {
140520251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
140620251734STobias Grosser 
140720251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
140820251734STobias Grosser       // otherwise try to call pet functionality that is not available in
140920251734STobias Grosser       // Polly.
141020251734STobias Grosser       if (IsUser) {
141120251734STobias Grosser         P = isl_printer_start_line(P);
141220251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
141320251734STobias Grosser         P = isl_printer_end_line(P);
141420251734STobias Grosser         isl_id_free(Id);
141520251734STobias Grosser         isl_ast_print_options_free(Options);
141620251734STobias Grosser         return P;
141720251734STobias Grosser       }
141820251734STobias Grosser 
141969b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
142069b46751STobias Grosser       isl_id_free(Id);
142169b46751STobias Grosser       Data->Kernels.push_back(Kernel);
142269b46751STobias Grosser     }
142369b46751STobias Grosser 
142469b46751STobias Grosser     return print_host_user(P, Options, Node, User);
142569b46751STobias Grosser   }
142669b46751STobias Grosser 
142769b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
142869b46751STobias Grosser   ///
142969b46751STobias Grosser   /// @param Kernel The kernel to print
143069b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
143169b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
143269b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
143369b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
143469b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
143569b46751STobias Grosser     char *String = isl_printer_get_str(P);
143669b46751STobias Grosser     printf("%s\n", String);
143769b46751STobias Grosser     free(String);
143869b46751STobias Grosser     isl_printer_free(P);
143969b46751STobias Grosser   }
144069b46751STobias Grosser 
144169b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
144269b46751STobias Grosser   ///
144369b46751STobias Grosser   /// @param Tree An AST describing GPU code
144469b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
144569b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
144669b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
144769b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
144869b46751STobias Grosser 
144969b46751STobias Grosser     PrintGPUUserData Data;
145069b46751STobias Grosser     Data.PPCGProg = PPCGProg;
145169b46751STobias Grosser 
145269b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
145369b46751STobias Grosser     Options =
145469b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
145569b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
145669b46751STobias Grosser     char *String = isl_printer_get_str(P);
145769b46751STobias Grosser     printf("# host\n");
145869b46751STobias Grosser     printf("%s\n", String);
145969b46751STobias Grosser     free(String);
146069b46751STobias Grosser     isl_printer_free(P);
146169b46751STobias Grosser 
146269b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
146369b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
146469b46751STobias Grosser       printKernel(Kernel);
146569b46751STobias Grosser     }
146669b46751STobias Grosser   }
146769b46751STobias Grosser 
1468f384594dSTobias Grosser   // Generate a GPU program using PPCG.
1469f384594dSTobias Grosser   //
1470f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
1471f384594dSTobias Grosser   //
1472f384594dSTobias Grosser   //  1) Compute new schedule for the program.
1473f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
1474f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
1475f384594dSTobias Grosser   //
1476f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
1477f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
1478f384594dSTobias Grosser   // strategy directly from this pass.
1479f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
1480f384594dSTobias Grosser 
1481f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
1482f384594dSTobias Grosser 
1483f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
1484f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
1485f384594dSTobias Grosser     PPCGGen->print = nullptr;
1486f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
148760c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
1488f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
1489f384594dSTobias Grosser     PPCGGen->tree = nullptr;
1490f384594dSTobias Grosser     PPCGGen->types.n = 0;
1491f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
1492f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
1493f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
1494f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
1495f384594dSTobias Grosser 
1496f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
1497f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
1498f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
14992341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
1500f384594dSTobias Grosser 
1501f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
1502f384594dSTobias Grosser 
1503aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
1504aef5196fSTobias Grosser 
150569b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
1506aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
150769b46751STobias Grosser     } else {
1508aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
150969b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
151069b46751STobias Grosser     }
1511aef5196fSTobias Grosser 
1512f384594dSTobias Grosser     if (DumpSchedule) {
1513f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
1514f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
1515f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
1516f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
1517f384594dSTobias Grosser       if (Schedule)
1518f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
1519f384594dSTobias Grosser       else
1520f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
1521f384594dSTobias Grosser 
1522f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
1523f384594dSTobias Grosser       isl_printer_free(P);
1524f384594dSTobias Grosser     }
1525f384594dSTobias Grosser 
152669b46751STobias Grosser     if (DumpCode) {
152769b46751STobias Grosser       printf("Code\n");
152869b46751STobias Grosser       printf("====\n");
152969b46751STobias Grosser       if (PPCGGen->tree)
153069b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
153169b46751STobias Grosser       else
153269b46751STobias Grosser         printf("No code generated\n");
153369b46751STobias Grosser     }
153469b46751STobias Grosser 
1535f384594dSTobias Grosser     isl_schedule_free(Schedule);
1536f384594dSTobias Grosser 
1537f384594dSTobias Grosser     return PPCGGen;
1538f384594dSTobias Grosser   }
1539f384594dSTobias Grosser 
1540f384594dSTobias Grosser   /// Free gpu_gen structure.
1541f384594dSTobias Grosser   ///
1542f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
1543f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
1544f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
1545f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
1546f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
1547f384594dSTobias Grosser     free(PPCGGen);
1548f384594dSTobias Grosser   }
1549f384594dSTobias Grosser 
1550b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
1551b307ed4dSTobias Grosser   ///
1552b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
1553b307ed4dSTobias Grosser   /// ourselves.
1554b307ed4dSTobias Grosser   ///
1555b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
1556b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
1557b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
1558b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
1559b307ed4dSTobias Grosser     free(PPCGScop->options);
1560b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
1561b307ed4dSTobias Grosser   }
1562b307ed4dSTobias Grosser 
156338fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
156438fc0aedSTobias Grosser   ///
156532837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
156632837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
156732837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
156838fc0aedSTobias Grosser     ScopAnnotator Annotator;
156938fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
157038fc0aedSTobias Grosser 
157138fc0aedSTobias Grosser     Region *R = &S->getRegion();
157238fc0aedSTobias Grosser 
157338fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
157438fc0aedSTobias Grosser 
157538fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
157638fc0aedSTobias Grosser 
157738fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
157838fc0aedSTobias Grosser 
157932837fe3STobias Grosser     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S,
158032837fe3STobias Grosser                                Prog);
158138fc0aedSTobias Grosser 
158238fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
158338fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
158438fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
158538fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
158638fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
158738fc0aedSTobias Grosser     // code generating this scop.
158838fc0aedSTobias Grosser     BasicBlock *StartBlock =
158938fc0aedSTobias Grosser         executeScopConditionally(*S, this, Builder.getTrue());
159038fc0aedSTobias Grosser 
159138fc0aedSTobias Grosser     // TODO: Handle LICM
159238fc0aedSTobias Grosser     // TODO: Verify run-time checks
159338fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
159438fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
159538fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
159638fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
1597fa7b0802STobias Grosser 
1598fa7b0802STobias Grosser     NodeBuilder.initializeAfterRTH();
159938fc0aedSTobias Grosser     NodeBuilder.create(Root);
16008ed5e599STobias Grosser     NodeBuilder.finalize();
160138fc0aedSTobias Grosser   }
160238fc0aedSTobias Grosser 
1603e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
1604e938517eSTobias Grosser     S = &CurrentScop;
160538fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
160638fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
160738fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
160838fc0aedSTobias Grosser     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
160938fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
1610e938517eSTobias Grosser 
16112d58a64eSTobias Grosser     // We currently do not support scops with invariant loads.
16122d58a64eSTobias Grosser     if (S->hasInvariantAccesses())
16132d58a64eSTobias Grosser       return false;
16142d58a64eSTobias Grosser 
1615e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
1616e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
1617f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
161838fc0aedSTobias Grosser 
161938fc0aedSTobias Grosser     if (PPCGGen->tree)
162032837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
162138fc0aedSTobias Grosser 
1622b307ed4dSTobias Grosser     freeOptions(PPCGScop);
1623f384594dSTobias Grosser     freePPCGGen(PPCGGen);
1624e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
1625e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
1626e938517eSTobias Grosser 
1627e938517eSTobias Grosser     return true;
1628e938517eSTobias Grosser   }
16299dfe4e7cSTobias Grosser 
16309dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
16319dfe4e7cSTobias Grosser 
16329dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
16339dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
16349dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
16359dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
16369dfe4e7cSTobias Grosser     AU.addRequired<ScopDetection>();
16379dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
16389dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
16399dfe4e7cSTobias Grosser 
16409dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
16419dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
16429dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
16439dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
16449dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
16459dfe4e7cSTobias Grosser     AU.addPreserved<PostDominatorTreeWrapperPass>();
16469dfe4e7cSTobias Grosser     AU.addPreserved<ScopDetection>();
16479dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
16489dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
16499dfe4e7cSTobias Grosser 
16509dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
16519dfe4e7cSTobias Grosser     //        region tree.
16529dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
16539dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
16549dfe4e7cSTobias Grosser   }
16559dfe4e7cSTobias Grosser };
16569dfe4e7cSTobias Grosser }
16579dfe4e7cSTobias Grosser 
16589dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
16599dfe4e7cSTobias Grosser 
16609dfe4e7cSTobias Grosser Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
16619dfe4e7cSTobias Grosser 
16629dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
16639dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
16649dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
16659dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
16669dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
16679dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
16689dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
16699dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScopDetection);
16709dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
16719dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
1672