19dfe4e7cSTobias Grosser //===------ PPCGCodeGeneration.cpp - Polly Accelerator Code Generation. ---===//
29dfe4e7cSTobias Grosser //
39dfe4e7cSTobias Grosser //                     The LLVM Compiler Infrastructure
49dfe4e7cSTobias Grosser //
59dfe4e7cSTobias Grosser // This file is distributed under the University of Illinois Open Source
69dfe4e7cSTobias Grosser // License. See LICENSE.TXT for details.
79dfe4e7cSTobias Grosser //
89dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===//
99dfe4e7cSTobias Grosser //
109dfe4e7cSTobias Grosser // Take a scop created by ScopInfo and map it to GPU code using the ppcg
119dfe4e7cSTobias Grosser // GPU mapping strategy.
129dfe4e7cSTobias Grosser //
139dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===//
149dfe4e7cSTobias Grosser 
159dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h"
1638fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h"
179dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h"
189dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h"
19f384594dSTobias Grosser #include "polly/Options.h"
209dfe4e7cSTobias Grosser #include "polly/ScopInfo.h"
21edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h"
2274dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h"
239dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h"
249dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h"
259dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h"
269dfe4e7cSTobias Grosser #include "llvm/Analysis/PostDominators.h"
279dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
2874dc3cb4STobias Grosser #include "llvm/Analysis/TargetLibraryInfo.h"
2974dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h"
3074dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h"
31e1a98343STobias Grosser #include "llvm/IR/Verifier.h"
3274dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h"
3374dc3cb4STobias Grosser #include "llvm/Support/TargetSelect.h"
3474dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h"
359a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h"
369dfe4e7cSTobias Grosser 
37f384594dSTobias Grosser #include "isl/union_map.h"
38f384594dSTobias Grosser 
39e938517eSTobias Grosser extern "C" {
40a56f8f8eSTobias Grosser #include "ppcg/cuda.h"
41a56f8f8eSTobias Grosser #include "ppcg/gpu.h"
42a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h"
43a56f8f8eSTobias Grosser #include "ppcg/ppcg.h"
44a56f8f8eSTobias Grosser #include "ppcg/schedule.h"
45e938517eSTobias Grosser }
46e938517eSTobias Grosser 
479dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h"
489dfe4e7cSTobias Grosser 
499dfe4e7cSTobias Grosser using namespace polly;
509dfe4e7cSTobias Grosser using namespace llvm;
519dfe4e7cSTobias Grosser 
529dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg"
539dfe4e7cSTobias Grosser 
54f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
55f384594dSTobias Grosser                                   cl::desc("Dump the computed GPU Schedule"),
56681bd568STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
57f384594dSTobias Grosser                                   cl::cat(PollyCategory));
5869b46751STobias Grosser 
5969b46751STobias Grosser static cl::opt<bool>
6069b46751STobias Grosser     DumpCode("polly-acc-dump-code",
6169b46751STobias Grosser              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
6269b46751STobias Grosser              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
6369b46751STobias Grosser 
6432837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
6532837fe3STobias Grosser                                   cl::desc("Dump the kernel LLVM-IR"),
6632837fe3STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
6732837fe3STobias Grosser                                   cl::cat(PollyCategory));
6832837fe3STobias Grosser 
6974dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
7074dc3cb4STobias Grosser                                    cl::desc("Dump the kernel assembly code"),
7174dc3cb4STobias Grosser                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
7274dc3cb4STobias Grosser                                    cl::cat(PollyCategory));
7374dc3cb4STobias Grosser 
7474dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath",
7574dc3cb4STobias Grosser                               cl::desc("Allow unsafe math optimizations"),
7674dc3cb4STobias Grosser                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
7774dc3cb4STobias Grosser                               cl::cat(PollyCategory));
7874dc3cb4STobias Grosser 
7974dc3cb4STobias Grosser static cl::opt<std::string>
8074dc3cb4STobias Grosser     CudaVersion("polly-acc-cuda-version",
8174dc3cb4STobias Grosser                 cl::desc("The CUDA version to compile for"), cl::Hidden,
8274dc3cb4STobias Grosser                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
8374dc3cb4STobias Grosser 
8460c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
8560c60025STobias Grosser ///
8660c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
8760c60025STobias Grosser /// of the scheduled ScopStmts.
8860c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
89edb885cbSTobias Grosser     void *StmtT, isl_ast_build *Build,
9060c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
9160c60025STobias Grosser                                        isl_id *Id, void *User),
9260c60025STobias Grosser     void *UserIndex,
9360c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
94edb885cbSTobias Grosser     void *UserExpr) {
9560c60025STobias Grosser 
96edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
9760c60025STobias Grosser 
98edb885cbSTobias Grosser   isl_ctx *Ctx;
99edb885cbSTobias Grosser 
100edb885cbSTobias Grosser   if (!Stmt || !Build)
101edb885cbSTobias Grosser     return NULL;
102edb885cbSTobias Grosser 
103edb885cbSTobias Grosser   Ctx = isl_ast_build_get_ctx(Build);
104edb885cbSTobias Grosser   isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0);
105edb885cbSTobias Grosser 
106edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
107edb885cbSTobias Grosser     isl_map *AddrFunc = Acc->getAddressFunction();
108edb885cbSTobias Grosser     AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain());
109edb885cbSTobias Grosser     isl_id *RefId = Acc->getId();
110edb885cbSTobias Grosser     isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc);
111edb885cbSTobias Grosser     isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA);
112edb885cbSTobias Grosser     MPA = isl_multi_pw_aff_coalesce(MPA);
113edb885cbSTobias Grosser     MPA = FunctionIndex(MPA, RefId, UserIndex);
114edb885cbSTobias Grosser     isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA);
115edb885cbSTobias Grosser     Access = FunctionExpr(Access, RefId, UserExpr);
116edb885cbSTobias Grosser     RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access);
117edb885cbSTobias Grosser   }
118edb885cbSTobias Grosser 
119edb885cbSTobias Grosser   return RefToExpr;
12060c60025STobias Grosser }
121f384594dSTobias Grosser 
12238fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
12338fc0aedSTobias Grosser ///
12438fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
12538fc0aedSTobias Grosser /// generates code for general-prupose AST nodes, with special functionality
12638fc0aedSTobias Grosser /// for generating GPU specific user nodes.
12738fc0aedSTobias Grosser ///
12838fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
12938fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
13038fc0aedSTobias Grosser public:
13138fc0aedSTobias Grosser   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P,
13238fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
13332837fe3STobias Grosser                  DominatorTree &DT, Scop &S, gpu_prog *Prog)
134edb885cbSTobias Grosser       : IslNodeBuilder(Builder, Annotator, P, DL, LI, SE, DT, S), Prog(Prog) {
135edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
136edb885cbSTobias Grosser   }
13738fc0aedSTobias Grosser 
138fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
139fa7b0802STobias Grosser   void initializeAfterRTH();
140fa7b0802STobias Grosser 
141fa7b0802STobias Grosser   /// Finalize the generated scop.
142fa7b0802STobias Grosser   virtual void finalize();
143fa7b0802STobias Grosser 
14438fc0aedSTobias Grosser private:
14574dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
14674dc3cb4STobias Grosser   ///
14774dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
14874dc3cb4STobias Grosser   /// more.
14974dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
15074dc3cb4STobias Grosser 
15113c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
15213c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
1537287aeddSTobias Grosser 
154fa7b0802STobias Grosser   /// The current GPU context.
155fa7b0802STobias Grosser   Value *GPUContext;
156fa7b0802STobias Grosser 
15732837fe3STobias Grosser   /// A module containing GPU code.
15832837fe3STobias Grosser   ///
15932837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
16032837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
16132837fe3STobias Grosser 
16232837fe3STobias Grosser   /// The GPU program we generate code for.
16332837fe3STobias Grosser   gpu_prog *Prog;
16432837fe3STobias Grosser 
165472f9654STobias Grosser   /// Class to free isl_ids.
166472f9654STobias Grosser   class IslIdDeleter {
167472f9654STobias Grosser   public:
168472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
169472f9654STobias Grosser   };
170472f9654STobias Grosser 
171472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
172472f9654STobias Grosser   ///
173472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
174472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
175472f9654STobias Grosser 
176edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
177edb885cbSTobias Grosser 
17838fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
17938fc0aedSTobias Grosser   ///
18038fc0aedSTobias Grosser   /// These AST nodes can be of type:
18138fc0aedSTobias Grosser   ///
18238fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
18338fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
18413c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
1855260c041STobias Grosser   ///   - In-kernel synchronization
1865260c041STobias Grosser   ///   - In-kernel memory copy statement
18738fc0aedSTobias Grosser   ///
1881fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
1891fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
19032837fe3STobias Grosser 
19113c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
19213c78e4dSTobias Grosser 
19313c78e4dSTobias Grosser   /// Create code for a data transfer statement
19413c78e4dSTobias Grosser   ///
19513c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
19613c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
19713c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
19813c78e4dSTobias Grosser                           enum DataDirection Direction);
19913c78e4dSTobias Grosser 
200edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
201edb885cbSTobias Grosser   ///
202edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
203edb885cbSTobias Grosser   ///
204edb885cbSTobias Grosser   /// @returns A set of values referenced by the kernel.
205edb885cbSTobias Grosser   SetVector<Value *> getReferencesInKernel(ppcg_kernel *Kernel);
206edb885cbSTobias Grosser 
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 
21413c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
21513c78e4dSTobias Grosser   ///
21613c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
21713c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
21813c78e4dSTobias 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.
284*57793596STobias Grosser   ///
285*57793596STobias Grosser   /// @returns The Assembly string of the kernel.
286*57793596STobias Grosser   std::string finalizeKernelFunction();
287fa7b0802STobias Grosser 
2887287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
289fa7b0802STobias Grosser   void allocateDeviceArrays();
290fa7b0802STobias Grosser 
2917287aeddSTobias Grosser   /// Free all allocated device arrays.
2927287aeddSTobias Grosser   void freeDeviceArrays();
2937287aeddSTobias Grosser 
294fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
295fa7b0802STobias Grosser   ///
296fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
297fa7b0802STobias Grosser   Value *createCallInitContext();
298fa7b0802STobias Grosser 
299fa7b0802STobias Grosser   /// Create a call to free the GPU context.
300fa7b0802STobias Grosser   ///
301fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
302fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
303fa7b0802STobias Grosser 
3047287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
3057287aeddSTobias Grosser   ///
3067287aeddSTobias Grosser   /// @param Size The size of memory to allocate
3077287aeddSTobias Grosser   ///
3087287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
309fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
3107287aeddSTobias Grosser 
3117287aeddSTobias Grosser   /// Create a call to free a device array.
3127287aeddSTobias Grosser   ///
3137287aeddSTobias Grosser   /// @param Array The device array to free.
3147287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
31513c78e4dSTobias Grosser 
31613c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
31713c78e4dSTobias Grosser   ///
31813c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
31913c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
32013c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
32113c78e4dSTobias Grosser                                       Value *Size);
32213c78e4dSTobias Grosser 
32313c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
32413c78e4dSTobias Grosser   ///
32513c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
32613c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
32713c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
32813c78e4dSTobias Grosser                                       Value *Size);
329*57793596STobias Grosser 
330*57793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
331*57793596STobias Grosser   ///
332*57793596STobias Grosser   /// @param Buffer The string describing the kernel.
333*57793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
334*57793596STobias Grosser   ///
335*57793596STobias Grosser   /// @returns A pointer to a kernel object
336*57793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
337*57793596STobias Grosser 
338*57793596STobias Grosser   /// Create a call to free a GPU kernel.
339*57793596STobias Grosser   ///
340*57793596STobias Grosser   /// @param GPUKernel THe kernel to free.
341*57793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
3421fb9b64dSTobias Grosser };
3431fb9b64dSTobias Grosser 
344fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
345fa7b0802STobias Grosser   GPUContext = createCallInitContext();
346fa7b0802STobias Grosser   allocateDeviceArrays();
347fa7b0802STobias Grosser }
348fa7b0802STobias Grosser 
349fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
3507287aeddSTobias Grosser   freeDeviceArrays();
351fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
352fa7b0802STobias Grosser   IslNodeBuilder::finalize();
353fa7b0802STobias Grosser }
354fa7b0802STobias Grosser 
355fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
356fa7b0802STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
357fa7b0802STobias Grosser 
358fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
359fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
36013c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
3617287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
3627287aeddSTobias Grosser     DevArrayName.append(Array->name);
363fa7b0802STobias Grosser 
36413c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
3657287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
3667287aeddSTobias Grosser     DevArray->setName(DevArrayName);
36713c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
368fa7b0802STobias Grosser   }
369fa7b0802STobias Grosser 
370fa7b0802STobias Grosser   isl_ast_build_free(Build);
371fa7b0802STobias Grosser }
372fa7b0802STobias Grosser 
3737287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
37413c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
37513c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
3767287aeddSTobias Grosser }
3777287aeddSTobias Grosser 
378*57793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
379*57793596STobias Grosser   const char *Name = "polly_getKernel";
380*57793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
381*57793596STobias Grosser   Function *F = M->getFunction(Name);
382*57793596STobias Grosser 
383*57793596STobias Grosser   // If F is not available, declare it.
384*57793596STobias Grosser   if (!F) {
385*57793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
386*57793596STobias Grosser     std::vector<Type *> Args;
387*57793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
388*57793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
389*57793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
390*57793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
391*57793596STobias Grosser   }
392*57793596STobias Grosser 
393*57793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
394*57793596STobias Grosser }
395*57793596STobias Grosser 
396*57793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
397*57793596STobias Grosser   const char *Name = "polly_freeKernel";
398*57793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
399*57793596STobias Grosser   Function *F = M->getFunction(Name);
400*57793596STobias Grosser 
401*57793596STobias Grosser   // If F is not available, declare it.
402*57793596STobias Grosser   if (!F) {
403*57793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
404*57793596STobias Grosser     std::vector<Type *> Args;
405*57793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
406*57793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
407*57793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
408*57793596STobias Grosser   }
409*57793596STobias Grosser 
410*57793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
411*57793596STobias Grosser }
412*57793596STobias Grosser 
4137287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
4147287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
4157287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
4167287aeddSTobias Grosser   Function *F = M->getFunction(Name);
4177287aeddSTobias Grosser 
4187287aeddSTobias Grosser   // If F is not available, declare it.
4197287aeddSTobias Grosser   if (!F) {
4207287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
4217287aeddSTobias Grosser     std::vector<Type *> Args;
4227287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
4237287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
4247287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
4257287aeddSTobias Grosser   }
4267287aeddSTobias Grosser 
4277287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
4287287aeddSTobias Grosser }
4297287aeddSTobias Grosser 
430fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
431fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
432fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
433fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
434fa7b0802STobias Grosser 
435fa7b0802STobias Grosser   // If F is not available, declare it.
436fa7b0802STobias Grosser   if (!F) {
437fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
438fa7b0802STobias Grosser     std::vector<Type *> Args;
439fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
440fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
441fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
442fa7b0802STobias Grosser   }
443fa7b0802STobias Grosser 
444fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
445fa7b0802STobias Grosser }
446fa7b0802STobias Grosser 
44713c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
44813c78e4dSTobias Grosser                                                     Value *DeviceData,
44913c78e4dSTobias Grosser                                                     Value *Size) {
45013c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
45113c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
45213c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
45313c78e4dSTobias Grosser 
45413c78e4dSTobias Grosser   // If F is not available, declare it.
45513c78e4dSTobias Grosser   if (!F) {
45613c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
45713c78e4dSTobias Grosser     std::vector<Type *> Args;
45813c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
45913c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
46013c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
46113c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
46213c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
46313c78e4dSTobias Grosser   }
46413c78e4dSTobias Grosser 
46513c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
46613c78e4dSTobias Grosser }
46713c78e4dSTobias Grosser 
46813c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
46913c78e4dSTobias Grosser                                                     Value *HostData,
47013c78e4dSTobias Grosser                                                     Value *Size) {
47113c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
47213c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
47313c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
47413c78e4dSTobias Grosser 
47513c78e4dSTobias Grosser   // If F is not available, declare it.
47613c78e4dSTobias Grosser   if (!F) {
47713c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
47813c78e4dSTobias Grosser     std::vector<Type *> Args;
47913c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
48013c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
48113c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
48213c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
48313c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
48413c78e4dSTobias Grosser   }
48513c78e4dSTobias Grosser 
48613c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
48713c78e4dSTobias Grosser }
48813c78e4dSTobias Grosser 
489fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
490fa7b0802STobias Grosser   const char *Name = "polly_initContext";
491fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
492fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
493fa7b0802STobias Grosser 
494fa7b0802STobias Grosser   // If F is not available, declare it.
495fa7b0802STobias Grosser   if (!F) {
496fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
497fa7b0802STobias Grosser     std::vector<Type *> Args;
498fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
499fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
500fa7b0802STobias Grosser   }
501fa7b0802STobias Grosser 
502fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
503fa7b0802STobias Grosser }
504fa7b0802STobias Grosser 
505fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
506fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
507fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
508fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
509fa7b0802STobias Grosser 
510fa7b0802STobias Grosser   // If F is not available, declare it.
511fa7b0802STobias Grosser   if (!F) {
512fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
513fa7b0802STobias Grosser     std::vector<Type *> Args;
514fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
515fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
516fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
517fa7b0802STobias Grosser   }
518fa7b0802STobias Grosser 
519fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
520fa7b0802STobias Grosser }
521fa7b0802STobias Grosser 
5225260c041STobias Grosser /// Check if one string is a prefix of another.
5235260c041STobias Grosser ///
5245260c041STobias Grosser /// @param String The string in which to look for the prefix.
5255260c041STobias Grosser /// @param Prefix The prefix to look for.
5265260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
5275260c041STobias Grosser   return String.find(Prefix) == 0;
5285260c041STobias Grosser }
5295260c041STobias Grosser 
53013c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
53113c78e4dSTobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
53213c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
53313c78e4dSTobias Grosser 
53413c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
53513c78e4dSTobias Grosser     auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]);
53613c78e4dSTobias Grosser     isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero);
53713c78e4dSTobias Grosser 
53813c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
53913c78e4dSTobias Grosser       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]);
54013c78e4dSTobias Grosser       isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
54113c78e4dSTobias Grosser       Res = isl_ast_expr_mul(Res, Expr);
54213c78e4dSTobias Grosser     }
54313c78e4dSTobias Grosser 
54413c78e4dSTobias Grosser     Value *NumElements = ExprBuilder.create(Res);
54513c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
54613c78e4dSTobias Grosser   }
54713c78e4dSTobias Grosser   isl_ast_build_free(Build);
54813c78e4dSTobias Grosser   return ArraySize;
54913c78e4dSTobias Grosser }
55013c78e4dSTobias Grosser 
55113c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
55213c78e4dSTobias Grosser                                         enum DataDirection Direction) {
55313c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
55413c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
55513c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
55613c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
55713c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
55813c78e4dSTobias Grosser 
55913c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
56013c78e4dSTobias Grosser   Value *HostPtr = ScopArray->getBasePtr();
56113c78e4dSTobias Grosser 
56213c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
56313c78e4dSTobias Grosser 
56413c78e4dSTobias Grosser   if (gpu_array_is_scalar(Array)) {
56513c78e4dSTobias Grosser     HostPtr = Builder.CreateAlloca(ScopArray->getElementType());
56613c78e4dSTobias Grosser     Builder.CreateStore(ScopArray->getBasePtr(), HostPtr);
56713c78e4dSTobias Grosser   }
56813c78e4dSTobias Grosser 
56913c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
57013c78e4dSTobias Grosser 
57113c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
57213c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
57313c78e4dSTobias Grosser   else
57413c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
57513c78e4dSTobias Grosser 
57613c78e4dSTobias Grosser   isl_id_free(Id);
57713c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
57813c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
57913c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
58013c78e4dSTobias Grosser }
58113c78e4dSTobias Grosser 
5821fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
58332837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
58432837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
58532837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
58632837fe3STobias Grosser   isl_id_free(Id);
58732837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
58832837fe3STobias Grosser 
58932837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
59032837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
59132837fe3STobias Grosser     createKernel(UserStmt);
59232837fe3STobias Grosser     isl_ast_expr_free(Expr);
59332837fe3STobias Grosser     return;
59432837fe3STobias Grosser   }
59532837fe3STobias Grosser 
59613c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
59713c78e4dSTobias Grosser     createDataTransfer(UserStmt, HOST_TO_DEVICE);
59832837fe3STobias Grosser     isl_ast_expr_free(Expr);
59913c78e4dSTobias Grosser     return;
60013c78e4dSTobias Grosser   }
60113c78e4dSTobias Grosser 
60213c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
60313c78e4dSTobias Grosser     createDataTransfer(UserStmt, DEVICE_TO_HOST);
60413c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
60538fc0aedSTobias Grosser     return;
60638fc0aedSTobias Grosser   }
60738fc0aedSTobias Grosser 
6085260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
6095260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
6105260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
6115260c041STobias Grosser   isl_id_free(Anno);
6125260c041STobias Grosser 
6135260c041STobias Grosser   switch (KernelStmt->type) {
6145260c041STobias Grosser   case ppcg_kernel_domain:
615edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
6165260c041STobias Grosser     isl_ast_node_free(UserStmt);
6175260c041STobias Grosser     return;
6185260c041STobias Grosser   case ppcg_kernel_copy:
6195260c041STobias Grosser     // TODO: Create kernel copy stmt
6205260c041STobias Grosser     isl_ast_expr_free(Expr);
6215260c041STobias Grosser     isl_ast_node_free(UserStmt);
6225260c041STobias Grosser     return;
6235260c041STobias Grosser   case ppcg_kernel_sync:
6245260c041STobias Grosser     createKernelSync();
6255260c041STobias Grosser     isl_ast_expr_free(Expr);
6265260c041STobias Grosser     isl_ast_node_free(UserStmt);
6275260c041STobias Grosser     return;
6285260c041STobias Grosser   }
6295260c041STobias Grosser 
6305260c041STobias Grosser   isl_ast_expr_free(Expr);
6315260c041STobias Grosser   isl_ast_node_free(UserStmt);
6325260c041STobias Grosser   return;
6335260c041STobias Grosser }
6345260c041STobias Grosser 
635edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
636edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
637edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
638edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
639edb885cbSTobias Grosser 
640edb885cbSTobias Grosser   LoopToScevMapT LTS;
641edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
642edb885cbSTobias Grosser 
643edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
644edb885cbSTobias Grosser 
645edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
646edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
647edb885cbSTobias Grosser   else
648edb885cbSTobias Grosser     assert(0 && "Region statement not supported\n");
649edb885cbSTobias Grosser }
650edb885cbSTobias Grosser 
6515260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
6525260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
6535260c041STobias Grosser   auto *Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
6545260c041STobias Grosser   Builder.CreateCall(Sync, {});
6555260c041STobias Grosser }
6565260c041STobias Grosser 
657edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
658edb885cbSTobias Grosser ///
659edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
660edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
661edb885cbSTobias Grosser ///
662edb885cbSTobias Grosser /// @param Node The node to collect references for.
663edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
664edb885cbSTobias Grosser ///
665edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
666edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
667edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
668edb885cbSTobias Grosser     return isl_bool_true;
669edb885cbSTobias Grosser 
670edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
671edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
672edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
673edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
674edb885cbSTobias Grosser   isl_id_free(Id);
675edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
676edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
677edb885cbSTobias Grosser 
678edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
679edb885cbSTobias Grosser     return isl_bool_true;
680edb885cbSTobias Grosser 
681edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
682edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
683edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
684edb885cbSTobias Grosser   isl_id_free(Id);
685edb885cbSTobias Grosser 
686edb885cbSTobias Grosser   addReferencesFromStmt(Stmt, User);
687edb885cbSTobias Grosser 
688edb885cbSTobias Grosser   return isl_bool_true;
689edb885cbSTobias Grosser }
690edb885cbSTobias Grosser 
691edb885cbSTobias Grosser SetVector<Value *> GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
692edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
693edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
694edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
695edb885cbSTobias Grosser   SubtreeReferences References = {
696edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
697edb885cbSTobias Grosser 
698edb885cbSTobias Grosser   for (const auto &I : IDToValue)
699edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
700edb885cbSTobias Grosser 
701edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
702edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
703edb885cbSTobias Grosser 
704edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
705edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
706edb885cbSTobias Grosser 
707edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
708edb885cbSTobias Grosser     SubtreeValues.remove(SAI.second->getBasePtr());
709edb885cbSTobias Grosser 
710edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
711edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
712edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
713edb885cbSTobias Grosser     assert(IDToValue.count(Id));
714edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
715edb885cbSTobias Grosser     SubtreeValues.remove(Val);
716edb885cbSTobias Grosser     isl_id_free(Id);
717edb885cbSTobias Grosser   }
718edb885cbSTobias Grosser   isl_space_free(Space);
719edb885cbSTobias Grosser 
720edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
721edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
722edb885cbSTobias Grosser     assert(IDToValue.count(Id));
723edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
724edb885cbSTobias Grosser     SubtreeValues.remove(Val);
725edb885cbSTobias Grosser     isl_id_free(Id);
726edb885cbSTobias Grosser   }
727edb885cbSTobias Grosser 
728edb885cbSTobias Grosser   return SubtreeValues;
729edb885cbSTobias Grosser }
730edb885cbSTobias Grosser 
73174dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
73274dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
73374dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
73474dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
73574dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
73674dc3cb4STobias Grosser 
73774dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
73874dc3cb4STobias Grosser     DT.eraseNode(BB);
73974dc3cb4STobias Grosser }
74074dc3cb4STobias Grosser 
74174dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
74274dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
74374dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
74474dc3cb4STobias Grosser     if (L)
74574dc3cb4STobias Grosser       SE.forgetLoop(L);
74674dc3cb4STobias Grosser   }
74774dc3cb4STobias Grosser }
74874dc3cb4STobias Grosser 
74974dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
75074dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
75174dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
75274dc3cb4STobias Grosser     if (L)
75374dc3cb4STobias Grosser       SE.forgetLoop(L);
75474dc3cb4STobias Grosser     LI.removeBlock(&BB);
75574dc3cb4STobias Grosser   }
75674dc3cb4STobias Grosser }
75774dc3cb4STobias Grosser 
75832837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
75932837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
76032837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
76132837fe3STobias Grosser   isl_id_free(Id);
76232837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
76332837fe3STobias Grosser 
764edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel);
765edb885cbSTobias Grosser 
76632837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
76732837fe3STobias Grosser 
76832837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
769472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
770edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
77132837fe3STobias Grosser 
772edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
773edb885cbSTobias Grosser 
774edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
775edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
776edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
777edb885cbSTobias Grosser   for (const Loop *L : Loops) {
778edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
779edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
780edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
781edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
782edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
783edb885cbSTobias Grosser     SubtreeValues.insert(V);
784edb885cbSTobias Grosser   }
785edb885cbSTobias Grosser 
786edb885cbSTobias Grosser   createKernelFunction(Kernel, SubtreeValues);
78732837fe3STobias Grosser 
78859ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
78959ab0705STobias Grosser 
79074dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
79174dc3cb4STobias Grosser   clearDominators(F);
79274dc3cb4STobias Grosser   clearScalarEvolution(F);
79374dc3cb4STobias Grosser   clearLoops(F);
79474dc3cb4STobias Grosser 
79532837fe3STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
796472f9654STobias Grosser   IDToValue = HostIDs;
79732837fe3STobias Grosser 
798edb885cbSTobias Grosser   ValueMap = HostValueMap;
799edb885cbSTobias Grosser   ScalarMap.clear();
800edb885cbSTobias Grosser   PHIOpMap.clear();
801edb885cbSTobias Grosser   EscapeMap.clear();
802edb885cbSTobias Grosser   IDToSAI.clear();
80374dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
80474dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
80574dc3cb4STobias Grosser     S.invalidateScopArrayInfo(BasePtr, ScopArrayInfo::MK_Array);
80674dc3cb4STobias Grosser   LocalArrays.clear();
807edb885cbSTobias Grosser 
808*57793596STobias Grosser   std::string ASMString = finalizeKernelFunction();
809*57793596STobias Grosser   std::string Name = "kernel_" + std::to_string(Kernel->id);
810*57793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
811*57793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
812*57793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
813*57793596STobias Grosser   createCallFreeKernel(GPUKernel);
81432837fe3STobias Grosser }
81532837fe3STobias Grosser 
81632837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
81732837fe3STobias Grosser ///
81832837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
81932837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
82032837fe3STobias Grosser   std::string Ret = "e";
82132837fe3STobias Grosser 
82232837fe3STobias Grosser   if (!is64Bit)
82332837fe3STobias Grosser     Ret += "-p:32:32";
82432837fe3STobias Grosser 
82532837fe3STobias Grosser   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
82632837fe3STobias Grosser 
82732837fe3STobias Grosser   return Ret;
82832837fe3STobias Grosser }
82932837fe3STobias Grosser 
830edb885cbSTobias Grosser Function *
831edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
832edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
83332837fe3STobias Grosser   std::vector<Type *> Args;
83432837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
83532837fe3STobias Grosser 
83632837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
83732837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
83832837fe3STobias Grosser       continue;
83932837fe3STobias Grosser 
84032837fe3STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
84132837fe3STobias Grosser   }
84232837fe3STobias Grosser 
843f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
844f6044bd0STobias Grosser 
845f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++)
846f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
847f6044bd0STobias Grosser 
848c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
849c84a1995STobias Grosser 
850c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++)
851c84a1995STobias Grosser     Args.push_back(Builder.getInt64Ty());
852c84a1995STobias Grosser 
853edb885cbSTobias Grosser   for (auto *V : SubtreeValues)
854edb885cbSTobias Grosser     Args.push_back(V->getType());
855edb885cbSTobias Grosser 
85632837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
85732837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
85832837fe3STobias Grosser                               GPUModule.get());
85932837fe3STobias Grosser   FN->setCallingConv(CallingConv::PTX_Kernel);
86032837fe3STobias Grosser 
86132837fe3STobias Grosser   auto Arg = FN->arg_begin();
86232837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
86332837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
86432837fe3STobias Grosser       continue;
86532837fe3STobias Grosser 
866edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
867edb885cbSTobias Grosser 
868edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
869edb885cbSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
870edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
871edb885cbSTobias Grosser     Value *Val = &*Arg;
872edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
873edb885cbSTobias Grosser     isl_ast_build *Build =
874edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
875edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
876edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
877edb885cbSTobias Grosser           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
878edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
879edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
880edb885cbSTobias Grosser     }
881edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
882edb885cbSTobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, ScopArrayInfo::MK_Array);
88374dc3cb4STobias Grosser     LocalArrays.push_back(Val);
884edb885cbSTobias Grosser 
885edb885cbSTobias Grosser     isl_ast_build_free(Build);
886edb885cbSTobias Grosser     isl_id_free(Id);
887edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
88832837fe3STobias Grosser     Arg++;
88932837fe3STobias Grosser   }
89032837fe3STobias Grosser 
891f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
892f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
893f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
894f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
895f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
896f6044bd0STobias Grosser     Arg++;
897f6044bd0STobias Grosser   }
898f6044bd0STobias Grosser 
899c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
900c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
901c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
902c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
903c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
904c84a1995STobias Grosser     Arg++;
905c84a1995STobias Grosser   }
906c84a1995STobias Grosser 
907edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
908edb885cbSTobias Grosser     Arg->setName(V->getName());
909edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
910edb885cbSTobias Grosser     Arg++;
911edb885cbSTobias Grosser   }
912edb885cbSTobias Grosser 
91332837fe3STobias Grosser   return FN;
91432837fe3STobias Grosser }
91532837fe3STobias Grosser 
916472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
917472f9654STobias Grosser   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
918472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
919472f9654STobias Grosser 
920472f9654STobias Grosser   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
921472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
922472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
923472f9654STobias Grosser 
924472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
925472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
926472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
927472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
928472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
929472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
930472f9654STobias Grosser     IDToValue[Id] = Val;
931472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
932472f9654STobias Grosser   };
933472f9654STobias Grosser 
934472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
935472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
936472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
937472f9654STobias Grosser   }
938472f9654STobias Grosser 
939472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
940472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
941472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
942472f9654STobias Grosser   }
943472f9654STobias Grosser }
944472f9654STobias Grosser 
945edb885cbSTobias Grosser void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel,
946edb885cbSTobias Grosser                                           SetVector<Value *> &SubtreeValues) {
94732837fe3STobias Grosser 
94832837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
94932837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
95032837fe3STobias Grosser   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
95132837fe3STobias Grosser   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
95232837fe3STobias Grosser 
953edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
95432837fe3STobias Grosser 
95559ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
95632837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
95732837fe3STobias Grosser 
95859ab0705STobias Grosser   DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
95959ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
96059ab0705STobias Grosser 
96132837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
96232837fe3STobias Grosser   Builder.CreateRetVoid();
96332837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
964472f9654STobias Grosser 
965472f9654STobias Grosser   insertKernelIntrinsics(Kernel);
96632837fe3STobias Grosser }
96732837fe3STobias Grosser 
96874dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
96974dc3cb4STobias Grosser   llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda"));
97074dc3cb4STobias Grosser   std::string ErrMsg;
97174dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
97274dc3cb4STobias Grosser 
97374dc3cb4STobias Grosser   if (!GPUTarget) {
97474dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
97574dc3cb4STobias Grosser     return "";
97674dc3cb4STobias Grosser   }
97774dc3cb4STobias Grosser 
97874dc3cb4STobias Grosser   TargetOptions Options;
97974dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
98074dc3cb4STobias Grosser   std::unique_ptr<TargetMachine> TargetM(
98174dc3cb4STobias Grosser       GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "",
98274dc3cb4STobias Grosser                                      Options, Optional<Reloc::Model>()));
98374dc3cb4STobias Grosser 
98474dc3cb4STobias Grosser   SmallString<0> ASMString;
98574dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
98674dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
98774dc3cb4STobias Grosser 
98874dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
98974dc3cb4STobias Grosser 
99074dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
99174dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
99274dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
99374dc3cb4STobias Grosser     return "";
99474dc3cb4STobias Grosser   }
99574dc3cb4STobias Grosser 
99674dc3cb4STobias Grosser   PM.run(*GPUModule);
99774dc3cb4STobias Grosser 
99874dc3cb4STobias Grosser   return ASMStream.str();
99974dc3cb4STobias Grosser }
100074dc3cb4STobias Grosser 
1001*57793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
1002e1a98343STobias Grosser   // Verify module.
1003e1a98343STobias Grosser   llvm::legacy::PassManager Passes;
1004e1a98343STobias Grosser   Passes.add(createVerifierPass());
1005e1a98343STobias Grosser   Passes.run(*GPUModule);
100632837fe3STobias Grosser 
100732837fe3STobias Grosser   if (DumpKernelIR)
100832837fe3STobias Grosser     outs() << *GPUModule << "\n";
100932837fe3STobias Grosser 
10109a18d559STobias Grosser   // Optimize module.
10119a18d559STobias Grosser   llvm::legacy::PassManager OptPasses;
10129a18d559STobias Grosser   PassManagerBuilder PassBuilder;
10139a18d559STobias Grosser   PassBuilder.OptLevel = 3;
10149a18d559STobias Grosser   PassBuilder.SizeLevel = 0;
10159a18d559STobias Grosser   PassBuilder.populateModulePassManager(OptPasses);
10169a18d559STobias Grosser   OptPasses.run(*GPUModule);
10179a18d559STobias Grosser 
101874dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
101974dc3cb4STobias Grosser 
102074dc3cb4STobias Grosser   if (DumpKernelASM)
102174dc3cb4STobias Grosser     outs() << Assembly << "\n";
102274dc3cb4STobias Grosser 
102332837fe3STobias Grosser   GPUModule.release();
1024472f9654STobias Grosser   KernelIDs.clear();
1025*57793596STobias Grosser 
1026*57793596STobias Grosser   return Assembly;
102732837fe3STobias Grosser }
102832837fe3STobias Grosser 
10299dfe4e7cSTobias Grosser namespace {
10309dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
10319dfe4e7cSTobias Grosser public:
10329dfe4e7cSTobias Grosser   static char ID;
10339dfe4e7cSTobias Grosser 
1034e938517eSTobias Grosser   /// The scop that is currently processed.
1035e938517eSTobias Grosser   Scop *S;
1036e938517eSTobias Grosser 
103738fc0aedSTobias Grosser   LoopInfo *LI;
103838fc0aedSTobias Grosser   DominatorTree *DT;
103938fc0aedSTobias Grosser   ScalarEvolution *SE;
104038fc0aedSTobias Grosser   const DataLayout *DL;
104138fc0aedSTobias Grosser   RegionInfo *RI;
104238fc0aedSTobias Grosser 
10439dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
10449dfe4e7cSTobias Grosser 
1045e938517eSTobias Grosser   /// Construct compilation options for PPCG.
1046e938517eSTobias Grosser   ///
1047e938517eSTobias Grosser   /// @returns The compilation options.
1048e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
1049e938517eSTobias Grosser     auto DebugOptions =
1050e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
1051e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
1052e938517eSTobias Grosser 
1053e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
1054e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
1055e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
1056e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
1057e938517eSTobias Grosser 
1058e938517eSTobias Grosser     Options->debug = DebugOptions;
1059e938517eSTobias Grosser 
1060e938517eSTobias Grosser     Options->reschedule = true;
1061e938517eSTobias Grosser     Options->scale_tile_loops = false;
1062e938517eSTobias Grosser     Options->wrap = false;
1063e938517eSTobias Grosser 
1064e938517eSTobias Grosser     Options->non_negative_parameters = false;
1065e938517eSTobias Grosser     Options->ctx = nullptr;
1066e938517eSTobias Grosser     Options->sizes = nullptr;
1067e938517eSTobias Grosser 
10684eaedde5STobias Grosser     Options->tile_size = 32;
10694eaedde5STobias Grosser 
1070e938517eSTobias Grosser     Options->use_private_memory = false;
1071e938517eSTobias Grosser     Options->use_shared_memory = false;
1072e938517eSTobias Grosser     Options->max_shared_memory = 0;
1073e938517eSTobias Grosser 
1074e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
1075e938517eSTobias Grosser     Options->openmp = false;
1076e938517eSTobias Grosser     Options->linearize_device_arrays = true;
1077e938517eSTobias Grosser     Options->live_range_reordering = false;
1078e938517eSTobias Grosser 
1079e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
1080e938517eSTobias Grosser     Options->opencl_use_gpu = false;
1081e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
1082e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
1083e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
1084e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
1085e938517eSTobias Grosser 
1086e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
1087e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
1088e938517eSTobias Grosser 
1089e938517eSTobias Grosser     return Options;
1090e938517eSTobias Grosser   }
1091e938517eSTobias Grosser 
1092f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
1093f384594dSTobias Grosser   ///
1094f384594dSTobias Grosser   /// Instead of a normal access of the form:
1095f384594dSTobias Grosser   ///
1096f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
1097f384594dSTobias Grosser   ///
1098f384594dSTobias Grosser   /// a tagged access has the form
1099f384594dSTobias Grosser   ///
1100f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
1101f384594dSTobias Grosser   ///
1102f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
1103f384594dSTobias Grosser   /// triggered the access.
1104f384594dSTobias Grosser   ///
1105f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
1106f384594dSTobias Grosser   ///
1107f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
1108f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
1109f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
1110f384594dSTobias Grosser 
1111f384594dSTobias Grosser     for (auto &Stmt : *S)
1112f384594dSTobias Grosser       for (auto &Acc : Stmt)
1113f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
1114f384594dSTobias Grosser           isl_map *Relation = Acc->getAccessRelation();
1115f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
1116f384594dSTobias Grosser 
1117f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
1118f384594dSTobias Grosser           Space = isl_space_range(Space);
1119f384594dSTobias Grosser           Space = isl_space_from_range(Space);
11206293ba69STobias Grosser           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1121f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
1122f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
1123f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
1124f384594dSTobias Grosser         }
1125f384594dSTobias Grosser 
1126f384594dSTobias Grosser     return Accesses;
1127f384594dSTobias Grosser   }
1128f384594dSTobias Grosser 
1129f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
1130f384594dSTobias Grosser   ///
1131f384594dSTobias Grosser   /// @see getTaggedAccesses
1132f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
1133f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
1134f384594dSTobias Grosser   }
1135f384594dSTobias Grosser 
1136f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
1137f384594dSTobias Grosser   ///
1138f384594dSTobias Grosser   /// @see getTaggedAccesses
1139f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
1140f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
1141f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
1142f384594dSTobias Grosser   }
1143f384594dSTobias Grosser 
1144f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
1145f384594dSTobias Grosser   ///
1146f384594dSTobias Grosser   /// @see getTaggedAccesses
1147f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
1148f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
1149f384594dSTobias Grosser   }
1150f384594dSTobias Grosser 
1151aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
1152aef5196fSTobias Grosser   ///
1153aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
1154aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
1155aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
1156aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
1157aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
1158aef5196fSTobias Grosser   /// the data format that ppcg expects.
1159aef5196fSTobias Grosser   ///
1160aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
1161aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
1162aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
1163bd81a7eeSTobias Grosser         S->getIslCtx(),
1164bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
1165aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
1166aef5196fSTobias Grosser     auto *Space = S->getParamSpace();
1167aef5196fSTobias Grosser 
1168aef5196fSTobias Grosser     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
1169aef5196fSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
1170aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1171aef5196fSTobias Grosser     }
1172aef5196fSTobias Grosser 
1173aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
1174aef5196fSTobias Grosser       auto Id = Array.second->getBasePtrId();
1175aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1176aef5196fSTobias Grosser     }
1177aef5196fSTobias Grosser 
1178aef5196fSTobias Grosser     isl_space_free(Space);
1179aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
1180aef5196fSTobias Grosser 
1181aef5196fSTobias Grosser     return Names;
1182aef5196fSTobias Grosser   }
1183aef5196fSTobias Grosser 
1184e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
1185e938517eSTobias Grosser   ///
1186f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
1187f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
1188f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
1189f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
1190e938517eSTobias Grosser   ///
1191e938517eSTobias Grosser   /// @returns A new ppcg scop.
1192e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
1193e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
1194e938517eSTobias Grosser 
1195e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
1196e938517eSTobias Grosser 
1197e938517eSTobias Grosser     PPCGScop->start = 0;
1198e938517eSTobias Grosser     PPCGScop->end = 0;
1199e938517eSTobias Grosser 
1200f384594dSTobias Grosser     PPCGScop->context = S->getContext();
1201f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
1202e938517eSTobias Grosser     PPCGScop->call = nullptr;
1203f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
1204f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
1205e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
1206f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
1207f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
1208f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
1209f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
1210e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
1211f384594dSTobias Grosser     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
1212e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
1213e938517eSTobias Grosser 
1214e938517eSTobias Grosser     PPCGScop->independence = nullptr;
1215e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
1216e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
1217e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
1218e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
1219e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
1220e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
1221e938517eSTobias Grosser 
1222f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
1223aef5196fSTobias Grosser     PPCGScop->names = getNames();
1224e938517eSTobias Grosser 
1225e938517eSTobias Grosser     PPCGScop->pet = nullptr;
1226e938517eSTobias Grosser 
1227f384594dSTobias Grosser     compute_tagger(PPCGScop);
1228f384594dSTobias Grosser     compute_dependences(PPCGScop);
1229f384594dSTobias Grosser 
1230e938517eSTobias Grosser     return PPCGScop;
1231e938517eSTobias Grosser   }
1232e938517eSTobias Grosser 
123360f63b49STobias Grosser   /// Collect the array acesses in a statement.
123460f63b49STobias Grosser   ///
123560f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
123660f63b49STobias Grosser   ///
123760f63b49STobias Grosser   /// @returns A list of array accesses.
123860f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
123960f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
124060f63b49STobias Grosser 
124160f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
124260f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
124360f63b49STobias Grosser       Access->read = Acc->isRead();
124460f63b49STobias Grosser       Access->write = Acc->isWrite();
124560f63b49STobias Grosser       Access->access = Acc->getAccessRelation();
124660f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
124760f63b49STobias Grosser       Space = isl_space_range(Space);
124860f63b49STobias Grosser       Space = isl_space_from_range(Space);
12496293ba69STobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
125060f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
125160f63b49STobias Grosser       Access->tagged_access =
125260f63b49STobias Grosser           isl_map_domain_product(Acc->getAccessRelation(), Universe);
125360f63b49STobias Grosser       Access->exact_write = Acc->isWrite();
125460f63b49STobias Grosser       Access->ref_id = Acc->getId();
125560f63b49STobias Grosser       Access->next = Accesses;
125660f63b49STobias Grosser       Accesses = Access;
125760f63b49STobias Grosser     }
125860f63b49STobias Grosser 
125960f63b49STobias Grosser     return Accesses;
126060f63b49STobias Grosser   }
126160f63b49STobias Grosser 
126269b46751STobias Grosser   /// Collect the list of GPU statements.
126369b46751STobias Grosser   ///
126469b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
126569b46751STobias Grosser   /// as well as a list with all memory accesses.
126669b46751STobias Grosser   ///
126769b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
126869b46751STobias Grosser   ///
126969b46751STobias Grosser   /// @returns A linked-list of statements.
127069b46751STobias Grosser   gpu_stmt *getStatements() {
127169b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
127269b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
127369b46751STobias Grosser 
127469b46751STobias Grosser     int i = 0;
127569b46751STobias Grosser     for (auto &Stmt : *S) {
127669b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
127769b46751STobias Grosser 
127869b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
127969b46751STobias Grosser 
128069b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
128169b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
128260f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
128369b46751STobias Grosser       i++;
128469b46751STobias Grosser     }
128569b46751STobias Grosser 
128669b46751STobias Grosser     return Stmts;
128769b46751STobias Grosser   }
128869b46751STobias Grosser 
128960f63b49STobias Grosser   /// Derive the extent of an array.
129060f63b49STobias Grosser   ///
129160f63b49STobias Grosser   /// The extent of an array is defined by the set of memory locations for
129260f63b49STobias Grosser   /// which a memory access in the iteration domain exists.
129360f63b49STobias Grosser   ///
129460f63b49STobias Grosser   /// @param Array The array to derive the extent for.
129560f63b49STobias Grosser   ///
129660f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
129760f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
129860f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
129960f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
130060f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
130160f63b49STobias Grosser     isl_set *AccessSet =
130260f63b49STobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace());
130360f63b49STobias Grosser     isl_union_set_free(AccessUSet);
130460f63b49STobias Grosser 
130560f63b49STobias Grosser     return AccessSet;
130660f63b49STobias Grosser   }
130760f63b49STobias Grosser 
130860f63b49STobias Grosser   /// Derive the bounds of an array.
130960f63b49STobias Grosser   ///
131060f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
131160f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
131260f63b49STobias Grosser   /// ScopArrayInfo.
131360f63b49STobias Grosser   ///
131460f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
131560f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
131660f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
131760f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
131860f63b49STobias Grosser       isl_set *Dom = isl_set_copy(PPCGArray.extent);
131960f63b49STobias Grosser       Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
132060f63b49STobias Grosser       isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
132160f63b49STobias Grosser       isl_set_free(Dom);
132260f63b49STobias Grosser       Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
132360f63b49STobias Grosser       isl_local_space *LS = isl_local_space_from_space(isl_set_get_space(Dom));
132460f63b49STobias Grosser       isl_aff *One = isl_aff_zero_on_domain(LS);
132560f63b49STobias Grosser       One = isl_aff_add_constant_si(One, 1);
132660f63b49STobias Grosser       Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
132760f63b49STobias Grosser       Bound = isl_pw_aff_gist(Bound, S->getContext());
132860f63b49STobias Grosser       PPCGArray.bound[0] = Bound;
132960f63b49STobias Grosser     }
133060f63b49STobias Grosser 
133160f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
133260f63b49STobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
133360f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
133460f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
133560f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
133660f63b49STobias Grosser       PPCGArray.bound[i] = Bound;
133760f63b49STobias Grosser     }
133860f63b49STobias Grosser   }
133960f63b49STobias Grosser 
134060f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
134160f63b49STobias Grosser   ///
134260f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
134360f63b49STobias Grosser   void createArrays(gpu_prog *PPCGProg) {
134460f63b49STobias Grosser     int i = 0;
134560f63b49STobias Grosser     for (auto &Element : S->arrays()) {
134660f63b49STobias Grosser       ScopArrayInfo *Array = Element.second.get();
134760f63b49STobias Grosser 
134860f63b49STobias Grosser       std::string TypeName;
134960f63b49STobias Grosser       raw_string_ostream OS(TypeName);
135060f63b49STobias Grosser 
135160f63b49STobias Grosser       OS << *Array->getElementType();
135260f63b49STobias Grosser       TypeName = OS.str();
135360f63b49STobias Grosser 
135460f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
135560f63b49STobias Grosser 
135660f63b49STobias Grosser       PPCGArray.space = Array->getSpace();
135760f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
135860f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
135960f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
136060f63b49STobias Grosser       PPCGArray.extent = nullptr;
136160f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
136260f63b49STobias Grosser       PPCGArray.bound =
136360f63b49STobias Grosser           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
136460f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
136560f63b49STobias Grosser       PPCGArray.n_ref = 0;
136660f63b49STobias Grosser       PPCGArray.refs = nullptr;
136760f63b49STobias Grosser       PPCGArray.accessed = true;
136860f63b49STobias Grosser       PPCGArray.read_only_scalar = false;
136960f63b49STobias Grosser       PPCGArray.has_compound_element = false;
137060f63b49STobias Grosser       PPCGArray.local = false;
137160f63b49STobias Grosser       PPCGArray.declare_local = false;
137260f63b49STobias Grosser       PPCGArray.global = false;
137360f63b49STobias Grosser       PPCGArray.linearize = false;
137460f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
137513c78e4dSTobias Grosser       PPCGArray.user = Array;
137660f63b49STobias Grosser 
137760f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
13782d010dafSTobias Grosser       i++;
1379b9fc860aSTobias Grosser 
1380b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
138160f63b49STobias Grosser     }
138260f63b49STobias Grosser   }
138360f63b49STobias Grosser 
138460f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
138560f63b49STobias Grosser   ///
138660f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
138760f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
138860f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
138960f63b49STobias Grosser 
139060f63b49STobias Grosser     for (auto &Item : S->arrays()) {
139160f63b49STobias Grosser       ScopArrayInfo *Array = Item.second.get();
139260f63b49STobias Grosser       isl_space *Space = Array->getSpace();
139360f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
139460f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
139560f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
139660f63b49STobias Grosser     }
139760f63b49STobias Grosser 
139860f63b49STobias Grosser     return Maps;
139960f63b49STobias Grosser   }
140060f63b49STobias Grosser 
1401e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
1402e938517eSTobias Grosser   ///
1403e938517eSTobias Grosser   /// @returns A new gpu grogram description.
1404e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
1405e938517eSTobias Grosser 
1406e938517eSTobias Grosser     if (!PPCGScop)
1407e938517eSTobias Grosser       return nullptr;
1408e938517eSTobias Grosser 
1409e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
1410e938517eSTobias Grosser 
1411e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
1412e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
1413aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
141460f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
141560f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
141660f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
141760f63b49STobias Grosser     PPCGProg->tagged_must_kill =
141860f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
141960f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
142060f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
142160f63b49STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
1422e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
1423e938517eSTobias Grosser     PPCGProg->array_order = nullptr;
142469b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
142569b46751STobias Grosser     PPCGProg->stmts = getStatements();
142660f63b49STobias Grosser     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
142760f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
142860f63b49STobias Grosser                                        PPCGProg->n_array);
142960f63b49STobias Grosser 
143060f63b49STobias Grosser     createArrays(PPCGProg);
1431e938517eSTobias Grosser 
1432e938517eSTobias Grosser     return PPCGProg;
1433e938517eSTobias Grosser   }
1434e938517eSTobias Grosser 
143569b46751STobias Grosser   struct PrintGPUUserData {
143669b46751STobias Grosser     struct cuda_info *CudaInfo;
143769b46751STobias Grosser     struct gpu_prog *PPCGProg;
143869b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
143969b46751STobias Grosser   };
144069b46751STobias Grosser 
144169b46751STobias Grosser   /// Print a user statement node in the host code.
144269b46751STobias Grosser   ///
144369b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
144469b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
144569b46751STobias Grosser   /// host ast.
144669b46751STobias Grosser   ///
144769b46751STobias Grosser   /// @param P The printer to print to
144869b46751STobias Grosser   /// @param Options The printing options to use
144969b46751STobias Grosser   /// @param Node The node to print
145069b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
145169b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
145269b46751STobias Grosser   ///
145369b46751STobias Grosser   /// @returns A printer to which the output has been printed.
145469b46751STobias Grosser   static __isl_give isl_printer *
145569b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
145669b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
145769b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
145869b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
145969b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
146069b46751STobias Grosser 
146169b46751STobias Grosser     if (Id) {
146220251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
146320251734STobias Grosser 
146420251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
146520251734STobias Grosser       // otherwise try to call pet functionality that is not available in
146620251734STobias Grosser       // Polly.
146720251734STobias Grosser       if (IsUser) {
146820251734STobias Grosser         P = isl_printer_start_line(P);
146920251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
147020251734STobias Grosser         P = isl_printer_end_line(P);
147120251734STobias Grosser         isl_id_free(Id);
147220251734STobias Grosser         isl_ast_print_options_free(Options);
147320251734STobias Grosser         return P;
147420251734STobias Grosser       }
147520251734STobias Grosser 
147669b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
147769b46751STobias Grosser       isl_id_free(Id);
147869b46751STobias Grosser       Data->Kernels.push_back(Kernel);
147969b46751STobias Grosser     }
148069b46751STobias Grosser 
148169b46751STobias Grosser     return print_host_user(P, Options, Node, User);
148269b46751STobias Grosser   }
148369b46751STobias Grosser 
148469b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
148569b46751STobias Grosser   ///
148669b46751STobias Grosser   /// @param Kernel The kernel to print
148769b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
148869b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
148969b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
149069b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
149169b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
149269b46751STobias Grosser     char *String = isl_printer_get_str(P);
149369b46751STobias Grosser     printf("%s\n", String);
149469b46751STobias Grosser     free(String);
149569b46751STobias Grosser     isl_printer_free(P);
149669b46751STobias Grosser   }
149769b46751STobias Grosser 
149869b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
149969b46751STobias Grosser   ///
150069b46751STobias Grosser   /// @param Tree An AST describing GPU code
150169b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
150269b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
150369b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
150469b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
150569b46751STobias Grosser 
150669b46751STobias Grosser     PrintGPUUserData Data;
150769b46751STobias Grosser     Data.PPCGProg = PPCGProg;
150869b46751STobias Grosser 
150969b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
151069b46751STobias Grosser     Options =
151169b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
151269b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
151369b46751STobias Grosser     char *String = isl_printer_get_str(P);
151469b46751STobias Grosser     printf("# host\n");
151569b46751STobias Grosser     printf("%s\n", String);
151669b46751STobias Grosser     free(String);
151769b46751STobias Grosser     isl_printer_free(P);
151869b46751STobias Grosser 
151969b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
152069b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
152169b46751STobias Grosser       printKernel(Kernel);
152269b46751STobias Grosser     }
152369b46751STobias Grosser   }
152469b46751STobias Grosser 
1525f384594dSTobias Grosser   // Generate a GPU program using PPCG.
1526f384594dSTobias Grosser   //
1527f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
1528f384594dSTobias Grosser   //
1529f384594dSTobias Grosser   //  1) Compute new schedule for the program.
1530f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
1531f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
1532f384594dSTobias Grosser   //
1533f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
1534f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
1535f384594dSTobias Grosser   // strategy directly from this pass.
1536f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
1537f384594dSTobias Grosser 
1538f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
1539f384594dSTobias Grosser 
1540f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
1541f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
1542f384594dSTobias Grosser     PPCGGen->print = nullptr;
1543f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
154460c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
1545f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
1546f384594dSTobias Grosser     PPCGGen->tree = nullptr;
1547f384594dSTobias Grosser     PPCGGen->types.n = 0;
1548f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
1549f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
1550f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
1551f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
1552f384594dSTobias Grosser 
1553f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
1554f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
1555f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
15562341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
1557f384594dSTobias Grosser 
1558f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
1559f384594dSTobias Grosser 
1560aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
1561aef5196fSTobias Grosser 
156269b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
1563aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
156469b46751STobias Grosser     } else {
1565aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
156669b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
156769b46751STobias Grosser     }
1568aef5196fSTobias Grosser 
1569f384594dSTobias Grosser     if (DumpSchedule) {
1570f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
1571f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
1572f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
1573f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
1574f384594dSTobias Grosser       if (Schedule)
1575f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
1576f384594dSTobias Grosser       else
1577f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
1578f384594dSTobias Grosser 
1579f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
1580f384594dSTobias Grosser       isl_printer_free(P);
1581f384594dSTobias Grosser     }
1582f384594dSTobias Grosser 
158369b46751STobias Grosser     if (DumpCode) {
158469b46751STobias Grosser       printf("Code\n");
158569b46751STobias Grosser       printf("====\n");
158669b46751STobias Grosser       if (PPCGGen->tree)
158769b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
158869b46751STobias Grosser       else
158969b46751STobias Grosser         printf("No code generated\n");
159069b46751STobias Grosser     }
159169b46751STobias Grosser 
1592f384594dSTobias Grosser     isl_schedule_free(Schedule);
1593f384594dSTobias Grosser 
1594f384594dSTobias Grosser     return PPCGGen;
1595f384594dSTobias Grosser   }
1596f384594dSTobias Grosser 
1597f384594dSTobias Grosser   /// Free gpu_gen structure.
1598f384594dSTobias Grosser   ///
1599f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
1600f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
1601f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
1602f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
1603f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
1604f384594dSTobias Grosser     free(PPCGGen);
1605f384594dSTobias Grosser   }
1606f384594dSTobias Grosser 
1607b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
1608b307ed4dSTobias Grosser   ///
1609b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
1610b307ed4dSTobias Grosser   /// ourselves.
1611b307ed4dSTobias Grosser   ///
1612b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
1613b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
1614b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
1615b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
1616b307ed4dSTobias Grosser     free(PPCGScop->options);
1617b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
1618b307ed4dSTobias Grosser   }
1619b307ed4dSTobias Grosser 
162038fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
162138fc0aedSTobias Grosser   ///
162232837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
162332837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
162432837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
162538fc0aedSTobias Grosser     ScopAnnotator Annotator;
162638fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
162738fc0aedSTobias Grosser 
162838fc0aedSTobias Grosser     Region *R = &S->getRegion();
162938fc0aedSTobias Grosser 
163038fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
163138fc0aedSTobias Grosser 
163238fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
163338fc0aedSTobias Grosser 
163438fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
163538fc0aedSTobias Grosser 
163632837fe3STobias Grosser     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S,
163732837fe3STobias Grosser                                Prog);
163838fc0aedSTobias Grosser 
163938fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
164038fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
164138fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
164238fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
164338fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
164438fc0aedSTobias Grosser     // code generating this scop.
164538fc0aedSTobias Grosser     BasicBlock *StartBlock =
164638fc0aedSTobias Grosser         executeScopConditionally(*S, this, Builder.getTrue());
164738fc0aedSTobias Grosser 
164838fc0aedSTobias Grosser     // TODO: Handle LICM
164938fc0aedSTobias Grosser     // TODO: Verify run-time checks
165038fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
165138fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
165238fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
165338fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
1654fa7b0802STobias Grosser 
1655fa7b0802STobias Grosser     NodeBuilder.initializeAfterRTH();
165638fc0aedSTobias Grosser     NodeBuilder.create(Root);
16578ed5e599STobias Grosser     NodeBuilder.finalize();
165838fc0aedSTobias Grosser   }
165938fc0aedSTobias Grosser 
1660e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
1661e938517eSTobias Grosser     S = &CurrentScop;
166238fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
166338fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
166438fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
166538fc0aedSTobias Grosser     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
166638fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
1667e938517eSTobias Grosser 
16682d58a64eSTobias Grosser     // We currently do not support scops with invariant loads.
16692d58a64eSTobias Grosser     if (S->hasInvariantAccesses())
16702d58a64eSTobias Grosser       return false;
16712d58a64eSTobias Grosser 
1672e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
1673e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
1674f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
167538fc0aedSTobias Grosser 
167638fc0aedSTobias Grosser     if (PPCGGen->tree)
167732837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
167838fc0aedSTobias Grosser 
1679b307ed4dSTobias Grosser     freeOptions(PPCGScop);
1680f384594dSTobias Grosser     freePPCGGen(PPCGGen);
1681e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
1682e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
1683e938517eSTobias Grosser 
1684e938517eSTobias Grosser     return true;
1685e938517eSTobias Grosser   }
16869dfe4e7cSTobias Grosser 
16879dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
16889dfe4e7cSTobias Grosser 
16899dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
16909dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
16919dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
16929dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
16939dfe4e7cSTobias Grosser     AU.addRequired<ScopDetection>();
16949dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
16959dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
16969dfe4e7cSTobias Grosser 
16979dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
16989dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
16999dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
17009dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
17019dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
17029dfe4e7cSTobias Grosser     AU.addPreserved<PostDominatorTreeWrapperPass>();
17039dfe4e7cSTobias Grosser     AU.addPreserved<ScopDetection>();
17049dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
17059dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
17069dfe4e7cSTobias Grosser 
17079dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
17089dfe4e7cSTobias Grosser     //        region tree.
17099dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
17109dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
17119dfe4e7cSTobias Grosser   }
17129dfe4e7cSTobias Grosser };
17139dfe4e7cSTobias Grosser }
17149dfe4e7cSTobias Grosser 
17159dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
17169dfe4e7cSTobias Grosser 
17179dfe4e7cSTobias Grosser Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
17189dfe4e7cSTobias Grosser 
17199dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
17209dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
17219dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
17229dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
17239dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
17249dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
17259dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
17269dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScopDetection);
17279dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
17289dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
1729