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 
15cb1aef8dSTobias Grosser #include "polly/CodeGen/IslAst.h"
169dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h"
1738fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h"
189dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h"
199dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h"
20f384594dSTobias Grosser #include "polly/Options.h"
21629109b6STobias Grosser #include "polly/ScopDetection.h"
229dfe4e7cSTobias Grosser #include "polly/ScopInfo.h"
23edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h"
2474dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h"
259dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h"
269dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h"
279dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h"
289dfe4e7cSTobias Grosser #include "llvm/Analysis/PostDominators.h"
299dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
3074dc3cb4STobias Grosser #include "llvm/Analysis/TargetLibraryInfo.h"
3174dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h"
3274dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h"
33e1a98343STobias Grosser #include "llvm/IR/Verifier.h"
3474dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h"
3574dc3cb4STobias Grosser #include "llvm/Support/TargetSelect.h"
3674dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h"
379a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h"
38750160e2STobias Grosser #include "llvm/Transforms/Utils/BasicBlockUtils.h"
399dfe4e7cSTobias Grosser 
40f384594dSTobias Grosser #include "isl/union_map.h"
41f384594dSTobias Grosser 
42e938517eSTobias Grosser extern "C" {
43a56f8f8eSTobias Grosser #include "ppcg/cuda.h"
44a56f8f8eSTobias Grosser #include "ppcg/gpu.h"
45a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h"
46a56f8f8eSTobias Grosser #include "ppcg/ppcg.h"
47a56f8f8eSTobias Grosser #include "ppcg/schedule.h"
48e938517eSTobias Grosser }
49e938517eSTobias Grosser 
509dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h"
519dfe4e7cSTobias Grosser 
529dfe4e7cSTobias Grosser using namespace polly;
539dfe4e7cSTobias Grosser using namespace llvm;
549dfe4e7cSTobias Grosser 
559dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg"
569dfe4e7cSTobias Grosser 
57f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
58f384594dSTobias Grosser                                   cl::desc("Dump the computed GPU Schedule"),
59681bd568STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
60f384594dSTobias Grosser                                   cl::cat(PollyCategory));
6169b46751STobias Grosser 
6269b46751STobias Grosser static cl::opt<bool>
6369b46751STobias Grosser     DumpCode("polly-acc-dump-code",
6469b46751STobias Grosser              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
6569b46751STobias Grosser              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
6669b46751STobias Grosser 
6732837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
6832837fe3STobias Grosser                                   cl::desc("Dump the kernel LLVM-IR"),
6932837fe3STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
7032837fe3STobias Grosser                                   cl::cat(PollyCategory));
7132837fe3STobias Grosser 
7274dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
7374dc3cb4STobias Grosser                                    cl::desc("Dump the kernel assembly code"),
7474dc3cb4STobias Grosser                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
7574dc3cb4STobias Grosser                                    cl::cat(PollyCategory));
7674dc3cb4STobias Grosser 
7774dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath",
7874dc3cb4STobias Grosser                               cl::desc("Allow unsafe math optimizations"),
7974dc3cb4STobias Grosser                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
8074dc3cb4STobias Grosser                               cl::cat(PollyCategory));
81b513b491STobias Grosser static cl::opt<bool> SharedMemory("polly-acc-use-shared",
82b513b491STobias Grosser                                   cl::desc("Use shared memory"), cl::Hidden,
83b513b491STobias Grosser                                   cl::init(false), cl::ZeroOrMore,
84b513b491STobias Grosser                                   cl::cat(PollyCategory));
85130ca30fSTobias Grosser static cl::opt<bool> PrivateMemory("polly-acc-use-private",
86130ca30fSTobias Grosser                                    cl::desc("Use private memory"), cl::Hidden,
87130ca30fSTobias Grosser                                    cl::init(false), cl::ZeroOrMore,
88130ca30fSTobias Grosser                                    cl::cat(PollyCategory));
8974dc3cb4STobias Grosser 
9074dc3cb4STobias Grosser static cl::opt<std::string>
9174dc3cb4STobias Grosser     CudaVersion("polly-acc-cuda-version",
9274dc3cb4STobias Grosser                 cl::desc("The CUDA version to compile for"), cl::Hidden,
9374dc3cb4STobias Grosser                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
9474dc3cb4STobias Grosser 
9560c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
9660c60025STobias Grosser ///
9760c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
9860c60025STobias Grosser /// of the scheduled ScopStmts.
9960c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
100edb885cbSTobias Grosser     void *StmtT, isl_ast_build *Build,
10160c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
10260c60025STobias Grosser                                        isl_id *Id, void *User),
10360c60025STobias Grosser     void *UserIndex,
10460c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
105edb885cbSTobias Grosser     void *UserExpr) {
10660c60025STobias Grosser 
107edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
10860c60025STobias Grosser 
109edb885cbSTobias Grosser   isl_ctx *Ctx;
110edb885cbSTobias Grosser 
111edb885cbSTobias Grosser   if (!Stmt || !Build)
112edb885cbSTobias Grosser     return NULL;
113edb885cbSTobias Grosser 
114edb885cbSTobias Grosser   Ctx = isl_ast_build_get_ctx(Build);
115edb885cbSTobias Grosser   isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0);
116edb885cbSTobias Grosser 
117edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
118edb885cbSTobias Grosser     isl_map *AddrFunc = Acc->getAddressFunction();
119edb885cbSTobias Grosser     AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain());
120edb885cbSTobias Grosser     isl_id *RefId = Acc->getId();
121edb885cbSTobias Grosser     isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc);
122edb885cbSTobias Grosser     isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA);
123edb885cbSTobias Grosser     MPA = isl_multi_pw_aff_coalesce(MPA);
124edb885cbSTobias Grosser     MPA = FunctionIndex(MPA, RefId, UserIndex);
125edb885cbSTobias Grosser     isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA);
126edb885cbSTobias Grosser     Access = FunctionExpr(Access, RefId, UserExpr);
127edb885cbSTobias Grosser     RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access);
128edb885cbSTobias Grosser   }
129edb885cbSTobias Grosser 
130edb885cbSTobias Grosser   return RefToExpr;
13160c60025STobias Grosser }
132f384594dSTobias Grosser 
13338fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
13438fc0aedSTobias Grosser ///
13538fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
13638fc0aedSTobias Grosser /// generates code for general-prupose AST nodes, with special functionality
13738fc0aedSTobias Grosser /// for generating GPU specific user nodes.
13838fc0aedSTobias Grosser ///
13938fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
14038fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
14138fc0aedSTobias Grosser public:
14238fc0aedSTobias Grosser   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P,
14338fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
14432837fe3STobias Grosser                  DominatorTree &DT, Scop &S, gpu_prog *Prog)
145edb885cbSTobias Grosser       : IslNodeBuilder(Builder, Annotator, P, DL, LI, SE, DT, S), Prog(Prog) {
146edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
147edb885cbSTobias Grosser   }
14838fc0aedSTobias Grosser 
149fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
150fa7b0802STobias Grosser   void initializeAfterRTH();
151fa7b0802STobias Grosser 
152fa7b0802STobias Grosser   /// Finalize the generated scop.
153fa7b0802STobias Grosser   virtual void finalize();
154fa7b0802STobias Grosser 
1555857b701STobias Grosser   /// Track if the full build process was successful.
1565857b701STobias Grosser   ///
1575857b701STobias Grosser   /// This value is set to false, if throughout the build process an error
1585857b701STobias Grosser   /// occurred which prevents us from generating valid GPU code.
1595857b701STobias Grosser   bool BuildSuccessful = true;
1605857b701STobias Grosser 
16138fc0aedSTobias Grosser private:
16274dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
16374dc3cb4STobias Grosser   ///
16474dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
16574dc3cb4STobias Grosser   /// more.
16674dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
16774dc3cb4STobias Grosser 
16813c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
16913c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
1707287aeddSTobias Grosser 
171fa7b0802STobias Grosser   /// The current GPU context.
172fa7b0802STobias Grosser   Value *GPUContext;
173fa7b0802STobias Grosser 
174b513b491STobias Grosser   /// The set of isl_ids allocated in the kernel
175b513b491STobias Grosser   std::vector<isl_id *> KernelIds;
176b513b491STobias Grosser 
17732837fe3STobias Grosser   /// A module containing GPU code.
17832837fe3STobias Grosser   ///
17932837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
18032837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
18132837fe3STobias Grosser 
18232837fe3STobias Grosser   /// The GPU program we generate code for.
18332837fe3STobias Grosser   gpu_prog *Prog;
18432837fe3STobias Grosser 
185472f9654STobias Grosser   /// Class to free isl_ids.
186472f9654STobias Grosser   class IslIdDeleter {
187472f9654STobias Grosser   public:
188472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
189472f9654STobias Grosser   };
190472f9654STobias Grosser 
191472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
192472f9654STobias Grosser   ///
193472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
194472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
195472f9654STobias Grosser 
196edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
197edb885cbSTobias Grosser 
19838fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
19938fc0aedSTobias Grosser   ///
20038fc0aedSTobias Grosser   /// These AST nodes can be of type:
20138fc0aedSTobias Grosser   ///
20238fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
20338fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
20413c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
2055260c041STobias Grosser   ///   - In-kernel synchronization
2065260c041STobias Grosser   ///   - In-kernel memory copy statement
20738fc0aedSTobias Grosser   ///
2081fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
2091fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
21032837fe3STobias Grosser 
21113c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
21213c78e4dSTobias Grosser 
21313c78e4dSTobias Grosser   /// Create code for a data transfer statement
21413c78e4dSTobias Grosser   ///
21513c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
21613c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
21713c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
21813c78e4dSTobias Grosser                           enum DataDirection Direction);
21913c78e4dSTobias Grosser 
220edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
221edb885cbSTobias Grosser   ///
222edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
223edb885cbSTobias Grosser   ///
224edb885cbSTobias Grosser   /// @returns A set of values referenced by the kernel.
225edb885cbSTobias Grosser   SetVector<Value *> getReferencesInKernel(ppcg_kernel *Kernel);
226edb885cbSTobias Grosser 
22779a947c2STobias Grosser   /// Compute the sizes of the execution grid for a given kernel.
22879a947c2STobias Grosser   ///
22979a947c2STobias Grosser   /// @param Kernel The kernel to compute grid sizes for.
23079a947c2STobias Grosser   ///
23179a947c2STobias Grosser   /// @returns A tuple with grid sizes for X and Y dimension
23279a947c2STobias Grosser   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
23379a947c2STobias Grosser 
23479a947c2STobias Grosser   /// Compute the sizes of the thread blocks for a given kernel.
23579a947c2STobias Grosser   ///
23679a947c2STobias Grosser   /// @param Kernel The kernel to compute thread block sizes for.
23779a947c2STobias Grosser   ///
23879a947c2STobias Grosser   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
23979a947c2STobias Grosser   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
24079a947c2STobias Grosser 
24179a947c2STobias Grosser   /// Create kernel launch parameters.
24279a947c2STobias Grosser   ///
24379a947c2STobias Grosser   /// @param Kernel        The kernel to create parameters for.
24479a947c2STobias Grosser   /// @param F             The kernel function that has been created.
24557693272STobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
24679a947c2STobias Grosser   ///
24779a947c2STobias Grosser   /// @returns A stack allocated array with pointers to the parameter
24879a947c2STobias Grosser   ///          values that are passed to the kernel.
24957693272STobias Grosser   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
25057693272STobias Grosser                                 SetVector<Value *> SubtreeValues);
25179a947c2STobias Grosser 
252b513b491STobias Grosser   /// Create declarations for kernel variable.
253b513b491STobias Grosser   ///
254b513b491STobias Grosser   /// This includes shared memory declarations.
255b513b491STobias Grosser   ///
256b513b491STobias Grosser   /// @param Kernel        The kernel definition to create variables for.
257b513b491STobias Grosser   /// @param FN            The function into which to generate the variables.
258b513b491STobias Grosser   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
259b513b491STobias Grosser 
260c1c6a2a6STobias Grosser   /// Add CUDA annotations to module.
261c1c6a2a6STobias Grosser   ///
262c1c6a2a6STobias Grosser   /// Add a set of CUDA annotations that declares the maximal block dimensions
263c1c6a2a6STobias Grosser   /// that will be used to execute the CUDA kernel. This allows the NVIDIA
264c1c6a2a6STobias Grosser   /// PTX compiler to bound the number of allocated registers to ensure the
265c1c6a2a6STobias Grosser   /// resulting kernel is known to run with up to as many block dimensions
266c1c6a2a6STobias Grosser   /// as specified here.
267c1c6a2a6STobias Grosser   ///
268c1c6a2a6STobias Grosser   /// @param M         The module to add the annotations to.
269c1c6a2a6STobias Grosser   /// @param BlockDimX The size of block dimension X.
270c1c6a2a6STobias Grosser   /// @param BlockDimY The size of block dimension Y.
271c1c6a2a6STobias Grosser   /// @param BlockDimZ The size of block dimension Z.
272c1c6a2a6STobias Grosser   void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY,
273c1c6a2a6STobias Grosser                           Value *BlockDimZ);
274c1c6a2a6STobias Grosser 
27532837fe3STobias Grosser   /// Create GPU kernel.
27632837fe3STobias Grosser   ///
27732837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
27832837fe3STobias Grosser   ///
27932837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
28032837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
28132837fe3STobias Grosser 
28213c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
28313c78e4dSTobias Grosser   ///
28413c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
28513c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
28613c78e4dSTobias Grosser 
287aaabbbf8STobias Grosser   /// Generate code to compute the minimal offset at which an array is accessed.
288aaabbbf8STobias Grosser   ///
289aaabbbf8STobias Grosser   /// The offset of an array is the minimal array location accessed in a scop.
290aaabbbf8STobias Grosser   ///
291aaabbbf8STobias Grosser   /// Example:
292aaabbbf8STobias Grosser   ///
293aaabbbf8STobias Grosser   ///   for (long i = 0; i < 100; i++)
294aaabbbf8STobias Grosser   ///     A[i + 42] += ...
295aaabbbf8STobias Grosser   ///
296aaabbbf8STobias Grosser   ///   getArrayOffset(A) results in 42.
297aaabbbf8STobias Grosser   ///
298aaabbbf8STobias Grosser   /// @param Array The array for which to compute the offset.
299aaabbbf8STobias Grosser   /// @returns An llvm::Value that contains the offset of the array.
300aaabbbf8STobias Grosser   Value *getArrayOffset(gpu_array_info *Array);
301aaabbbf8STobias Grosser 
30200bb5a99STobias Grosser   /// Prepare the kernel arguments for kernel code generation
30300bb5a99STobias Grosser   ///
30400bb5a99STobias Grosser   /// @param Kernel The kernel to generate code for.
30500bb5a99STobias Grosser   /// @param FN     The function created for the kernel.
30600bb5a99STobias Grosser   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
30700bb5a99STobias Grosser 
30832837fe3STobias Grosser   /// Create kernel function.
30932837fe3STobias Grosser   ///
31032837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
31132837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
31232837fe3STobias Grosser   /// start block of this newly created function.
31332837fe3STobias Grosser   ///
31432837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
315edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
316edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
317edb885cbSTobias Grosser                             SetVector<Value *> &SubtreeValues);
31832837fe3STobias Grosser 
31932837fe3STobias Grosser   /// Create the declaration of a kernel function.
32032837fe3STobias Grosser   ///
32132837fe3STobias Grosser   /// The kernel function takes as arguments:
32232837fe3STobias Grosser   ///
32332837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
324f6044bd0STobias Grosser   ///   - Host iterators
325c84a1995STobias Grosser   ///   - Parameters
32632837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
32732837fe3STobias Grosser   ///
32832837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
329edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
330edb885cbSTobias Grosser   ///
33132837fe3STobias Grosser   /// @returns The newly declared function.
332edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
333edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
33432837fe3STobias Grosser 
335472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
336472f9654STobias Grosser   ///
337472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
338472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
339472f9654STobias Grosser 
340b513b491STobias Grosser   /// Create a global-to-shared or shared-to-global copy statement.
341b513b491STobias Grosser   ///
342b513b491STobias Grosser   /// @param CopyStmt The copy statement to generate code for
343b513b491STobias Grosser   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
344b513b491STobias Grosser 
345edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
346edb885cbSTobias Grosser   ///
347edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
348edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
349edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
350edb885cbSTobias Grosser 
3515260c041STobias Grosser   /// Create an in-kernel synchronization call.
3525260c041STobias Grosser   void createKernelSync();
3535260c041STobias Grosser 
35474dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
35574dc3cb4STobias Grosser   ///
35674dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
35774dc3cb4STobias Grosser   std::string createKernelASM();
35874dc3cb4STobias Grosser 
35974dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
36074dc3cb4STobias Grosser   ///
36174dc3cb4STobias Grosser   /// @param F The function to remove references to.
36274dc3cb4STobias Grosser   void clearDominators(Function *F);
36374dc3cb4STobias Grosser 
36474dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
36574dc3cb4STobias Grosser   ///
36674dc3cb4STobias Grosser   /// @param F The function to remove references to.
36774dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
36874dc3cb4STobias Grosser 
36974dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
37074dc3cb4STobias Grosser   ///
37174dc3cb4STobias Grosser   /// @param F The function to remove references to.
37274dc3cb4STobias Grosser   void clearLoops(Function *F);
37374dc3cb4STobias Grosser 
37432837fe3STobias Grosser   /// Finalize the generation of the kernel function.
37532837fe3STobias Grosser   ///
37632837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
37732837fe3STobias Grosser   /// dump its IR to stderr.
37857793596STobias Grosser   ///
37957793596STobias Grosser   /// @returns The Assembly string of the kernel.
38057793596STobias Grosser   std::string finalizeKernelFunction();
381fa7b0802STobias Grosser 
3827287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
383fa7b0802STobias Grosser   void allocateDeviceArrays();
384fa7b0802STobias Grosser 
3857287aeddSTobias Grosser   /// Free all allocated device arrays.
3867287aeddSTobias Grosser   void freeDeviceArrays();
3877287aeddSTobias Grosser 
388fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
389fa7b0802STobias Grosser   ///
390fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
391fa7b0802STobias Grosser   Value *createCallInitContext();
392fa7b0802STobias Grosser 
39379a947c2STobias Grosser   /// Create a call to get the device pointer for a kernel allocation.
39479a947c2STobias Grosser   ///
39579a947c2STobias Grosser   /// @param Allocation The Polly GPU allocation
39679a947c2STobias Grosser   ///
39779a947c2STobias Grosser   /// @returns The device parameter corresponding to this allocation.
39879a947c2STobias Grosser   Value *createCallGetDevicePtr(Value *Allocation);
39979a947c2STobias Grosser 
400fa7b0802STobias Grosser   /// Create a call to free the GPU context.
401fa7b0802STobias Grosser   ///
402fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
403fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
404fa7b0802STobias Grosser 
4057287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
4067287aeddSTobias Grosser   ///
4077287aeddSTobias Grosser   /// @param Size The size of memory to allocate
4087287aeddSTobias Grosser   ///
4097287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
410fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
4117287aeddSTobias Grosser 
4127287aeddSTobias Grosser   /// Create a call to free a device array.
4137287aeddSTobias Grosser   ///
4147287aeddSTobias Grosser   /// @param Array The device array to free.
4157287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
41613c78e4dSTobias Grosser 
41713c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
41813c78e4dSTobias Grosser   ///
41913c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
42013c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
42113c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
42213c78e4dSTobias Grosser                                       Value *Size);
42313c78e4dSTobias Grosser 
42413c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
42513c78e4dSTobias Grosser   ///
42613c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
42713c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
42813c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
42913c78e4dSTobias Grosser                                       Value *Size);
43057793596STobias Grosser 
43157793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
43257793596STobias Grosser   ///
43357793596STobias Grosser   /// @param Buffer The string describing the kernel.
43457793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
43557793596STobias Grosser   ///
43657793596STobias Grosser   /// @returns A pointer to a kernel object
43757793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
43857793596STobias Grosser 
43957793596STobias Grosser   /// Create a call to free a GPU kernel.
44057793596STobias Grosser   ///
44157793596STobias Grosser   /// @param GPUKernel THe kernel to free.
44257793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
44379a947c2STobias Grosser 
44479a947c2STobias Grosser   /// Create a call to launch a GPU kernel.
44579a947c2STobias Grosser   ///
44679a947c2STobias Grosser   /// @param GPUKernel  The kernel to launch.
44779a947c2STobias Grosser   /// @param GridDimX   The size of the first grid dimension.
44879a947c2STobias Grosser   /// @param GridDimY   The size of the second grid dimension.
44979a947c2STobias Grosser   /// @param GridBlockX The size of the first block dimension.
45079a947c2STobias Grosser   /// @param GridBlockY The size of the second block dimension.
45179a947c2STobias Grosser   /// @param GridBlockZ The size of the third block dimension.
45279a947c2STobias Grosser   /// @param Paramters  A pointer to an array that contains itself pointers to
45379a947c2STobias Grosser   ///                   the parameter values passed for each kernel argument.
45479a947c2STobias Grosser   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
45579a947c2STobias Grosser                               Value *GridDimY, Value *BlockDimX,
45679a947c2STobias Grosser                               Value *BlockDimY, Value *BlockDimZ,
45779a947c2STobias Grosser                               Value *Parameters);
4581fb9b64dSTobias Grosser };
4591fb9b64dSTobias Grosser 
460fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
461750160e2STobias Grosser   BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(),
462750160e2STobias Grosser                                  &*Builder.GetInsertPoint(), &DT, &LI);
463750160e2STobias Grosser   NewBB->setName("polly.acc.initialize");
464750160e2STobias Grosser   Builder.SetInsertPoint(&NewBB->front());
465750160e2STobias Grosser 
466fa7b0802STobias Grosser   GPUContext = createCallInitContext();
467fa7b0802STobias Grosser   allocateDeviceArrays();
468fa7b0802STobias Grosser }
469fa7b0802STobias Grosser 
470fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
4717287aeddSTobias Grosser   freeDeviceArrays();
472fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
473fa7b0802STobias Grosser   IslNodeBuilder::finalize();
474fa7b0802STobias Grosser }
475fa7b0802STobias Grosser 
476fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
477fa7b0802STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
478fa7b0802STobias Grosser 
479fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
480fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
48113c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
4827287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
4837287aeddSTobias Grosser     DevArrayName.append(Array->name);
484fa7b0802STobias Grosser 
48513c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
486aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(Array);
487aaabbbf8STobias Grosser     if (Offset)
488aaabbbf8STobias Grosser       ArraySize = Builder.CreateSub(
489aaabbbf8STobias Grosser           ArraySize,
490aaabbbf8STobias Grosser           Builder.CreateMul(Offset,
491aaabbbf8STobias Grosser                             Builder.getInt64(ScopArray->getElemSizeInBytes())));
4927287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
4937287aeddSTobias Grosser     DevArray->setName(DevArrayName);
49413c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
495fa7b0802STobias Grosser   }
496fa7b0802STobias Grosser 
497fa7b0802STobias Grosser   isl_ast_build_free(Build);
498fa7b0802STobias Grosser }
499fa7b0802STobias Grosser 
500c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX,
501c1c6a2a6STobias Grosser                                         Value *BlockDimY, Value *BlockDimZ) {
502c1c6a2a6STobias Grosser   auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations");
503c1c6a2a6STobias Grosser 
504c1c6a2a6STobias Grosser   for (auto &F : *M) {
505c1c6a2a6STobias Grosser     if (F.getCallingConv() != CallingConv::PTX_Kernel)
506c1c6a2a6STobias Grosser       continue;
507c1c6a2a6STobias Grosser 
508c1c6a2a6STobias Grosser     Value *V[] = {BlockDimX, BlockDimY, BlockDimZ};
509c1c6a2a6STobias Grosser 
510c1c6a2a6STobias Grosser     Metadata *Elements[] = {
511c1c6a2a6STobias Grosser         ValueAsMetadata::get(&F),   MDString::get(M->getContext(), "maxntidx"),
512c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"),
513c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"),
514c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[2]),
515c1c6a2a6STobias Grosser     };
516c1c6a2a6STobias Grosser     MDNode *Node = MDNode::get(M->getContext(), Elements);
517c1c6a2a6STobias Grosser     AnnotationNode->addOperand(Node);
518c1c6a2a6STobias Grosser   }
519c1c6a2a6STobias Grosser }
520c1c6a2a6STobias Grosser 
5217287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
52213c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
52313c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
5247287aeddSTobias Grosser }
5257287aeddSTobias Grosser 
52657793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
52757793596STobias Grosser   const char *Name = "polly_getKernel";
52857793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
52957793596STobias Grosser   Function *F = M->getFunction(Name);
53057793596STobias Grosser 
53157793596STobias Grosser   // If F is not available, declare it.
53257793596STobias Grosser   if (!F) {
53357793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
53457793596STobias Grosser     std::vector<Type *> Args;
53557793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
53657793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
53757793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
53857793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
53957793596STobias Grosser   }
54057793596STobias Grosser 
54157793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
54257793596STobias Grosser }
54357793596STobias Grosser 
54479a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
54579a947c2STobias Grosser   const char *Name = "polly_getDevicePtr";
54679a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
54779a947c2STobias Grosser   Function *F = M->getFunction(Name);
54879a947c2STobias Grosser 
54979a947c2STobias Grosser   // If F is not available, declare it.
55079a947c2STobias Grosser   if (!F) {
55179a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
55279a947c2STobias Grosser     std::vector<Type *> Args;
55379a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
55479a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
55579a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
55679a947c2STobias Grosser   }
55779a947c2STobias Grosser 
55879a947c2STobias Grosser   return Builder.CreateCall(F, {Allocation});
55979a947c2STobias Grosser }
56079a947c2STobias Grosser 
56179a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
56279a947c2STobias Grosser                                             Value *GridDimY, Value *BlockDimX,
56379a947c2STobias Grosser                                             Value *BlockDimY, Value *BlockDimZ,
56479a947c2STobias Grosser                                             Value *Parameters) {
56579a947c2STobias Grosser   const char *Name = "polly_launchKernel";
56679a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
56779a947c2STobias Grosser   Function *F = M->getFunction(Name);
56879a947c2STobias Grosser 
56979a947c2STobias Grosser   // If F is not available, declare it.
57079a947c2STobias Grosser   if (!F) {
57179a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
57279a947c2STobias Grosser     std::vector<Type *> Args;
57379a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
57479a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
57579a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
57679a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
57779a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
57879a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
57979a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
58079a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
58179a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
58279a947c2STobias Grosser   }
58379a947c2STobias Grosser 
58479a947c2STobias Grosser   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
58579a947c2STobias Grosser                          BlockDimZ, Parameters});
58679a947c2STobias Grosser }
58779a947c2STobias Grosser 
58857793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
58957793596STobias Grosser   const char *Name = "polly_freeKernel";
59057793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
59157793596STobias Grosser   Function *F = M->getFunction(Name);
59257793596STobias Grosser 
59357793596STobias Grosser   // If F is not available, declare it.
59457793596STobias Grosser   if (!F) {
59557793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
59657793596STobias Grosser     std::vector<Type *> Args;
59757793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
59857793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
59957793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
60057793596STobias Grosser   }
60157793596STobias Grosser 
60257793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
60357793596STobias Grosser }
60457793596STobias Grosser 
6057287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
6067287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
6077287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
6087287aeddSTobias Grosser   Function *F = M->getFunction(Name);
6097287aeddSTobias Grosser 
6107287aeddSTobias Grosser   // If F is not available, declare it.
6117287aeddSTobias Grosser   if (!F) {
6127287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
6137287aeddSTobias Grosser     std::vector<Type *> Args;
6147287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
6157287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
6167287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
6177287aeddSTobias Grosser   }
6187287aeddSTobias Grosser 
6197287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
6207287aeddSTobias Grosser }
6217287aeddSTobias Grosser 
622fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
623fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
624fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
625fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
626fa7b0802STobias Grosser 
627fa7b0802STobias Grosser   // If F is not available, declare it.
628fa7b0802STobias Grosser   if (!F) {
629fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
630fa7b0802STobias Grosser     std::vector<Type *> Args;
631fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
632fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
633fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
634fa7b0802STobias Grosser   }
635fa7b0802STobias Grosser 
636fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
637fa7b0802STobias Grosser }
638fa7b0802STobias Grosser 
63913c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
64013c78e4dSTobias Grosser                                                     Value *DeviceData,
64113c78e4dSTobias Grosser                                                     Value *Size) {
64213c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
64313c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
64413c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
64513c78e4dSTobias Grosser 
64613c78e4dSTobias Grosser   // If F is not available, declare it.
64713c78e4dSTobias Grosser   if (!F) {
64813c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
64913c78e4dSTobias Grosser     std::vector<Type *> Args;
65013c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
65113c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
65213c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
65313c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
65413c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
65513c78e4dSTobias Grosser   }
65613c78e4dSTobias Grosser 
65713c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
65813c78e4dSTobias Grosser }
65913c78e4dSTobias Grosser 
66013c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
66113c78e4dSTobias Grosser                                                     Value *HostData,
66213c78e4dSTobias Grosser                                                     Value *Size) {
66313c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
66413c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
66513c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
66613c78e4dSTobias Grosser 
66713c78e4dSTobias Grosser   // If F is not available, declare it.
66813c78e4dSTobias Grosser   if (!F) {
66913c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
67013c78e4dSTobias Grosser     std::vector<Type *> Args;
67113c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
67213c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
67313c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
67413c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
67513c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
67613c78e4dSTobias Grosser   }
67713c78e4dSTobias Grosser 
67813c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
67913c78e4dSTobias Grosser }
68013c78e4dSTobias Grosser 
681fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
682fa7b0802STobias Grosser   const char *Name = "polly_initContext";
683fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
684fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
685fa7b0802STobias Grosser 
686fa7b0802STobias Grosser   // If F is not available, declare it.
687fa7b0802STobias Grosser   if (!F) {
688fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
689fa7b0802STobias Grosser     std::vector<Type *> Args;
690fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
691fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
692fa7b0802STobias Grosser   }
693fa7b0802STobias Grosser 
694fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
695fa7b0802STobias Grosser }
696fa7b0802STobias Grosser 
697fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
698fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
699fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
700fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
701fa7b0802STobias Grosser 
702fa7b0802STobias Grosser   // If F is not available, declare it.
703fa7b0802STobias Grosser   if (!F) {
704fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
705fa7b0802STobias Grosser     std::vector<Type *> Args;
706fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
707fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
708fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
709fa7b0802STobias Grosser   }
710fa7b0802STobias Grosser 
711fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
712fa7b0802STobias Grosser }
713fa7b0802STobias Grosser 
7145260c041STobias Grosser /// Check if one string is a prefix of another.
7155260c041STobias Grosser ///
7165260c041STobias Grosser /// @param String The string in which to look for the prefix.
7175260c041STobias Grosser /// @param Prefix The prefix to look for.
7185260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
7195260c041STobias Grosser   return String.find(Prefix) == 0;
7205260c041STobias Grosser }
7215260c041STobias Grosser 
72213c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
72313c78e4dSTobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
72413c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
72513c78e4dSTobias Grosser 
72613c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
72713c78e4dSTobias Grosser     auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]);
72813c78e4dSTobias Grosser     isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero);
72913c78e4dSTobias Grosser 
73013c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
73113c78e4dSTobias Grosser       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]);
73213c78e4dSTobias Grosser       isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
73313c78e4dSTobias Grosser       Res = isl_ast_expr_mul(Res, Expr);
73413c78e4dSTobias Grosser     }
73513c78e4dSTobias Grosser 
73613c78e4dSTobias Grosser     Value *NumElements = ExprBuilder.create(Res);
737b79f4d39STobias Grosser     if (NumElements->getType() != ArraySize->getType())
738b79f4d39STobias Grosser       NumElements = Builder.CreateSExt(NumElements, ArraySize->getType());
73913c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
74013c78e4dSTobias Grosser   }
74113c78e4dSTobias Grosser   isl_ast_build_free(Build);
74213c78e4dSTobias Grosser   return ArraySize;
74313c78e4dSTobias Grosser }
74413c78e4dSTobias Grosser 
745aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) {
746aaabbbf8STobias Grosser   if (gpu_array_is_scalar(Array))
747aaabbbf8STobias Grosser     return nullptr;
748aaabbbf8STobias Grosser 
749aaabbbf8STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
750aaabbbf8STobias Grosser 
751aaabbbf8STobias Grosser   isl_set *Min = isl_set_lexmin(isl_set_copy(Array->extent));
752aaabbbf8STobias Grosser 
753aaabbbf8STobias Grosser   isl_set *ZeroSet = isl_set_universe(isl_set_get_space(Min));
754aaabbbf8STobias Grosser 
755aaabbbf8STobias Grosser   for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++)
756aaabbbf8STobias Grosser     ZeroSet = isl_set_fix_si(ZeroSet, isl_dim_set, i, 0);
757aaabbbf8STobias Grosser 
758aaabbbf8STobias Grosser   if (isl_set_is_subset(Min, ZeroSet)) {
759aaabbbf8STobias Grosser     isl_set_free(Min);
760aaabbbf8STobias Grosser     isl_set_free(ZeroSet);
761aaabbbf8STobias Grosser     isl_ast_build_free(Build);
762aaabbbf8STobias Grosser     return nullptr;
763aaabbbf8STobias Grosser   }
764aaabbbf8STobias Grosser   isl_set_free(ZeroSet);
765aaabbbf8STobias Grosser 
766aaabbbf8STobias Grosser   isl_ast_expr *Result =
767aaabbbf8STobias Grosser       isl_ast_expr_from_val(isl_val_int_from_si(isl_set_get_ctx(Min), 0));
768aaabbbf8STobias Grosser 
769aaabbbf8STobias Grosser   for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) {
770aaabbbf8STobias Grosser     if (i > 0) {
771aaabbbf8STobias Grosser       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i - 1]);
772aaabbbf8STobias Grosser       isl_ast_expr *BExpr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
773aaabbbf8STobias Grosser       Result = isl_ast_expr_mul(Result, BExpr);
774aaabbbf8STobias Grosser     }
775aaabbbf8STobias Grosser     isl_pw_aff *DimMin = isl_set_dim_min(isl_set_copy(Min), i);
776aaabbbf8STobias Grosser     isl_ast_expr *MExpr = isl_ast_build_expr_from_pw_aff(Build, DimMin);
777aaabbbf8STobias Grosser     Result = isl_ast_expr_add(Result, MExpr);
778aaabbbf8STobias Grosser   }
779aaabbbf8STobias Grosser 
780aaabbbf8STobias Grosser   Value *ResultValue = ExprBuilder.create(Result);
781aaabbbf8STobias Grosser   isl_set_free(Min);
782aaabbbf8STobias Grosser   isl_ast_build_free(Build);
783aaabbbf8STobias Grosser 
784aaabbbf8STobias Grosser   return ResultValue;
785aaabbbf8STobias Grosser }
786aaabbbf8STobias Grosser 
78713c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
78813c78e4dSTobias Grosser                                         enum DataDirection Direction) {
78913c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
79013c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
79113c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
79213c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
79313c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
79413c78e4dSTobias Grosser 
79513c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
796aaabbbf8STobias Grosser   Value *Offset = getArrayOffset(Array);
79713c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
79813c78e4dSTobias Grosser 
799b06ff457STobias Grosser   Value *HostPtr;
800b06ff457STobias Grosser 
801b06ff457STobias Grosser   if (gpu_array_is_scalar(Array))
802b06ff457STobias Grosser     HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
803b06ff457STobias Grosser   else
804b06ff457STobias Grosser     HostPtr = ScopArray->getBasePtr();
80513c78e4dSTobias Grosser 
806aaabbbf8STobias Grosser   if (Offset) {
807aaabbbf8STobias Grosser     HostPtr = Builder.CreatePointerCast(
808aaabbbf8STobias Grosser         HostPtr, ScopArray->getElementType()->getPointerTo());
809aaabbbf8STobias Grosser     HostPtr = Builder.CreateGEP(HostPtr, Offset);
810aaabbbf8STobias Grosser   }
811aaabbbf8STobias Grosser 
81213c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
81313c78e4dSTobias Grosser 
814aaabbbf8STobias Grosser   if (Offset) {
815aaabbbf8STobias Grosser     Size = Builder.CreateSub(
816aaabbbf8STobias Grosser         Size, Builder.CreateMul(
817aaabbbf8STobias Grosser                   Offset, Builder.getInt64(ScopArray->getElemSizeInBytes())));
818aaabbbf8STobias Grosser   }
819aaabbbf8STobias Grosser 
82013c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
82113c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
82213c78e4dSTobias Grosser   else
82313c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
82413c78e4dSTobias Grosser 
82513c78e4dSTobias Grosser   isl_id_free(Id);
82613c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
82713c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
82813c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
82913c78e4dSTobias Grosser }
83013c78e4dSTobias Grosser 
8311fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
83232837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
83332837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
83432837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
83532837fe3STobias Grosser   isl_id_free(Id);
83632837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
83732837fe3STobias Grosser 
83832837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
83932837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
84032837fe3STobias Grosser     createKernel(UserStmt);
84132837fe3STobias Grosser     isl_ast_expr_free(Expr);
84232837fe3STobias Grosser     return;
84332837fe3STobias Grosser   }
84432837fe3STobias Grosser 
84513c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
84613c78e4dSTobias Grosser     createDataTransfer(UserStmt, HOST_TO_DEVICE);
84732837fe3STobias Grosser     isl_ast_expr_free(Expr);
84813c78e4dSTobias Grosser     return;
84913c78e4dSTobias Grosser   }
85013c78e4dSTobias Grosser 
85113c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
85213c78e4dSTobias Grosser     createDataTransfer(UserStmt, DEVICE_TO_HOST);
85313c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
85438fc0aedSTobias Grosser     return;
85538fc0aedSTobias Grosser   }
85638fc0aedSTobias Grosser 
8575260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
8585260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
8595260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
8605260c041STobias Grosser   isl_id_free(Anno);
8615260c041STobias Grosser 
8625260c041STobias Grosser   switch (KernelStmt->type) {
8635260c041STobias Grosser   case ppcg_kernel_domain:
864edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
8655260c041STobias Grosser     isl_ast_node_free(UserStmt);
8665260c041STobias Grosser     return;
8675260c041STobias Grosser   case ppcg_kernel_copy:
868b513b491STobias Grosser     createKernelCopy(KernelStmt);
8695260c041STobias Grosser     isl_ast_expr_free(Expr);
8705260c041STobias Grosser     isl_ast_node_free(UserStmt);
8715260c041STobias Grosser     return;
8725260c041STobias Grosser   case ppcg_kernel_sync:
8735260c041STobias Grosser     createKernelSync();
8745260c041STobias Grosser     isl_ast_expr_free(Expr);
8755260c041STobias Grosser     isl_ast_node_free(UserStmt);
8765260c041STobias Grosser     return;
8775260c041STobias Grosser   }
8785260c041STobias Grosser 
8795260c041STobias Grosser   isl_ast_expr_free(Expr);
8805260c041STobias Grosser   isl_ast_node_free(UserStmt);
8815260c041STobias Grosser   return;
8825260c041STobias Grosser }
883b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
884b513b491STobias Grosser   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
885b513b491STobias Grosser   LocalIndex = isl_ast_expr_address_of(LocalIndex);
886b513b491STobias Grosser   Value *LocalAddr = ExprBuilder.create(LocalIndex);
887b513b491STobias Grosser   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
888b513b491STobias Grosser   Index = isl_ast_expr_address_of(Index);
889b513b491STobias Grosser   Value *GlobalAddr = ExprBuilder.create(Index);
890b513b491STobias Grosser 
891b513b491STobias Grosser   if (KernelStmt->u.c.read) {
892b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read");
893b513b491STobias Grosser     Builder.CreateStore(Load, LocalAddr);
894b513b491STobias Grosser   } else {
895b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write");
896b513b491STobias Grosser     Builder.CreateStore(Load, GlobalAddr);
897b513b491STobias Grosser   }
898b513b491STobias Grosser }
8995260c041STobias Grosser 
900edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
901edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
902edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
903edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
904edb885cbSTobias Grosser 
905edb885cbSTobias Grosser   LoopToScevMapT LTS;
906edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
907edb885cbSTobias Grosser 
908edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
909edb885cbSTobias Grosser 
910edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
911edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
912edb885cbSTobias Grosser   else
913a82c4b5dSTobias Grosser     RegionGen.copyStmt(*Stmt, LTS, Indexes);
914edb885cbSTobias Grosser }
915edb885cbSTobias Grosser 
9165260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
9175260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9185260c041STobias Grosser   auto *Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
9195260c041STobias Grosser   Builder.CreateCall(Sync, {});
9205260c041STobias Grosser }
9215260c041STobias Grosser 
922edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
923edb885cbSTobias Grosser ///
924edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
925edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
926edb885cbSTobias Grosser ///
927edb885cbSTobias Grosser /// @param Node The node to collect references for.
928edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
929edb885cbSTobias Grosser ///
930edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
931edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
932edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
933edb885cbSTobias Grosser     return isl_bool_true;
934edb885cbSTobias Grosser 
935edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
936edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
937edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
938edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
939edb885cbSTobias Grosser   isl_id_free(Id);
940edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
941edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
942edb885cbSTobias Grosser 
943edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
944edb885cbSTobias Grosser     return isl_bool_true;
945edb885cbSTobias Grosser 
946edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
947edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
948edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
949edb885cbSTobias Grosser   isl_id_free(Id);
950edb885cbSTobias Grosser 
95100bb5a99STobias Grosser   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
952edb885cbSTobias Grosser 
953edb885cbSTobias Grosser   return isl_bool_true;
954edb885cbSTobias Grosser }
955edb885cbSTobias Grosser 
956edb885cbSTobias Grosser SetVector<Value *> GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
957edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
958edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
959edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
960edb885cbSTobias Grosser   SubtreeReferences References = {
961edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
962edb885cbSTobias Grosser 
963edb885cbSTobias Grosser   for (const auto &I : IDToValue)
964edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
965edb885cbSTobias Grosser 
966edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
967edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
968edb885cbSTobias Grosser 
969edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
970edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
971edb885cbSTobias Grosser 
972edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
973d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
974edb885cbSTobias Grosser 
975edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
976edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
977edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
978edb885cbSTobias Grosser     assert(IDToValue.count(Id));
979edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
980edb885cbSTobias Grosser     SubtreeValues.remove(Val);
981edb885cbSTobias Grosser     isl_id_free(Id);
982edb885cbSTobias Grosser   }
983edb885cbSTobias Grosser   isl_space_free(Space);
984edb885cbSTobias Grosser 
985edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
986edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
987edb885cbSTobias Grosser     assert(IDToValue.count(Id));
988edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
989edb885cbSTobias Grosser     SubtreeValues.remove(Val);
990edb885cbSTobias Grosser     isl_id_free(Id);
991edb885cbSTobias Grosser   }
992edb885cbSTobias Grosser 
993edb885cbSTobias Grosser   return SubtreeValues;
994edb885cbSTobias Grosser }
995edb885cbSTobias Grosser 
99674dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
99774dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
99874dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
99974dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
100074dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
100174dc3cb4STobias Grosser 
100274dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
100374dc3cb4STobias Grosser     DT.eraseNode(BB);
100474dc3cb4STobias Grosser }
100574dc3cb4STobias Grosser 
100674dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
100774dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
100874dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
100974dc3cb4STobias Grosser     if (L)
101074dc3cb4STobias Grosser       SE.forgetLoop(L);
101174dc3cb4STobias Grosser   }
101274dc3cb4STobias Grosser }
101374dc3cb4STobias Grosser 
101474dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
101574dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
101674dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
101774dc3cb4STobias Grosser     if (L)
101874dc3cb4STobias Grosser       SE.forgetLoop(L);
101974dc3cb4STobias Grosser     LI.removeBlock(&BB);
102074dc3cb4STobias Grosser   }
102174dc3cb4STobias Grosser }
102274dc3cb4STobias Grosser 
102379a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
102479a947c2STobias Grosser   std::vector<Value *> Sizes;
102579a947c2STobias Grosser   isl_ast_build *Context = isl_ast_build_from_context(S.getContext());
102679a947c2STobias Grosser 
102779a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
102879a947c2STobias Grosser     isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i);
102979a947c2STobias Grosser     isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size);
103079a947c2STobias Grosser     Value *Res = ExprBuilder.create(GridSize);
103179a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
103279a947c2STobias Grosser     Sizes.push_back(Res);
103379a947c2STobias Grosser   }
103479a947c2STobias Grosser   isl_ast_build_free(Context);
103579a947c2STobias Grosser 
103679a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
103779a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
103879a947c2STobias Grosser 
103979a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
104079a947c2STobias Grosser }
104179a947c2STobias Grosser 
104279a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
104379a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
104479a947c2STobias Grosser   std::vector<Value *> Sizes;
104579a947c2STobias Grosser 
104679a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
104779a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
104879a947c2STobias Grosser     Sizes.push_back(Res);
104979a947c2STobias Grosser   }
105079a947c2STobias Grosser 
105179a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
105279a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
105379a947c2STobias Grosser 
105479a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
105579a947c2STobias Grosser }
105679a947c2STobias Grosser 
105757693272STobias Grosser Value *
105857693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
105957693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
10604e18d71cSTobias Grosser   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(),
10614e18d71cSTobias Grosser                                  std::distance(F->arg_begin(), F->arg_end()));
106279a947c2STobias Grosser 
106379a947c2STobias Grosser   BasicBlock *EntryBlock =
106479a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
106579a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
106679a947c2STobias Grosser   Instruction *Parameters =
106779a947c2STobias Grosser       new AllocaInst(ArrayTy, Launch + "_params", EntryBlock->getTerminator());
106879a947c2STobias Grosser 
106979a947c2STobias Grosser   int Index = 0;
107079a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
107179a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
107279a947c2STobias Grosser       continue;
107379a947c2STobias Grosser 
107479a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
107579a947c2STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
107679a947c2STobias Grosser 
10770a893f7dSTobias Grosser     Value *DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
107879a947c2STobias Grosser     DevArray = createCallGetDevicePtr(DevArray);
1079aaabbbf8STobias Grosser 
1080aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(&Prog->array[i]);
1081aaabbbf8STobias Grosser 
1082aaabbbf8STobias Grosser     if (Offset) {
1083aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(
1084aaabbbf8STobias Grosser           DevArray, SAI->getElementType()->getPointerTo());
1085aaabbbf8STobias Grosser       DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset));
1086aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1087aaabbbf8STobias Grosser     }
1088*fe74a7a1STobias Grosser     Value *Slot = Builder.CreateGEP(
1089*fe74a7a1STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1090aaabbbf8STobias Grosser 
1091*fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1092*fe74a7a1STobias Grosser       Value *ValPtr = BlockGen.getOrCreateAlloca(SAI);
1093*fe74a7a1STobias Grosser       Value *ValPtrCast =
1094*fe74a7a1STobias Grosser           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1095*fe74a7a1STobias Grosser       Builder.CreateStore(ValPtrCast, Slot);
1096*fe74a7a1STobias Grosser     } else {
109779a947c2STobias Grosser       Instruction *Param = new AllocaInst(
109879a947c2STobias Grosser           Builder.getInt8PtrTy(), Launch + "_param_" + std::to_string(Index),
109979a947c2STobias Grosser           EntryBlock->getTerminator());
110079a947c2STobias Grosser       Builder.CreateStore(DevArray, Param);
110179a947c2STobias Grosser       Value *ParamTyped =
110279a947c2STobias Grosser           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
110379a947c2STobias Grosser       Builder.CreateStore(ParamTyped, Slot);
1104*fe74a7a1STobias Grosser     }
110579a947c2STobias Grosser     Index++;
110679a947c2STobias Grosser   }
110779a947c2STobias Grosser 
1108a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1109a490147cSTobias Grosser 
1110a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1111a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1112a490147cSTobias Grosser     Value *Val = IDToValue[Id];
1113a490147cSTobias Grosser     isl_id_free(Id);
1114a490147cSTobias Grosser     Instruction *Param = new AllocaInst(
1115a490147cSTobias Grosser         Val->getType(), Launch + "_param_" + std::to_string(Index),
1116a490147cSTobias Grosser         EntryBlock->getTerminator());
1117a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
1118a490147cSTobias Grosser     Value *Slot = Builder.CreateGEP(
1119a490147cSTobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1120a490147cSTobias Grosser     Value *ParamTyped =
1121a490147cSTobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1122a490147cSTobias Grosser     Builder.CreateStore(ParamTyped, Slot);
1123a490147cSTobias Grosser     Index++;
1124a490147cSTobias Grosser   }
1125a490147cSTobias Grosser 
1126d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1127d8b94bcaSTobias Grosser 
1128d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
1129d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1130d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
1131d8b94bcaSTobias Grosser     isl_id_free(Id);
1132d8b94bcaSTobias Grosser     Instruction *Param = new AllocaInst(
1133d8b94bcaSTobias Grosser         Val->getType(), Launch + "_param_" + std::to_string(Index),
1134d8b94bcaSTobias Grosser         EntryBlock->getTerminator());
1135d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
1136d8b94bcaSTobias Grosser     Value *Slot = Builder.CreateGEP(
1137d8b94bcaSTobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1138d8b94bcaSTobias Grosser     Value *ParamTyped =
1139d8b94bcaSTobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1140d8b94bcaSTobias Grosser     Builder.CreateStore(ParamTyped, Slot);
1141d8b94bcaSTobias Grosser     Index++;
1142d8b94bcaSTobias Grosser   }
1143d8b94bcaSTobias Grosser 
114457693272STobias Grosser   for (auto Val : SubtreeValues) {
114557693272STobias Grosser     Instruction *Param = new AllocaInst(
114657693272STobias Grosser         Val->getType(), Launch + "_param_" + std::to_string(Index),
114757693272STobias Grosser         EntryBlock->getTerminator());
114857693272STobias Grosser     Builder.CreateStore(Val, Param);
114957693272STobias Grosser     Value *Slot = Builder.CreateGEP(
115057693272STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
115157693272STobias Grosser     Value *ParamTyped =
115257693272STobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
115357693272STobias Grosser     Builder.CreateStore(ParamTyped, Slot);
115457693272STobias Grosser     Index++;
115557693272STobias Grosser   }
115657693272STobias Grosser 
115779a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
115879a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
115979a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
116079a947c2STobias Grosser }
116179a947c2STobias Grosser 
116232837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
116332837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
116432837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
116532837fe3STobias Grosser   isl_id_free(Id);
116632837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
116732837fe3STobias Grosser 
1168c1c6a2a6STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1169c1c6a2a6STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1170c1c6a2a6STobias Grosser 
1171edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel);
1172edb885cbSTobias Grosser 
117332837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
117432837fe3STobias Grosser 
117532837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1176472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1177edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
1178b06ff457STobias Grosser   BlockGenerator::ScalarAllocaMapTy HostScalarMap = ScalarMap;
1179b06ff457STobias Grosser   BlockGenerator::ScalarAllocaMapTy HostPHIOpMap = PHIOpMap;
1180b06ff457STobias Grosser   ScalarMap.clear();
1181b06ff457STobias Grosser   PHIOpMap.clear();
118232837fe3STobias Grosser 
1183edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1184edb885cbSTobias Grosser 
1185edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
1186edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
1187edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
1188edb885cbSTobias Grosser   for (const Loop *L : Loops) {
1189edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1190edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1191edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1192edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1193edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1194edb885cbSTobias Grosser     SubtreeValues.insert(V);
1195edb885cbSTobias Grosser   }
1196edb885cbSTobias Grosser 
1197edb885cbSTobias Grosser   createKernelFunction(Kernel, SubtreeValues);
119832837fe3STobias Grosser 
119959ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
120059ab0705STobias Grosser 
120174dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
1202c1c6a2a6STobias Grosser   addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
120374dc3cb4STobias Grosser   clearDominators(F);
120474dc3cb4STobias Grosser   clearScalarEvolution(F);
120574dc3cb4STobias Grosser   clearLoops(F);
120674dc3cb4STobias Grosser 
120732837fe3STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
1208472f9654STobias Grosser   IDToValue = HostIDs;
120932837fe3STobias Grosser 
1210b06ff457STobias Grosser   ValueMap = std::move(HostValueMap);
1211b06ff457STobias Grosser   ScalarMap = std::move(HostScalarMap);
1212b06ff457STobias Grosser   PHIOpMap = std::move(HostPHIOpMap);
1213edb885cbSTobias Grosser   EscapeMap.clear();
1214edb885cbSTobias Grosser   IDToSAI.clear();
121574dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
121674dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
121774dc3cb4STobias Grosser     S.invalidateScopArrayInfo(BasePtr, ScopArrayInfo::MK_Array);
121874dc3cb4STobias Grosser   LocalArrays.clear();
1219edb885cbSTobias Grosser 
122057693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
122179a947c2STobias Grosser 
122257793596STobias Grosser   std::string ASMString = finalizeKernelFunction();
122357793596STobias Grosser   std::string Name = "kernel_" + std::to_string(Kernel->id);
122457793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
122557793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
122657793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
122779a947c2STobias Grosser 
122879a947c2STobias Grosser   Value *GridDimX, *GridDimY;
122979a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
123079a947c2STobias Grosser 
123179a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
123279a947c2STobias Grosser                          BlockDimZ, Parameters);
123357793596STobias Grosser   createCallFreeKernel(GPUKernel);
1234b513b491STobias Grosser 
1235b513b491STobias Grosser   for (auto Id : KernelIds)
1236b513b491STobias Grosser     isl_id_free(Id);
1237b513b491STobias Grosser 
1238b513b491STobias Grosser   KernelIds.clear();
123932837fe3STobias Grosser }
124032837fe3STobias Grosser 
124132837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
124232837fe3STobias Grosser ///
124332837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
124432837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
124532837fe3STobias Grosser   std::string Ret = "e";
124632837fe3STobias Grosser 
124732837fe3STobias Grosser   if (!is64Bit)
124832837fe3STobias Grosser     Ret += "-p:32:32";
124932837fe3STobias Grosser 
125032837fe3STobias Grosser   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
125132837fe3STobias Grosser 
125232837fe3STobias Grosser   return Ret;
125332837fe3STobias Grosser }
125432837fe3STobias Grosser 
1255edb885cbSTobias Grosser Function *
1256edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1257edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
125832837fe3STobias Grosser   std::vector<Type *> Args;
125932837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
126032837fe3STobias Grosser 
126132837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
126232837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
126332837fe3STobias Grosser       continue;
126432837fe3STobias Grosser 
1265*fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1266*fe74a7a1STobias Grosser       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1267*fe74a7a1STobias Grosser       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
1268*fe74a7a1STobias Grosser       Args.push_back(SAI->getElementType());
1269*fe74a7a1STobias Grosser     } else {
127032837fe3STobias Grosser       Args.push_back(Builder.getInt8PtrTy());
127132837fe3STobias Grosser     }
1272*fe74a7a1STobias Grosser   }
127332837fe3STobias Grosser 
1274f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1275f6044bd0STobias Grosser 
1276f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++)
1277f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
1278f6044bd0STobias Grosser 
1279c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1280c84a1995STobias Grosser 
1281cf66ef26STobias Grosser   for (long i = 0; i < NumVars; i++) {
1282cf66ef26STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1283cf66ef26STobias Grosser     Value *Val = IDToValue[Id];
1284cf66ef26STobias Grosser     isl_id_free(Id);
1285cf66ef26STobias Grosser     Args.push_back(Val->getType());
1286cf66ef26STobias Grosser   }
1287c84a1995STobias Grosser 
1288edb885cbSTobias Grosser   for (auto *V : SubtreeValues)
1289edb885cbSTobias Grosser     Args.push_back(V->getType());
1290edb885cbSTobias Grosser 
129132837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
129232837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
129332837fe3STobias Grosser                               GPUModule.get());
129432837fe3STobias Grosser   FN->setCallingConv(CallingConv::PTX_Kernel);
129532837fe3STobias Grosser 
129632837fe3STobias Grosser   auto Arg = FN->arg_begin();
129732837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
129832837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
129932837fe3STobias Grosser       continue;
130032837fe3STobias Grosser 
1301edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
1302edb885cbSTobias Grosser 
1303edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1304edb885cbSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1305edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
1306edb885cbSTobias Grosser     Value *Val = &*Arg;
1307edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1308edb885cbSTobias Grosser     isl_ast_build *Build =
1309edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
1310f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1311edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1312edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
1313edb885cbSTobias Grosser           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
1314edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
1315edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
1316edb885cbSTobias Grosser     }
1317edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
1318edb885cbSTobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, ScopArrayInfo::MK_Array);
131974dc3cb4STobias Grosser     LocalArrays.push_back(Val);
1320edb885cbSTobias Grosser 
1321edb885cbSTobias Grosser     isl_ast_build_free(Build);
1322b513b491STobias Grosser     KernelIds.push_back(Id);
1323edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
132432837fe3STobias Grosser     Arg++;
132532837fe3STobias Grosser   }
132632837fe3STobias Grosser 
1327f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1328f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1329f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
1330f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
1331f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1332f6044bd0STobias Grosser     Arg++;
1333f6044bd0STobias Grosser   }
1334f6044bd0STobias Grosser 
1335c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
1336c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1337c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
133812453403STobias Grosser     Value *Val = IDToValue[Id];
133912453403STobias Grosser     ValueMap[Val] = &*Arg;
1340c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
1341c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1342c84a1995STobias Grosser     Arg++;
1343c84a1995STobias Grosser   }
1344c84a1995STobias Grosser 
1345edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
1346edb885cbSTobias Grosser     Arg->setName(V->getName());
1347edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
1348edb885cbSTobias Grosser     Arg++;
1349edb885cbSTobias Grosser   }
1350edb885cbSTobias Grosser 
135132837fe3STobias Grosser   return FN;
135232837fe3STobias Grosser }
135332837fe3STobias Grosser 
1354472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
1355472f9654STobias Grosser   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
1356472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
1357472f9654STobias Grosser 
1358472f9654STobias Grosser   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
1359472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
1360472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
1361472f9654STobias Grosser 
1362472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1363472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
1364472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1365472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1366472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1367472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1368472f9654STobias Grosser     IDToValue[Id] = Val;
1369472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1370472f9654STobias Grosser   };
1371472f9654STobias Grosser 
1372472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
1373472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1374472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
1375472f9654STobias Grosser   }
1376472f9654STobias Grosser 
1377472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
1378472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1379472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
1380472f9654STobias Grosser   }
1381472f9654STobias Grosser }
1382472f9654STobias Grosser 
138300bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
138400bb5a99STobias Grosser   auto Arg = FN->arg_begin();
138500bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
138600bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
138700bb5a99STobias Grosser       continue;
138800bb5a99STobias Grosser 
138900bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
139000bb5a99STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
139100bb5a99STobias Grosser     isl_id_free(Id);
139200bb5a99STobias Grosser 
139300bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
139400bb5a99STobias Grosser       Arg++;
139500bb5a99STobias Grosser       continue;
139600bb5a99STobias Grosser     }
139700bb5a99STobias Grosser 
1398*fe74a7a1STobias Grosser     Value *Val = &*Arg;
1399*fe74a7a1STobias Grosser 
1400*fe74a7a1STobias Grosser     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
140100bb5a99STobias Grosser       Type *TypePtr = SAI->getElementType()->getPointerTo();
1402*fe74a7a1STobias Grosser       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
1403*fe74a7a1STobias Grosser       Val = Builder.CreateLoad(TypedArgPtr);
1404*fe74a7a1STobias Grosser     }
1405*fe74a7a1STobias Grosser 
1406*fe74a7a1STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
140700bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
140800bb5a99STobias Grosser 
140900bb5a99STobias Grosser     Arg++;
141000bb5a99STobias Grosser   }
141100bb5a99STobias Grosser }
141200bb5a99STobias Grosser 
1413b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
1414b513b491STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1415b513b491STobias Grosser 
1416b513b491STobias Grosser   for (int i = 0; i < Kernel->n_var; ++i) {
1417b513b491STobias Grosser     struct ppcg_kernel_var &Var = Kernel->var[i];
1418b513b491STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
1419b513b491STobias Grosser     Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType();
1420b513b491STobias Grosser 
1421f919d8b3STobias Grosser     Type *ArrayTy = EleTy;
1422b513b491STobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1423b513b491STobias Grosser 
1424f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1425928d7573STobias Grosser     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
1426b513b491STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1427f919d8b3STobias Grosser       long Bound = isl_val_get_num_si(Val);
1428b513b491STobias Grosser       isl_val_free(Val);
1429b513b491STobias Grosser       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
1430928d7573STobias Grosser     }
1431928d7573STobias Grosser 
1432928d7573STobias Grosser     for (int j = Var.array->n_index - 1; j >= 0; --j) {
1433928d7573STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1434928d7573STobias Grosser       long Bound = isl_val_get_num_si(Val);
1435928d7573STobias Grosser       isl_val_free(Val);
1436b513b491STobias Grosser       ArrayTy = ArrayType::get(ArrayTy, Bound);
1437b513b491STobias Grosser     }
1438b513b491STobias Grosser 
1439130ca30fSTobias Grosser     const ScopArrayInfo *SAI;
1440130ca30fSTobias Grosser     Value *Allocation;
1441130ca30fSTobias Grosser     if (Var.type == ppcg_access_shared) {
1442130ca30fSTobias Grosser       auto GlobalVar = new GlobalVariable(
1443130ca30fSTobias Grosser           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
1444130ca30fSTobias Grosser           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
1445130ca30fSTobias Grosser       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
1446f919d8b3STobias Grosser       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
1447f919d8b3STobias Grosser 
1448130ca30fSTobias Grosser       Allocation = GlobalVar;
1449130ca30fSTobias Grosser     } else if (Var.type == ppcg_access_private) {
1450130ca30fSTobias Grosser       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
1451130ca30fSTobias Grosser     } else {
1452130ca30fSTobias Grosser       llvm_unreachable("unknown variable type");
1453130ca30fSTobias Grosser     }
1454130ca30fSTobias Grosser     SAI = S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes,
1455130ca30fSTobias Grosser                                      ScopArrayInfo::MK_Array);
1456b513b491STobias Grosser     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
1457130ca30fSTobias Grosser     IDToValue[Id] = Allocation;
1458130ca30fSTobias Grosser     LocalArrays.push_back(Allocation);
1459b513b491STobias Grosser     KernelIds.push_back(Id);
1460b513b491STobias Grosser     IDToSAI[Id] = SAI;
1461b513b491STobias Grosser   }
1462b513b491STobias Grosser }
1463b513b491STobias Grosser 
1464edb885cbSTobias Grosser void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel,
1465edb885cbSTobias Grosser                                           SetVector<Value *> &SubtreeValues) {
146632837fe3STobias Grosser 
146732837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
146832837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
146932837fe3STobias Grosser   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
147032837fe3STobias Grosser   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
147132837fe3STobias Grosser 
1472edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
147332837fe3STobias Grosser 
147459ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
147532837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
147632837fe3STobias Grosser 
147759ab0705STobias Grosser   DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
147859ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
147959ab0705STobias Grosser 
148032837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
148132837fe3STobias Grosser   Builder.CreateRetVoid();
148232837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
1483472f9654STobias Grosser 
1484629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
1485629109b6STobias Grosser 
148600bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
1487b513b491STobias Grosser   createKernelVariables(Kernel, FN);
1488472f9654STobias Grosser   insertKernelIntrinsics(Kernel);
148932837fe3STobias Grosser }
149032837fe3STobias Grosser 
149174dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
149274dc3cb4STobias Grosser   llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda"));
149374dc3cb4STobias Grosser   std::string ErrMsg;
149474dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
149574dc3cb4STobias Grosser 
149674dc3cb4STobias Grosser   if (!GPUTarget) {
149774dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
149874dc3cb4STobias Grosser     return "";
149974dc3cb4STobias Grosser   }
150074dc3cb4STobias Grosser 
150174dc3cb4STobias Grosser   TargetOptions Options;
150274dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
150374dc3cb4STobias Grosser   std::unique_ptr<TargetMachine> TargetM(
150474dc3cb4STobias Grosser       GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "",
150574dc3cb4STobias Grosser                                      Options, Optional<Reloc::Model>()));
150674dc3cb4STobias Grosser 
150774dc3cb4STobias Grosser   SmallString<0> ASMString;
150874dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
150974dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
151074dc3cb4STobias Grosser 
151174dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
151274dc3cb4STobias Grosser 
151374dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
151474dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
151574dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
151674dc3cb4STobias Grosser     return "";
151774dc3cb4STobias Grosser   }
151874dc3cb4STobias Grosser 
151974dc3cb4STobias Grosser   PM.run(*GPUModule);
152074dc3cb4STobias Grosser 
152174dc3cb4STobias Grosser   return ASMStream.str();
152274dc3cb4STobias Grosser }
152374dc3cb4STobias Grosser 
152457793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
15255857b701STobias Grosser   if (verifyModule(*GPUModule)) {
15265857b701STobias Grosser     BuildSuccessful = false;
15275857b701STobias Grosser     return "";
15285857b701STobias Grosser   }
152932837fe3STobias Grosser 
153032837fe3STobias Grosser   if (DumpKernelIR)
153132837fe3STobias Grosser     outs() << *GPUModule << "\n";
153232837fe3STobias Grosser 
15339a18d559STobias Grosser   // Optimize module.
15349a18d559STobias Grosser   llvm::legacy::PassManager OptPasses;
15359a18d559STobias Grosser   PassManagerBuilder PassBuilder;
15369a18d559STobias Grosser   PassBuilder.OptLevel = 3;
15379a18d559STobias Grosser   PassBuilder.SizeLevel = 0;
15389a18d559STobias Grosser   PassBuilder.populateModulePassManager(OptPasses);
15399a18d559STobias Grosser   OptPasses.run(*GPUModule);
15409a18d559STobias Grosser 
154174dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
154274dc3cb4STobias Grosser 
154374dc3cb4STobias Grosser   if (DumpKernelASM)
154474dc3cb4STobias Grosser     outs() << Assembly << "\n";
154574dc3cb4STobias Grosser 
154632837fe3STobias Grosser   GPUModule.release();
1547472f9654STobias Grosser   KernelIDs.clear();
154857793596STobias Grosser 
154957793596STobias Grosser   return Assembly;
155032837fe3STobias Grosser }
155132837fe3STobias Grosser 
15529dfe4e7cSTobias Grosser namespace {
15539dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
15549dfe4e7cSTobias Grosser public:
15559dfe4e7cSTobias Grosser   static char ID;
15569dfe4e7cSTobias Grosser 
1557e938517eSTobias Grosser   /// The scop that is currently processed.
1558e938517eSTobias Grosser   Scop *S;
1559e938517eSTobias Grosser 
156038fc0aedSTobias Grosser   LoopInfo *LI;
156138fc0aedSTobias Grosser   DominatorTree *DT;
156238fc0aedSTobias Grosser   ScalarEvolution *SE;
156338fc0aedSTobias Grosser   const DataLayout *DL;
156438fc0aedSTobias Grosser   RegionInfo *RI;
156538fc0aedSTobias Grosser 
15669dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
15679dfe4e7cSTobias Grosser 
1568e938517eSTobias Grosser   /// Construct compilation options for PPCG.
1569e938517eSTobias Grosser   ///
1570e938517eSTobias Grosser   /// @returns The compilation options.
1571e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
1572e938517eSTobias Grosser     auto DebugOptions =
1573e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
1574e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
1575e938517eSTobias Grosser 
1576e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
1577e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
1578e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
1579e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
15808950ceadSTobias Grosser     DebugOptions->verbose = false;
1581e938517eSTobias Grosser 
1582e938517eSTobias Grosser     Options->debug = DebugOptions;
1583e938517eSTobias Grosser 
1584e938517eSTobias Grosser     Options->reschedule = true;
1585e938517eSTobias Grosser     Options->scale_tile_loops = false;
1586e938517eSTobias Grosser     Options->wrap = false;
1587e938517eSTobias Grosser 
1588e938517eSTobias Grosser     Options->non_negative_parameters = false;
1589e938517eSTobias Grosser     Options->ctx = nullptr;
1590e938517eSTobias Grosser     Options->sizes = nullptr;
1591e938517eSTobias Grosser 
15924eaedde5STobias Grosser     Options->tile_size = 32;
15934eaedde5STobias Grosser 
1594130ca30fSTobias Grosser     Options->use_private_memory = PrivateMemory;
1595b513b491STobias Grosser     Options->use_shared_memory = SharedMemory;
1596b513b491STobias Grosser     Options->max_shared_memory = 48 * 1024;
1597e938517eSTobias Grosser 
1598e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
1599e938517eSTobias Grosser     Options->openmp = false;
1600e938517eSTobias Grosser     Options->linearize_device_arrays = true;
1601e938517eSTobias Grosser     Options->live_range_reordering = false;
1602e938517eSTobias Grosser 
1603e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
1604e938517eSTobias Grosser     Options->opencl_use_gpu = false;
1605e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
1606e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
1607e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
1608e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
1609e938517eSTobias Grosser 
1610e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
1611e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
1612e938517eSTobias Grosser 
1613e938517eSTobias Grosser     return Options;
1614e938517eSTobias Grosser   }
1615e938517eSTobias Grosser 
1616f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
1617f384594dSTobias Grosser   ///
1618f384594dSTobias Grosser   /// Instead of a normal access of the form:
1619f384594dSTobias Grosser   ///
1620f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
1621f384594dSTobias Grosser   ///
1622f384594dSTobias Grosser   /// a tagged access has the form
1623f384594dSTobias Grosser   ///
1624f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
1625f384594dSTobias Grosser   ///
1626f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
1627f384594dSTobias Grosser   /// triggered the access.
1628f384594dSTobias Grosser   ///
1629f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
1630f384594dSTobias Grosser   ///
1631f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
1632f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
1633f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
1634f384594dSTobias Grosser 
1635f384594dSTobias Grosser     for (auto &Stmt : *S)
1636f384594dSTobias Grosser       for (auto &Acc : Stmt)
1637f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
1638f384594dSTobias Grosser           isl_map *Relation = Acc->getAccessRelation();
1639f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
1640f384594dSTobias Grosser 
1641f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
1642f384594dSTobias Grosser           Space = isl_space_range(Space);
1643f384594dSTobias Grosser           Space = isl_space_from_range(Space);
16446293ba69STobias Grosser           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1645f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
1646f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
1647f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
1648f384594dSTobias Grosser         }
1649f384594dSTobias Grosser 
1650f384594dSTobias Grosser     return Accesses;
1651f384594dSTobias Grosser   }
1652f384594dSTobias Grosser 
1653f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
1654f384594dSTobias Grosser   ///
1655f384594dSTobias Grosser   /// @see getTaggedAccesses
1656f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
1657f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
1658f384594dSTobias Grosser   }
1659f384594dSTobias Grosser 
1660f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
1661f384594dSTobias Grosser   ///
1662f384594dSTobias Grosser   /// @see getTaggedAccesses
1663f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
1664f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
1665f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
1666f384594dSTobias Grosser   }
1667f384594dSTobias Grosser 
1668f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
1669f384594dSTobias Grosser   ///
1670f384594dSTobias Grosser   /// @see getTaggedAccesses
1671f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
1672f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
1673f384594dSTobias Grosser   }
1674f384594dSTobias Grosser 
1675aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
1676aef5196fSTobias Grosser   ///
1677aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
1678aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
1679aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
1680aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
1681aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
1682aef5196fSTobias Grosser   /// the data format that ppcg expects.
1683aef5196fSTobias Grosser   ///
1684aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
1685aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
1686aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
1687bd81a7eeSTobias Grosser         S->getIslCtx(),
1688bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
1689aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
1690aef5196fSTobias Grosser     auto *Space = S->getParamSpace();
1691aef5196fSTobias Grosser 
1692aef5196fSTobias Grosser     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
1693aef5196fSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
1694aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1695aef5196fSTobias Grosser     }
1696aef5196fSTobias Grosser 
1697aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
1698d7754a12SRoman Gareev       auto Id = Array->getBasePtrId();
1699aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1700aef5196fSTobias Grosser     }
1701aef5196fSTobias Grosser 
1702aef5196fSTobias Grosser     isl_space_free(Space);
1703aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
1704aef5196fSTobias Grosser 
1705aef5196fSTobias Grosser     return Names;
1706aef5196fSTobias Grosser   }
1707aef5196fSTobias Grosser 
1708e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
1709e938517eSTobias Grosser   ///
1710f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
1711f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
1712f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
1713f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
1714e938517eSTobias Grosser   ///
1715e938517eSTobias Grosser   /// @returns A new ppcg scop.
1716e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
1717e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
1718e938517eSTobias Grosser 
1719e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
1720e938517eSTobias Grosser 
1721e938517eSTobias Grosser     PPCGScop->start = 0;
1722e938517eSTobias Grosser     PPCGScop->end = 0;
1723e938517eSTobias Grosser 
1724f384594dSTobias Grosser     PPCGScop->context = S->getContext();
1725f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
1726e938517eSTobias Grosser     PPCGScop->call = nullptr;
1727f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
1728f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
1729e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
1730f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
1731f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
1732f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
1733f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
1734e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
1735f384594dSTobias Grosser     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
1736e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
1737e938517eSTobias Grosser 
1738e938517eSTobias Grosser     PPCGScop->independence = nullptr;
1739e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
1740e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
1741e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
1742e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
1743e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
1744e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
1745e938517eSTobias Grosser 
1746f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
1747aef5196fSTobias Grosser     PPCGScop->names = getNames();
1748e938517eSTobias Grosser 
1749e938517eSTobias Grosser     PPCGScop->pet = nullptr;
1750e938517eSTobias Grosser 
1751f384594dSTobias Grosser     compute_tagger(PPCGScop);
1752f384594dSTobias Grosser     compute_dependences(PPCGScop);
1753f384594dSTobias Grosser 
1754e938517eSTobias Grosser     return PPCGScop;
1755e938517eSTobias Grosser   }
1756e938517eSTobias Grosser 
175760f63b49STobias Grosser   /// Collect the array acesses in a statement.
175860f63b49STobias Grosser   ///
175960f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
176060f63b49STobias Grosser   ///
176160f63b49STobias Grosser   /// @returns A list of array accesses.
176260f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
176360f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
176460f63b49STobias Grosser 
176560f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
176660f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
176760f63b49STobias Grosser       Access->read = Acc->isRead();
176860f63b49STobias Grosser       Access->write = Acc->isWrite();
176960f63b49STobias Grosser       Access->access = Acc->getAccessRelation();
177060f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
177160f63b49STobias Grosser       Space = isl_space_range(Space);
177260f63b49STobias Grosser       Space = isl_space_from_range(Space);
17736293ba69STobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
177460f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
177560f63b49STobias Grosser       Access->tagged_access =
177660f63b49STobias Grosser           isl_map_domain_product(Acc->getAccessRelation(), Universe);
1777b513b491STobias Grosser       Access->exact_write = !Acc->isMayWrite();
177860f63b49STobias Grosser       Access->ref_id = Acc->getId();
177960f63b49STobias Grosser       Access->next = Accesses;
1780b513b491STobias Grosser       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
178160f63b49STobias Grosser       Accesses = Access;
178260f63b49STobias Grosser     }
178360f63b49STobias Grosser 
178460f63b49STobias Grosser     return Accesses;
178560f63b49STobias Grosser   }
178660f63b49STobias Grosser 
178769b46751STobias Grosser   /// Collect the list of GPU statements.
178869b46751STobias Grosser   ///
178969b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
179069b46751STobias Grosser   /// as well as a list with all memory accesses.
179169b46751STobias Grosser   ///
179269b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
179369b46751STobias Grosser   ///
179469b46751STobias Grosser   /// @returns A linked-list of statements.
179569b46751STobias Grosser   gpu_stmt *getStatements() {
179669b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
179769b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
179869b46751STobias Grosser 
179969b46751STobias Grosser     int i = 0;
180069b46751STobias Grosser     for (auto &Stmt : *S) {
180169b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
180269b46751STobias Grosser 
180369b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
180469b46751STobias Grosser 
180569b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
180669b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
180760f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
180869b46751STobias Grosser       i++;
180969b46751STobias Grosser     }
181069b46751STobias Grosser 
181169b46751STobias Grosser     return Stmts;
181269b46751STobias Grosser   }
181369b46751STobias Grosser 
181460f63b49STobias Grosser   /// Derive the extent of an array.
181560f63b49STobias Grosser   ///
1816d58acf86STobias Grosser   /// The extent of an array is the set of elements that are within the
1817d58acf86STobias Grosser   /// accessed array. For the inner dimensions, the extent constraints are
1818d58acf86STobias Grosser   /// 0 and the size of the corresponding array dimension. For the first
1819d58acf86STobias Grosser   /// (outermost) dimension, the extent constraints are the minimal and maximal
1820d58acf86STobias Grosser   /// subscript value for the first dimension.
182160f63b49STobias Grosser   ///
182260f63b49STobias Grosser   /// @param Array The array to derive the extent for.
182360f63b49STobias Grosser   ///
182460f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
182560f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
1826d58acf86STobias Grosser     unsigned NumDims = Array->getNumberOfDimensions();
182760f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
182860f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
1829d58acf86STobias Grosser     Accesses = isl_union_map_detect_equalities(Accesses);
183060f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
1831d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
1832d58acf86STobias Grosser     AccessUSet = isl_union_set_detect_equalities(AccessUSet);
1833d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
1834d58acf86STobias Grosser 
1835d58acf86STobias Grosser     if (isl_union_set_is_empty(AccessUSet)) {
1836d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
1837d58acf86STobias Grosser       return isl_set_empty(Array->getSpace());
1838d58acf86STobias Grosser     }
1839d58acf86STobias Grosser 
1840d58acf86STobias Grosser     if (Array->getNumberOfDimensions() == 0) {
1841d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
1842d58acf86STobias Grosser       return isl_set_universe(Array->getSpace());
1843d58acf86STobias Grosser     }
1844d58acf86STobias Grosser 
184560f63b49STobias Grosser     isl_set *AccessSet =
184660f63b49STobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace());
184760f63b49STobias Grosser 
1848d58acf86STobias Grosser     isl_union_set_free(AccessUSet);
1849d58acf86STobias Grosser     isl_local_space *LS = isl_local_space_from_space(Array->getSpace());
1850d58acf86STobias Grosser 
1851d58acf86STobias Grosser     isl_pw_aff *Val =
1852d58acf86STobias Grosser         isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0));
1853d58acf86STobias Grosser 
1854d58acf86STobias Grosser     isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0);
1855d58acf86STobias Grosser     isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0);
1856d58acf86STobias Grosser     OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in,
1857d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
1858d58acf86STobias Grosser     OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in,
1859d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
1860d58acf86STobias Grosser     OuterMin =
1861d58acf86STobias Grosser         isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, Array->getBasePtrId());
1862d58acf86STobias Grosser     OuterMax =
1863d58acf86STobias Grosser         isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, Array->getBasePtrId());
1864d58acf86STobias Grosser 
1865d58acf86STobias Grosser     isl_set *Extent = isl_set_universe(Array->getSpace());
1866d58acf86STobias Grosser 
1867d58acf86STobias Grosser     Extent = isl_set_intersect(
1868d58acf86STobias Grosser         Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val)));
1869d58acf86STobias Grosser     Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val));
1870d58acf86STobias Grosser 
1871d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i)
1872d58acf86STobias Grosser       Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0);
1873d58acf86STobias Grosser 
1874d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i) {
1875d58acf86STobias Grosser       isl_pw_aff *PwAff =
1876d58acf86STobias Grosser           const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i));
1877d58acf86STobias Grosser       isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain(
1878d58acf86STobias Grosser           isl_local_space_from_space(Array->getSpace()), isl_dim_set, i));
1879d58acf86STobias Grosser       PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in,
1880d58acf86STobias Grosser                                   isl_pw_aff_dim(Val, isl_dim_in));
1881d58acf86STobias Grosser       PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in,
1882d58acf86STobias Grosser                                       isl_pw_aff_get_tuple_id(Val, isl_dim_in));
1883d58acf86STobias Grosser       auto *Set = isl_pw_aff_gt_set(PwAff, Val);
1884d58acf86STobias Grosser       Extent = isl_set_intersect(Set, Extent);
1885d58acf86STobias Grosser     }
1886d58acf86STobias Grosser 
1887d58acf86STobias Grosser     return Extent;
188860f63b49STobias Grosser   }
188960f63b49STobias Grosser 
189060f63b49STobias Grosser   /// Derive the bounds of an array.
189160f63b49STobias Grosser   ///
189260f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
189360f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
189460f63b49STobias Grosser   /// ScopArrayInfo.
189560f63b49STobias Grosser   ///
189660f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
189760f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
189860f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
189960f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
190002293ed7STobias Grosser       if (isl_set_is_empty(PPCGArray.extent)) {
190102293ed7STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
190202293ed7STobias Grosser         isl_local_space *LS = isl_local_space_from_space(
190302293ed7STobias Grosser             isl_space_params(isl_set_get_space(Dom)));
190402293ed7STobias Grosser         isl_set_free(Dom);
190502293ed7STobias Grosser         isl_aff *Zero = isl_aff_zero_on_domain(LS);
190602293ed7STobias Grosser         PPCGArray.bound[0] = isl_pw_aff_from_aff(Zero);
190702293ed7STobias Grosser       } else {
190860f63b49STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
190960f63b49STobias Grosser         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
191060f63b49STobias Grosser         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
191160f63b49STobias Grosser         isl_set_free(Dom);
191260f63b49STobias Grosser         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
191302293ed7STobias Grosser         isl_local_space *LS =
191402293ed7STobias Grosser             isl_local_space_from_space(isl_set_get_space(Dom));
191560f63b49STobias Grosser         isl_aff *One = isl_aff_zero_on_domain(LS);
191660f63b49STobias Grosser         One = isl_aff_add_constant_si(One, 1);
191760f63b49STobias Grosser         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
191860f63b49STobias Grosser         Bound = isl_pw_aff_gist(Bound, S->getContext());
191960f63b49STobias Grosser         PPCGArray.bound[0] = Bound;
192060f63b49STobias Grosser       }
192102293ed7STobias Grosser     }
192260f63b49STobias Grosser 
192360f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
192460f63b49STobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
192560f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
192660f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
192760f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
192860f63b49STobias Grosser       PPCGArray.bound[i] = Bound;
192960f63b49STobias Grosser     }
193060f63b49STobias Grosser   }
193160f63b49STobias Grosser 
193260f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
193360f63b49STobias Grosser   ///
193460f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
193560f63b49STobias Grosser   void createArrays(gpu_prog *PPCGProg) {
193660f63b49STobias Grosser     int i = 0;
1937d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
193860f63b49STobias Grosser       std::string TypeName;
193960f63b49STobias Grosser       raw_string_ostream OS(TypeName);
194060f63b49STobias Grosser 
194160f63b49STobias Grosser       OS << *Array->getElementType();
194260f63b49STobias Grosser       TypeName = OS.str();
194360f63b49STobias Grosser 
194460f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
194560f63b49STobias Grosser 
194660f63b49STobias Grosser       PPCGArray.space = Array->getSpace();
194760f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
194860f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
194960f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
195060f63b49STobias Grosser       PPCGArray.extent = nullptr;
195160f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
195260f63b49STobias Grosser       PPCGArray.bound =
195360f63b49STobias Grosser           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
195460f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
195560f63b49STobias Grosser       PPCGArray.n_ref = 0;
195660f63b49STobias Grosser       PPCGArray.refs = nullptr;
195760f63b49STobias Grosser       PPCGArray.accessed = true;
1958*fe74a7a1STobias Grosser       PPCGArray.read_only_scalar =
1959*fe74a7a1STobias Grosser           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
196060f63b49STobias Grosser       PPCGArray.has_compound_element = false;
196160f63b49STobias Grosser       PPCGArray.local = false;
196260f63b49STobias Grosser       PPCGArray.declare_local = false;
196360f63b49STobias Grosser       PPCGArray.global = false;
196460f63b49STobias Grosser       PPCGArray.linearize = false;
196560f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
196613c78e4dSTobias Grosser       PPCGArray.user = Array;
196760f63b49STobias Grosser 
196860f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
19692d010dafSTobias Grosser       i++;
1970b9fc860aSTobias Grosser 
1971b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
197260f63b49STobias Grosser     }
197360f63b49STobias Grosser   }
197460f63b49STobias Grosser 
197560f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
197660f63b49STobias Grosser   ///
197760f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
197860f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
197960f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
198060f63b49STobias Grosser 
1981d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
198260f63b49STobias Grosser       isl_space *Space = Array->getSpace();
198360f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
198460f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
198560f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
198660f63b49STobias Grosser     }
198760f63b49STobias Grosser 
198860f63b49STobias Grosser     return Maps;
198960f63b49STobias Grosser   }
199060f63b49STobias Grosser 
1991e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
1992e938517eSTobias Grosser   ///
1993e938517eSTobias Grosser   /// @returns A new gpu grogram description.
1994e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
1995e938517eSTobias Grosser 
1996e938517eSTobias Grosser     if (!PPCGScop)
1997e938517eSTobias Grosser       return nullptr;
1998e938517eSTobias Grosser 
1999e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
2000e938517eSTobias Grosser 
2001e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
2002e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
2003aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
200460f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
200560f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
200660f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
200760f63b49STobias Grosser     PPCGProg->tagged_must_kill =
200860f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
200960f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
201060f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
2011e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
2012e938517eSTobias Grosser     PPCGProg->array_order = nullptr;
201369b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
201469b46751STobias Grosser     PPCGProg->stmts = getStatements();
201560f63b49STobias Grosser     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
201660f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
201760f63b49STobias Grosser                                        PPCGProg->n_array);
201860f63b49STobias Grosser 
201960f63b49STobias Grosser     createArrays(PPCGProg);
2020e938517eSTobias Grosser 
2021d58acf86STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
2022d58acf86STobias Grosser 
2023e938517eSTobias Grosser     return PPCGProg;
2024e938517eSTobias Grosser   }
2025e938517eSTobias Grosser 
202669b46751STobias Grosser   struct PrintGPUUserData {
202769b46751STobias Grosser     struct cuda_info *CudaInfo;
202869b46751STobias Grosser     struct gpu_prog *PPCGProg;
202969b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
203069b46751STobias Grosser   };
203169b46751STobias Grosser 
203269b46751STobias Grosser   /// Print a user statement node in the host code.
203369b46751STobias Grosser   ///
203469b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
203569b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
203669b46751STobias Grosser   /// host ast.
203769b46751STobias Grosser   ///
203869b46751STobias Grosser   /// @param P The printer to print to
203969b46751STobias Grosser   /// @param Options The printing options to use
204069b46751STobias Grosser   /// @param Node The node to print
204169b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
204269b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
204369b46751STobias Grosser   ///
204469b46751STobias Grosser   /// @returns A printer to which the output has been printed.
204569b46751STobias Grosser   static __isl_give isl_printer *
204669b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
204769b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
204869b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
204969b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
205069b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
205169b46751STobias Grosser 
205269b46751STobias Grosser     if (Id) {
205320251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
205420251734STobias Grosser 
205520251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
205620251734STobias Grosser       // otherwise try to call pet functionality that is not available in
205720251734STobias Grosser       // Polly.
205820251734STobias Grosser       if (IsUser) {
205920251734STobias Grosser         P = isl_printer_start_line(P);
206020251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
206120251734STobias Grosser         P = isl_printer_end_line(P);
206220251734STobias Grosser         isl_id_free(Id);
206320251734STobias Grosser         isl_ast_print_options_free(Options);
206420251734STobias Grosser         return P;
206520251734STobias Grosser       }
206620251734STobias Grosser 
206769b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
206869b46751STobias Grosser       isl_id_free(Id);
206969b46751STobias Grosser       Data->Kernels.push_back(Kernel);
207069b46751STobias Grosser     }
207169b46751STobias Grosser 
207269b46751STobias Grosser     return print_host_user(P, Options, Node, User);
207369b46751STobias Grosser   }
207469b46751STobias Grosser 
207569b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
207669b46751STobias Grosser   ///
207769b46751STobias Grosser   /// @param Kernel The kernel to print
207869b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
207969b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
208069b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
208169b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
208269b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
208369b46751STobias Grosser     char *String = isl_printer_get_str(P);
208469b46751STobias Grosser     printf("%s\n", String);
208569b46751STobias Grosser     free(String);
208669b46751STobias Grosser     isl_printer_free(P);
208769b46751STobias Grosser   }
208869b46751STobias Grosser 
208969b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
209069b46751STobias Grosser   ///
209169b46751STobias Grosser   /// @param Tree An AST describing GPU code
209269b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
209369b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
209469b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
209569b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
209669b46751STobias Grosser 
209769b46751STobias Grosser     PrintGPUUserData Data;
209869b46751STobias Grosser     Data.PPCGProg = PPCGProg;
209969b46751STobias Grosser 
210069b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
210169b46751STobias Grosser     Options =
210269b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
210369b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
210469b46751STobias Grosser     char *String = isl_printer_get_str(P);
210569b46751STobias Grosser     printf("# host\n");
210669b46751STobias Grosser     printf("%s\n", String);
210769b46751STobias Grosser     free(String);
210869b46751STobias Grosser     isl_printer_free(P);
210969b46751STobias Grosser 
211069b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
211169b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
211269b46751STobias Grosser       printKernel(Kernel);
211369b46751STobias Grosser     }
211469b46751STobias Grosser   }
211569b46751STobias Grosser 
2116f384594dSTobias Grosser   // Generate a GPU program using PPCG.
2117f384594dSTobias Grosser   //
2118f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
2119f384594dSTobias Grosser   //
2120f384594dSTobias Grosser   //  1) Compute new schedule for the program.
2121f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
2122f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
2123f384594dSTobias Grosser   //
2124f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
2125f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
2126f384594dSTobias Grosser   // strategy directly from this pass.
2127f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
2128f384594dSTobias Grosser 
2129f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
2130f384594dSTobias Grosser 
2131f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
2132f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
2133f384594dSTobias Grosser     PPCGGen->print = nullptr;
2134f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
213560c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
2136f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
2137f384594dSTobias Grosser     PPCGGen->tree = nullptr;
2138f384594dSTobias Grosser     PPCGGen->types.n = 0;
2139f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
2140f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
2141f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
2142f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
2143f384594dSTobias Grosser 
2144f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
2145f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
2146f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
21472341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
2148f384594dSTobias Grosser 
2149f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
2150f384594dSTobias Grosser 
2151aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
2152aef5196fSTobias Grosser 
215369b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
2154aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
215569b46751STobias Grosser     } else {
2156aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
215769b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
215869b46751STobias Grosser     }
2159aef5196fSTobias Grosser 
2160f384594dSTobias Grosser     if (DumpSchedule) {
2161f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
2162f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
2163f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
2164f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
2165f384594dSTobias Grosser       if (Schedule)
2166f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
2167f384594dSTobias Grosser       else
2168f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
2169f384594dSTobias Grosser 
2170f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
2171f384594dSTobias Grosser       isl_printer_free(P);
2172f384594dSTobias Grosser     }
2173f384594dSTobias Grosser 
217469b46751STobias Grosser     if (DumpCode) {
217569b46751STobias Grosser       printf("Code\n");
217669b46751STobias Grosser       printf("====\n");
217769b46751STobias Grosser       if (PPCGGen->tree)
217869b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
217969b46751STobias Grosser       else
218069b46751STobias Grosser         printf("No code generated\n");
218169b46751STobias Grosser     }
218269b46751STobias Grosser 
2183f384594dSTobias Grosser     isl_schedule_free(Schedule);
2184f384594dSTobias Grosser 
2185f384594dSTobias Grosser     return PPCGGen;
2186f384594dSTobias Grosser   }
2187f384594dSTobias Grosser 
2188f384594dSTobias Grosser   /// Free gpu_gen structure.
2189f384594dSTobias Grosser   ///
2190f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
2191f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
2192f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
2193f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
2194f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
2195f384594dSTobias Grosser     free(PPCGGen);
2196f384594dSTobias Grosser   }
2197f384594dSTobias Grosser 
2198b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
2199b307ed4dSTobias Grosser   ///
2200b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
2201b307ed4dSTobias Grosser   /// ourselves.
2202b307ed4dSTobias Grosser   ///
2203b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
2204b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
2205b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
2206b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
2207b307ed4dSTobias Grosser     free(PPCGScop->options);
2208b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
2209b307ed4dSTobias Grosser   }
2210b307ed4dSTobias Grosser 
221138fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
221238fc0aedSTobias Grosser   ///
221332837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
221432837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
221532837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
221638fc0aedSTobias Grosser     ScopAnnotator Annotator;
221738fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
221838fc0aedSTobias Grosser 
221938fc0aedSTobias Grosser     Region *R = &S->getRegion();
222038fc0aedSTobias Grosser 
222138fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
222238fc0aedSTobias Grosser 
222338fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
222438fc0aedSTobias Grosser 
222538fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
222638fc0aedSTobias Grosser 
222732837fe3STobias Grosser     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S,
222832837fe3STobias Grosser                                Prog);
222938fc0aedSTobias Grosser 
223038fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
223138fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
223238fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
223338fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
223438fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
223538fc0aedSTobias Grosser     // code generating this scop.
223638fc0aedSTobias Grosser     BasicBlock *StartBlock =
223738fc0aedSTobias Grosser         executeScopConditionally(*S, this, Builder.getTrue());
223838fc0aedSTobias Grosser 
223938fc0aedSTobias Grosser     // TODO: Handle LICM
224038fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
224138fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
224238fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
2243cb1aef8dSTobias Grosser 
2244cb1aef8dSTobias Grosser     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx());
2245cb1aef8dSTobias Grosser     isl_ast_expr *Condition = IslAst::buildRunCondition(S, Build);
2246cb1aef8dSTobias Grosser     isl_ast_build_free(Build);
2247cb1aef8dSTobias Grosser 
2248cb1aef8dSTobias Grosser     Value *RTC = NodeBuilder.createRTC(Condition);
2249cb1aef8dSTobias Grosser     Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
2250cb1aef8dSTobias Grosser 
225138fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
2252fa7b0802STobias Grosser 
2253fa7b0802STobias Grosser     NodeBuilder.initializeAfterRTH();
225438fc0aedSTobias Grosser     NodeBuilder.create(Root);
22558ed5e599STobias Grosser     NodeBuilder.finalize();
22565857b701STobias Grosser 
22575857b701STobias Grosser     if (!NodeBuilder.BuildSuccessful)
22585857b701STobias Grosser       SplitBlock->getTerminator()->setOperand(0, Builder.getFalse());
225938fc0aedSTobias Grosser   }
226038fc0aedSTobias Grosser 
2261e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
2262e938517eSTobias Grosser     S = &CurrentScop;
226338fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
226438fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
226538fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
226638fc0aedSTobias Grosser     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
226738fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
2268e938517eSTobias Grosser 
22692d58a64eSTobias Grosser     // We currently do not support scops with invariant loads.
22702d58a64eSTobias Grosser     if (S->hasInvariantAccesses())
22712d58a64eSTobias Grosser       return false;
22722d58a64eSTobias Grosser 
2273e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
2274e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
2275f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
227638fc0aedSTobias Grosser 
227738fc0aedSTobias Grosser     if (PPCGGen->tree)
227832837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
227938fc0aedSTobias Grosser 
2280b307ed4dSTobias Grosser     freeOptions(PPCGScop);
2281f384594dSTobias Grosser     freePPCGGen(PPCGGen);
2282e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
2283e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
2284e938517eSTobias Grosser 
2285e938517eSTobias Grosser     return true;
2286e938517eSTobias Grosser   }
22879dfe4e7cSTobias Grosser 
22889dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
22899dfe4e7cSTobias Grosser 
22909dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
22919dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
22929dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
22939dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
22949dfe4e7cSTobias Grosser     AU.addRequired<ScopDetection>();
22959dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
22969dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
22979dfe4e7cSTobias Grosser 
22989dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
22999dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
23009dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
23019dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
23029dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
23039dfe4e7cSTobias Grosser     AU.addPreserved<PostDominatorTreeWrapperPass>();
23049dfe4e7cSTobias Grosser     AU.addPreserved<ScopDetection>();
23059dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
23069dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
23079dfe4e7cSTobias Grosser 
23089dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
23099dfe4e7cSTobias Grosser     //        region tree.
23109dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
23119dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
23129dfe4e7cSTobias Grosser   }
23139dfe4e7cSTobias Grosser };
23149dfe4e7cSTobias Grosser }
23159dfe4e7cSTobias Grosser 
23169dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
23179dfe4e7cSTobias Grosser 
23189dfe4e7cSTobias Grosser Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
23199dfe4e7cSTobias Grosser 
23209dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
23219dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
23229dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
23239dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
23249dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
23259dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
23269dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
23279dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScopDetection);
23289dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
23299dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
2330