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/ScalarEvolutionAliasAnalysis.h"
2974dc3cb4STobias Grosser #include "llvm/Analysis/TargetLibraryInfo.h"
3074dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h"
3174dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h"
32e1a98343STobias Grosser #include "llvm/IR/Verifier.h"
3374dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h"
3474dc3cb4STobias Grosser #include "llvm/Support/TargetSelect.h"
3574dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h"
369a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h"
37750160e2STobias Grosser #include "llvm/Transforms/Utils/BasicBlockUtils.h"
389dfe4e7cSTobias Grosser 
39f384594dSTobias Grosser #include "isl/union_map.h"
40f384594dSTobias Grosser 
41e938517eSTobias Grosser extern "C" {
42a56f8f8eSTobias Grosser #include "ppcg/cuda.h"
43a56f8f8eSTobias Grosser #include "ppcg/gpu.h"
44a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h"
45a56f8f8eSTobias Grosser #include "ppcg/ppcg.h"
46a56f8f8eSTobias Grosser #include "ppcg/schedule.h"
47e938517eSTobias Grosser }
48e938517eSTobias Grosser 
499dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h"
509dfe4e7cSTobias Grosser 
519dfe4e7cSTobias Grosser using namespace polly;
529dfe4e7cSTobias Grosser using namespace llvm;
539dfe4e7cSTobias Grosser 
549dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg"
559dfe4e7cSTobias Grosser 
56f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
57f384594dSTobias Grosser                                   cl::desc("Dump the computed GPU Schedule"),
58681bd568STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
59f384594dSTobias Grosser                                   cl::cat(PollyCategory));
6069b46751STobias Grosser 
6169b46751STobias Grosser static cl::opt<bool>
6269b46751STobias Grosser     DumpCode("polly-acc-dump-code",
6369b46751STobias Grosser              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
6469b46751STobias Grosser              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
6569b46751STobias Grosser 
6632837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
6732837fe3STobias Grosser                                   cl::desc("Dump the kernel LLVM-IR"),
6832837fe3STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
6932837fe3STobias Grosser                                   cl::cat(PollyCategory));
7032837fe3STobias Grosser 
7174dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
7274dc3cb4STobias Grosser                                    cl::desc("Dump the kernel assembly code"),
7374dc3cb4STobias Grosser                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
7474dc3cb4STobias Grosser                                    cl::cat(PollyCategory));
7574dc3cb4STobias Grosser 
7674dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath",
7774dc3cb4STobias Grosser                               cl::desc("Allow unsafe math optimizations"),
7874dc3cb4STobias Grosser                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
7974dc3cb4STobias Grosser                               cl::cat(PollyCategory));
80b513b491STobias Grosser static cl::opt<bool> SharedMemory("polly-acc-use-shared",
81b513b491STobias Grosser                                   cl::desc("Use shared memory"), cl::Hidden,
82b513b491STobias Grosser                                   cl::init(false), cl::ZeroOrMore,
83b513b491STobias Grosser                                   cl::cat(PollyCategory));
84130ca30fSTobias Grosser static cl::opt<bool> PrivateMemory("polly-acc-use-private",
85130ca30fSTobias Grosser                                    cl::desc("Use private memory"), cl::Hidden,
86130ca30fSTobias Grosser                                    cl::init(false), cl::ZeroOrMore,
87130ca30fSTobias Grosser                                    cl::cat(PollyCategory));
8874dc3cb4STobias Grosser 
8974dc3cb4STobias Grosser static cl::opt<std::string>
9074dc3cb4STobias Grosser     CudaVersion("polly-acc-cuda-version",
9174dc3cb4STobias Grosser                 cl::desc("The CUDA version to compile for"), cl::Hidden,
9274dc3cb4STobias Grosser                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
9374dc3cb4STobias Grosser 
9482f2af35STobias Grosser static cl::opt<int>
9582f2af35STobias Grosser     MinCompute("polly-acc-mincompute",
9682f2af35STobias Grosser                cl::desc("Minimal number of compute statements to run on GPU."),
9782f2af35STobias Grosser                cl::Hidden, cl::init(10 * 512 * 512));
9882f2af35STobias Grosser 
9960c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
10060c60025STobias Grosser ///
10160c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
10260c60025STobias Grosser /// of the scheduled ScopStmts.
10360c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
104edb885cbSTobias Grosser     void *StmtT, isl_ast_build *Build,
10560c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
10660c60025STobias Grosser                                        isl_id *Id, void *User),
10760c60025STobias Grosser     void *UserIndex,
10860c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
109edb885cbSTobias Grosser     void *UserExpr) {
11060c60025STobias Grosser 
111edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
11260c60025STobias Grosser 
113edb885cbSTobias Grosser   isl_ctx *Ctx;
114edb885cbSTobias Grosser 
115edb885cbSTobias Grosser   if (!Stmt || !Build)
116edb885cbSTobias Grosser     return NULL;
117edb885cbSTobias Grosser 
118edb885cbSTobias Grosser   Ctx = isl_ast_build_get_ctx(Build);
119edb885cbSTobias Grosser   isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0);
120edb885cbSTobias Grosser 
121edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
122edb885cbSTobias Grosser     isl_map *AddrFunc = Acc->getAddressFunction();
123edb885cbSTobias Grosser     AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain());
124edb885cbSTobias Grosser     isl_id *RefId = Acc->getId();
125edb885cbSTobias Grosser     isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc);
126edb885cbSTobias Grosser     isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA);
127edb885cbSTobias Grosser     MPA = isl_multi_pw_aff_coalesce(MPA);
128edb885cbSTobias Grosser     MPA = FunctionIndex(MPA, RefId, UserIndex);
129edb885cbSTobias Grosser     isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA);
130edb885cbSTobias Grosser     Access = FunctionExpr(Access, RefId, UserExpr);
131edb885cbSTobias Grosser     RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access);
132edb885cbSTobias Grosser   }
133edb885cbSTobias Grosser 
134edb885cbSTobias Grosser   return RefToExpr;
13560c60025STobias Grosser }
136f384594dSTobias Grosser 
13738fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
13838fc0aedSTobias Grosser ///
13938fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
14038fc0aedSTobias Grosser /// generates code for general-prupose AST nodes, with special functionality
14138fc0aedSTobias Grosser /// for generating GPU specific user nodes.
14238fc0aedSTobias Grosser ///
14338fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
14438fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
14538fc0aedSTobias Grosser public:
1462d950f36SPhilip Pfaffe   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator,
14738fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
148acf80064SEli Friedman                  DominatorTree &DT, Scop &S, BasicBlock *StartBlock,
149acf80064SEli Friedman                  gpu_prog *Prog)
1502d950f36SPhilip Pfaffe       : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock),
151acf80064SEli Friedman         Prog(Prog) {
152edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
153edb885cbSTobias Grosser   }
15438fc0aedSTobias Grosser 
155fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
156fa7b0802STobias Grosser   void initializeAfterRTH();
157fa7b0802STobias Grosser 
158fa7b0802STobias Grosser   /// Finalize the generated scop.
159fa7b0802STobias Grosser   virtual void finalize();
160fa7b0802STobias Grosser 
1615857b701STobias Grosser   /// Track if the full build process was successful.
1625857b701STobias Grosser   ///
1635857b701STobias Grosser   /// This value is set to false, if throughout the build process an error
1645857b701STobias Grosser   /// occurred which prevents us from generating valid GPU code.
1655857b701STobias Grosser   bool BuildSuccessful = true;
1665857b701STobias Grosser 
167bc653f20STobias Grosser   /// The maximal number of loops surrounding a sequential kernel.
168bc653f20STobias Grosser   unsigned DeepestSequential = 0;
169bc653f20STobias Grosser 
170bc653f20STobias Grosser   /// The maximal number of loops surrounding a parallel kernel.
171bc653f20STobias Grosser   unsigned DeepestParallel = 0;
172bc653f20STobias Grosser 
17338fc0aedSTobias Grosser private:
17474dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
17574dc3cb4STobias Grosser   ///
17674dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
17774dc3cb4STobias Grosser   /// more.
17874dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
17974dc3cb4STobias Grosser 
18013c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
18113c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
1827287aeddSTobias Grosser 
183fa7b0802STobias Grosser   /// The current GPU context.
184fa7b0802STobias Grosser   Value *GPUContext;
185fa7b0802STobias Grosser 
186b513b491STobias Grosser   /// The set of isl_ids allocated in the kernel
187b513b491STobias Grosser   std::vector<isl_id *> KernelIds;
188b513b491STobias Grosser 
18932837fe3STobias Grosser   /// A module containing GPU code.
19032837fe3STobias Grosser   ///
19132837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
19232837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
19332837fe3STobias Grosser 
19432837fe3STobias Grosser   /// The GPU program we generate code for.
19532837fe3STobias Grosser   gpu_prog *Prog;
19632837fe3STobias Grosser 
197472f9654STobias Grosser   /// Class to free isl_ids.
198472f9654STobias Grosser   class IslIdDeleter {
199472f9654STobias Grosser   public:
200472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
201472f9654STobias Grosser   };
202472f9654STobias Grosser 
203472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
204472f9654STobias Grosser   ///
205472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
206472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
207472f9654STobias Grosser 
208edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
209edb885cbSTobias Grosser 
21038fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
21138fc0aedSTobias Grosser   ///
21238fc0aedSTobias Grosser   /// These AST nodes can be of type:
21338fc0aedSTobias Grosser   ///
21438fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
21538fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
21613c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
2175260c041STobias Grosser   ///   - In-kernel synchronization
2185260c041STobias Grosser   ///   - In-kernel memory copy statement
21938fc0aedSTobias Grosser   ///
2201fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
2211fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
22232837fe3STobias Grosser 
22313c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
22413c78e4dSTobias Grosser 
22513c78e4dSTobias Grosser   /// Create code for a data transfer statement
22613c78e4dSTobias Grosser   ///
22713c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
22813c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
22913c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
23013c78e4dSTobias Grosser                           enum DataDirection Direction);
23113c78e4dSTobias Grosser 
232edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
233edb885cbSTobias Grosser   ///
234edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
235edb885cbSTobias Grosser   ///
236edb885cbSTobias Grosser   /// @returns A set of values referenced by the kernel.
237edb885cbSTobias Grosser   SetVector<Value *> getReferencesInKernel(ppcg_kernel *Kernel);
238edb885cbSTobias Grosser 
23979a947c2STobias Grosser   /// Compute the sizes of the execution grid for a given kernel.
24079a947c2STobias Grosser   ///
24179a947c2STobias Grosser   /// @param Kernel The kernel to compute grid sizes for.
24279a947c2STobias Grosser   ///
24379a947c2STobias Grosser   /// @returns A tuple with grid sizes for X and Y dimension
24479a947c2STobias Grosser   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
24579a947c2STobias Grosser 
24679a947c2STobias Grosser   /// Compute the sizes of the thread blocks for a given kernel.
24779a947c2STobias Grosser   ///
24879a947c2STobias Grosser   /// @param Kernel The kernel to compute thread block sizes for.
24979a947c2STobias Grosser   ///
25079a947c2STobias Grosser   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
25179a947c2STobias Grosser   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
25279a947c2STobias Grosser 
25379a947c2STobias Grosser   /// Create kernel launch parameters.
25479a947c2STobias Grosser   ///
25579a947c2STobias Grosser   /// @param Kernel        The kernel to create parameters for.
25679a947c2STobias Grosser   /// @param F             The kernel function that has been created.
25757693272STobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
25879a947c2STobias Grosser   ///
25979a947c2STobias Grosser   /// @returns A stack allocated array with pointers to the parameter
26079a947c2STobias Grosser   ///          values that are passed to the kernel.
26157693272STobias Grosser   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
26257693272STobias Grosser                                 SetVector<Value *> SubtreeValues);
26379a947c2STobias Grosser 
264b513b491STobias Grosser   /// Create declarations for kernel variable.
265b513b491STobias Grosser   ///
266b513b491STobias Grosser   /// This includes shared memory declarations.
267b513b491STobias Grosser   ///
268b513b491STobias Grosser   /// @param Kernel        The kernel definition to create variables for.
269b513b491STobias Grosser   /// @param FN            The function into which to generate the variables.
270b513b491STobias Grosser   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
271b513b491STobias Grosser 
272c1c6a2a6STobias Grosser   /// Add CUDA annotations to module.
273c1c6a2a6STobias Grosser   ///
274c1c6a2a6STobias Grosser   /// Add a set of CUDA annotations that declares the maximal block dimensions
275c1c6a2a6STobias Grosser   /// that will be used to execute the CUDA kernel. This allows the NVIDIA
276c1c6a2a6STobias Grosser   /// PTX compiler to bound the number of allocated registers to ensure the
277c1c6a2a6STobias Grosser   /// resulting kernel is known to run with up to as many block dimensions
278c1c6a2a6STobias Grosser   /// as specified here.
279c1c6a2a6STobias Grosser   ///
280c1c6a2a6STobias Grosser   /// @param M         The module to add the annotations to.
281c1c6a2a6STobias Grosser   /// @param BlockDimX The size of block dimension X.
282c1c6a2a6STobias Grosser   /// @param BlockDimY The size of block dimension Y.
283c1c6a2a6STobias Grosser   /// @param BlockDimZ The size of block dimension Z.
284c1c6a2a6STobias Grosser   void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY,
285c1c6a2a6STobias Grosser                           Value *BlockDimZ);
286c1c6a2a6STobias Grosser 
28732837fe3STobias Grosser   /// Create GPU kernel.
28832837fe3STobias Grosser   ///
28932837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
29032837fe3STobias Grosser   ///
29132837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
29232837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
29332837fe3STobias Grosser 
29413c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
29513c78e4dSTobias Grosser   ///
29613c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
29713c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
29813c78e4dSTobias Grosser 
299aaabbbf8STobias Grosser   /// Generate code to compute the minimal offset at which an array is accessed.
300aaabbbf8STobias Grosser   ///
301aaabbbf8STobias Grosser   /// The offset of an array is the minimal array location accessed in a scop.
302aaabbbf8STobias Grosser   ///
303aaabbbf8STobias Grosser   /// Example:
304aaabbbf8STobias Grosser   ///
305aaabbbf8STobias Grosser   ///   for (long i = 0; i < 100; i++)
306aaabbbf8STobias Grosser   ///     A[i + 42] += ...
307aaabbbf8STobias Grosser   ///
308aaabbbf8STobias Grosser   ///   getArrayOffset(A) results in 42.
309aaabbbf8STobias Grosser   ///
310aaabbbf8STobias Grosser   /// @param Array The array for which to compute the offset.
311aaabbbf8STobias Grosser   /// @returns An llvm::Value that contains the offset of the array.
312aaabbbf8STobias Grosser   Value *getArrayOffset(gpu_array_info *Array);
313aaabbbf8STobias Grosser 
31400bb5a99STobias Grosser   /// Prepare the kernel arguments for kernel code generation
31500bb5a99STobias Grosser   ///
31600bb5a99STobias Grosser   /// @param Kernel The kernel to generate code for.
31700bb5a99STobias Grosser   /// @param FN     The function created for the kernel.
31800bb5a99STobias Grosser   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
31900bb5a99STobias Grosser 
32032837fe3STobias Grosser   /// Create kernel function.
32132837fe3STobias Grosser   ///
32232837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
32332837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
32432837fe3STobias Grosser   /// start block of this newly created function.
32532837fe3STobias Grosser   ///
32632837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
327edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
328edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
329edb885cbSTobias Grosser                             SetVector<Value *> &SubtreeValues);
33032837fe3STobias Grosser 
33132837fe3STobias Grosser   /// Create the declaration of a kernel function.
33232837fe3STobias Grosser   ///
33332837fe3STobias Grosser   /// The kernel function takes as arguments:
33432837fe3STobias Grosser   ///
33532837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
336f6044bd0STobias Grosser   ///   - Host iterators
337c84a1995STobias Grosser   ///   - Parameters
33832837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
33932837fe3STobias Grosser   ///
34032837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
341edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
342edb885cbSTobias Grosser   ///
34332837fe3STobias Grosser   /// @returns The newly declared function.
344edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
345edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
34632837fe3STobias Grosser 
347472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
348472f9654STobias Grosser   ///
349472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
350472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
351472f9654STobias Grosser 
352b513b491STobias Grosser   /// Create a global-to-shared or shared-to-global copy statement.
353b513b491STobias Grosser   ///
354b513b491STobias Grosser   /// @param CopyStmt The copy statement to generate code for
355b513b491STobias Grosser   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
356b513b491STobias Grosser 
357edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
358edb885cbSTobias Grosser   ///
359edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
360edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
361edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
362edb885cbSTobias Grosser 
3635260c041STobias Grosser   /// Create an in-kernel synchronization call.
3645260c041STobias Grosser   void createKernelSync();
3655260c041STobias Grosser 
36674dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
36774dc3cb4STobias Grosser   ///
36874dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
36974dc3cb4STobias Grosser   std::string createKernelASM();
37074dc3cb4STobias Grosser 
37174dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
37274dc3cb4STobias Grosser   ///
37374dc3cb4STobias Grosser   /// @param F The function to remove references to.
37474dc3cb4STobias Grosser   void clearDominators(Function *F);
37574dc3cb4STobias Grosser 
37674dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
37774dc3cb4STobias Grosser   ///
37874dc3cb4STobias Grosser   /// @param F The function to remove references to.
37974dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
38074dc3cb4STobias Grosser 
38174dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
38274dc3cb4STobias Grosser   ///
38374dc3cb4STobias Grosser   /// @param F The function to remove references to.
38474dc3cb4STobias Grosser   void clearLoops(Function *F);
38574dc3cb4STobias Grosser 
38632837fe3STobias Grosser   /// Finalize the generation of the kernel function.
38732837fe3STobias Grosser   ///
38832837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
38932837fe3STobias Grosser   /// dump its IR to stderr.
39057793596STobias Grosser   ///
39157793596STobias Grosser   /// @returns The Assembly string of the kernel.
39257793596STobias Grosser   std::string finalizeKernelFunction();
393fa7b0802STobias Grosser 
39451dfc275STobias Grosser   /// Finalize the generation of the kernel arguments.
39551dfc275STobias Grosser   ///
39651dfc275STobias Grosser   /// This function ensures that not-read-only scalars used in a kernel are
39751dfc275STobias Grosser   /// stored back to the global memory location they ared backed up with before
39851dfc275STobias Grosser   /// the kernel terminates.
39951dfc275STobias Grosser   ///
40051dfc275STobias Grosser   /// @params Kernel The kernel to finalize kernel arguments for.
40151dfc275STobias Grosser   void finalizeKernelArguments(ppcg_kernel *Kernel);
40251dfc275STobias Grosser 
4037287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
404fa7b0802STobias Grosser   void allocateDeviceArrays();
405fa7b0802STobias Grosser 
4067287aeddSTobias Grosser   /// Free all allocated device arrays.
4077287aeddSTobias Grosser   void freeDeviceArrays();
4087287aeddSTobias Grosser 
409fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
410fa7b0802STobias Grosser   ///
411fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
412fa7b0802STobias Grosser   Value *createCallInitContext();
413fa7b0802STobias Grosser 
41479a947c2STobias Grosser   /// Create a call to get the device pointer for a kernel allocation.
41579a947c2STobias Grosser   ///
41679a947c2STobias Grosser   /// @param Allocation The Polly GPU allocation
41779a947c2STobias Grosser   ///
41879a947c2STobias Grosser   /// @returns The device parameter corresponding to this allocation.
41979a947c2STobias Grosser   Value *createCallGetDevicePtr(Value *Allocation);
42079a947c2STobias Grosser 
421fa7b0802STobias Grosser   /// Create a call to free the GPU context.
422fa7b0802STobias Grosser   ///
423fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
424fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
425fa7b0802STobias Grosser 
4267287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
4277287aeddSTobias Grosser   ///
4287287aeddSTobias Grosser   /// @param Size The size of memory to allocate
4297287aeddSTobias Grosser   ///
4307287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
431fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
4327287aeddSTobias Grosser 
4337287aeddSTobias Grosser   /// Create a call to free a device array.
4347287aeddSTobias Grosser   ///
4357287aeddSTobias Grosser   /// @param Array The device array to free.
4367287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
43713c78e4dSTobias Grosser 
43813c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
43913c78e4dSTobias Grosser   ///
44013c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
44113c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
44213c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
44313c78e4dSTobias Grosser                                       Value *Size);
44413c78e4dSTobias Grosser 
44513c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
44613c78e4dSTobias Grosser   ///
44713c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
44813c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
44913c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
45013c78e4dSTobias Grosser                                       Value *Size);
45157793596STobias Grosser 
45257793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
45357793596STobias Grosser   ///
45457793596STobias Grosser   /// @param Buffer The string describing the kernel.
45557793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
45657793596STobias Grosser   ///
45757793596STobias Grosser   /// @returns A pointer to a kernel object
45857793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
45957793596STobias Grosser 
46057793596STobias Grosser   /// Create a call to free a GPU kernel.
46157793596STobias Grosser   ///
46257793596STobias Grosser   /// @param GPUKernel THe kernel to free.
46357793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
46479a947c2STobias Grosser 
46579a947c2STobias Grosser   /// Create a call to launch a GPU kernel.
46679a947c2STobias Grosser   ///
46779a947c2STobias Grosser   /// @param GPUKernel  The kernel to launch.
46879a947c2STobias Grosser   /// @param GridDimX   The size of the first grid dimension.
46979a947c2STobias Grosser   /// @param GridDimY   The size of the second grid dimension.
47079a947c2STobias Grosser   /// @param GridBlockX The size of the first block dimension.
47179a947c2STobias Grosser   /// @param GridBlockY The size of the second block dimension.
47279a947c2STobias Grosser   /// @param GridBlockZ The size of the third block dimension.
47379a947c2STobias Grosser   /// @param Paramters  A pointer to an array that contains itself pointers to
47479a947c2STobias Grosser   ///                   the parameter values passed for each kernel argument.
47579a947c2STobias Grosser   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
47679a947c2STobias Grosser                               Value *GridDimY, Value *BlockDimX,
47779a947c2STobias Grosser                               Value *BlockDimY, Value *BlockDimZ,
47879a947c2STobias Grosser                               Value *Parameters);
4791fb9b64dSTobias Grosser };
4801fb9b64dSTobias Grosser 
481fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
482750160e2STobias Grosser   BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(),
483750160e2STobias Grosser                                  &*Builder.GetInsertPoint(), &DT, &LI);
484750160e2STobias Grosser   NewBB->setName("polly.acc.initialize");
485750160e2STobias Grosser   Builder.SetInsertPoint(&NewBB->front());
486750160e2STobias Grosser 
487fa7b0802STobias Grosser   GPUContext = createCallInitContext();
488fa7b0802STobias Grosser   allocateDeviceArrays();
489fa7b0802STobias Grosser }
490fa7b0802STobias Grosser 
491fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
4927287aeddSTobias Grosser   freeDeviceArrays();
493fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
494fa7b0802STobias Grosser   IslNodeBuilder::finalize();
495fa7b0802STobias Grosser }
496fa7b0802STobias Grosser 
497fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
498fa7b0802STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
499fa7b0802STobias Grosser 
500fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
501fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
50213c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
5037287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
5047287aeddSTobias Grosser     DevArrayName.append(Array->name);
505fa7b0802STobias Grosser 
50613c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
507aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(Array);
508aaabbbf8STobias Grosser     if (Offset)
509aaabbbf8STobias Grosser       ArraySize = Builder.CreateSub(
510aaabbbf8STobias Grosser           ArraySize,
511aaabbbf8STobias Grosser           Builder.CreateMul(Offset,
512aaabbbf8STobias Grosser                             Builder.getInt64(ScopArray->getElemSizeInBytes())));
5137287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
5147287aeddSTobias Grosser     DevArray->setName(DevArrayName);
51513c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
516fa7b0802STobias Grosser   }
517fa7b0802STobias Grosser 
518fa7b0802STobias Grosser   isl_ast_build_free(Build);
519fa7b0802STobias Grosser }
520fa7b0802STobias Grosser 
521c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX,
522c1c6a2a6STobias Grosser                                         Value *BlockDimY, Value *BlockDimZ) {
523c1c6a2a6STobias Grosser   auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations");
524c1c6a2a6STobias Grosser 
525c1c6a2a6STobias Grosser   for (auto &F : *M) {
526c1c6a2a6STobias Grosser     if (F.getCallingConv() != CallingConv::PTX_Kernel)
527c1c6a2a6STobias Grosser       continue;
528c1c6a2a6STobias Grosser 
529c1c6a2a6STobias Grosser     Value *V[] = {BlockDimX, BlockDimY, BlockDimZ};
530c1c6a2a6STobias Grosser 
531c1c6a2a6STobias Grosser     Metadata *Elements[] = {
532c1c6a2a6STobias Grosser         ValueAsMetadata::get(&F),   MDString::get(M->getContext(), "maxntidx"),
533c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"),
534c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"),
535c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[2]),
536c1c6a2a6STobias Grosser     };
537c1c6a2a6STobias Grosser     MDNode *Node = MDNode::get(M->getContext(), Elements);
538c1c6a2a6STobias Grosser     AnnotationNode->addOperand(Node);
539c1c6a2a6STobias Grosser   }
540c1c6a2a6STobias Grosser }
541c1c6a2a6STobias Grosser 
5427287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
54313c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
54413c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
5457287aeddSTobias Grosser }
5467287aeddSTobias Grosser 
54757793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
54857793596STobias Grosser   const char *Name = "polly_getKernel";
54957793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
55057793596STobias Grosser   Function *F = M->getFunction(Name);
55157793596STobias Grosser 
55257793596STobias Grosser   // If F is not available, declare it.
55357793596STobias Grosser   if (!F) {
55457793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
55557793596STobias Grosser     std::vector<Type *> Args;
55657793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
55757793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
55857793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
55957793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
56057793596STobias Grosser   }
56157793596STobias Grosser 
56257793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
56357793596STobias Grosser }
56457793596STobias Grosser 
56579a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
56679a947c2STobias Grosser   const char *Name = "polly_getDevicePtr";
56779a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
56879a947c2STobias Grosser   Function *F = M->getFunction(Name);
56979a947c2STobias Grosser 
57079a947c2STobias Grosser   // If F is not available, declare it.
57179a947c2STobias Grosser   if (!F) {
57279a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
57379a947c2STobias Grosser     std::vector<Type *> Args;
57479a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
57579a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
57679a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
57779a947c2STobias Grosser   }
57879a947c2STobias Grosser 
57979a947c2STobias Grosser   return Builder.CreateCall(F, {Allocation});
58079a947c2STobias Grosser }
58179a947c2STobias Grosser 
58279a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
58379a947c2STobias Grosser                                             Value *GridDimY, Value *BlockDimX,
58479a947c2STobias Grosser                                             Value *BlockDimY, Value *BlockDimZ,
58579a947c2STobias Grosser                                             Value *Parameters) {
58679a947c2STobias Grosser   const char *Name = "polly_launchKernel";
58779a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
58879a947c2STobias Grosser   Function *F = M->getFunction(Name);
58979a947c2STobias Grosser 
59079a947c2STobias Grosser   // If F is not available, declare it.
59179a947c2STobias Grosser   if (!F) {
59279a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
59379a947c2STobias Grosser     std::vector<Type *> Args;
59479a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
59579a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
59679a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
59779a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
59879a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
59979a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
60079a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
60179a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
60279a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
60379a947c2STobias Grosser   }
60479a947c2STobias Grosser 
605ff40087aSTobias Grosser   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
60679a947c2STobias Grosser                          BlockDimZ, Parameters});
60779a947c2STobias Grosser }
60879a947c2STobias Grosser 
60957793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
61057793596STobias Grosser   const char *Name = "polly_freeKernel";
61157793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
61257793596STobias Grosser   Function *F = M->getFunction(Name);
61357793596STobias Grosser 
61457793596STobias Grosser   // If F is not available, declare it.
61557793596STobias Grosser   if (!F) {
61657793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
61757793596STobias Grosser     std::vector<Type *> Args;
61857793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
61957793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
62057793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
62157793596STobias Grosser   }
62257793596STobias Grosser 
62357793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
62457793596STobias Grosser }
62557793596STobias Grosser 
6267287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
6277287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
6287287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
6297287aeddSTobias Grosser   Function *F = M->getFunction(Name);
6307287aeddSTobias Grosser 
6317287aeddSTobias Grosser   // If F is not available, declare it.
6327287aeddSTobias Grosser   if (!F) {
6337287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
6347287aeddSTobias Grosser     std::vector<Type *> Args;
6357287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
6367287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
6377287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
6387287aeddSTobias Grosser   }
6397287aeddSTobias Grosser 
6407287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
6417287aeddSTobias Grosser }
6427287aeddSTobias Grosser 
643fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
644fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
645fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
646fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
647fa7b0802STobias Grosser 
648fa7b0802STobias Grosser   // If F is not available, declare it.
649fa7b0802STobias Grosser   if (!F) {
650fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
651fa7b0802STobias Grosser     std::vector<Type *> Args;
652fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
653fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
654fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
655fa7b0802STobias Grosser   }
656fa7b0802STobias Grosser 
657fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
658fa7b0802STobias Grosser }
659fa7b0802STobias Grosser 
66013c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
66113c78e4dSTobias Grosser                                                     Value *DeviceData,
66213c78e4dSTobias Grosser                                                     Value *Size) {
66313c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
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, {HostData, DeviceData, Size});
67913c78e4dSTobias Grosser }
68013c78e4dSTobias Grosser 
68113c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
68213c78e4dSTobias Grosser                                                     Value *HostData,
68313c78e4dSTobias Grosser                                                     Value *Size) {
68413c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
68513c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
68613c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
68713c78e4dSTobias Grosser 
68813c78e4dSTobias Grosser   // If F is not available, declare it.
68913c78e4dSTobias Grosser   if (!F) {
69013c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
69113c78e4dSTobias Grosser     std::vector<Type *> Args;
69213c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
69313c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
69413c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
69513c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
69613c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
69713c78e4dSTobias Grosser   }
69813c78e4dSTobias Grosser 
69913c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
70013c78e4dSTobias Grosser }
70113c78e4dSTobias Grosser 
702fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
703fa7b0802STobias Grosser   const char *Name = "polly_initContext";
704fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
705fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
706fa7b0802STobias Grosser 
707fa7b0802STobias Grosser   // If F is not available, declare it.
708fa7b0802STobias Grosser   if (!F) {
709fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
710fa7b0802STobias Grosser     std::vector<Type *> Args;
711fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
712fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
713fa7b0802STobias Grosser   }
714fa7b0802STobias Grosser 
715fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
716fa7b0802STobias Grosser }
717fa7b0802STobias Grosser 
718fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
719fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
720fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
721fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
722fa7b0802STobias Grosser 
723fa7b0802STobias Grosser   // If F is not available, declare it.
724fa7b0802STobias Grosser   if (!F) {
725fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
726fa7b0802STobias Grosser     std::vector<Type *> Args;
727fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
728fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
729fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
730fa7b0802STobias Grosser   }
731fa7b0802STobias Grosser 
732fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
733fa7b0802STobias Grosser }
734fa7b0802STobias Grosser 
7355260c041STobias Grosser /// Check if one string is a prefix of another.
7365260c041STobias Grosser ///
7375260c041STobias Grosser /// @param String The string in which to look for the prefix.
7385260c041STobias Grosser /// @param Prefix The prefix to look for.
7395260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
7405260c041STobias Grosser   return String.find(Prefix) == 0;
7415260c041STobias Grosser }
7425260c041STobias Grosser 
74313c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
74413c78e4dSTobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
74513c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
74613c78e4dSTobias Grosser 
74713c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
74813c78e4dSTobias Grosser     auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]);
74913c78e4dSTobias Grosser     isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero);
75013c78e4dSTobias Grosser 
75113c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
75213c78e4dSTobias Grosser       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]);
75313c78e4dSTobias Grosser       isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
75413c78e4dSTobias Grosser       Res = isl_ast_expr_mul(Res, Expr);
75513c78e4dSTobias Grosser     }
75613c78e4dSTobias Grosser 
75713c78e4dSTobias Grosser     Value *NumElements = ExprBuilder.create(Res);
758b79f4d39STobias Grosser     if (NumElements->getType() != ArraySize->getType())
759b79f4d39STobias Grosser       NumElements = Builder.CreateSExt(NumElements, ArraySize->getType());
76013c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
76113c78e4dSTobias Grosser   }
76213c78e4dSTobias Grosser   isl_ast_build_free(Build);
76313c78e4dSTobias Grosser   return ArraySize;
76413c78e4dSTobias Grosser }
76513c78e4dSTobias Grosser 
766aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) {
767aaabbbf8STobias Grosser   if (gpu_array_is_scalar(Array))
768aaabbbf8STobias Grosser     return nullptr;
769aaabbbf8STobias Grosser 
770aaabbbf8STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
771aaabbbf8STobias Grosser 
772aaabbbf8STobias Grosser   isl_set *Min = isl_set_lexmin(isl_set_copy(Array->extent));
773aaabbbf8STobias Grosser 
774aaabbbf8STobias Grosser   isl_set *ZeroSet = isl_set_universe(isl_set_get_space(Min));
775aaabbbf8STobias Grosser 
776aaabbbf8STobias Grosser   for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++)
777aaabbbf8STobias Grosser     ZeroSet = isl_set_fix_si(ZeroSet, isl_dim_set, i, 0);
778aaabbbf8STobias Grosser 
779aaabbbf8STobias Grosser   if (isl_set_is_subset(Min, ZeroSet)) {
780aaabbbf8STobias Grosser     isl_set_free(Min);
781aaabbbf8STobias Grosser     isl_set_free(ZeroSet);
782aaabbbf8STobias Grosser     isl_ast_build_free(Build);
783aaabbbf8STobias Grosser     return nullptr;
784aaabbbf8STobias Grosser   }
785aaabbbf8STobias Grosser   isl_set_free(ZeroSet);
786aaabbbf8STobias Grosser 
787aaabbbf8STobias Grosser   isl_ast_expr *Result =
788aaabbbf8STobias Grosser       isl_ast_expr_from_val(isl_val_int_from_si(isl_set_get_ctx(Min), 0));
789aaabbbf8STobias Grosser 
790aaabbbf8STobias Grosser   for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) {
791aaabbbf8STobias Grosser     if (i > 0) {
792aaabbbf8STobias Grosser       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i - 1]);
793aaabbbf8STobias Grosser       isl_ast_expr *BExpr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
794aaabbbf8STobias Grosser       Result = isl_ast_expr_mul(Result, BExpr);
795aaabbbf8STobias Grosser     }
796aaabbbf8STobias Grosser     isl_pw_aff *DimMin = isl_set_dim_min(isl_set_copy(Min), i);
797aaabbbf8STobias Grosser     isl_ast_expr *MExpr = isl_ast_build_expr_from_pw_aff(Build, DimMin);
798aaabbbf8STobias Grosser     Result = isl_ast_expr_add(Result, MExpr);
799aaabbbf8STobias Grosser   }
800aaabbbf8STobias Grosser 
801aaabbbf8STobias Grosser   Value *ResultValue = ExprBuilder.create(Result);
802aaabbbf8STobias Grosser   isl_set_free(Min);
803aaabbbf8STobias Grosser   isl_ast_build_free(Build);
804aaabbbf8STobias Grosser 
805aaabbbf8STobias Grosser   return ResultValue;
806aaabbbf8STobias Grosser }
807aaabbbf8STobias Grosser 
80813c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
80913c78e4dSTobias Grosser                                         enum DataDirection Direction) {
81013c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
81113c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
81213c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
81313c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
81413c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
81513c78e4dSTobias Grosser 
81613c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
817aaabbbf8STobias Grosser   Value *Offset = getArrayOffset(Array);
81813c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
81913c78e4dSTobias Grosser 
820b06ff457STobias Grosser   Value *HostPtr;
821b06ff457STobias Grosser 
822b06ff457STobias Grosser   if (gpu_array_is_scalar(Array))
823b06ff457STobias Grosser     HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
824b06ff457STobias Grosser   else
825b06ff457STobias Grosser     HostPtr = ScopArray->getBasePtr();
82613c78e4dSTobias Grosser 
827aaabbbf8STobias Grosser   if (Offset) {
828aaabbbf8STobias Grosser     HostPtr = Builder.CreatePointerCast(
829aaabbbf8STobias Grosser         HostPtr, ScopArray->getElementType()->getPointerTo());
830aaabbbf8STobias Grosser     HostPtr = Builder.CreateGEP(HostPtr, Offset);
831aaabbbf8STobias Grosser   }
832aaabbbf8STobias Grosser 
83313c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
83413c78e4dSTobias Grosser 
835aaabbbf8STobias Grosser   if (Offset) {
836aaabbbf8STobias Grosser     Size = Builder.CreateSub(
837ff40087aSTobias Grosser         Size, Builder.CreateMul(
838ff40087aSTobias Grosser                   Offset, Builder.getInt64(ScopArray->getElemSizeInBytes())));
839aaabbbf8STobias Grosser   }
840aaabbbf8STobias Grosser 
84113c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
84213c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
84313c78e4dSTobias Grosser   else
84413c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
84513c78e4dSTobias Grosser 
84613c78e4dSTobias Grosser   isl_id_free(Id);
84713c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
84813c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
84913c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
85013c78e4dSTobias Grosser }
85113c78e4dSTobias Grosser 
8521fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
85332837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
85432837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
85532837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
85632837fe3STobias Grosser   isl_id_free(Id);
85732837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
85832837fe3STobias Grosser 
85932837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
86032837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
86132837fe3STobias Grosser     createKernel(UserStmt);
86232837fe3STobias Grosser     isl_ast_expr_free(Expr);
86332837fe3STobias Grosser     return;
86432837fe3STobias Grosser   }
86532837fe3STobias Grosser 
86613c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
86713c78e4dSTobias Grosser     createDataTransfer(UserStmt, HOST_TO_DEVICE);
86832837fe3STobias Grosser     isl_ast_expr_free(Expr);
86913c78e4dSTobias Grosser     return;
87013c78e4dSTobias Grosser   }
87113c78e4dSTobias Grosser 
87213c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
87313c78e4dSTobias Grosser     createDataTransfer(UserStmt, DEVICE_TO_HOST);
87413c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
87538fc0aedSTobias Grosser     return;
87638fc0aedSTobias Grosser   }
87738fc0aedSTobias Grosser 
8785260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
8795260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
8805260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
8815260c041STobias Grosser   isl_id_free(Anno);
8825260c041STobias Grosser 
8835260c041STobias Grosser   switch (KernelStmt->type) {
8845260c041STobias Grosser   case ppcg_kernel_domain:
885edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
8865260c041STobias Grosser     isl_ast_node_free(UserStmt);
8875260c041STobias Grosser     return;
8885260c041STobias Grosser   case ppcg_kernel_copy:
889b513b491STobias Grosser     createKernelCopy(KernelStmt);
8905260c041STobias Grosser     isl_ast_expr_free(Expr);
8915260c041STobias Grosser     isl_ast_node_free(UserStmt);
8925260c041STobias Grosser     return;
8935260c041STobias Grosser   case ppcg_kernel_sync:
8945260c041STobias Grosser     createKernelSync();
8955260c041STobias Grosser     isl_ast_expr_free(Expr);
8965260c041STobias Grosser     isl_ast_node_free(UserStmt);
8975260c041STobias Grosser     return;
8985260c041STobias Grosser   }
8995260c041STobias Grosser 
9005260c041STobias Grosser   isl_ast_expr_free(Expr);
9015260c041STobias Grosser   isl_ast_node_free(UserStmt);
9025260c041STobias Grosser   return;
9035260c041STobias Grosser }
904b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
905b513b491STobias Grosser   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
906b513b491STobias Grosser   LocalIndex = isl_ast_expr_address_of(LocalIndex);
907b513b491STobias Grosser   Value *LocalAddr = ExprBuilder.create(LocalIndex);
908b513b491STobias Grosser   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
909b513b491STobias Grosser   Index = isl_ast_expr_address_of(Index);
910b513b491STobias Grosser   Value *GlobalAddr = ExprBuilder.create(Index);
911b513b491STobias Grosser 
912b513b491STobias Grosser   if (KernelStmt->u.c.read) {
913b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read");
914b513b491STobias Grosser     Builder.CreateStore(Load, LocalAddr);
915b513b491STobias Grosser   } else {
916b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write");
917b513b491STobias Grosser     Builder.CreateStore(Load, GlobalAddr);
918b513b491STobias Grosser   }
919b513b491STobias Grosser }
9205260c041STobias Grosser 
921edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
922edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
923edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
924edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
925edb885cbSTobias Grosser 
926edb885cbSTobias Grosser   LoopToScevMapT LTS;
927edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
928edb885cbSTobias Grosser 
929edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
930edb885cbSTobias Grosser 
931edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
932edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
933edb885cbSTobias Grosser   else
934a82c4b5dSTobias Grosser     RegionGen.copyStmt(*Stmt, LTS, Indexes);
935edb885cbSTobias Grosser }
936edb885cbSTobias Grosser 
9375260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
9385260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9395260c041STobias Grosser   auto *Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
9405260c041STobias Grosser   Builder.CreateCall(Sync, {});
9415260c041STobias Grosser }
9425260c041STobias Grosser 
943edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
944edb885cbSTobias Grosser ///
945edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
946edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
947edb885cbSTobias Grosser ///
948edb885cbSTobias Grosser /// @param Node The node to collect references for.
949edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
950edb885cbSTobias Grosser ///
951edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
952edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
953edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
954edb885cbSTobias Grosser     return isl_bool_true;
955edb885cbSTobias Grosser 
956edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
957edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
958edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
959edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
960edb885cbSTobias Grosser   isl_id_free(Id);
961edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
962edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
963edb885cbSTobias Grosser 
964edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
965edb885cbSTobias Grosser     return isl_bool_true;
966edb885cbSTobias Grosser 
967edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
968edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
969edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
970edb885cbSTobias Grosser   isl_id_free(Id);
971edb885cbSTobias Grosser 
97200bb5a99STobias Grosser   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
973edb885cbSTobias Grosser 
974edb885cbSTobias Grosser   return isl_bool_true;
975edb885cbSTobias Grosser }
976edb885cbSTobias Grosser 
977edb885cbSTobias Grosser SetVector<Value *> GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
978edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
979edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
980edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
981edb885cbSTobias Grosser   SubtreeReferences References = {
982edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
983edb885cbSTobias Grosser 
984edb885cbSTobias Grosser   for (const auto &I : IDToValue)
985edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
986edb885cbSTobias Grosser 
987edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
988edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
989edb885cbSTobias Grosser 
990edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
991edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
992edb885cbSTobias Grosser 
993edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
994d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
995edb885cbSTobias Grosser 
996edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
997edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
998edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
999edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1000edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1001edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1002edb885cbSTobias Grosser     isl_id_free(Id);
1003edb885cbSTobias Grosser   }
1004edb885cbSTobias Grosser   isl_space_free(Space);
1005edb885cbSTobias Grosser 
1006edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
1007edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1008edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1009edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1010edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1011edb885cbSTobias Grosser     isl_id_free(Id);
1012edb885cbSTobias Grosser   }
1013edb885cbSTobias Grosser 
1014edb885cbSTobias Grosser   return SubtreeValues;
1015edb885cbSTobias Grosser }
1016edb885cbSTobias Grosser 
101774dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
101874dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
101974dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
102074dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
102174dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
102274dc3cb4STobias Grosser 
102374dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
102474dc3cb4STobias Grosser     DT.eraseNode(BB);
102574dc3cb4STobias Grosser }
102674dc3cb4STobias Grosser 
102774dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
102874dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
102974dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
103074dc3cb4STobias Grosser     if (L)
103174dc3cb4STobias Grosser       SE.forgetLoop(L);
103274dc3cb4STobias Grosser   }
103374dc3cb4STobias Grosser }
103474dc3cb4STobias Grosser 
103574dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
103674dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
103774dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
103874dc3cb4STobias Grosser     if (L)
103974dc3cb4STobias Grosser       SE.forgetLoop(L);
104074dc3cb4STobias Grosser     LI.removeBlock(&BB);
104174dc3cb4STobias Grosser   }
104274dc3cb4STobias Grosser }
104374dc3cb4STobias Grosser 
104479a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
104579a947c2STobias Grosser   std::vector<Value *> Sizes;
104679a947c2STobias Grosser   isl_ast_build *Context = isl_ast_build_from_context(S.getContext());
104779a947c2STobias Grosser 
104879a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
104979a947c2STobias Grosser     isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i);
105079a947c2STobias Grosser     isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size);
105179a947c2STobias Grosser     Value *Res = ExprBuilder.create(GridSize);
105279a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
105379a947c2STobias Grosser     Sizes.push_back(Res);
105479a947c2STobias Grosser   }
105579a947c2STobias Grosser   isl_ast_build_free(Context);
105679a947c2STobias Grosser 
105779a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
105879a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
105979a947c2STobias Grosser 
106079a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
106179a947c2STobias Grosser }
106279a947c2STobias Grosser 
106379a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
106479a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
106579a947c2STobias Grosser   std::vector<Value *> Sizes;
106679a947c2STobias Grosser 
106779a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
106879a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
106979a947c2STobias Grosser     Sizes.push_back(Res);
107079a947c2STobias Grosser   }
107179a947c2STobias Grosser 
107279a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
107379a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
107479a947c2STobias Grosser 
107579a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
107679a947c2STobias Grosser }
107779a947c2STobias Grosser 
107857693272STobias Grosser Value *
107957693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
108057693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
10814e18d71cSTobias Grosser   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(),
10824e18d71cSTobias Grosser                                  std::distance(F->arg_begin(), F->arg_end()));
108379a947c2STobias Grosser 
108479a947c2STobias Grosser   BasicBlock *EntryBlock =
108579a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
108667726b32STobias Grosser   auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace();
108779a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
108867726b32STobias Grosser   Instruction *Parameters = new AllocaInst(
108967726b32STobias Grosser       ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator());
109079a947c2STobias Grosser 
109179a947c2STobias Grosser   int Index = 0;
109279a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
109379a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
109479a947c2STobias Grosser       continue;
109579a947c2STobias Grosser 
109679a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
109779a947c2STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
109879a947c2STobias Grosser 
10990a893f7dSTobias Grosser     Value *DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
110079a947c2STobias Grosser     DevArray = createCallGetDevicePtr(DevArray);
1101aaabbbf8STobias Grosser 
1102aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(&Prog->array[i]);
1103aaabbbf8STobias Grosser 
1104aaabbbf8STobias Grosser     if (Offset) {
1105aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(
1106aaabbbf8STobias Grosser           DevArray, SAI->getElementType()->getPointerTo());
1107aaabbbf8STobias Grosser       DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset));
1108aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1109aaabbbf8STobias Grosser     }
1110fe74a7a1STobias Grosser     Value *Slot = Builder.CreateGEP(
1111fe74a7a1STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1112aaabbbf8STobias Grosser 
1113fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1114fe74a7a1STobias Grosser       Value *ValPtr = BlockGen.getOrCreateAlloca(SAI);
1115fe74a7a1STobias Grosser       Value *ValPtrCast =
1116fe74a7a1STobias Grosser           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1117fe74a7a1STobias Grosser       Builder.CreateStore(ValPtrCast, Slot);
1118fe74a7a1STobias Grosser     } else {
111967726b32STobias Grosser       Instruction *Param =
112067726b32STobias Grosser           new AllocaInst(Builder.getInt8PtrTy(), AddressSpace,
112167726b32STobias Grosser                          Launch + "_param_" + std::to_string(Index),
112279a947c2STobias Grosser                          EntryBlock->getTerminator());
112379a947c2STobias Grosser       Builder.CreateStore(DevArray, Param);
112479a947c2STobias Grosser       Value *ParamTyped =
112579a947c2STobias Grosser           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
112679a947c2STobias Grosser       Builder.CreateStore(ParamTyped, Slot);
1127fe74a7a1STobias Grosser     }
112879a947c2STobias Grosser     Index++;
112979a947c2STobias Grosser   }
113079a947c2STobias Grosser 
1131a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1132a490147cSTobias Grosser 
1133a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1134a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1135a490147cSTobias Grosser     Value *Val = IDToValue[Id];
1136a490147cSTobias Grosser     isl_id_free(Id);
113767726b32STobias Grosser     Instruction *Param =
113867726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
113967726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1140a490147cSTobias Grosser                        EntryBlock->getTerminator());
1141a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
1142a490147cSTobias Grosser     Value *Slot = Builder.CreateGEP(
1143a490147cSTobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1144a490147cSTobias Grosser     Value *ParamTyped =
1145a490147cSTobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1146a490147cSTobias Grosser     Builder.CreateStore(ParamTyped, Slot);
1147a490147cSTobias Grosser     Index++;
1148a490147cSTobias Grosser   }
1149a490147cSTobias Grosser 
1150d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1151d8b94bcaSTobias Grosser 
1152d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
1153d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1154d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
1155d8b94bcaSTobias Grosser     isl_id_free(Id);
115667726b32STobias Grosser     Instruction *Param =
115767726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
115867726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1159d8b94bcaSTobias Grosser                        EntryBlock->getTerminator());
1160d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
1161d8b94bcaSTobias Grosser     Value *Slot = Builder.CreateGEP(
1162d8b94bcaSTobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1163d8b94bcaSTobias Grosser     Value *ParamTyped =
1164d8b94bcaSTobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1165d8b94bcaSTobias Grosser     Builder.CreateStore(ParamTyped, Slot);
1166d8b94bcaSTobias Grosser     Index++;
1167d8b94bcaSTobias Grosser   }
1168d8b94bcaSTobias Grosser 
116957693272STobias Grosser   for (auto Val : SubtreeValues) {
117067726b32STobias Grosser     Instruction *Param =
117167726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
117267726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
117357693272STobias Grosser                        EntryBlock->getTerminator());
117457693272STobias Grosser     Builder.CreateStore(Val, Param);
117557693272STobias Grosser     Value *Slot = Builder.CreateGEP(
117657693272STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
117757693272STobias Grosser     Value *ParamTyped =
117857693272STobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
117957693272STobias Grosser     Builder.CreateStore(ParamTyped, Slot);
118057693272STobias Grosser     Index++;
118157693272STobias Grosser   }
118257693272STobias Grosser 
118379a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
118479a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
118579a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
118679a947c2STobias Grosser }
118779a947c2STobias Grosser 
118832837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
118932837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
119032837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
119132837fe3STobias Grosser   isl_id_free(Id);
119232837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
119332837fe3STobias Grosser 
1194bc653f20STobias Grosser   if (Kernel->n_grid > 1)
1195bc653f20STobias Grosser     DeepestParallel =
1196bc653f20STobias Grosser         std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set));
1197bc653f20STobias Grosser   else
1198bc653f20STobias Grosser     DeepestSequential =
1199bc653f20STobias Grosser         std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set));
1200bc653f20STobias Grosser 
1201c1c6a2a6STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1202c1c6a2a6STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1203c1c6a2a6STobias Grosser 
1204edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel);
1205edb885cbSTobias Grosser 
120632837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
120732837fe3STobias Grosser 
120832837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1209472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1210edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
1211587f1f57STobias Grosser   BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap;
1212b06ff457STobias Grosser   ScalarMap.clear();
121332837fe3STobias Grosser 
1214edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1215edb885cbSTobias Grosser 
1216edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
1217edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
1218edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
1219edb885cbSTobias Grosser   for (const Loop *L : Loops) {
1220edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1221edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1222edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1223edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1224edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1225edb885cbSTobias Grosser     SubtreeValues.insert(V);
1226edb885cbSTobias Grosser   }
1227edb885cbSTobias Grosser 
1228edb885cbSTobias Grosser   createKernelFunction(Kernel, SubtreeValues);
122932837fe3STobias Grosser 
123059ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
123159ab0705STobias Grosser 
123251dfc275STobias Grosser   finalizeKernelArguments(Kernel);
123374dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
1234c1c6a2a6STobias Grosser   addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
123574dc3cb4STobias Grosser   clearDominators(F);
123674dc3cb4STobias Grosser   clearScalarEvolution(F);
123774dc3cb4STobias Grosser   clearLoops(F);
123874dc3cb4STobias Grosser 
1239472f9654STobias Grosser   IDToValue = HostIDs;
124032837fe3STobias Grosser 
1241b06ff457STobias Grosser   ValueMap = std::move(HostValueMap);
1242b06ff457STobias Grosser   ScalarMap = std::move(HostScalarMap);
1243edb885cbSTobias Grosser   EscapeMap.clear();
1244edb885cbSTobias Grosser   IDToSAI.clear();
124574dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
124674dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
12474d5a9172STobias Grosser     S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array);
124874dc3cb4STobias Grosser   LocalArrays.clear();
1249edb885cbSTobias Grosser 
125051dfc275STobias Grosser   std::string ASMString = finalizeKernelFunction();
125151dfc275STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
125257693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
125379a947c2STobias Grosser 
125457793596STobias Grosser   std::string Name = "kernel_" + std::to_string(Kernel->id);
125557793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
125657793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
125757793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
125879a947c2STobias Grosser 
125979a947c2STobias Grosser   Value *GridDimX, *GridDimY;
126079a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
126179a947c2STobias Grosser 
126279a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
126379a947c2STobias Grosser                          BlockDimZ, Parameters);
126457793596STobias Grosser   createCallFreeKernel(GPUKernel);
1265b513b491STobias Grosser 
1266b513b491STobias Grosser   for (auto Id : KernelIds)
1267b513b491STobias Grosser     isl_id_free(Id);
1268b513b491STobias Grosser 
1269b513b491STobias Grosser   KernelIds.clear();
127032837fe3STobias Grosser }
127132837fe3STobias Grosser 
127232837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
127332837fe3STobias Grosser ///
127432837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
127532837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
127632837fe3STobias Grosser   std::string Ret = "e";
127732837fe3STobias Grosser 
127832837fe3STobias Grosser   if (!is64Bit)
127932837fe3STobias Grosser     Ret += "-p:32:32";
128032837fe3STobias Grosser 
128132837fe3STobias Grosser   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
128232837fe3STobias Grosser 
128332837fe3STobias Grosser   return Ret;
128432837fe3STobias Grosser }
128532837fe3STobias Grosser 
1286edb885cbSTobias Grosser Function *
1287edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1288edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
128932837fe3STobias Grosser   std::vector<Type *> Args;
129032837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
129132837fe3STobias Grosser 
129232837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
129332837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
129432837fe3STobias Grosser       continue;
129532837fe3STobias Grosser 
1296fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1297fe74a7a1STobias Grosser       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1298fe74a7a1STobias Grosser       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
1299fe74a7a1STobias Grosser       Args.push_back(SAI->getElementType());
1300fe74a7a1STobias Grosser     } else {
130132837fe3STobias Grosser       Args.push_back(Builder.getInt8PtrTy());
130232837fe3STobias Grosser     }
1303fe74a7a1STobias Grosser   }
130432837fe3STobias Grosser 
1305f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1306f6044bd0STobias Grosser 
1307f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++)
1308f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
1309f6044bd0STobias Grosser 
1310c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1311c84a1995STobias Grosser 
1312cf66ef26STobias Grosser   for (long i = 0; i < NumVars; i++) {
1313cf66ef26STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1314cf66ef26STobias Grosser     Value *Val = IDToValue[Id];
1315cf66ef26STobias Grosser     isl_id_free(Id);
1316cf66ef26STobias Grosser     Args.push_back(Val->getType());
1317cf66ef26STobias Grosser   }
1318c84a1995STobias Grosser 
1319edb885cbSTobias Grosser   for (auto *V : SubtreeValues)
1320edb885cbSTobias Grosser     Args.push_back(V->getType());
1321edb885cbSTobias Grosser 
132232837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
132332837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
132432837fe3STobias Grosser                               GPUModule.get());
132532837fe3STobias Grosser   FN->setCallingConv(CallingConv::PTX_Kernel);
132632837fe3STobias Grosser 
132732837fe3STobias Grosser   auto Arg = FN->arg_begin();
132832837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
132932837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
133032837fe3STobias Grosser       continue;
133132837fe3STobias Grosser 
1332edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
1333edb885cbSTobias Grosser 
1334edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1335edb885cbSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1336edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
1337edb885cbSTobias Grosser     Value *Val = &*Arg;
1338edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1339edb885cbSTobias Grosser     isl_ast_build *Build =
1340edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
1341f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1342edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1343edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
1344edb885cbSTobias Grosser           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
1345edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
1346edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
1347edb885cbSTobias Grosser     }
1348edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
13494d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array);
135074dc3cb4STobias Grosser     LocalArrays.push_back(Val);
1351edb885cbSTobias Grosser 
1352edb885cbSTobias Grosser     isl_ast_build_free(Build);
1353b513b491STobias Grosser     KernelIds.push_back(Id);
1354edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
135532837fe3STobias Grosser     Arg++;
135632837fe3STobias Grosser   }
135732837fe3STobias Grosser 
1358f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1359f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1360f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
1361f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
1362f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1363f6044bd0STobias Grosser     Arg++;
1364f6044bd0STobias Grosser   }
1365f6044bd0STobias Grosser 
1366c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
1367c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1368c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
136912453403STobias Grosser     Value *Val = IDToValue[Id];
137012453403STobias Grosser     ValueMap[Val] = &*Arg;
1371c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
1372c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1373c84a1995STobias Grosser     Arg++;
1374c84a1995STobias Grosser   }
1375c84a1995STobias Grosser 
1376edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
1377edb885cbSTobias Grosser     Arg->setName(V->getName());
1378edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
1379edb885cbSTobias Grosser     Arg++;
1380edb885cbSTobias Grosser   }
1381edb885cbSTobias Grosser 
138232837fe3STobias Grosser   return FN;
138332837fe3STobias Grosser }
138432837fe3STobias Grosser 
1385472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
1386472f9654STobias Grosser   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
1387472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
1388472f9654STobias Grosser 
1389472f9654STobias Grosser   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
1390472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
1391472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
1392472f9654STobias Grosser 
1393472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1394472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
1395472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1396472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1397472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1398472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1399472f9654STobias Grosser     IDToValue[Id] = Val;
1400472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1401472f9654STobias Grosser   };
1402472f9654STobias Grosser 
1403472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
1404472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1405472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
1406472f9654STobias Grosser   }
1407472f9654STobias Grosser 
1408472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
1409472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1410472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
1411472f9654STobias Grosser   }
1412472f9654STobias Grosser }
1413472f9654STobias Grosser 
141400bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
141500bb5a99STobias Grosser   auto Arg = FN->arg_begin();
141600bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
141700bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
141800bb5a99STobias Grosser       continue;
141900bb5a99STobias Grosser 
142000bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
142100bb5a99STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
142200bb5a99STobias Grosser     isl_id_free(Id);
142300bb5a99STobias Grosser 
142400bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
142500bb5a99STobias Grosser       Arg++;
142600bb5a99STobias Grosser       continue;
142700bb5a99STobias Grosser     }
142800bb5a99STobias Grosser 
1429fe74a7a1STobias Grosser     Value *Val = &*Arg;
1430fe74a7a1STobias Grosser 
1431fe74a7a1STobias Grosser     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
143200bb5a99STobias Grosser       Type *TypePtr = SAI->getElementType()->getPointerTo();
1433fe74a7a1STobias Grosser       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
1434fe74a7a1STobias Grosser       Val = Builder.CreateLoad(TypedArgPtr);
1435fe74a7a1STobias Grosser     }
1436fe74a7a1STobias Grosser 
1437fe74a7a1STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
143800bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
143900bb5a99STobias Grosser 
144000bb5a99STobias Grosser     Arg++;
144100bb5a99STobias Grosser   }
144200bb5a99STobias Grosser }
144300bb5a99STobias Grosser 
144451dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) {
144551dfc275STobias Grosser   auto *FN = Builder.GetInsertBlock()->getParent();
144651dfc275STobias Grosser   auto Arg = FN->arg_begin();
144751dfc275STobias Grosser 
144851dfc275STobias Grosser   bool StoredScalar = false;
144951dfc275STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
145051dfc275STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
145151dfc275STobias Grosser       continue;
145251dfc275STobias Grosser 
145351dfc275STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
145451dfc275STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
145551dfc275STobias Grosser     isl_id_free(Id);
145651dfc275STobias Grosser 
145751dfc275STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
145851dfc275STobias Grosser       Arg++;
145951dfc275STobias Grosser       continue;
146051dfc275STobias Grosser     }
146151dfc275STobias Grosser 
146251dfc275STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
146351dfc275STobias Grosser       Arg++;
146451dfc275STobias Grosser       continue;
146551dfc275STobias Grosser     }
146651dfc275STobias Grosser 
146751dfc275STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
146851dfc275STobias Grosser     Value *ArgPtr = &*Arg;
146951dfc275STobias Grosser     Type *TypePtr = SAI->getElementType()->getPointerTo();
147051dfc275STobias Grosser     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
147151dfc275STobias Grosser     Value *Val = Builder.CreateLoad(Alloca);
147251dfc275STobias Grosser     Builder.CreateStore(Val, TypedArgPtr);
147351dfc275STobias Grosser     StoredScalar = true;
147451dfc275STobias Grosser 
147551dfc275STobias Grosser     Arg++;
147651dfc275STobias Grosser   }
147751dfc275STobias Grosser 
147851dfc275STobias Grosser   if (StoredScalar)
147951dfc275STobias Grosser     /// In case more than one thread contains scalar stores, the generated
148051dfc275STobias Grosser     /// code might be incorrect, if we only store at the end of the kernel.
148151dfc275STobias Grosser     /// To support this case we need to store these scalars back at each
148251dfc275STobias Grosser     /// memory store or at least before each kernel barrier.
148351dfc275STobias Grosser     if (Kernel->n_block != 0 || Kernel->n_grid != 0)
148451dfc275STobias Grosser       BuildSuccessful = 0;
148551dfc275STobias Grosser }
148651dfc275STobias Grosser 
1487b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
1488b513b491STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1489b513b491STobias Grosser 
1490b513b491STobias Grosser   for (int i = 0; i < Kernel->n_var; ++i) {
1491b513b491STobias Grosser     struct ppcg_kernel_var &Var = Kernel->var[i];
1492b513b491STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
1493b513b491STobias Grosser     Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType();
1494b513b491STobias Grosser 
1495f919d8b3STobias Grosser     Type *ArrayTy = EleTy;
1496b513b491STobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1497b513b491STobias Grosser 
1498f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1499928d7573STobias Grosser     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
1500b513b491STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1501f919d8b3STobias Grosser       long Bound = isl_val_get_num_si(Val);
1502b513b491STobias Grosser       isl_val_free(Val);
1503b513b491STobias Grosser       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
1504928d7573STobias Grosser     }
1505928d7573STobias Grosser 
1506928d7573STobias Grosser     for (int j = Var.array->n_index - 1; j >= 0; --j) {
1507928d7573STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1508928d7573STobias Grosser       long Bound = isl_val_get_num_si(Val);
1509928d7573STobias Grosser       isl_val_free(Val);
1510b513b491STobias Grosser       ArrayTy = ArrayType::get(ArrayTy, Bound);
1511b513b491STobias Grosser     }
1512b513b491STobias Grosser 
1513130ca30fSTobias Grosser     const ScopArrayInfo *SAI;
1514130ca30fSTobias Grosser     Value *Allocation;
1515130ca30fSTobias Grosser     if (Var.type == ppcg_access_shared) {
1516130ca30fSTobias Grosser       auto GlobalVar = new GlobalVariable(
1517130ca30fSTobias Grosser           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
1518130ca30fSTobias Grosser           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
1519130ca30fSTobias Grosser       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
1520f919d8b3STobias Grosser       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
1521f919d8b3STobias Grosser 
1522130ca30fSTobias Grosser       Allocation = GlobalVar;
1523130ca30fSTobias Grosser     } else if (Var.type == ppcg_access_private) {
1524130ca30fSTobias Grosser       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
1525130ca30fSTobias Grosser     } else {
1526130ca30fSTobias Grosser       llvm_unreachable("unknown variable type");
1527130ca30fSTobias Grosser     }
15284d5a9172STobias Grosser     SAI =
15294d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array);
1530b513b491STobias Grosser     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
1531130ca30fSTobias Grosser     IDToValue[Id] = Allocation;
1532130ca30fSTobias Grosser     LocalArrays.push_back(Allocation);
1533b513b491STobias Grosser     KernelIds.push_back(Id);
1534b513b491STobias Grosser     IDToSAI[Id] = SAI;
1535b513b491STobias Grosser   }
1536b513b491STobias Grosser }
1537b513b491STobias Grosser 
1538edb885cbSTobias Grosser void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel,
1539edb885cbSTobias Grosser                                           SetVector<Value *> &SubtreeValues) {
154032837fe3STobias Grosser 
154132837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
154232837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
154332837fe3STobias Grosser   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
154432837fe3STobias Grosser   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
154532837fe3STobias Grosser 
1546edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
154732837fe3STobias Grosser 
154859ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
154932837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
155032837fe3STobias Grosser 
155159ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
155259ab0705STobias Grosser 
155332837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
155432837fe3STobias Grosser   Builder.CreateRetVoid();
155532837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
1556472f9654STobias Grosser 
1557629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
1558629109b6STobias Grosser 
155900bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
1560b513b491STobias Grosser   createKernelVariables(Kernel, FN);
1561472f9654STobias Grosser   insertKernelIntrinsics(Kernel);
156232837fe3STobias Grosser }
156332837fe3STobias Grosser 
156474dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
156574dc3cb4STobias Grosser   llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda"));
156674dc3cb4STobias Grosser   std::string ErrMsg;
156774dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
156874dc3cb4STobias Grosser 
156974dc3cb4STobias Grosser   if (!GPUTarget) {
157074dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
157174dc3cb4STobias Grosser     return "";
157274dc3cb4STobias Grosser   }
157374dc3cb4STobias Grosser 
157474dc3cb4STobias Grosser   TargetOptions Options;
157574dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
157674dc3cb4STobias Grosser   std::unique_ptr<TargetMachine> TargetM(
157774dc3cb4STobias Grosser       GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "",
157874dc3cb4STobias Grosser                                      Options, Optional<Reloc::Model>()));
157974dc3cb4STobias Grosser 
158074dc3cb4STobias Grosser   SmallString<0> ASMString;
158174dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
158274dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
158374dc3cb4STobias Grosser 
158474dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
158574dc3cb4STobias Grosser 
158674dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
158774dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
158874dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
158974dc3cb4STobias Grosser     return "";
159074dc3cb4STobias Grosser   }
159174dc3cb4STobias Grosser 
159274dc3cb4STobias Grosser   PM.run(*GPUModule);
159374dc3cb4STobias Grosser 
159474dc3cb4STobias Grosser   return ASMStream.str();
159574dc3cb4STobias Grosser }
159674dc3cb4STobias Grosser 
159757793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
15985857b701STobias Grosser   if (verifyModule(*GPUModule)) {
15995857b701STobias Grosser     BuildSuccessful = false;
16005857b701STobias Grosser     return "";
16015857b701STobias Grosser   }
160232837fe3STobias Grosser 
160332837fe3STobias Grosser   if (DumpKernelIR)
160432837fe3STobias Grosser     outs() << *GPUModule << "\n";
160532837fe3STobias Grosser 
16069a18d559STobias Grosser   // Optimize module.
16079a18d559STobias Grosser   llvm::legacy::PassManager OptPasses;
16089a18d559STobias Grosser   PassManagerBuilder PassBuilder;
16099a18d559STobias Grosser   PassBuilder.OptLevel = 3;
16109a18d559STobias Grosser   PassBuilder.SizeLevel = 0;
16119a18d559STobias Grosser   PassBuilder.populateModulePassManager(OptPasses);
16129a18d559STobias Grosser   OptPasses.run(*GPUModule);
16139a18d559STobias Grosser 
161474dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
161574dc3cb4STobias Grosser 
161674dc3cb4STobias Grosser   if (DumpKernelASM)
161774dc3cb4STobias Grosser     outs() << Assembly << "\n";
161874dc3cb4STobias Grosser 
161932837fe3STobias Grosser   GPUModule.release();
1620472f9654STobias Grosser   KernelIDs.clear();
162157793596STobias Grosser 
162257793596STobias Grosser   return Assembly;
162332837fe3STobias Grosser }
162432837fe3STobias Grosser 
16259dfe4e7cSTobias Grosser namespace {
16269dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
16279dfe4e7cSTobias Grosser public:
16289dfe4e7cSTobias Grosser   static char ID;
16299dfe4e7cSTobias Grosser 
1630e938517eSTobias Grosser   /// The scop that is currently processed.
1631e938517eSTobias Grosser   Scop *S;
1632e938517eSTobias Grosser 
163338fc0aedSTobias Grosser   LoopInfo *LI;
163438fc0aedSTobias Grosser   DominatorTree *DT;
163538fc0aedSTobias Grosser   ScalarEvolution *SE;
163638fc0aedSTobias Grosser   const DataLayout *DL;
163738fc0aedSTobias Grosser   RegionInfo *RI;
163838fc0aedSTobias Grosser 
16399dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
16409dfe4e7cSTobias Grosser 
1641e938517eSTobias Grosser   /// Construct compilation options for PPCG.
1642e938517eSTobias Grosser   ///
1643e938517eSTobias Grosser   /// @returns The compilation options.
1644e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
1645e938517eSTobias Grosser     auto DebugOptions =
1646e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
1647e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
1648e938517eSTobias Grosser 
1649e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
1650e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
1651e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
1652e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
16538950ceadSTobias Grosser     DebugOptions->verbose = false;
1654e938517eSTobias Grosser 
1655e938517eSTobias Grosser     Options->debug = DebugOptions;
1656e938517eSTobias Grosser 
1657e938517eSTobias Grosser     Options->reschedule = true;
1658e938517eSTobias Grosser     Options->scale_tile_loops = false;
1659e938517eSTobias Grosser     Options->wrap = false;
1660e938517eSTobias Grosser 
1661e938517eSTobias Grosser     Options->non_negative_parameters = false;
1662e938517eSTobias Grosser     Options->ctx = nullptr;
1663e938517eSTobias Grosser     Options->sizes = nullptr;
1664e938517eSTobias Grosser 
16654eaedde5STobias Grosser     Options->tile_size = 32;
16664eaedde5STobias Grosser 
1667130ca30fSTobias Grosser     Options->use_private_memory = PrivateMemory;
1668b513b491STobias Grosser     Options->use_shared_memory = SharedMemory;
1669b513b491STobias Grosser     Options->max_shared_memory = 48 * 1024;
1670e938517eSTobias Grosser 
1671e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
1672e938517eSTobias Grosser     Options->openmp = false;
1673e938517eSTobias Grosser     Options->linearize_device_arrays = true;
1674e938517eSTobias Grosser     Options->live_range_reordering = false;
1675e938517eSTobias Grosser 
1676e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
1677e938517eSTobias Grosser     Options->opencl_use_gpu = false;
1678e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
1679e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
1680e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
1681e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
1682e938517eSTobias Grosser 
1683e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
1684e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
1685e938517eSTobias Grosser 
1686e938517eSTobias Grosser     return Options;
1687e938517eSTobias Grosser   }
1688e938517eSTobias Grosser 
1689f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
1690f384594dSTobias Grosser   ///
1691f384594dSTobias Grosser   /// Instead of a normal access of the form:
1692f384594dSTobias Grosser   ///
1693f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
1694f384594dSTobias Grosser   ///
1695f384594dSTobias Grosser   /// a tagged access has the form
1696f384594dSTobias Grosser   ///
1697f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
1698f384594dSTobias Grosser   ///
1699f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
1700f384594dSTobias Grosser   /// triggered the access.
1701f384594dSTobias Grosser   ///
1702f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
1703f384594dSTobias Grosser   ///
1704f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
1705f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
1706f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
1707f384594dSTobias Grosser 
1708f384594dSTobias Grosser     for (auto &Stmt : *S)
1709f384594dSTobias Grosser       for (auto &Acc : Stmt)
1710f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
1711f384594dSTobias Grosser           isl_map *Relation = Acc->getAccessRelation();
1712f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
1713f384594dSTobias Grosser 
1714f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
1715f384594dSTobias Grosser           Space = isl_space_range(Space);
1716f384594dSTobias Grosser           Space = isl_space_from_range(Space);
17176293ba69STobias Grosser           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1718f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
1719f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
1720f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
1721f384594dSTobias Grosser         }
1722f384594dSTobias Grosser 
1723f384594dSTobias Grosser     return Accesses;
1724f384594dSTobias Grosser   }
1725f384594dSTobias Grosser 
1726f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
1727f384594dSTobias Grosser   ///
1728f384594dSTobias Grosser   /// @see getTaggedAccesses
1729f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
1730f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
1731f384594dSTobias Grosser   }
1732f384594dSTobias Grosser 
1733f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
1734f384594dSTobias Grosser   ///
1735f384594dSTobias Grosser   /// @see getTaggedAccesses
1736f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
1737f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
1738f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
1739f384594dSTobias Grosser   }
1740f384594dSTobias Grosser 
1741f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
1742f384594dSTobias Grosser   ///
1743f384594dSTobias Grosser   /// @see getTaggedAccesses
1744f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
1745f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
1746f384594dSTobias Grosser   }
1747f384594dSTobias Grosser 
1748aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
1749aef5196fSTobias Grosser   ///
1750aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
1751aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
1752aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
1753aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
1754aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
1755aef5196fSTobias Grosser   /// the data format that ppcg expects.
1756aef5196fSTobias Grosser   ///
1757aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
1758aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
1759aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
1760bd81a7eeSTobias Grosser         S->getIslCtx(),
1761bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
1762aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
1763aef5196fSTobias Grosser     auto *Space = S->getParamSpace();
1764aef5196fSTobias Grosser 
1765aef5196fSTobias Grosser     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
1766aef5196fSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
1767aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1768aef5196fSTobias Grosser     }
1769aef5196fSTobias Grosser 
1770aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
1771d7754a12SRoman Gareev       auto Id = Array->getBasePtrId();
1772aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1773aef5196fSTobias Grosser     }
1774aef5196fSTobias Grosser 
1775aef5196fSTobias Grosser     isl_space_free(Space);
1776aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
1777aef5196fSTobias Grosser 
1778aef5196fSTobias Grosser     return Names;
1779aef5196fSTobias Grosser   }
1780aef5196fSTobias Grosser 
1781e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
1782e938517eSTobias Grosser   ///
1783f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
1784f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
1785f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
1786f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
1787e938517eSTobias Grosser   ///
1788e938517eSTobias Grosser   /// @returns A new ppcg scop.
1789e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
1790e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
1791e938517eSTobias Grosser 
1792e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
1793e938517eSTobias Grosser 
1794e938517eSTobias Grosser     PPCGScop->start = 0;
1795e938517eSTobias Grosser     PPCGScop->end = 0;
1796e938517eSTobias Grosser 
1797f384594dSTobias Grosser     PPCGScop->context = S->getContext();
1798f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
1799e938517eSTobias Grosser     PPCGScop->call = nullptr;
1800f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
1801f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
1802e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
1803f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
1804f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
1805f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
1806f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
1807e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
1808f384594dSTobias Grosser     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
1809e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
1810e938517eSTobias Grosser 
1811e938517eSTobias Grosser     PPCGScop->independence = nullptr;
1812e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
1813e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
1814e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
1815e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
1816e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
1817e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
1818e938517eSTobias Grosser 
1819f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
1820aef5196fSTobias Grosser     PPCGScop->names = getNames();
1821e938517eSTobias Grosser 
1822e938517eSTobias Grosser     PPCGScop->pet = nullptr;
1823e938517eSTobias Grosser 
1824f384594dSTobias Grosser     compute_tagger(PPCGScop);
1825f384594dSTobias Grosser     compute_dependences(PPCGScop);
1826f384594dSTobias Grosser 
1827e938517eSTobias Grosser     return PPCGScop;
1828e938517eSTobias Grosser   }
1829e938517eSTobias Grosser 
183060f63b49STobias Grosser   /// Collect the array acesses in a statement.
183160f63b49STobias Grosser   ///
183260f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
183360f63b49STobias Grosser   ///
183460f63b49STobias Grosser   /// @returns A list of array accesses.
183560f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
183660f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
183760f63b49STobias Grosser 
183860f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
183960f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
184060f63b49STobias Grosser       Access->read = Acc->isRead();
184160f63b49STobias Grosser       Access->write = Acc->isWrite();
184260f63b49STobias Grosser       Access->access = Acc->getAccessRelation();
184360f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
184460f63b49STobias Grosser       Space = isl_space_range(Space);
184560f63b49STobias Grosser       Space = isl_space_from_range(Space);
18466293ba69STobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
184760f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
184860f63b49STobias Grosser       Access->tagged_access =
184960f63b49STobias Grosser           isl_map_domain_product(Acc->getAccessRelation(), Universe);
1850b513b491STobias Grosser       Access->exact_write = !Acc->isMayWrite();
185160f63b49STobias Grosser       Access->ref_id = Acc->getId();
185260f63b49STobias Grosser       Access->next = Accesses;
1853b513b491STobias Grosser       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
185460f63b49STobias Grosser       Accesses = Access;
185560f63b49STobias Grosser     }
185660f63b49STobias Grosser 
185760f63b49STobias Grosser     return Accesses;
185860f63b49STobias Grosser   }
185960f63b49STobias Grosser 
186069b46751STobias Grosser   /// Collect the list of GPU statements.
186169b46751STobias Grosser   ///
186269b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
186369b46751STobias Grosser   /// as well as a list with all memory accesses.
186469b46751STobias Grosser   ///
186569b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
186669b46751STobias Grosser   ///
186769b46751STobias Grosser   /// @returns A linked-list of statements.
186869b46751STobias Grosser   gpu_stmt *getStatements() {
186969b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
187069b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
187169b46751STobias Grosser 
187269b46751STobias Grosser     int i = 0;
187369b46751STobias Grosser     for (auto &Stmt : *S) {
187469b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
187569b46751STobias Grosser 
187669b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
187769b46751STobias Grosser 
187869b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
187969b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
188060f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
188169b46751STobias Grosser       i++;
188269b46751STobias Grosser     }
188369b46751STobias Grosser 
188469b46751STobias Grosser     return Stmts;
188569b46751STobias Grosser   }
188669b46751STobias Grosser 
188760f63b49STobias Grosser   /// Derive the extent of an array.
188860f63b49STobias Grosser   ///
1889d58acf86STobias Grosser   /// The extent of an array is the set of elements that are within the
1890d58acf86STobias Grosser   /// accessed array. For the inner dimensions, the extent constraints are
1891d58acf86STobias Grosser   /// 0 and the size of the corresponding array dimension. For the first
1892d58acf86STobias Grosser   /// (outermost) dimension, the extent constraints are the minimal and maximal
1893d58acf86STobias Grosser   /// subscript value for the first dimension.
189460f63b49STobias Grosser   ///
189560f63b49STobias Grosser   /// @param Array The array to derive the extent for.
189660f63b49STobias Grosser   ///
189760f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
189860f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
1899d58acf86STobias Grosser     unsigned NumDims = Array->getNumberOfDimensions();
190060f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
190160f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
1902d58acf86STobias Grosser     Accesses = isl_union_map_detect_equalities(Accesses);
190360f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
1904d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
1905d58acf86STobias Grosser     AccessUSet = isl_union_set_detect_equalities(AccessUSet);
1906d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
1907d58acf86STobias Grosser 
1908d58acf86STobias Grosser     if (isl_union_set_is_empty(AccessUSet)) {
1909d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
1910d58acf86STobias Grosser       return isl_set_empty(Array->getSpace());
1911d58acf86STobias Grosser     }
1912d58acf86STobias Grosser 
1913d58acf86STobias Grosser     if (Array->getNumberOfDimensions() == 0) {
1914d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
1915d58acf86STobias Grosser       return isl_set_universe(Array->getSpace());
1916d58acf86STobias Grosser     }
1917d58acf86STobias Grosser 
191860f63b49STobias Grosser     isl_set *AccessSet =
191960f63b49STobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace());
192060f63b49STobias Grosser 
1921d58acf86STobias Grosser     isl_union_set_free(AccessUSet);
1922d58acf86STobias Grosser     isl_local_space *LS = isl_local_space_from_space(Array->getSpace());
1923d58acf86STobias Grosser 
1924d58acf86STobias Grosser     isl_pw_aff *Val =
1925d58acf86STobias Grosser         isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0));
1926d58acf86STobias Grosser 
1927d58acf86STobias Grosser     isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0);
1928d58acf86STobias Grosser     isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0);
1929d58acf86STobias Grosser     OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in,
1930d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
1931d58acf86STobias Grosser     OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in,
1932d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
1933d58acf86STobias Grosser     OuterMin =
1934d58acf86STobias Grosser         isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, Array->getBasePtrId());
1935d58acf86STobias Grosser     OuterMax =
1936d58acf86STobias Grosser         isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, Array->getBasePtrId());
1937d58acf86STobias Grosser 
1938d58acf86STobias Grosser     isl_set *Extent = isl_set_universe(Array->getSpace());
1939d58acf86STobias Grosser 
1940d58acf86STobias Grosser     Extent = isl_set_intersect(
1941d58acf86STobias Grosser         Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val)));
1942d58acf86STobias Grosser     Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val));
1943d58acf86STobias Grosser 
1944d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i)
1945d58acf86STobias Grosser       Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0);
1946d58acf86STobias Grosser 
1947d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i) {
1948d58acf86STobias Grosser       isl_pw_aff *PwAff =
1949d58acf86STobias Grosser           const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i));
1950d58acf86STobias Grosser       isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain(
1951d58acf86STobias Grosser           isl_local_space_from_space(Array->getSpace()), isl_dim_set, i));
1952d58acf86STobias Grosser       PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in,
1953d58acf86STobias Grosser                                   isl_pw_aff_dim(Val, isl_dim_in));
1954d58acf86STobias Grosser       PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in,
1955d58acf86STobias Grosser                                       isl_pw_aff_get_tuple_id(Val, isl_dim_in));
1956d58acf86STobias Grosser       auto *Set = isl_pw_aff_gt_set(PwAff, Val);
1957d58acf86STobias Grosser       Extent = isl_set_intersect(Set, Extent);
1958d58acf86STobias Grosser     }
1959d58acf86STobias Grosser 
1960d58acf86STobias Grosser     return Extent;
196160f63b49STobias Grosser   }
196260f63b49STobias Grosser 
196360f63b49STobias Grosser   /// Derive the bounds of an array.
196460f63b49STobias Grosser   ///
196560f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
196660f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
196760f63b49STobias Grosser   /// ScopArrayInfo.
196860f63b49STobias Grosser   ///
196960f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
197060f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
197160f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
197260f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
197302293ed7STobias Grosser       if (isl_set_is_empty(PPCGArray.extent)) {
197402293ed7STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
197502293ed7STobias Grosser         isl_local_space *LS = isl_local_space_from_space(
197602293ed7STobias Grosser             isl_space_params(isl_set_get_space(Dom)));
197702293ed7STobias Grosser         isl_set_free(Dom);
197802293ed7STobias Grosser         isl_aff *Zero = isl_aff_zero_on_domain(LS);
197902293ed7STobias Grosser         PPCGArray.bound[0] = isl_pw_aff_from_aff(Zero);
198002293ed7STobias Grosser       } else {
198160f63b49STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
198260f63b49STobias Grosser         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
198360f63b49STobias Grosser         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
198460f63b49STobias Grosser         isl_set_free(Dom);
198560f63b49STobias Grosser         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
198602293ed7STobias Grosser         isl_local_space *LS =
198702293ed7STobias Grosser             isl_local_space_from_space(isl_set_get_space(Dom));
198860f63b49STobias Grosser         isl_aff *One = isl_aff_zero_on_domain(LS);
198960f63b49STobias Grosser         One = isl_aff_add_constant_si(One, 1);
199060f63b49STobias Grosser         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
199160f63b49STobias Grosser         Bound = isl_pw_aff_gist(Bound, S->getContext());
199260f63b49STobias Grosser         PPCGArray.bound[0] = Bound;
199360f63b49STobias Grosser       }
199402293ed7STobias Grosser     }
199560f63b49STobias Grosser 
199660f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
199760f63b49STobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
199860f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
199960f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
200060f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
200160f63b49STobias Grosser       PPCGArray.bound[i] = Bound;
200260f63b49STobias Grosser     }
200360f63b49STobias Grosser   }
200460f63b49STobias Grosser 
200560f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
200660f63b49STobias Grosser   ///
200760f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
200860f63b49STobias Grosser   void createArrays(gpu_prog *PPCGProg) {
200960f63b49STobias Grosser     int i = 0;
2010d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
201160f63b49STobias Grosser       std::string TypeName;
201260f63b49STobias Grosser       raw_string_ostream OS(TypeName);
201360f63b49STobias Grosser 
201460f63b49STobias Grosser       OS << *Array->getElementType();
201560f63b49STobias Grosser       TypeName = OS.str();
201660f63b49STobias Grosser 
201760f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
201860f63b49STobias Grosser 
201960f63b49STobias Grosser       PPCGArray.space = Array->getSpace();
202060f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
202160f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
202260f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
202360f63b49STobias Grosser       PPCGArray.extent = nullptr;
202460f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
202560f63b49STobias Grosser       PPCGArray.bound =
202660f63b49STobias Grosser           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
202760f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
202860f63b49STobias Grosser       PPCGArray.n_ref = 0;
202960f63b49STobias Grosser       PPCGArray.refs = nullptr;
203060f63b49STobias Grosser       PPCGArray.accessed = true;
2031fe74a7a1STobias Grosser       PPCGArray.read_only_scalar =
2032fe74a7a1STobias Grosser           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
203360f63b49STobias Grosser       PPCGArray.has_compound_element = false;
203460f63b49STobias Grosser       PPCGArray.local = false;
203560f63b49STobias Grosser       PPCGArray.declare_local = false;
203660f63b49STobias Grosser       PPCGArray.global = false;
203760f63b49STobias Grosser       PPCGArray.linearize = false;
203860f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
203913c78e4dSTobias Grosser       PPCGArray.user = Array;
204060f63b49STobias Grosser 
204160f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
20422d010dafSTobias Grosser       i++;
2043b9fc860aSTobias Grosser 
2044b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
204560f63b49STobias Grosser     }
204660f63b49STobias Grosser   }
204760f63b49STobias Grosser 
204860f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
204960f63b49STobias Grosser   ///
205060f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
205160f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
205260f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
205360f63b49STobias Grosser 
2054d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
205560f63b49STobias Grosser       isl_space *Space = Array->getSpace();
205660f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
205760f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
205860f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
205960f63b49STobias Grosser     }
206060f63b49STobias Grosser 
206160f63b49STobias Grosser     return Maps;
206260f63b49STobias Grosser   }
206360f63b49STobias Grosser 
2064e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
2065e938517eSTobias Grosser   ///
2066e938517eSTobias Grosser   /// @returns A new gpu grogram description.
2067e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
2068e938517eSTobias Grosser 
2069e938517eSTobias Grosser     if (!PPCGScop)
2070e938517eSTobias Grosser       return nullptr;
2071e938517eSTobias Grosser 
2072e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
2073e938517eSTobias Grosser 
2074e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
2075e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
2076aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
207760f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
207860f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
207960f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
208060f63b49STobias Grosser     PPCGProg->tagged_must_kill =
208160f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
208260f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
208360f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
2084e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
2085e938517eSTobias Grosser     PPCGProg->array_order = nullptr;
208669b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
208769b46751STobias Grosser     PPCGProg->stmts = getStatements();
208860f63b49STobias Grosser     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
208960f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
209060f63b49STobias Grosser                                        PPCGProg->n_array);
209160f63b49STobias Grosser 
209260f63b49STobias Grosser     createArrays(PPCGProg);
2093e938517eSTobias Grosser 
2094d58acf86STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
2095d58acf86STobias Grosser 
2096e938517eSTobias Grosser     return PPCGProg;
2097e938517eSTobias Grosser   }
2098e938517eSTobias Grosser 
209969b46751STobias Grosser   struct PrintGPUUserData {
210069b46751STobias Grosser     struct cuda_info *CudaInfo;
210169b46751STobias Grosser     struct gpu_prog *PPCGProg;
210269b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
210369b46751STobias Grosser   };
210469b46751STobias Grosser 
210569b46751STobias Grosser   /// Print a user statement node in the host code.
210669b46751STobias Grosser   ///
210769b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
210869b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
210969b46751STobias Grosser   /// host ast.
211069b46751STobias Grosser   ///
211169b46751STobias Grosser   /// @param P The printer to print to
211269b46751STobias Grosser   /// @param Options The printing options to use
211369b46751STobias Grosser   /// @param Node The node to print
211469b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
211569b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
211669b46751STobias Grosser   ///
211769b46751STobias Grosser   /// @returns A printer to which the output has been printed.
211869b46751STobias Grosser   static __isl_give isl_printer *
211969b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
212069b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
212169b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
212269b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
212369b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
212469b46751STobias Grosser 
212569b46751STobias Grosser     if (Id) {
212620251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
212720251734STobias Grosser 
212820251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
212920251734STobias Grosser       // otherwise try to call pet functionality that is not available in
213020251734STobias Grosser       // Polly.
213120251734STobias Grosser       if (IsUser) {
213220251734STobias Grosser         P = isl_printer_start_line(P);
213320251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
213420251734STobias Grosser         P = isl_printer_end_line(P);
213520251734STobias Grosser         isl_id_free(Id);
213620251734STobias Grosser         isl_ast_print_options_free(Options);
213720251734STobias Grosser         return P;
213820251734STobias Grosser       }
213920251734STobias Grosser 
214069b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
214169b46751STobias Grosser       isl_id_free(Id);
214269b46751STobias Grosser       Data->Kernels.push_back(Kernel);
214369b46751STobias Grosser     }
214469b46751STobias Grosser 
214569b46751STobias Grosser     return print_host_user(P, Options, Node, User);
214669b46751STobias Grosser   }
214769b46751STobias Grosser 
214869b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
214969b46751STobias Grosser   ///
215069b46751STobias Grosser   /// @param Kernel The kernel to print
215169b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
215269b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
215369b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
215469b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
215569b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
215669b46751STobias Grosser     char *String = isl_printer_get_str(P);
215769b46751STobias Grosser     printf("%s\n", String);
215869b46751STobias Grosser     free(String);
215969b46751STobias Grosser     isl_printer_free(P);
216069b46751STobias Grosser   }
216169b46751STobias Grosser 
216269b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
216369b46751STobias Grosser   ///
216469b46751STobias Grosser   /// @param Tree An AST describing GPU code
216569b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
216669b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
216769b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
216869b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
216969b46751STobias Grosser 
217069b46751STobias Grosser     PrintGPUUserData Data;
217169b46751STobias Grosser     Data.PPCGProg = PPCGProg;
217269b46751STobias Grosser 
217369b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
217469b46751STobias Grosser     Options =
217569b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
217669b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
217769b46751STobias Grosser     char *String = isl_printer_get_str(P);
217869b46751STobias Grosser     printf("# host\n");
217969b46751STobias Grosser     printf("%s\n", String);
218069b46751STobias Grosser     free(String);
218169b46751STobias Grosser     isl_printer_free(P);
218269b46751STobias Grosser 
218369b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
218469b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
218569b46751STobias Grosser       printKernel(Kernel);
218669b46751STobias Grosser     }
218769b46751STobias Grosser   }
218869b46751STobias Grosser 
2189f384594dSTobias Grosser   // Generate a GPU program using PPCG.
2190f384594dSTobias Grosser   //
2191f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
2192f384594dSTobias Grosser   //
2193f384594dSTobias Grosser   //  1) Compute new schedule for the program.
2194f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
2195f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
2196f384594dSTobias Grosser   //
2197f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
2198f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
2199f384594dSTobias Grosser   // strategy directly from this pass.
2200f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
2201f384594dSTobias Grosser 
2202f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
2203f384594dSTobias Grosser 
2204f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
2205f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
2206f384594dSTobias Grosser     PPCGGen->print = nullptr;
2207f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
220860c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
2209f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
2210f384594dSTobias Grosser     PPCGGen->tree = nullptr;
2211f384594dSTobias Grosser     PPCGGen->types.n = 0;
2212f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
2213f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
2214f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
2215f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
2216f384594dSTobias Grosser 
2217f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
2218f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
2219f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
22202341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
2221f384594dSTobias Grosser 
2222f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
2223f384594dSTobias Grosser 
2224aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
2225aef5196fSTobias Grosser 
222669b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
2227aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
222869b46751STobias Grosser     } else {
2229aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
223069b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
223169b46751STobias Grosser     }
2232aef5196fSTobias Grosser 
2233f384594dSTobias Grosser     if (DumpSchedule) {
2234f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
2235f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
2236f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
2237f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
2238f384594dSTobias Grosser       if (Schedule)
2239f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
2240f384594dSTobias Grosser       else
2241f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
2242f384594dSTobias Grosser 
2243f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
2244f384594dSTobias Grosser       isl_printer_free(P);
2245f384594dSTobias Grosser     }
2246f384594dSTobias Grosser 
224769b46751STobias Grosser     if (DumpCode) {
224869b46751STobias Grosser       printf("Code\n");
224969b46751STobias Grosser       printf("====\n");
225069b46751STobias Grosser       if (PPCGGen->tree)
225169b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
225269b46751STobias Grosser       else
225369b46751STobias Grosser         printf("No code generated\n");
225469b46751STobias Grosser     }
225569b46751STobias Grosser 
2256f384594dSTobias Grosser     isl_schedule_free(Schedule);
2257f384594dSTobias Grosser 
2258f384594dSTobias Grosser     return PPCGGen;
2259f384594dSTobias Grosser   }
2260f384594dSTobias Grosser 
2261f384594dSTobias Grosser   /// Free gpu_gen structure.
2262f384594dSTobias Grosser   ///
2263f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
2264f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
2265f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
2266f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
2267f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
2268f384594dSTobias Grosser     free(PPCGGen);
2269f384594dSTobias Grosser   }
2270f384594dSTobias Grosser 
2271b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
2272b307ed4dSTobias Grosser   ///
2273b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
2274b307ed4dSTobias Grosser   /// ourselves.
2275b307ed4dSTobias Grosser   ///
2276b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
2277b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
2278b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
2279b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
2280b307ed4dSTobias Grosser     free(PPCGScop->options);
2281b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
2282b307ed4dSTobias Grosser   }
2283b307ed4dSTobias Grosser 
228482f2af35STobias Grosser   /// Approximate the number of points in the set.
228582f2af35STobias Grosser   ///
228682f2af35STobias Grosser   /// This function returns an ast expression that overapproximates the number
228782f2af35STobias Grosser   /// of points in an isl set through the rectangular hull surrounding this set.
228882f2af35STobias Grosser   ///
228982f2af35STobias Grosser   /// @param Set   The set to count.
229082f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
229182f2af35STobias Grosser   ///              expression.
229282f2af35STobias Grosser   ///
229382f2af35STobias Grosser   /// @returns An approximation of the number of points in the set.
229482f2af35STobias Grosser   __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set,
229582f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
229682f2af35STobias Grosser 
229782f2af35STobias Grosser     isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1);
229882f2af35STobias Grosser     auto *Expr = isl_ast_expr_from_val(isl_val_copy(One));
229982f2af35STobias Grosser 
230082f2af35STobias Grosser     isl_space *Space = isl_set_get_space(Set);
230182f2af35STobias Grosser     Space = isl_space_params(Space);
230282f2af35STobias Grosser     auto *Univ = isl_set_universe(Space);
230382f2af35STobias Grosser     isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One);
230482f2af35STobias Grosser 
230582f2af35STobias Grosser     for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) {
230682f2af35STobias Grosser       isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i);
230782f2af35STobias Grosser       isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i);
230882f2af35STobias Grosser       isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min);
230982f2af35STobias Grosser       DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff));
231082f2af35STobias Grosser       auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize);
231182f2af35STobias Grosser       Expr = isl_ast_expr_mul(Expr, DimSizeExpr);
231282f2af35STobias Grosser     }
231382f2af35STobias Grosser 
231482f2af35STobias Grosser     isl_set_free(Set);
231582f2af35STobias Grosser     isl_pw_aff_free(OneAff);
231682f2af35STobias Grosser 
231782f2af35STobias Grosser     return Expr;
231882f2af35STobias Grosser   }
231982f2af35STobias Grosser 
232082f2af35STobias Grosser   /// Approximate a number of dynamic instructions executed by a given
232182f2af35STobias Grosser   /// statement.
232282f2af35STobias Grosser   ///
232382f2af35STobias Grosser   /// @param Stmt  The statement for which to compute the number of dynamic
232482f2af35STobias Grosser   ///              instructions.
232582f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
232682f2af35STobias Grosser   ///              expression.
232782f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
232882f2af35STobias Grosser   ///          by @p Stmt.
232982f2af35STobias Grosser   __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt,
233082f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
233182f2af35STobias Grosser     auto Iterations = approxPointsInSet(Stmt.getDomain(), Build);
233282f2af35STobias Grosser 
233382f2af35STobias Grosser     long InstCount = 0;
233482f2af35STobias Grosser 
233582f2af35STobias Grosser     if (Stmt.isBlockStmt()) {
233682f2af35STobias Grosser       auto *BB = Stmt.getBasicBlock();
233782f2af35STobias Grosser       InstCount = std::distance(BB->begin(), BB->end());
233882f2af35STobias Grosser     } else {
233982f2af35STobias Grosser       auto *R = Stmt.getRegion();
234082f2af35STobias Grosser 
234182f2af35STobias Grosser       for (auto *BB : R->blocks()) {
234282f2af35STobias Grosser         InstCount += std::distance(BB->begin(), BB->end());
234382f2af35STobias Grosser       }
234482f2af35STobias Grosser     }
234582f2af35STobias Grosser 
234682f2af35STobias Grosser     isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount);
234782f2af35STobias Grosser     auto *InstExpr = isl_ast_expr_from_val(InstVal);
234882f2af35STobias Grosser     return isl_ast_expr_mul(InstExpr, Iterations);
234982f2af35STobias Grosser   }
235082f2af35STobias Grosser 
235182f2af35STobias Grosser   /// Approximate dynamic instructions executed in scop.
235282f2af35STobias Grosser   ///
235382f2af35STobias Grosser   /// @param S     The scop for which to approximate dynamic instructions.
235482f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
235582f2af35STobias Grosser   ///              expression.
235682f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
235782f2af35STobias Grosser   ///          in @p S.
235882f2af35STobias Grosser   __isl_give isl_ast_expr *
235982f2af35STobias Grosser   getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) {
236082f2af35STobias Grosser     isl_ast_expr *Instructions;
236182f2af35STobias Grosser 
236282f2af35STobias Grosser     isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0);
236382f2af35STobias Grosser     Instructions = isl_ast_expr_from_val(Zero);
236482f2af35STobias Grosser 
236582f2af35STobias Grosser     for (ScopStmt &Stmt : S) {
236682f2af35STobias Grosser       isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build);
236782f2af35STobias Grosser       Instructions = isl_ast_expr_add(Instructions, StmtInstructions);
236882f2af35STobias Grosser     }
236982f2af35STobias Grosser     return Instructions;
237082f2af35STobias Grosser   }
237182f2af35STobias Grosser 
237282f2af35STobias Grosser   /// Create a check that ensures sufficient compute in scop.
237382f2af35STobias Grosser   ///
237482f2af35STobias Grosser   /// @param S     The scop for which to ensure sufficient compute.
237582f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
237682f2af35STobias Grosser   ///              expression.
237782f2af35STobias Grosser   /// @returns An expression that evaluates to TRUE in case of sufficient
237882f2af35STobias Grosser   ///          compute and to FALSE, otherwise.
237982f2af35STobias Grosser   __isl_give isl_ast_expr *
238082f2af35STobias Grosser   createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) {
238182f2af35STobias Grosser     auto Iterations = getNumberOfIterations(S, Build);
238282f2af35STobias Grosser     auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute);
238382f2af35STobias Grosser     auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal);
238482f2af35STobias Grosser     return isl_ast_expr_ge(Iterations, MinComputeExpr);
238582f2af35STobias Grosser   }
238682f2af35STobias Grosser 
238738fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
238838fc0aedSTobias Grosser   ///
238932837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
239032837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
239132837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
239238fc0aedSTobias Grosser     ScopAnnotator Annotator;
239338fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
239438fc0aedSTobias Grosser 
239538fc0aedSTobias Grosser     Region *R = &S->getRegion();
239638fc0aedSTobias Grosser 
239738fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
239838fc0aedSTobias Grosser 
239938fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
240038fc0aedSTobias Grosser 
240138fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
240238fc0aedSTobias Grosser 
240338fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
240438fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
240538fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
240638fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
240738fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
240838fc0aedSTobias Grosser     // code generating this scop.
240938fc0aedSTobias Grosser     BasicBlock *StartBlock =
24102d950f36SPhilip Pfaffe         executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI);
241138fc0aedSTobias Grosser 
24122d950f36SPhilip Pfaffe     GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S,
2413acf80064SEli Friedman                                StartBlock, Prog);
2414acf80064SEli Friedman 
241538fc0aedSTobias Grosser     // TODO: Handle LICM
241638fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
241738fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
241838fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
2419cb1aef8dSTobias Grosser 
2420cb1aef8dSTobias Grosser     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx());
2421cb1aef8dSTobias Grosser     isl_ast_expr *Condition = IslAst::buildRunCondition(S, Build);
242282f2af35STobias Grosser     isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build);
242382f2af35STobias Grosser     Condition = isl_ast_expr_and(Condition, SufficientCompute);
2424cb1aef8dSTobias Grosser     isl_ast_build_free(Build);
2425cb1aef8dSTobias Grosser 
2426cb1aef8dSTobias Grosser     Value *RTC = NodeBuilder.createRTC(Condition);
2427cb1aef8dSTobias Grosser     Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
2428cb1aef8dSTobias Grosser 
242938fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
2430fa7b0802STobias Grosser 
2431fa7b0802STobias Grosser     NodeBuilder.initializeAfterRTH();
243238fc0aedSTobias Grosser     NodeBuilder.create(Root);
24338ed5e599STobias Grosser     NodeBuilder.finalize();
24345857b701STobias Grosser 
2435bc653f20STobias Grosser     /// In case a sequential kernel has more surrounding loops as any parallel
2436bc653f20STobias Grosser     /// kernel, the SCoP is probably mostly sequential. Hence, there is no
2437de244eb4STobias Grosser     /// point in running it on a GPU.
2438bc653f20STobias Grosser     if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel)
2439bc653f20STobias Grosser       SplitBlock->getTerminator()->setOperand(0, Builder.getFalse());
2440bc653f20STobias Grosser 
24415857b701STobias Grosser     if (!NodeBuilder.BuildSuccessful)
24425857b701STobias Grosser       SplitBlock->getTerminator()->setOperand(0, Builder.getFalse());
244338fc0aedSTobias Grosser   }
244438fc0aedSTobias Grosser 
2445e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
2446e938517eSTobias Grosser     S = &CurrentScop;
244738fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
244838fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
244938fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2450*7b5a4dfdSTobias Grosser     DL = &S->getRegion().getEntry()->getModule()->getDataLayout();
245138fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
2452e938517eSTobias Grosser 
24532d58a64eSTobias Grosser     // We currently do not support scops with invariant loads.
24542d58a64eSTobias Grosser     if (S->hasInvariantAccesses())
24552d58a64eSTobias Grosser       return false;
24562d58a64eSTobias Grosser 
2457e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
2458e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
2459f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
246038fc0aedSTobias Grosser 
246138fc0aedSTobias Grosser     if (PPCGGen->tree)
246232837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
246338fc0aedSTobias Grosser 
2464b307ed4dSTobias Grosser     freeOptions(PPCGScop);
2465f384594dSTobias Grosser     freePPCGGen(PPCGGen);
2466e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
2467e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
2468e938517eSTobias Grosser 
2469e938517eSTobias Grosser     return true;
2470e938517eSTobias Grosser   }
24719dfe4e7cSTobias Grosser 
24729dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
24739dfe4e7cSTobias Grosser 
24749dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
24759dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
24769dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
24779dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
24789dfe4e7cSTobias Grosser     AU.addRequired<ScopDetection>();
24799dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
24809dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
24819dfe4e7cSTobias Grosser 
24829dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
24839dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
24849dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
24859dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
24869dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
24879dfe4e7cSTobias Grosser     AU.addPreserved<ScopDetection>();
24889dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
24899dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
24909dfe4e7cSTobias Grosser 
24919dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
24929dfe4e7cSTobias Grosser     //        region tree.
24939dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
24949dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
24959dfe4e7cSTobias Grosser   }
24969dfe4e7cSTobias Grosser };
249724222c73STobias Grosser } // namespace
24989dfe4e7cSTobias Grosser 
24999dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
25009dfe4e7cSTobias Grosser 
25019dfe4e7cSTobias Grosser Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
25029dfe4e7cSTobias Grosser 
25039dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
25049dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
25059dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
25069dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
25079dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
25089dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
25099dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
25109dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScopDetection);
25119dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
25129dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
2513