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 
89*abed4969SSiddharth Bhat static cl::opt<bool> ManagedMemory("polly-acc-codegen-managed-memory",
90*abed4969SSiddharth Bhat                                    cl::desc("Generate Host kernel code assuming"
91*abed4969SSiddharth Bhat                                             " that all memory has been"
92*abed4969SSiddharth Bhat                                             " declared as managed memory"),
93*abed4969SSiddharth Bhat                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
94*abed4969SSiddharth Bhat                                    cl::cat(PollyCategory));
95*abed4969SSiddharth Bhat 
9674dc3cb4STobias Grosser static cl::opt<std::string>
9774dc3cb4STobias Grosser     CudaVersion("polly-acc-cuda-version",
9874dc3cb4STobias Grosser                 cl::desc("The CUDA version to compile for"), cl::Hidden,
9974dc3cb4STobias Grosser                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
10074dc3cb4STobias Grosser 
10182f2af35STobias Grosser static cl::opt<int>
10282f2af35STobias Grosser     MinCompute("polly-acc-mincompute",
10382f2af35STobias Grosser                cl::desc("Minimal number of compute statements to run on GPU."),
10482f2af35STobias Grosser                cl::Hidden, cl::init(10 * 512 * 512));
10582f2af35STobias Grosser 
10660c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
10760c60025STobias Grosser ///
10860c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
10960c60025STobias Grosser /// of the scheduled ScopStmts.
11060c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
111edb885cbSTobias Grosser     void *StmtT, isl_ast_build *Build,
11260c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
11360c60025STobias Grosser                                        isl_id *Id, void *User),
11460c60025STobias Grosser     void *UserIndex,
11560c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
116edb885cbSTobias Grosser     void *UserExpr) {
11760c60025STobias Grosser 
118edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
11960c60025STobias Grosser 
120edb885cbSTobias Grosser   isl_ctx *Ctx;
121edb885cbSTobias Grosser 
122edb885cbSTobias Grosser   if (!Stmt || !Build)
123edb885cbSTobias Grosser     return NULL;
124edb885cbSTobias Grosser 
125edb885cbSTobias Grosser   Ctx = isl_ast_build_get_ctx(Build);
126edb885cbSTobias Grosser   isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0);
127edb885cbSTobias Grosser 
128edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
129edb885cbSTobias Grosser     isl_map *AddrFunc = Acc->getAddressFunction();
130edb885cbSTobias Grosser     AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain());
131edb885cbSTobias Grosser     isl_id *RefId = Acc->getId();
132edb885cbSTobias Grosser     isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc);
133edb885cbSTobias Grosser     isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA);
134edb885cbSTobias Grosser     MPA = isl_multi_pw_aff_coalesce(MPA);
135edb885cbSTobias Grosser     MPA = FunctionIndex(MPA, RefId, UserIndex);
136edb885cbSTobias Grosser     isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA);
137edb885cbSTobias Grosser     Access = FunctionExpr(Access, RefId, UserExpr);
138edb885cbSTobias Grosser     RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access);
139edb885cbSTobias Grosser   }
140edb885cbSTobias Grosser 
141edb885cbSTobias Grosser   return RefToExpr;
14260c60025STobias Grosser }
143f384594dSTobias Grosser 
14438fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
14538fc0aedSTobias Grosser ///
14638fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
14738fc0aedSTobias Grosser /// generates code for general-prupose AST nodes, with special functionality
14838fc0aedSTobias Grosser /// for generating GPU specific user nodes.
14938fc0aedSTobias Grosser ///
15038fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
15138fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
15238fc0aedSTobias Grosser public:
1532d950f36SPhilip Pfaffe   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator,
15438fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
155acf80064SEli Friedman                  DominatorTree &DT, Scop &S, BasicBlock *StartBlock,
156acf80064SEli Friedman                  gpu_prog *Prog)
1572d950f36SPhilip Pfaffe       : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock),
158acf80064SEli Friedman         Prog(Prog) {
159edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
160edb885cbSTobias Grosser   }
16138fc0aedSTobias Grosser 
162fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
163fa7b0802STobias Grosser   void initializeAfterRTH();
164fa7b0802STobias Grosser 
165fa7b0802STobias Grosser   /// Finalize the generated scop.
166fa7b0802STobias Grosser   virtual void finalize();
167fa7b0802STobias Grosser 
1685857b701STobias Grosser   /// Track if the full build process was successful.
1695857b701STobias Grosser   ///
1705857b701STobias Grosser   /// This value is set to false, if throughout the build process an error
1715857b701STobias Grosser   /// occurred which prevents us from generating valid GPU code.
1725857b701STobias Grosser   bool BuildSuccessful = true;
1735857b701STobias Grosser 
174bc653f20STobias Grosser   /// The maximal number of loops surrounding a sequential kernel.
175bc653f20STobias Grosser   unsigned DeepestSequential = 0;
176bc653f20STobias Grosser 
177bc653f20STobias Grosser   /// The maximal number of loops surrounding a parallel kernel.
178bc653f20STobias Grosser   unsigned DeepestParallel = 0;
179bc653f20STobias Grosser 
18038fc0aedSTobias Grosser private:
18174dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
18274dc3cb4STobias Grosser   ///
18374dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
18474dc3cb4STobias Grosser   /// more.
18574dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
18674dc3cb4STobias Grosser 
18713c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
18813c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
1897287aeddSTobias Grosser 
190fa7b0802STobias Grosser   /// The current GPU context.
191fa7b0802STobias Grosser   Value *GPUContext;
192fa7b0802STobias Grosser 
193b513b491STobias Grosser   /// The set of isl_ids allocated in the kernel
194b513b491STobias Grosser   std::vector<isl_id *> KernelIds;
195b513b491STobias Grosser 
19632837fe3STobias Grosser   /// A module containing GPU code.
19732837fe3STobias Grosser   ///
19832837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
19932837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
20032837fe3STobias Grosser 
20132837fe3STobias Grosser   /// The GPU program we generate code for.
20232837fe3STobias Grosser   gpu_prog *Prog;
20332837fe3STobias Grosser 
204472f9654STobias Grosser   /// Class to free isl_ids.
205472f9654STobias Grosser   class IslIdDeleter {
206472f9654STobias Grosser   public:
207472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
208472f9654STobias Grosser   };
209472f9654STobias Grosser 
210472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
211472f9654STobias Grosser   ///
212472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
213472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
214472f9654STobias Grosser 
215edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
216edb885cbSTobias Grosser 
21738fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
21838fc0aedSTobias Grosser   ///
21938fc0aedSTobias Grosser   /// These AST nodes can be of type:
22038fc0aedSTobias Grosser   ///
22138fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
22238fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
22313c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
2245260c041STobias Grosser   ///   - In-kernel synchronization
2255260c041STobias Grosser   ///   - In-kernel memory copy statement
22638fc0aedSTobias Grosser   ///
2271fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
2281fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
22932837fe3STobias Grosser 
23013c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
23113c78e4dSTobias Grosser 
23213c78e4dSTobias Grosser   /// Create code for a data transfer statement
23313c78e4dSTobias Grosser   ///
23413c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
23513c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
23613c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
23713c78e4dSTobias Grosser                           enum DataDirection Direction);
23813c78e4dSTobias Grosser 
239edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
240edb885cbSTobias Grosser   ///
241edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
242edb885cbSTobias Grosser   ///
243edb885cbSTobias Grosser   /// @returns A set of values referenced by the kernel.
244edb885cbSTobias Grosser   SetVector<Value *> getReferencesInKernel(ppcg_kernel *Kernel);
245edb885cbSTobias Grosser 
24679a947c2STobias Grosser   /// Compute the sizes of the execution grid for a given kernel.
24779a947c2STobias Grosser   ///
24879a947c2STobias Grosser   /// @param Kernel The kernel to compute grid sizes for.
24979a947c2STobias Grosser   ///
25079a947c2STobias Grosser   /// @returns A tuple with grid sizes for X and Y dimension
25179a947c2STobias Grosser   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
25279a947c2STobias Grosser 
253*abed4969SSiddharth Bhat   /// Creates a array that can be sent to the kernel on the device using a
254*abed4969SSiddharth Bhat   /// host pointer. This is required for managed memory, when we directly send
255*abed4969SSiddharth Bhat   /// host pointers to the device.
256*abed4969SSiddharth Bhat   /// \note
257*abed4969SSiddharth Bhat   /// This is to be used only with managed memory
258*abed4969SSiddharth Bhat   Value *getOrCreateManagedDeviceArray(gpu_array_info *Array,
259*abed4969SSiddharth Bhat                                        ScopArrayInfo *ArrayInfo);
260*abed4969SSiddharth Bhat 
26179a947c2STobias Grosser   /// Compute the sizes of the thread blocks for a given kernel.
26279a947c2STobias Grosser   ///
26379a947c2STobias Grosser   /// @param Kernel The kernel to compute thread block sizes for.
26479a947c2STobias Grosser   ///
26579a947c2STobias Grosser   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
26679a947c2STobias Grosser   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
26779a947c2STobias Grosser 
26879a947c2STobias Grosser   /// Create kernel launch parameters.
26979a947c2STobias Grosser   ///
27079a947c2STobias Grosser   /// @param Kernel        The kernel to create parameters for.
27179a947c2STobias Grosser   /// @param F             The kernel function that has been created.
27257693272STobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
27379a947c2STobias Grosser   ///
27479a947c2STobias Grosser   /// @returns A stack allocated array with pointers to the parameter
27579a947c2STobias Grosser   ///          values that are passed to the kernel.
27657693272STobias Grosser   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
27757693272STobias Grosser                                 SetVector<Value *> SubtreeValues);
27879a947c2STobias Grosser 
279b513b491STobias Grosser   /// Create declarations for kernel variable.
280b513b491STobias Grosser   ///
281b513b491STobias Grosser   /// This includes shared memory declarations.
282b513b491STobias Grosser   ///
283b513b491STobias Grosser   /// @param Kernel        The kernel definition to create variables for.
284b513b491STobias Grosser   /// @param FN            The function into which to generate the variables.
285b513b491STobias Grosser   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
286b513b491STobias Grosser 
287c1c6a2a6STobias Grosser   /// Add CUDA annotations to module.
288c1c6a2a6STobias Grosser   ///
289c1c6a2a6STobias Grosser   /// Add a set of CUDA annotations that declares the maximal block dimensions
290c1c6a2a6STobias Grosser   /// that will be used to execute the CUDA kernel. This allows the NVIDIA
291c1c6a2a6STobias Grosser   /// PTX compiler to bound the number of allocated registers to ensure the
292c1c6a2a6STobias Grosser   /// resulting kernel is known to run with up to as many block dimensions
293c1c6a2a6STobias Grosser   /// as specified here.
294c1c6a2a6STobias Grosser   ///
295c1c6a2a6STobias Grosser   /// @param M         The module to add the annotations to.
296c1c6a2a6STobias Grosser   /// @param BlockDimX The size of block dimension X.
297c1c6a2a6STobias Grosser   /// @param BlockDimY The size of block dimension Y.
298c1c6a2a6STobias Grosser   /// @param BlockDimZ The size of block dimension Z.
299c1c6a2a6STobias Grosser   void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY,
300c1c6a2a6STobias Grosser                           Value *BlockDimZ);
301c1c6a2a6STobias Grosser 
30232837fe3STobias Grosser   /// Create GPU kernel.
30332837fe3STobias Grosser   ///
30432837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
30532837fe3STobias Grosser   ///
30632837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
30732837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
30832837fe3STobias Grosser 
30913c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
31013c78e4dSTobias Grosser   ///
31113c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
31213c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
31313c78e4dSTobias Grosser 
314aaabbbf8STobias Grosser   /// Generate code to compute the minimal offset at which an array is accessed.
315aaabbbf8STobias Grosser   ///
316aaabbbf8STobias Grosser   /// The offset of an array is the minimal array location accessed in a scop.
317aaabbbf8STobias Grosser   ///
318aaabbbf8STobias Grosser   /// Example:
319aaabbbf8STobias Grosser   ///
320aaabbbf8STobias Grosser   ///   for (long i = 0; i < 100; i++)
321aaabbbf8STobias Grosser   ///     A[i + 42] += ...
322aaabbbf8STobias Grosser   ///
323aaabbbf8STobias Grosser   ///   getArrayOffset(A) results in 42.
324aaabbbf8STobias Grosser   ///
325aaabbbf8STobias Grosser   /// @param Array The array for which to compute the offset.
326aaabbbf8STobias Grosser   /// @returns An llvm::Value that contains the offset of the array.
327aaabbbf8STobias Grosser   Value *getArrayOffset(gpu_array_info *Array);
328aaabbbf8STobias Grosser 
32900bb5a99STobias Grosser   /// Prepare the kernel arguments for kernel code generation
33000bb5a99STobias Grosser   ///
33100bb5a99STobias Grosser   /// @param Kernel The kernel to generate code for.
33200bb5a99STobias Grosser   /// @param FN     The function created for the kernel.
33300bb5a99STobias Grosser   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
33400bb5a99STobias Grosser 
33532837fe3STobias Grosser   /// Create kernel function.
33632837fe3STobias Grosser   ///
33732837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
33832837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
33932837fe3STobias Grosser   /// start block of this newly created function.
34032837fe3STobias Grosser   ///
34132837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
342edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
343edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
344edb885cbSTobias Grosser                             SetVector<Value *> &SubtreeValues);
34532837fe3STobias Grosser 
34632837fe3STobias Grosser   /// Create the declaration of a kernel function.
34732837fe3STobias Grosser   ///
34832837fe3STobias Grosser   /// The kernel function takes as arguments:
34932837fe3STobias Grosser   ///
35032837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
351f6044bd0STobias Grosser   ///   - Host iterators
352c84a1995STobias Grosser   ///   - Parameters
35332837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
35432837fe3STobias Grosser   ///
35532837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
356edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
357edb885cbSTobias Grosser   ///
35832837fe3STobias Grosser   /// @returns The newly declared function.
359edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
360edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
36132837fe3STobias Grosser 
362472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
363472f9654STobias Grosser   ///
364472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
365472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
366472f9654STobias Grosser 
367b513b491STobias Grosser   /// Create a global-to-shared or shared-to-global copy statement.
368b513b491STobias Grosser   ///
369b513b491STobias Grosser   /// @param CopyStmt The copy statement to generate code for
370b513b491STobias Grosser   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
371b513b491STobias Grosser 
372edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
373edb885cbSTobias Grosser   ///
374edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
375edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
376edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
377edb885cbSTobias Grosser 
3785260c041STobias Grosser   /// Create an in-kernel synchronization call.
3795260c041STobias Grosser   void createKernelSync();
3805260c041STobias Grosser 
38174dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
38274dc3cb4STobias Grosser   ///
38374dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
38474dc3cb4STobias Grosser   std::string createKernelASM();
38574dc3cb4STobias Grosser 
38674dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
38774dc3cb4STobias Grosser   ///
38874dc3cb4STobias Grosser   /// @param F The function to remove references to.
38974dc3cb4STobias Grosser   void clearDominators(Function *F);
39074dc3cb4STobias Grosser 
39174dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
39274dc3cb4STobias Grosser   ///
39374dc3cb4STobias Grosser   /// @param F The function to remove references to.
39474dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
39574dc3cb4STobias Grosser 
39674dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
39774dc3cb4STobias Grosser   ///
39874dc3cb4STobias Grosser   /// @param F The function to remove references to.
39974dc3cb4STobias Grosser   void clearLoops(Function *F);
40074dc3cb4STobias Grosser 
40132837fe3STobias Grosser   /// Finalize the generation of the kernel function.
40232837fe3STobias Grosser   ///
40332837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
40432837fe3STobias Grosser   /// dump its IR to stderr.
40557793596STobias Grosser   ///
40657793596STobias Grosser   /// @returns The Assembly string of the kernel.
40757793596STobias Grosser   std::string finalizeKernelFunction();
408fa7b0802STobias Grosser 
40951dfc275STobias Grosser   /// Finalize the generation of the kernel arguments.
41051dfc275STobias Grosser   ///
41151dfc275STobias Grosser   /// This function ensures that not-read-only scalars used in a kernel are
41251dfc275STobias Grosser   /// stored back to the global memory location they ared backed up with before
41351dfc275STobias Grosser   /// the kernel terminates.
41451dfc275STobias Grosser   ///
41551dfc275STobias Grosser   /// @params Kernel The kernel to finalize kernel arguments for.
41651dfc275STobias Grosser   void finalizeKernelArguments(ppcg_kernel *Kernel);
41751dfc275STobias Grosser 
4187287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
419fa7b0802STobias Grosser   void allocateDeviceArrays();
420fa7b0802STobias Grosser 
4217287aeddSTobias Grosser   /// Free all allocated device arrays.
4227287aeddSTobias Grosser   void freeDeviceArrays();
4237287aeddSTobias Grosser 
424fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
425fa7b0802STobias Grosser   ///
426fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
427fa7b0802STobias Grosser   Value *createCallInitContext();
428fa7b0802STobias Grosser 
42979a947c2STobias Grosser   /// Create a call to get the device pointer for a kernel allocation.
43079a947c2STobias Grosser   ///
43179a947c2STobias Grosser   /// @param Allocation The Polly GPU allocation
43279a947c2STobias Grosser   ///
43379a947c2STobias Grosser   /// @returns The device parameter corresponding to this allocation.
43479a947c2STobias Grosser   Value *createCallGetDevicePtr(Value *Allocation);
43579a947c2STobias Grosser 
436fa7b0802STobias Grosser   /// Create a call to free the GPU context.
437fa7b0802STobias Grosser   ///
438fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
439fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
440fa7b0802STobias Grosser 
4417287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
4427287aeddSTobias Grosser   ///
4437287aeddSTobias Grosser   /// @param Size The size of memory to allocate
4447287aeddSTobias Grosser   ///
4457287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
446fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
4477287aeddSTobias Grosser 
4487287aeddSTobias Grosser   /// Create a call to free a device array.
4497287aeddSTobias Grosser   ///
4507287aeddSTobias Grosser   /// @param Array The device array to free.
4517287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
45213c78e4dSTobias Grosser 
45313c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
45413c78e4dSTobias Grosser   ///
45513c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
45613c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
45713c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
45813c78e4dSTobias Grosser                                       Value *Size);
45913c78e4dSTobias Grosser 
46013c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
46113c78e4dSTobias Grosser   ///
46213c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
46313c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
46413c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
46513c78e4dSTobias Grosser                                       Value *Size);
46657793596STobias Grosser 
467*abed4969SSiddharth Bhat   /// Create a call to synchronize Host & Device.
468*abed4969SSiddharth Bhat   /// \note
469*abed4969SSiddharth Bhat   /// This is to be used only with managed memory.
470*abed4969SSiddharth Bhat   void createCallSynchronizeDevice();
471*abed4969SSiddharth Bhat 
47257793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
47357793596STobias Grosser   ///
47457793596STobias Grosser   /// @param Buffer The string describing the kernel.
47557793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
47657793596STobias Grosser   ///
47757793596STobias Grosser   /// @returns A pointer to a kernel object
47857793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
47957793596STobias Grosser 
48057793596STobias Grosser   /// Create a call to free a GPU kernel.
48157793596STobias Grosser   ///
48257793596STobias Grosser   /// @param GPUKernel THe kernel to free.
48357793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
48479a947c2STobias Grosser 
48579a947c2STobias Grosser   /// Create a call to launch a GPU kernel.
48679a947c2STobias Grosser   ///
48779a947c2STobias Grosser   /// @param GPUKernel  The kernel to launch.
48879a947c2STobias Grosser   /// @param GridDimX   The size of the first grid dimension.
48979a947c2STobias Grosser   /// @param GridDimY   The size of the second grid dimension.
49079a947c2STobias Grosser   /// @param GridBlockX The size of the first block dimension.
49179a947c2STobias Grosser   /// @param GridBlockY The size of the second block dimension.
49279a947c2STobias Grosser   /// @param GridBlockZ The size of the third block dimension.
49379a947c2STobias Grosser   /// @param Paramters  A pointer to an array that contains itself pointers to
49479a947c2STobias Grosser   ///                   the parameter values passed for each kernel argument.
49579a947c2STobias Grosser   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
49679a947c2STobias Grosser                               Value *GridDimY, Value *BlockDimX,
49779a947c2STobias Grosser                               Value *BlockDimY, Value *BlockDimZ,
49879a947c2STobias Grosser                               Value *Parameters);
4991fb9b64dSTobias Grosser };
5001fb9b64dSTobias Grosser 
501fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
502750160e2STobias Grosser   BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(),
503750160e2STobias Grosser                                  &*Builder.GetInsertPoint(), &DT, &LI);
504750160e2STobias Grosser   NewBB->setName("polly.acc.initialize");
505750160e2STobias Grosser   Builder.SetInsertPoint(&NewBB->front());
506750160e2STobias Grosser 
507fa7b0802STobias Grosser   GPUContext = createCallInitContext();
508*abed4969SSiddharth Bhat 
509*abed4969SSiddharth Bhat   if (!ManagedMemory)
510fa7b0802STobias Grosser     allocateDeviceArrays();
511fa7b0802STobias Grosser }
512fa7b0802STobias Grosser 
513fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
514*abed4969SSiddharth Bhat   if (!ManagedMemory)
5157287aeddSTobias Grosser     freeDeviceArrays();
516*abed4969SSiddharth Bhat 
517fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
518fa7b0802STobias Grosser   IslNodeBuilder::finalize();
519fa7b0802STobias Grosser }
520fa7b0802STobias Grosser 
521fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
522*abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory will directly send host pointers "
523*abed4969SSiddharth Bhat                            "to the kernel. There is no need for device arrays");
524fa7b0802STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
525fa7b0802STobias Grosser 
526fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
527fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
52813c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
5297287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
5307287aeddSTobias Grosser     DevArrayName.append(Array->name);
531fa7b0802STobias Grosser 
53213c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
533aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(Array);
534aaabbbf8STobias Grosser     if (Offset)
535aaabbbf8STobias Grosser       ArraySize = Builder.CreateSub(
536aaabbbf8STobias Grosser           ArraySize,
537aaabbbf8STobias Grosser           Builder.CreateMul(Offset,
538aaabbbf8STobias Grosser                             Builder.getInt64(ScopArray->getElemSizeInBytes())));
5397287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
5407287aeddSTobias Grosser     DevArray->setName(DevArrayName);
54113c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
542fa7b0802STobias Grosser   }
543fa7b0802STobias Grosser 
544fa7b0802STobias Grosser   isl_ast_build_free(Build);
545fa7b0802STobias Grosser }
546fa7b0802STobias Grosser 
547c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX,
548c1c6a2a6STobias Grosser                                         Value *BlockDimY, Value *BlockDimZ) {
549c1c6a2a6STobias Grosser   auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations");
550c1c6a2a6STobias Grosser 
551c1c6a2a6STobias Grosser   for (auto &F : *M) {
552c1c6a2a6STobias Grosser     if (F.getCallingConv() != CallingConv::PTX_Kernel)
553c1c6a2a6STobias Grosser       continue;
554c1c6a2a6STobias Grosser 
555c1c6a2a6STobias Grosser     Value *V[] = {BlockDimX, BlockDimY, BlockDimZ};
556c1c6a2a6STobias Grosser 
557c1c6a2a6STobias Grosser     Metadata *Elements[] = {
558c1c6a2a6STobias Grosser         ValueAsMetadata::get(&F),   MDString::get(M->getContext(), "maxntidx"),
559c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"),
560c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"),
561c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[2]),
562c1c6a2a6STobias Grosser     };
563c1c6a2a6STobias Grosser     MDNode *Node = MDNode::get(M->getContext(), Elements);
564c1c6a2a6STobias Grosser     AnnotationNode->addOperand(Node);
565c1c6a2a6STobias Grosser   }
566c1c6a2a6STobias Grosser }
567c1c6a2a6STobias Grosser 
5687287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
569*abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not use device arrays");
57013c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
57113c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
5727287aeddSTobias Grosser }
5737287aeddSTobias Grosser 
57457793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
57557793596STobias Grosser   const char *Name = "polly_getKernel";
57657793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
57757793596STobias Grosser   Function *F = M->getFunction(Name);
57857793596STobias Grosser 
57957793596STobias Grosser   // If F is not available, declare it.
58057793596STobias Grosser   if (!F) {
58157793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
58257793596STobias Grosser     std::vector<Type *> Args;
58357793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
58457793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
58557793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
58657793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
58757793596STobias Grosser   }
58857793596STobias Grosser 
58957793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
59057793596STobias Grosser }
59157793596STobias Grosser 
59279a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
59379a947c2STobias Grosser   const char *Name = "polly_getDevicePtr";
59479a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
59579a947c2STobias Grosser   Function *F = M->getFunction(Name);
59679a947c2STobias Grosser 
59779a947c2STobias Grosser   // If F is not available, declare it.
59879a947c2STobias Grosser   if (!F) {
59979a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
60079a947c2STobias Grosser     std::vector<Type *> Args;
60179a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
60279a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
60379a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
60479a947c2STobias Grosser   }
60579a947c2STobias Grosser 
60679a947c2STobias Grosser   return Builder.CreateCall(F, {Allocation});
60779a947c2STobias Grosser }
60879a947c2STobias Grosser 
60979a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
61079a947c2STobias Grosser                                             Value *GridDimY, Value *BlockDimX,
61179a947c2STobias Grosser                                             Value *BlockDimY, Value *BlockDimZ,
61279a947c2STobias Grosser                                             Value *Parameters) {
61379a947c2STobias Grosser   const char *Name = "polly_launchKernel";
61479a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
61579a947c2STobias Grosser   Function *F = M->getFunction(Name);
61679a947c2STobias Grosser 
61779a947c2STobias Grosser   // If F is not available, declare it.
61879a947c2STobias Grosser   if (!F) {
61979a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
62079a947c2STobias Grosser     std::vector<Type *> Args;
62179a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
62279a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
62379a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
62479a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
62579a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
62679a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
62779a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
62879a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
62979a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
63079a947c2STobias Grosser   }
63179a947c2STobias Grosser 
632ff40087aSTobias Grosser   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
63379a947c2STobias Grosser                          BlockDimZ, Parameters});
63479a947c2STobias Grosser }
63579a947c2STobias Grosser 
63657793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
63757793596STobias Grosser   const char *Name = "polly_freeKernel";
63857793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
63957793596STobias Grosser   Function *F = M->getFunction(Name);
64057793596STobias Grosser 
64157793596STobias Grosser   // If F is not available, declare it.
64257793596STobias Grosser   if (!F) {
64357793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
64457793596STobias Grosser     std::vector<Type *> Args;
64557793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
64657793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
64757793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
64857793596STobias Grosser   }
64957793596STobias Grosser 
65057793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
65157793596STobias Grosser }
65257793596STobias Grosser 
6537287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
654*abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not allocate or free memory "
655*abed4969SSiddharth Bhat                            "for device");
6567287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
6577287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
6587287aeddSTobias Grosser   Function *F = M->getFunction(Name);
6597287aeddSTobias Grosser 
6607287aeddSTobias Grosser   // If F is not available, declare it.
6617287aeddSTobias Grosser   if (!F) {
6627287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
6637287aeddSTobias Grosser     std::vector<Type *> Args;
6647287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
6657287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
6667287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
6677287aeddSTobias Grosser   }
6687287aeddSTobias Grosser 
6697287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
6707287aeddSTobias Grosser }
6717287aeddSTobias Grosser 
672fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
673*abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not allocate or free memory "
674*abed4969SSiddharth Bhat                            "for device");
675fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
676fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
677fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
678fa7b0802STobias Grosser 
679fa7b0802STobias Grosser   // If F is not available, declare it.
680fa7b0802STobias Grosser   if (!F) {
681fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
682fa7b0802STobias Grosser     std::vector<Type *> Args;
683fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
684fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
685fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
686fa7b0802STobias Grosser   }
687fa7b0802STobias Grosser 
688fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
689fa7b0802STobias Grosser }
690fa7b0802STobias Grosser 
69113c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
69213c78e4dSTobias Grosser                                                     Value *DeviceData,
69313c78e4dSTobias Grosser                                                     Value *Size) {
694*abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not transfer memory between "
695*abed4969SSiddharth Bhat                            "device and host");
69613c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
69713c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
69813c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
69913c78e4dSTobias Grosser 
70013c78e4dSTobias Grosser   // If F is not available, declare it.
70113c78e4dSTobias Grosser   if (!F) {
70213c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
70313c78e4dSTobias Grosser     std::vector<Type *> Args;
70413c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
70513c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
70613c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
70713c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
70813c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
70913c78e4dSTobias Grosser   }
71013c78e4dSTobias Grosser 
71113c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
71213c78e4dSTobias Grosser }
71313c78e4dSTobias Grosser 
71413c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
71513c78e4dSTobias Grosser                                                     Value *HostData,
71613c78e4dSTobias Grosser                                                     Value *Size) {
717*abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not transfer memory between "
718*abed4969SSiddharth Bhat                            "device and host");
71913c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
72013c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
72113c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
72213c78e4dSTobias Grosser 
72313c78e4dSTobias Grosser   // If F is not available, declare it.
72413c78e4dSTobias Grosser   if (!F) {
72513c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
72613c78e4dSTobias Grosser     std::vector<Type *> Args;
72713c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
72813c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
72913c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
73013c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
73113c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
73213c78e4dSTobias Grosser   }
73313c78e4dSTobias Grosser 
73413c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
73513c78e4dSTobias Grosser }
73613c78e4dSTobias Grosser 
737*abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() {
738*abed4969SSiddharth Bhat   assert(ManagedMemory && "explicit synchronization is only necessary for "
739*abed4969SSiddharth Bhat                           "managed memory");
740*abed4969SSiddharth Bhat   const char *Name = "polly_synchronizeDevice";
741*abed4969SSiddharth Bhat   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
742*abed4969SSiddharth Bhat   Function *F = M->getFunction(Name);
743*abed4969SSiddharth Bhat 
744*abed4969SSiddharth Bhat   // If F is not available, declare it.
745*abed4969SSiddharth Bhat   if (!F) {
746*abed4969SSiddharth Bhat     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
747*abed4969SSiddharth Bhat     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
748*abed4969SSiddharth Bhat     F = Function::Create(Ty, Linkage, Name, M);
749*abed4969SSiddharth Bhat   }
750*abed4969SSiddharth Bhat 
751*abed4969SSiddharth Bhat   Builder.CreateCall(F);
752*abed4969SSiddharth Bhat }
753*abed4969SSiddharth Bhat 
754fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
755fa7b0802STobias Grosser   const char *Name = "polly_initContext";
756fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
757fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
758fa7b0802STobias Grosser 
759fa7b0802STobias Grosser   // If F is not available, declare it.
760fa7b0802STobias Grosser   if (!F) {
761fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
762fa7b0802STobias Grosser     std::vector<Type *> Args;
763fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
764fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
765fa7b0802STobias Grosser   }
766fa7b0802STobias Grosser 
767fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
768fa7b0802STobias Grosser }
769fa7b0802STobias Grosser 
770fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
771fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
772fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
773fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
774fa7b0802STobias Grosser 
775fa7b0802STobias Grosser   // If F is not available, declare it.
776fa7b0802STobias Grosser   if (!F) {
777fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
778fa7b0802STobias Grosser     std::vector<Type *> Args;
779fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
780fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
781fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
782fa7b0802STobias Grosser   }
783fa7b0802STobias Grosser 
784fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
785fa7b0802STobias Grosser }
786fa7b0802STobias Grosser 
7875260c041STobias Grosser /// Check if one string is a prefix of another.
7885260c041STobias Grosser ///
7895260c041STobias Grosser /// @param String The string in which to look for the prefix.
7905260c041STobias Grosser /// @param Prefix The prefix to look for.
7915260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
7925260c041STobias Grosser   return String.find(Prefix) == 0;
7935260c041STobias Grosser }
7945260c041STobias Grosser 
79513c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
79613c78e4dSTobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
79713c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
79813c78e4dSTobias Grosser 
79913c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
80013c78e4dSTobias Grosser     auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]);
80113c78e4dSTobias Grosser     isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero);
80213c78e4dSTobias Grosser 
80313c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
80413c78e4dSTobias Grosser       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]);
80513c78e4dSTobias Grosser       isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
80613c78e4dSTobias Grosser       Res = isl_ast_expr_mul(Res, Expr);
80713c78e4dSTobias Grosser     }
80813c78e4dSTobias Grosser 
80913c78e4dSTobias Grosser     Value *NumElements = ExprBuilder.create(Res);
810b79f4d39STobias Grosser     if (NumElements->getType() != ArraySize->getType())
811b79f4d39STobias Grosser       NumElements = Builder.CreateSExt(NumElements, ArraySize->getType());
81213c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
81313c78e4dSTobias Grosser   }
81413c78e4dSTobias Grosser   isl_ast_build_free(Build);
81513c78e4dSTobias Grosser   return ArraySize;
81613c78e4dSTobias Grosser }
81713c78e4dSTobias Grosser 
818aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) {
819aaabbbf8STobias Grosser   if (gpu_array_is_scalar(Array))
820aaabbbf8STobias Grosser     return nullptr;
821aaabbbf8STobias Grosser 
822aaabbbf8STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
823aaabbbf8STobias Grosser 
824aaabbbf8STobias Grosser   isl_set *Min = isl_set_lexmin(isl_set_copy(Array->extent));
825aaabbbf8STobias Grosser 
826aaabbbf8STobias Grosser   isl_set *ZeroSet = isl_set_universe(isl_set_get_space(Min));
827aaabbbf8STobias Grosser 
828aaabbbf8STobias Grosser   for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++)
829aaabbbf8STobias Grosser     ZeroSet = isl_set_fix_si(ZeroSet, isl_dim_set, i, 0);
830aaabbbf8STobias Grosser 
831aaabbbf8STobias Grosser   if (isl_set_is_subset(Min, ZeroSet)) {
832aaabbbf8STobias Grosser     isl_set_free(Min);
833aaabbbf8STobias Grosser     isl_set_free(ZeroSet);
834aaabbbf8STobias Grosser     isl_ast_build_free(Build);
835aaabbbf8STobias Grosser     return nullptr;
836aaabbbf8STobias Grosser   }
837aaabbbf8STobias Grosser   isl_set_free(ZeroSet);
838aaabbbf8STobias Grosser 
839aaabbbf8STobias Grosser   isl_ast_expr *Result =
840aaabbbf8STobias Grosser       isl_ast_expr_from_val(isl_val_int_from_si(isl_set_get_ctx(Min), 0));
841aaabbbf8STobias Grosser 
842aaabbbf8STobias Grosser   for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) {
843aaabbbf8STobias Grosser     if (i > 0) {
844aaabbbf8STobias Grosser       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i - 1]);
845aaabbbf8STobias Grosser       isl_ast_expr *BExpr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
846aaabbbf8STobias Grosser       Result = isl_ast_expr_mul(Result, BExpr);
847aaabbbf8STobias Grosser     }
848aaabbbf8STobias Grosser     isl_pw_aff *DimMin = isl_set_dim_min(isl_set_copy(Min), i);
849aaabbbf8STobias Grosser     isl_ast_expr *MExpr = isl_ast_build_expr_from_pw_aff(Build, DimMin);
850aaabbbf8STobias Grosser     Result = isl_ast_expr_add(Result, MExpr);
851aaabbbf8STobias Grosser   }
852aaabbbf8STobias Grosser 
853aaabbbf8STobias Grosser   Value *ResultValue = ExprBuilder.create(Result);
854aaabbbf8STobias Grosser   isl_set_free(Min);
855aaabbbf8STobias Grosser   isl_ast_build_free(Build);
856aaabbbf8STobias Grosser 
857aaabbbf8STobias Grosser   return ResultValue;
858aaabbbf8STobias Grosser }
859aaabbbf8STobias Grosser 
860*abed4969SSiddharth Bhat Value *GPUNodeBuilder::getOrCreateManagedDeviceArray(gpu_array_info *Array,
861*abed4969SSiddharth Bhat                                                      ScopArrayInfo *ArrayInfo) {
862*abed4969SSiddharth Bhat 
863*abed4969SSiddharth Bhat   assert(ManagedMemory && "Only used when you wish to get a host "
864*abed4969SSiddharth Bhat                           "pointer for sending data to the kernel, "
865*abed4969SSiddharth Bhat                           "with managed memory");
866*abed4969SSiddharth Bhat   std::map<ScopArrayInfo *, Value *>::iterator it;
867*abed4969SSiddharth Bhat   if ((it = DeviceAllocations.find(ArrayInfo)) != DeviceAllocations.end()) {
868*abed4969SSiddharth Bhat     return it->second;
869*abed4969SSiddharth Bhat   } else {
870*abed4969SSiddharth Bhat     Value *HostPtr;
871*abed4969SSiddharth Bhat 
872*abed4969SSiddharth Bhat     if (gpu_array_is_scalar(Array))
873*abed4969SSiddharth Bhat       HostPtr = BlockGen.getOrCreateAlloca(ArrayInfo);
874*abed4969SSiddharth Bhat     else
875*abed4969SSiddharth Bhat       HostPtr = ArrayInfo->getBasePtr();
876*abed4969SSiddharth Bhat 
877*abed4969SSiddharth Bhat     Value *Offset = getArrayOffset(Array);
878*abed4969SSiddharth Bhat     if (Offset) {
879*abed4969SSiddharth Bhat       HostPtr = Builder.CreatePointerCast(
880*abed4969SSiddharth Bhat           HostPtr, ArrayInfo->getElementType()->getPointerTo());
881*abed4969SSiddharth Bhat       HostPtr = Builder.CreateGEP(HostPtr, Offset);
882*abed4969SSiddharth Bhat     }
883*abed4969SSiddharth Bhat 
884*abed4969SSiddharth Bhat     HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
885*abed4969SSiddharth Bhat     DeviceAllocations[ArrayInfo] = HostPtr;
886*abed4969SSiddharth Bhat     return HostPtr;
887*abed4969SSiddharth Bhat   }
888*abed4969SSiddharth Bhat }
889*abed4969SSiddharth Bhat 
89013c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
89113c78e4dSTobias Grosser                                         enum DataDirection Direction) {
892*abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory needs no data transfers");
89313c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
89413c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
89513c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
89613c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
89713c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
89813c78e4dSTobias Grosser 
89913c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
900aaabbbf8STobias Grosser   Value *Offset = getArrayOffset(Array);
90113c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
90213c78e4dSTobias Grosser 
903b06ff457STobias Grosser   Value *HostPtr;
904b06ff457STobias Grosser 
905b06ff457STobias Grosser   if (gpu_array_is_scalar(Array))
906b06ff457STobias Grosser     HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
907b06ff457STobias Grosser   else
908b06ff457STobias Grosser     HostPtr = ScopArray->getBasePtr();
90913c78e4dSTobias Grosser 
910aaabbbf8STobias Grosser   if (Offset) {
911aaabbbf8STobias Grosser     HostPtr = Builder.CreatePointerCast(
912aaabbbf8STobias Grosser         HostPtr, ScopArray->getElementType()->getPointerTo());
913aaabbbf8STobias Grosser     HostPtr = Builder.CreateGEP(HostPtr, Offset);
914aaabbbf8STobias Grosser   }
915aaabbbf8STobias Grosser 
91613c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
91713c78e4dSTobias Grosser 
918aaabbbf8STobias Grosser   if (Offset) {
919aaabbbf8STobias Grosser     Size = Builder.CreateSub(
920ff40087aSTobias Grosser         Size, Builder.CreateMul(
921ff40087aSTobias Grosser                   Offset, Builder.getInt64(ScopArray->getElemSizeInBytes())));
922aaabbbf8STobias Grosser   }
923aaabbbf8STobias Grosser 
92413c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
92513c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
92613c78e4dSTobias Grosser   else
92713c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
92813c78e4dSTobias Grosser 
92913c78e4dSTobias Grosser   isl_id_free(Id);
93013c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
93113c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
93213c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
93313c78e4dSTobias Grosser }
93413c78e4dSTobias Grosser 
9351fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
93632837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
93732837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
93832837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
93932837fe3STobias Grosser   isl_id_free(Id);
94032837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
94132837fe3STobias Grosser 
94232837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
94332837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
94432837fe3STobias Grosser     createKernel(UserStmt);
94532837fe3STobias Grosser     isl_ast_expr_free(Expr);
94632837fe3STobias Grosser     return;
94732837fe3STobias Grosser   }
94832837fe3STobias Grosser 
94913c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
950*abed4969SSiddharth Bhat     if (!ManagedMemory)
95113c78e4dSTobias Grosser       createDataTransfer(UserStmt, HOST_TO_DEVICE);
952*abed4969SSiddharth Bhat     else
953*abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
954*abed4969SSiddharth Bhat 
95532837fe3STobias Grosser     isl_ast_expr_free(Expr);
95613c78e4dSTobias Grosser     return;
95713c78e4dSTobias Grosser   }
95813c78e4dSTobias Grosser 
95913c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
960*abed4969SSiddharth Bhat     if (!ManagedMemory) {
96113c78e4dSTobias Grosser       createDataTransfer(UserStmt, DEVICE_TO_HOST);
962*abed4969SSiddharth Bhat     } else {
963*abed4969SSiddharth Bhat       createCallSynchronizeDevice();
964*abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
965*abed4969SSiddharth Bhat     }
96613c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
96738fc0aedSTobias Grosser     return;
96838fc0aedSTobias Grosser   }
96938fc0aedSTobias Grosser 
9705260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
9715260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
9725260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
9735260c041STobias Grosser   isl_id_free(Anno);
9745260c041STobias Grosser 
9755260c041STobias Grosser   switch (KernelStmt->type) {
9765260c041STobias Grosser   case ppcg_kernel_domain:
977edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
9785260c041STobias Grosser     isl_ast_node_free(UserStmt);
9795260c041STobias Grosser     return;
9805260c041STobias Grosser   case ppcg_kernel_copy:
981b513b491STobias Grosser     createKernelCopy(KernelStmt);
9825260c041STobias Grosser     isl_ast_expr_free(Expr);
9835260c041STobias Grosser     isl_ast_node_free(UserStmt);
9845260c041STobias Grosser     return;
9855260c041STobias Grosser   case ppcg_kernel_sync:
9865260c041STobias Grosser     createKernelSync();
9875260c041STobias Grosser     isl_ast_expr_free(Expr);
9885260c041STobias Grosser     isl_ast_node_free(UserStmt);
9895260c041STobias Grosser     return;
9905260c041STobias Grosser   }
9915260c041STobias Grosser 
9925260c041STobias Grosser   isl_ast_expr_free(Expr);
9935260c041STobias Grosser   isl_ast_node_free(UserStmt);
9945260c041STobias Grosser   return;
9955260c041STobias Grosser }
996b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
997b513b491STobias Grosser   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
998b513b491STobias Grosser   LocalIndex = isl_ast_expr_address_of(LocalIndex);
999b513b491STobias Grosser   Value *LocalAddr = ExprBuilder.create(LocalIndex);
1000b513b491STobias Grosser   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
1001b513b491STobias Grosser   Index = isl_ast_expr_address_of(Index);
1002b513b491STobias Grosser   Value *GlobalAddr = ExprBuilder.create(Index);
1003b513b491STobias Grosser 
1004b513b491STobias Grosser   if (KernelStmt->u.c.read) {
1005b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read");
1006b513b491STobias Grosser     Builder.CreateStore(Load, LocalAddr);
1007b513b491STobias Grosser   } else {
1008b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write");
1009b513b491STobias Grosser     Builder.CreateStore(Load, GlobalAddr);
1010b513b491STobias Grosser   }
1011b513b491STobias Grosser }
10125260c041STobias Grosser 
1013edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
1014edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
1015edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1016edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
1017edb885cbSTobias Grosser 
1018edb885cbSTobias Grosser   LoopToScevMapT LTS;
1019edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
1020edb885cbSTobias Grosser 
1021edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
1022edb885cbSTobias Grosser 
1023edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
1024edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
1025edb885cbSTobias Grosser   else
1026a82c4b5dSTobias Grosser     RegionGen.copyStmt(*Stmt, LTS, Indexes);
1027edb885cbSTobias Grosser }
1028edb885cbSTobias Grosser 
10295260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
10305260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10315260c041STobias Grosser   auto *Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
10325260c041STobias Grosser   Builder.CreateCall(Sync, {});
10335260c041STobias Grosser }
10345260c041STobias Grosser 
1035edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
1036edb885cbSTobias Grosser ///
1037edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
1038edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
1039edb885cbSTobias Grosser ///
1040edb885cbSTobias Grosser /// @param Node The node to collect references for.
1041edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
1042edb885cbSTobias Grosser ///
1043edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
1044edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
1045edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
1046edb885cbSTobias Grosser     return isl_bool_true;
1047edb885cbSTobias Grosser 
1048edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
1049edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
1050edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
1051edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
1052edb885cbSTobias Grosser   isl_id_free(Id);
1053edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
1054edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
1055edb885cbSTobias Grosser 
1056edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
1057edb885cbSTobias Grosser     return isl_bool_true;
1058edb885cbSTobias Grosser 
1059edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
1060edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
1061edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1062edb885cbSTobias Grosser   isl_id_free(Id);
1063edb885cbSTobias Grosser 
106400bb5a99STobias Grosser   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
1065edb885cbSTobias Grosser 
1066edb885cbSTobias Grosser   return isl_bool_true;
1067edb885cbSTobias Grosser }
1068edb885cbSTobias Grosser 
1069edb885cbSTobias Grosser SetVector<Value *> GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
1070edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
1071edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
1072edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1073edb885cbSTobias Grosser   SubtreeReferences References = {
1074edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
1075edb885cbSTobias Grosser 
1076edb885cbSTobias Grosser   for (const auto &I : IDToValue)
1077edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
1078edb885cbSTobias Grosser 
1079edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
1080edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
1081edb885cbSTobias Grosser 
1082edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
1083edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
1084edb885cbSTobias Grosser 
1085edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
1086d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
1087edb885cbSTobias Grosser 
1088edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
1089edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1090edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
1091edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1092edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1093edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1094edb885cbSTobias Grosser     isl_id_free(Id);
1095edb885cbSTobias Grosser   }
1096edb885cbSTobias Grosser   isl_space_free(Space);
1097edb885cbSTobias Grosser 
1098edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
1099edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1100edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1101edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1102edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1103edb885cbSTobias Grosser     isl_id_free(Id);
1104edb885cbSTobias Grosser   }
1105edb885cbSTobias Grosser 
1106edb885cbSTobias Grosser   return SubtreeValues;
1107edb885cbSTobias Grosser }
1108edb885cbSTobias Grosser 
110974dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
111074dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
111174dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
111274dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
111374dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
111474dc3cb4STobias Grosser 
111574dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
111674dc3cb4STobias Grosser     DT.eraseNode(BB);
111774dc3cb4STobias Grosser }
111874dc3cb4STobias Grosser 
111974dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
112074dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
112174dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
112274dc3cb4STobias Grosser     if (L)
112374dc3cb4STobias Grosser       SE.forgetLoop(L);
112474dc3cb4STobias Grosser   }
112574dc3cb4STobias Grosser }
112674dc3cb4STobias Grosser 
112774dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
112874dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
112974dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
113074dc3cb4STobias Grosser     if (L)
113174dc3cb4STobias Grosser       SE.forgetLoop(L);
113274dc3cb4STobias Grosser     LI.removeBlock(&BB);
113374dc3cb4STobias Grosser   }
113474dc3cb4STobias Grosser }
113574dc3cb4STobias Grosser 
113679a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
113779a947c2STobias Grosser   std::vector<Value *> Sizes;
113879a947c2STobias Grosser   isl_ast_build *Context = isl_ast_build_from_context(S.getContext());
113979a947c2STobias Grosser 
114079a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
114179a947c2STobias Grosser     isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i);
114279a947c2STobias Grosser     isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size);
114379a947c2STobias Grosser     Value *Res = ExprBuilder.create(GridSize);
114479a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
114579a947c2STobias Grosser     Sizes.push_back(Res);
114679a947c2STobias Grosser   }
114779a947c2STobias Grosser   isl_ast_build_free(Context);
114879a947c2STobias Grosser 
114979a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
115079a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
115179a947c2STobias Grosser 
115279a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
115379a947c2STobias Grosser }
115479a947c2STobias Grosser 
115579a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
115679a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
115779a947c2STobias Grosser   std::vector<Value *> Sizes;
115879a947c2STobias Grosser 
115979a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
116079a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
116179a947c2STobias Grosser     Sizes.push_back(Res);
116279a947c2STobias Grosser   }
116379a947c2STobias Grosser 
116479a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
116579a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
116679a947c2STobias Grosser 
116779a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
116879a947c2STobias Grosser }
116979a947c2STobias Grosser 
117057693272STobias Grosser Value *
117157693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
117257693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
11734e18d71cSTobias Grosser   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(),
11744e18d71cSTobias Grosser                                  std::distance(F->arg_begin(), F->arg_end()));
117579a947c2STobias Grosser 
117679a947c2STobias Grosser   BasicBlock *EntryBlock =
117779a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
117867726b32STobias Grosser   auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace();
117979a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
118067726b32STobias Grosser   Instruction *Parameters = new AllocaInst(
118167726b32STobias Grosser       ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator());
118279a947c2STobias Grosser 
118379a947c2STobias Grosser   int Index = 0;
118479a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
118579a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
118679a947c2STobias Grosser       continue;
118779a947c2STobias Grosser 
118879a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
118979a947c2STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
119079a947c2STobias Grosser 
1191*abed4969SSiddharth Bhat     Value *DevArray = nullptr;
1192*abed4969SSiddharth Bhat     if (ManagedMemory) {
1193*abed4969SSiddharth Bhat       DevArray = getOrCreateManagedDeviceArray(
1194*abed4969SSiddharth Bhat           &Prog->array[i], const_cast<ScopArrayInfo *>(SAI));
1195*abed4969SSiddharth Bhat     } else {
1196*abed4969SSiddharth Bhat       DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
119779a947c2STobias Grosser       DevArray = createCallGetDevicePtr(DevArray);
1198*abed4969SSiddharth Bhat     }
1199*abed4969SSiddharth Bhat     assert(DevArray != nullptr && "Array to be offloaded to device not "
1200*abed4969SSiddharth Bhat                                   "initialized");
1201aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(&Prog->array[i]);
1202aaabbbf8STobias Grosser 
1203aaabbbf8STobias Grosser     if (Offset) {
1204aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(
1205aaabbbf8STobias Grosser           DevArray, SAI->getElementType()->getPointerTo());
1206aaabbbf8STobias Grosser       DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset));
1207aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1208aaabbbf8STobias Grosser     }
1209fe74a7a1STobias Grosser     Value *Slot = Builder.CreateGEP(
1210fe74a7a1STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1211aaabbbf8STobias Grosser 
1212fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1213*abed4969SSiddharth Bhat       Value *ValPtr = nullptr;
1214*abed4969SSiddharth Bhat       if (ManagedMemory)
1215*abed4969SSiddharth Bhat         ValPtr = DevArray;
1216*abed4969SSiddharth Bhat       else
1217*abed4969SSiddharth Bhat         ValPtr = BlockGen.getOrCreateAlloca(SAI);
1218*abed4969SSiddharth Bhat 
1219*abed4969SSiddharth Bhat       assert(ValPtr != nullptr && "ValPtr that should point to a valid object"
1220*abed4969SSiddharth Bhat                                   " to be stored into Parameters");
1221fe74a7a1STobias Grosser       Value *ValPtrCast =
1222fe74a7a1STobias Grosser           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1223fe74a7a1STobias Grosser       Builder.CreateStore(ValPtrCast, Slot);
1224fe74a7a1STobias Grosser     } else {
122567726b32STobias Grosser       Instruction *Param =
122667726b32STobias Grosser           new AllocaInst(Builder.getInt8PtrTy(), AddressSpace,
122767726b32STobias Grosser                          Launch + "_param_" + std::to_string(Index),
122879a947c2STobias Grosser                          EntryBlock->getTerminator());
122979a947c2STobias Grosser       Builder.CreateStore(DevArray, Param);
123079a947c2STobias Grosser       Value *ParamTyped =
123179a947c2STobias Grosser           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
123279a947c2STobias Grosser       Builder.CreateStore(ParamTyped, Slot);
1233fe74a7a1STobias Grosser     }
123479a947c2STobias Grosser     Index++;
123579a947c2STobias Grosser   }
123679a947c2STobias Grosser 
1237a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1238a490147cSTobias Grosser 
1239a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1240a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1241a490147cSTobias Grosser     Value *Val = IDToValue[Id];
1242a490147cSTobias Grosser     isl_id_free(Id);
124367726b32STobias Grosser     Instruction *Param =
124467726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
124567726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1246a490147cSTobias Grosser                        EntryBlock->getTerminator());
1247a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
1248a490147cSTobias Grosser     Value *Slot = Builder.CreateGEP(
1249a490147cSTobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1250a490147cSTobias Grosser     Value *ParamTyped =
1251a490147cSTobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1252a490147cSTobias Grosser     Builder.CreateStore(ParamTyped, Slot);
1253a490147cSTobias Grosser     Index++;
1254a490147cSTobias Grosser   }
1255a490147cSTobias Grosser 
1256d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1257d8b94bcaSTobias Grosser 
1258d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
1259d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1260d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
1261d8b94bcaSTobias Grosser     isl_id_free(Id);
126267726b32STobias Grosser     Instruction *Param =
126367726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
126467726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1265d8b94bcaSTobias Grosser                        EntryBlock->getTerminator());
1266d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
1267d8b94bcaSTobias Grosser     Value *Slot = Builder.CreateGEP(
1268d8b94bcaSTobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1269d8b94bcaSTobias Grosser     Value *ParamTyped =
1270d8b94bcaSTobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1271d8b94bcaSTobias Grosser     Builder.CreateStore(ParamTyped, Slot);
1272d8b94bcaSTobias Grosser     Index++;
1273d8b94bcaSTobias Grosser   }
1274d8b94bcaSTobias Grosser 
127557693272STobias Grosser   for (auto Val : SubtreeValues) {
127667726b32STobias Grosser     Instruction *Param =
127767726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
127867726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
127957693272STobias Grosser                        EntryBlock->getTerminator());
128057693272STobias Grosser     Builder.CreateStore(Val, Param);
128157693272STobias Grosser     Value *Slot = Builder.CreateGEP(
128257693272STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
128357693272STobias Grosser     Value *ParamTyped =
128457693272STobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
128557693272STobias Grosser     Builder.CreateStore(ParamTyped, Slot);
128657693272STobias Grosser     Index++;
128757693272STobias Grosser   }
128857693272STobias Grosser 
128979a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
129079a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
129179a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
129279a947c2STobias Grosser }
129379a947c2STobias Grosser 
129432837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
129532837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
129632837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
129732837fe3STobias Grosser   isl_id_free(Id);
129832837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
129932837fe3STobias Grosser 
1300bc653f20STobias Grosser   if (Kernel->n_grid > 1)
1301bc653f20STobias Grosser     DeepestParallel =
1302bc653f20STobias Grosser         std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set));
1303bc653f20STobias Grosser   else
1304bc653f20STobias Grosser     DeepestSequential =
1305bc653f20STobias Grosser         std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set));
1306bc653f20STobias Grosser 
1307c1c6a2a6STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1308c1c6a2a6STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1309c1c6a2a6STobias Grosser 
1310edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel);
1311edb885cbSTobias Grosser 
131232837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
131332837fe3STobias Grosser 
131432837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1315472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1316edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
1317587f1f57STobias Grosser   BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap;
1318b06ff457STobias Grosser   ScalarMap.clear();
131932837fe3STobias Grosser 
1320edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1321edb885cbSTobias Grosser 
1322edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
1323edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
1324edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
1325edb885cbSTobias Grosser   for (const Loop *L : Loops) {
1326edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1327edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1328edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1329edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1330edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1331edb885cbSTobias Grosser     SubtreeValues.insert(V);
1332edb885cbSTobias Grosser   }
1333edb885cbSTobias Grosser 
1334edb885cbSTobias Grosser   createKernelFunction(Kernel, SubtreeValues);
133532837fe3STobias Grosser 
133659ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
133759ab0705STobias Grosser 
133851dfc275STobias Grosser   finalizeKernelArguments(Kernel);
133974dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
1340c1c6a2a6STobias Grosser   addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
134174dc3cb4STobias Grosser   clearDominators(F);
134274dc3cb4STobias Grosser   clearScalarEvolution(F);
134374dc3cb4STobias Grosser   clearLoops(F);
134474dc3cb4STobias Grosser 
1345472f9654STobias Grosser   IDToValue = HostIDs;
134632837fe3STobias Grosser 
1347b06ff457STobias Grosser   ValueMap = std::move(HostValueMap);
1348b06ff457STobias Grosser   ScalarMap = std::move(HostScalarMap);
1349edb885cbSTobias Grosser   EscapeMap.clear();
1350edb885cbSTobias Grosser   IDToSAI.clear();
135174dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
135274dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
13534d5a9172STobias Grosser     S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array);
135474dc3cb4STobias Grosser   LocalArrays.clear();
1355edb885cbSTobias Grosser 
135651dfc275STobias Grosser   std::string ASMString = finalizeKernelFunction();
135751dfc275STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
135857693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
135979a947c2STobias Grosser 
136057793596STobias Grosser   std::string Name = "kernel_" + std::to_string(Kernel->id);
136157793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
136257793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
136357793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
136479a947c2STobias Grosser 
136579a947c2STobias Grosser   Value *GridDimX, *GridDimY;
136679a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
136779a947c2STobias Grosser 
136879a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
136979a947c2STobias Grosser                          BlockDimZ, Parameters);
137057793596STobias Grosser   createCallFreeKernel(GPUKernel);
1371b513b491STobias Grosser 
1372b513b491STobias Grosser   for (auto Id : KernelIds)
1373b513b491STobias Grosser     isl_id_free(Id);
1374b513b491STobias Grosser 
1375b513b491STobias Grosser   KernelIds.clear();
137632837fe3STobias Grosser }
137732837fe3STobias Grosser 
137832837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
137932837fe3STobias Grosser ///
138032837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
138132837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
1382d277fedaSSiddharth Bhat   std::string Ret = "";
138332837fe3STobias Grosser 
1384d277fedaSSiddharth Bhat   if (!is64Bit) {
1385d277fedaSSiddharth Bhat     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
1386d277fedaSSiddharth Bhat            "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1387d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1388d277fedaSSiddharth Bhat   } else {
1389d277fedaSSiddharth Bhat     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
1390d277fedaSSiddharth Bhat            "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1391d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1392d277fedaSSiddharth Bhat   }
139332837fe3STobias Grosser 
139432837fe3STobias Grosser   return Ret;
139532837fe3STobias Grosser }
139632837fe3STobias Grosser 
1397edb885cbSTobias Grosser Function *
1398edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1399edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
140032837fe3STobias Grosser   std::vector<Type *> Args;
140132837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
140232837fe3STobias Grosser 
140332837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
140432837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
140532837fe3STobias Grosser       continue;
140632837fe3STobias Grosser 
1407fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1408fe74a7a1STobias Grosser       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1409fe74a7a1STobias Grosser       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
1410fe74a7a1STobias Grosser       Args.push_back(SAI->getElementType());
1411fe74a7a1STobias Grosser     } else {
1412d277fedaSSiddharth Bhat       static const int UseGlobalMemory = 1;
1413d277fedaSSiddharth Bhat       Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory));
141432837fe3STobias Grosser     }
1415fe74a7a1STobias Grosser   }
141632837fe3STobias Grosser 
1417f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1418f6044bd0STobias Grosser 
1419f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++)
1420f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
1421f6044bd0STobias Grosser 
1422c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1423c84a1995STobias Grosser 
1424cf66ef26STobias Grosser   for (long i = 0; i < NumVars; i++) {
1425cf66ef26STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1426cf66ef26STobias Grosser     Value *Val = IDToValue[Id];
1427cf66ef26STobias Grosser     isl_id_free(Id);
1428cf66ef26STobias Grosser     Args.push_back(Val->getType());
1429cf66ef26STobias Grosser   }
1430c84a1995STobias Grosser 
1431edb885cbSTobias Grosser   for (auto *V : SubtreeValues)
1432edb885cbSTobias Grosser     Args.push_back(V->getType());
1433edb885cbSTobias Grosser 
143432837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
143532837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
143632837fe3STobias Grosser                               GPUModule.get());
143732837fe3STobias Grosser   FN->setCallingConv(CallingConv::PTX_Kernel);
143832837fe3STobias Grosser 
143932837fe3STobias Grosser   auto Arg = FN->arg_begin();
144032837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
144132837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
144232837fe3STobias Grosser       continue;
144332837fe3STobias Grosser 
1444edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
1445edb885cbSTobias Grosser 
1446edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1447edb885cbSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1448edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
1449edb885cbSTobias Grosser     Value *Val = &*Arg;
1450edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1451edb885cbSTobias Grosser     isl_ast_build *Build =
1452edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
1453f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1454edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1455edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
1456edb885cbSTobias Grosser           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
1457edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
1458edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
1459edb885cbSTobias Grosser     }
1460edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
14614d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array);
146274dc3cb4STobias Grosser     LocalArrays.push_back(Val);
1463edb885cbSTobias Grosser 
1464edb885cbSTobias Grosser     isl_ast_build_free(Build);
1465b513b491STobias Grosser     KernelIds.push_back(Id);
1466edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
146732837fe3STobias Grosser     Arg++;
146832837fe3STobias Grosser   }
146932837fe3STobias Grosser 
1470f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1471f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1472f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
1473f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
1474f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1475f6044bd0STobias Grosser     Arg++;
1476f6044bd0STobias Grosser   }
1477f6044bd0STobias Grosser 
1478c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
1479c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1480c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
148112453403STobias Grosser     Value *Val = IDToValue[Id];
148212453403STobias Grosser     ValueMap[Val] = &*Arg;
1483c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
1484c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1485c84a1995STobias Grosser     Arg++;
1486c84a1995STobias Grosser   }
1487c84a1995STobias Grosser 
1488edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
1489edb885cbSTobias Grosser     Arg->setName(V->getName());
1490edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
1491edb885cbSTobias Grosser     Arg++;
1492edb885cbSTobias Grosser   }
1493edb885cbSTobias Grosser 
149432837fe3STobias Grosser   return FN;
149532837fe3STobias Grosser }
149632837fe3STobias Grosser 
1497472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
1498472f9654STobias Grosser   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
1499472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
1500472f9654STobias Grosser 
1501472f9654STobias Grosser   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
1502472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
1503472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
1504472f9654STobias Grosser 
1505472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1506472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
1507472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1508472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1509472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1510472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1511472f9654STobias Grosser     IDToValue[Id] = Val;
1512472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1513472f9654STobias Grosser   };
1514472f9654STobias Grosser 
1515472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
1516472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1517472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
1518472f9654STobias Grosser   }
1519472f9654STobias Grosser 
1520472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
1521472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1522472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
1523472f9654STobias Grosser   }
1524472f9654STobias Grosser }
1525472f9654STobias Grosser 
152600bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
152700bb5a99STobias Grosser   auto Arg = FN->arg_begin();
152800bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
152900bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
153000bb5a99STobias Grosser       continue;
153100bb5a99STobias Grosser 
153200bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
153300bb5a99STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
153400bb5a99STobias Grosser     isl_id_free(Id);
153500bb5a99STobias Grosser 
153600bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
153700bb5a99STobias Grosser       Arg++;
153800bb5a99STobias Grosser       continue;
153900bb5a99STobias Grosser     }
154000bb5a99STobias Grosser 
1541fe74a7a1STobias Grosser     Value *Val = &*Arg;
1542fe74a7a1STobias Grosser 
1543fe74a7a1STobias Grosser     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
154400bb5a99STobias Grosser       Type *TypePtr = SAI->getElementType()->getPointerTo();
1545fe74a7a1STobias Grosser       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
1546fe74a7a1STobias Grosser       Val = Builder.CreateLoad(TypedArgPtr);
1547fe74a7a1STobias Grosser     }
1548fe74a7a1STobias Grosser 
1549fe74a7a1STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
155000bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
155100bb5a99STobias Grosser 
155200bb5a99STobias Grosser     Arg++;
155300bb5a99STobias Grosser   }
155400bb5a99STobias Grosser }
155500bb5a99STobias Grosser 
155651dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) {
155751dfc275STobias Grosser   auto *FN = Builder.GetInsertBlock()->getParent();
155851dfc275STobias Grosser   auto Arg = FN->arg_begin();
155951dfc275STobias Grosser 
156051dfc275STobias Grosser   bool StoredScalar = false;
156151dfc275STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
156251dfc275STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
156351dfc275STobias Grosser       continue;
156451dfc275STobias Grosser 
156551dfc275STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
156651dfc275STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
156751dfc275STobias Grosser     isl_id_free(Id);
156851dfc275STobias Grosser 
156951dfc275STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
157051dfc275STobias Grosser       Arg++;
157151dfc275STobias Grosser       continue;
157251dfc275STobias Grosser     }
157351dfc275STobias Grosser 
157451dfc275STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
157551dfc275STobias Grosser       Arg++;
157651dfc275STobias Grosser       continue;
157751dfc275STobias Grosser     }
157851dfc275STobias Grosser 
157951dfc275STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
158051dfc275STobias Grosser     Value *ArgPtr = &*Arg;
158151dfc275STobias Grosser     Type *TypePtr = SAI->getElementType()->getPointerTo();
158251dfc275STobias Grosser     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
158351dfc275STobias Grosser     Value *Val = Builder.CreateLoad(Alloca);
158451dfc275STobias Grosser     Builder.CreateStore(Val, TypedArgPtr);
158551dfc275STobias Grosser     StoredScalar = true;
158651dfc275STobias Grosser 
158751dfc275STobias Grosser     Arg++;
158851dfc275STobias Grosser   }
158951dfc275STobias Grosser 
159051dfc275STobias Grosser   if (StoredScalar)
159151dfc275STobias Grosser     /// In case more than one thread contains scalar stores, the generated
159251dfc275STobias Grosser     /// code might be incorrect, if we only store at the end of the kernel.
159351dfc275STobias Grosser     /// To support this case we need to store these scalars back at each
159451dfc275STobias Grosser     /// memory store or at least before each kernel barrier.
159551dfc275STobias Grosser     if (Kernel->n_block != 0 || Kernel->n_grid != 0)
159651dfc275STobias Grosser       BuildSuccessful = 0;
159751dfc275STobias Grosser }
159851dfc275STobias Grosser 
1599b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
1600b513b491STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1601b513b491STobias Grosser 
1602b513b491STobias Grosser   for (int i = 0; i < Kernel->n_var; ++i) {
1603b513b491STobias Grosser     struct ppcg_kernel_var &Var = Kernel->var[i];
1604b513b491STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
1605b513b491STobias Grosser     Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType();
1606b513b491STobias Grosser 
1607f919d8b3STobias Grosser     Type *ArrayTy = EleTy;
1608b513b491STobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1609b513b491STobias Grosser 
1610f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1611928d7573STobias Grosser     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
1612b513b491STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1613f919d8b3STobias Grosser       long Bound = isl_val_get_num_si(Val);
1614b513b491STobias Grosser       isl_val_free(Val);
1615b513b491STobias Grosser       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
1616928d7573STobias Grosser     }
1617928d7573STobias Grosser 
1618928d7573STobias Grosser     for (int j = Var.array->n_index - 1; j >= 0; --j) {
1619928d7573STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1620928d7573STobias Grosser       long Bound = isl_val_get_num_si(Val);
1621928d7573STobias Grosser       isl_val_free(Val);
1622b513b491STobias Grosser       ArrayTy = ArrayType::get(ArrayTy, Bound);
1623b513b491STobias Grosser     }
1624b513b491STobias Grosser 
1625130ca30fSTobias Grosser     const ScopArrayInfo *SAI;
1626130ca30fSTobias Grosser     Value *Allocation;
1627130ca30fSTobias Grosser     if (Var.type == ppcg_access_shared) {
1628130ca30fSTobias Grosser       auto GlobalVar = new GlobalVariable(
1629130ca30fSTobias Grosser           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
1630130ca30fSTobias Grosser           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
1631130ca30fSTobias Grosser       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
1632f919d8b3STobias Grosser       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
1633f919d8b3STobias Grosser 
1634130ca30fSTobias Grosser       Allocation = GlobalVar;
1635130ca30fSTobias Grosser     } else if (Var.type == ppcg_access_private) {
1636130ca30fSTobias Grosser       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
1637130ca30fSTobias Grosser     } else {
1638130ca30fSTobias Grosser       llvm_unreachable("unknown variable type");
1639130ca30fSTobias Grosser     }
16404d5a9172STobias Grosser     SAI =
16414d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array);
1642b513b491STobias Grosser     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
1643130ca30fSTobias Grosser     IDToValue[Id] = Allocation;
1644130ca30fSTobias Grosser     LocalArrays.push_back(Allocation);
1645b513b491STobias Grosser     KernelIds.push_back(Id);
1646b513b491STobias Grosser     IDToSAI[Id] = SAI;
1647b513b491STobias Grosser   }
1648b513b491STobias Grosser }
1649b513b491STobias Grosser 
1650edb885cbSTobias Grosser void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel,
1651edb885cbSTobias Grosser                                           SetVector<Value *> &SubtreeValues) {
165232837fe3STobias Grosser 
165332837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
165432837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
165532837fe3STobias Grosser   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
165632837fe3STobias Grosser   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
165732837fe3STobias Grosser 
1658edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
165932837fe3STobias Grosser 
166059ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
166132837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
166232837fe3STobias Grosser 
166359ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
166459ab0705STobias Grosser 
166532837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
166632837fe3STobias Grosser   Builder.CreateRetVoid();
166732837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
1668472f9654STobias Grosser 
1669629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
1670629109b6STobias Grosser 
167100bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
1672b513b491STobias Grosser   createKernelVariables(Kernel, FN);
1673472f9654STobias Grosser   insertKernelIntrinsics(Kernel);
167432837fe3STobias Grosser }
167532837fe3STobias Grosser 
167674dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
167774dc3cb4STobias Grosser   llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda"));
167874dc3cb4STobias Grosser   std::string ErrMsg;
167974dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
168074dc3cb4STobias Grosser 
168174dc3cb4STobias Grosser   if (!GPUTarget) {
168274dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
168374dc3cb4STobias Grosser     return "";
168474dc3cb4STobias Grosser   }
168574dc3cb4STobias Grosser 
168674dc3cb4STobias Grosser   TargetOptions Options;
168774dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
168874dc3cb4STobias Grosser   std::unique_ptr<TargetMachine> TargetM(
168974dc3cb4STobias Grosser       GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "",
169074dc3cb4STobias Grosser                                      Options, Optional<Reloc::Model>()));
169174dc3cb4STobias Grosser 
169274dc3cb4STobias Grosser   SmallString<0> ASMString;
169374dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
169474dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
169574dc3cb4STobias Grosser 
169674dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
169774dc3cb4STobias Grosser 
169874dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
169974dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
170074dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
170174dc3cb4STobias Grosser     return "";
170274dc3cb4STobias Grosser   }
170374dc3cb4STobias Grosser 
170474dc3cb4STobias Grosser   PM.run(*GPUModule);
170574dc3cb4STobias Grosser 
170674dc3cb4STobias Grosser   return ASMStream.str();
170774dc3cb4STobias Grosser }
170874dc3cb4STobias Grosser 
170957793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
17105857b701STobias Grosser   if (verifyModule(*GPUModule)) {
17115857b701STobias Grosser     BuildSuccessful = false;
17125857b701STobias Grosser     return "";
17135857b701STobias Grosser   }
171432837fe3STobias Grosser 
171532837fe3STobias Grosser   if (DumpKernelIR)
171632837fe3STobias Grosser     outs() << *GPUModule << "\n";
171732837fe3STobias Grosser 
17189a18d559STobias Grosser   // Optimize module.
17199a18d559STobias Grosser   llvm::legacy::PassManager OptPasses;
17209a18d559STobias Grosser   PassManagerBuilder PassBuilder;
17219a18d559STobias Grosser   PassBuilder.OptLevel = 3;
17229a18d559STobias Grosser   PassBuilder.SizeLevel = 0;
17239a18d559STobias Grosser   PassBuilder.populateModulePassManager(OptPasses);
17249a18d559STobias Grosser   OptPasses.run(*GPUModule);
17259a18d559STobias Grosser 
172674dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
172774dc3cb4STobias Grosser 
172874dc3cb4STobias Grosser   if (DumpKernelASM)
172974dc3cb4STobias Grosser     outs() << Assembly << "\n";
173074dc3cb4STobias Grosser 
173132837fe3STobias Grosser   GPUModule.release();
1732472f9654STobias Grosser   KernelIDs.clear();
173357793596STobias Grosser 
173457793596STobias Grosser   return Assembly;
173532837fe3STobias Grosser }
173632837fe3STobias Grosser 
17379dfe4e7cSTobias Grosser namespace {
17389dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
17399dfe4e7cSTobias Grosser public:
17409dfe4e7cSTobias Grosser   static char ID;
17419dfe4e7cSTobias Grosser 
1742e938517eSTobias Grosser   /// The scop that is currently processed.
1743e938517eSTobias Grosser   Scop *S;
1744e938517eSTobias Grosser 
174538fc0aedSTobias Grosser   LoopInfo *LI;
174638fc0aedSTobias Grosser   DominatorTree *DT;
174738fc0aedSTobias Grosser   ScalarEvolution *SE;
174838fc0aedSTobias Grosser   const DataLayout *DL;
174938fc0aedSTobias Grosser   RegionInfo *RI;
175038fc0aedSTobias Grosser 
17519dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
17529dfe4e7cSTobias Grosser 
1753e938517eSTobias Grosser   /// Construct compilation options for PPCG.
1754e938517eSTobias Grosser   ///
1755e938517eSTobias Grosser   /// @returns The compilation options.
1756e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
1757e938517eSTobias Grosser     auto DebugOptions =
1758e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
1759e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
1760e938517eSTobias Grosser 
1761e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
1762e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
1763e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
1764e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
17658950ceadSTobias Grosser     DebugOptions->verbose = false;
1766e938517eSTobias Grosser 
1767e938517eSTobias Grosser     Options->debug = DebugOptions;
1768e938517eSTobias Grosser 
1769e938517eSTobias Grosser     Options->reschedule = true;
1770e938517eSTobias Grosser     Options->scale_tile_loops = false;
1771e938517eSTobias Grosser     Options->wrap = false;
1772e938517eSTobias Grosser 
1773e938517eSTobias Grosser     Options->non_negative_parameters = false;
1774e938517eSTobias Grosser     Options->ctx = nullptr;
1775e938517eSTobias Grosser     Options->sizes = nullptr;
1776e938517eSTobias Grosser 
17774eaedde5STobias Grosser     Options->tile_size = 32;
17784eaedde5STobias Grosser 
1779130ca30fSTobias Grosser     Options->use_private_memory = PrivateMemory;
1780b513b491STobias Grosser     Options->use_shared_memory = SharedMemory;
1781b513b491STobias Grosser     Options->max_shared_memory = 48 * 1024;
1782e938517eSTobias Grosser 
1783e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
1784e938517eSTobias Grosser     Options->openmp = false;
1785e938517eSTobias Grosser     Options->linearize_device_arrays = true;
1786e938517eSTobias Grosser     Options->live_range_reordering = false;
1787e938517eSTobias Grosser 
1788e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
1789e938517eSTobias Grosser     Options->opencl_use_gpu = false;
1790e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
1791e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
1792e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
1793e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
1794e938517eSTobias Grosser 
1795e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
1796e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
1797e938517eSTobias Grosser 
1798e938517eSTobias Grosser     return Options;
1799e938517eSTobias Grosser   }
1800e938517eSTobias Grosser 
1801f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
1802f384594dSTobias Grosser   ///
1803f384594dSTobias Grosser   /// Instead of a normal access of the form:
1804f384594dSTobias Grosser   ///
1805f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
1806f384594dSTobias Grosser   ///
1807f384594dSTobias Grosser   /// a tagged access has the form
1808f384594dSTobias Grosser   ///
1809f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
1810f384594dSTobias Grosser   ///
1811f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
1812f384594dSTobias Grosser   /// triggered the access.
1813f384594dSTobias Grosser   ///
1814f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
1815f384594dSTobias Grosser   ///
1816f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
1817f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
1818f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
1819f384594dSTobias Grosser 
1820f384594dSTobias Grosser     for (auto &Stmt : *S)
1821f384594dSTobias Grosser       for (auto &Acc : Stmt)
1822f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
1823f384594dSTobias Grosser           isl_map *Relation = Acc->getAccessRelation();
1824f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
1825f384594dSTobias Grosser 
1826f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
1827f384594dSTobias Grosser           Space = isl_space_range(Space);
1828f384594dSTobias Grosser           Space = isl_space_from_range(Space);
18296293ba69STobias Grosser           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1830f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
1831f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
1832f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
1833f384594dSTobias Grosser         }
1834f384594dSTobias Grosser 
1835f384594dSTobias Grosser     return Accesses;
1836f384594dSTobias Grosser   }
1837f384594dSTobias Grosser 
1838f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
1839f384594dSTobias Grosser   ///
1840f384594dSTobias Grosser   /// @see getTaggedAccesses
1841f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
1842f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
1843f384594dSTobias Grosser   }
1844f384594dSTobias Grosser 
1845f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
1846f384594dSTobias Grosser   ///
1847f384594dSTobias Grosser   /// @see getTaggedAccesses
1848f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
1849f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
1850f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
1851f384594dSTobias Grosser   }
1852f384594dSTobias Grosser 
1853f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
1854f384594dSTobias Grosser   ///
1855f384594dSTobias Grosser   /// @see getTaggedAccesses
1856f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
1857f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
1858f384594dSTobias Grosser   }
1859f384594dSTobias Grosser 
1860aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
1861aef5196fSTobias Grosser   ///
1862aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
1863aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
1864aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
1865aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
1866aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
1867aef5196fSTobias Grosser   /// the data format that ppcg expects.
1868aef5196fSTobias Grosser   ///
1869aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
1870aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
1871aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
1872bd81a7eeSTobias Grosser         S->getIslCtx(),
1873bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
1874aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
1875aef5196fSTobias Grosser     auto *Space = S->getParamSpace();
1876aef5196fSTobias Grosser 
1877aef5196fSTobias Grosser     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
1878aef5196fSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
1879aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1880aef5196fSTobias Grosser     }
1881aef5196fSTobias Grosser 
1882aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
1883d7754a12SRoman Gareev       auto Id = Array->getBasePtrId();
1884aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1885aef5196fSTobias Grosser     }
1886aef5196fSTobias Grosser 
1887aef5196fSTobias Grosser     isl_space_free(Space);
1888aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
1889aef5196fSTobias Grosser 
1890aef5196fSTobias Grosser     return Names;
1891aef5196fSTobias Grosser   }
1892aef5196fSTobias Grosser 
1893e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
1894e938517eSTobias Grosser   ///
1895f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
1896f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
1897f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
1898f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
1899e938517eSTobias Grosser   ///
1900e938517eSTobias Grosser   /// @returns A new ppcg scop.
1901e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
1902e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
1903e938517eSTobias Grosser 
1904e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
1905e938517eSTobias Grosser 
1906e938517eSTobias Grosser     PPCGScop->start = 0;
1907e938517eSTobias Grosser     PPCGScop->end = 0;
1908e938517eSTobias Grosser 
1909f384594dSTobias Grosser     PPCGScop->context = S->getContext();
1910f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
1911e938517eSTobias Grosser     PPCGScop->call = nullptr;
1912f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
1913f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
1914e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
1915f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
1916f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
1917f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
1918f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
1919e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
1920f384594dSTobias Grosser     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
1921e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
1922e938517eSTobias Grosser 
1923e938517eSTobias Grosser     PPCGScop->independence = nullptr;
1924e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
1925e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
1926e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
1927e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
1928e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
1929e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
1930e938517eSTobias Grosser 
1931f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
1932aef5196fSTobias Grosser     PPCGScop->names = getNames();
1933e938517eSTobias Grosser 
1934e938517eSTobias Grosser     PPCGScop->pet = nullptr;
1935e938517eSTobias Grosser 
1936f384594dSTobias Grosser     compute_tagger(PPCGScop);
1937f384594dSTobias Grosser     compute_dependences(PPCGScop);
1938f384594dSTobias Grosser 
1939e938517eSTobias Grosser     return PPCGScop;
1940e938517eSTobias Grosser   }
1941e938517eSTobias Grosser 
194260f63b49STobias Grosser   /// Collect the array acesses in a statement.
194360f63b49STobias Grosser   ///
194460f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
194560f63b49STobias Grosser   ///
194660f63b49STobias Grosser   /// @returns A list of array accesses.
194760f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
194860f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
194960f63b49STobias Grosser 
195060f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
195160f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
195260f63b49STobias Grosser       Access->read = Acc->isRead();
195360f63b49STobias Grosser       Access->write = Acc->isWrite();
195460f63b49STobias Grosser       Access->access = Acc->getAccessRelation();
195560f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
195660f63b49STobias Grosser       Space = isl_space_range(Space);
195760f63b49STobias Grosser       Space = isl_space_from_range(Space);
19586293ba69STobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
195960f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
196060f63b49STobias Grosser       Access->tagged_access =
196160f63b49STobias Grosser           isl_map_domain_product(Acc->getAccessRelation(), Universe);
1962b513b491STobias Grosser       Access->exact_write = !Acc->isMayWrite();
196360f63b49STobias Grosser       Access->ref_id = Acc->getId();
196460f63b49STobias Grosser       Access->next = Accesses;
1965b513b491STobias Grosser       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
196660f63b49STobias Grosser       Accesses = Access;
196760f63b49STobias Grosser     }
196860f63b49STobias Grosser 
196960f63b49STobias Grosser     return Accesses;
197060f63b49STobias Grosser   }
197160f63b49STobias Grosser 
197269b46751STobias Grosser   /// Collect the list of GPU statements.
197369b46751STobias Grosser   ///
197469b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
197569b46751STobias Grosser   /// as well as a list with all memory accesses.
197669b46751STobias Grosser   ///
197769b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
197869b46751STobias Grosser   ///
197969b46751STobias Grosser   /// @returns A linked-list of statements.
198069b46751STobias Grosser   gpu_stmt *getStatements() {
198169b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
198269b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
198369b46751STobias Grosser 
198469b46751STobias Grosser     int i = 0;
198569b46751STobias Grosser     for (auto &Stmt : *S) {
198669b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
198769b46751STobias Grosser 
198869b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
198969b46751STobias Grosser 
199069b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
199169b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
199260f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
199369b46751STobias Grosser       i++;
199469b46751STobias Grosser     }
199569b46751STobias Grosser 
199669b46751STobias Grosser     return Stmts;
199769b46751STobias Grosser   }
199869b46751STobias Grosser 
199960f63b49STobias Grosser   /// Derive the extent of an array.
200060f63b49STobias Grosser   ///
2001d58acf86STobias Grosser   /// The extent of an array is the set of elements that are within the
2002d58acf86STobias Grosser   /// accessed array. For the inner dimensions, the extent constraints are
2003d58acf86STobias Grosser   /// 0 and the size of the corresponding array dimension. For the first
2004d58acf86STobias Grosser   /// (outermost) dimension, the extent constraints are the minimal and maximal
2005d58acf86STobias Grosser   /// subscript value for the first dimension.
200660f63b49STobias Grosser   ///
200760f63b49STobias Grosser   /// @param Array The array to derive the extent for.
200860f63b49STobias Grosser   ///
200960f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
201060f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
2011d58acf86STobias Grosser     unsigned NumDims = Array->getNumberOfDimensions();
201260f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
201360f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
2014d58acf86STobias Grosser     Accesses = isl_union_map_detect_equalities(Accesses);
201560f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
2016d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2017d58acf86STobias Grosser     AccessUSet = isl_union_set_detect_equalities(AccessUSet);
2018d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2019d58acf86STobias Grosser 
2020d58acf86STobias Grosser     if (isl_union_set_is_empty(AccessUSet)) {
2021d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
2022d58acf86STobias Grosser       return isl_set_empty(Array->getSpace());
2023d58acf86STobias Grosser     }
2024d58acf86STobias Grosser 
2025d58acf86STobias Grosser     if (Array->getNumberOfDimensions() == 0) {
2026d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
2027d58acf86STobias Grosser       return isl_set_universe(Array->getSpace());
2028d58acf86STobias Grosser     }
2029d58acf86STobias Grosser 
203060f63b49STobias Grosser     isl_set *AccessSet =
203160f63b49STobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace());
203260f63b49STobias Grosser 
2033d58acf86STobias Grosser     isl_union_set_free(AccessUSet);
2034d58acf86STobias Grosser     isl_local_space *LS = isl_local_space_from_space(Array->getSpace());
2035d58acf86STobias Grosser 
2036d58acf86STobias Grosser     isl_pw_aff *Val =
2037d58acf86STobias Grosser         isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0));
2038d58acf86STobias Grosser 
2039d58acf86STobias Grosser     isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0);
2040d58acf86STobias Grosser     isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0);
2041d58acf86STobias Grosser     OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in,
2042d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
2043d58acf86STobias Grosser     OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in,
2044d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
2045d58acf86STobias Grosser     OuterMin =
2046d58acf86STobias Grosser         isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, Array->getBasePtrId());
2047d58acf86STobias Grosser     OuterMax =
2048d58acf86STobias Grosser         isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, Array->getBasePtrId());
2049d58acf86STobias Grosser 
2050d58acf86STobias Grosser     isl_set *Extent = isl_set_universe(Array->getSpace());
2051d58acf86STobias Grosser 
2052d58acf86STobias Grosser     Extent = isl_set_intersect(
2053d58acf86STobias Grosser         Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val)));
2054d58acf86STobias Grosser     Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val));
2055d58acf86STobias Grosser 
2056d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i)
2057d58acf86STobias Grosser       Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0);
2058d58acf86STobias Grosser 
2059d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i) {
2060d58acf86STobias Grosser       isl_pw_aff *PwAff =
2061d58acf86STobias Grosser           const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i));
2062d58acf86STobias Grosser       isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain(
2063d58acf86STobias Grosser           isl_local_space_from_space(Array->getSpace()), isl_dim_set, i));
2064d58acf86STobias Grosser       PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in,
2065d58acf86STobias Grosser                                   isl_pw_aff_dim(Val, isl_dim_in));
2066d58acf86STobias Grosser       PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in,
2067d58acf86STobias Grosser                                       isl_pw_aff_get_tuple_id(Val, isl_dim_in));
2068d58acf86STobias Grosser       auto *Set = isl_pw_aff_gt_set(PwAff, Val);
2069d58acf86STobias Grosser       Extent = isl_set_intersect(Set, Extent);
2070d58acf86STobias Grosser     }
2071d58acf86STobias Grosser 
2072d58acf86STobias Grosser     return Extent;
207360f63b49STobias Grosser   }
207460f63b49STobias Grosser 
207560f63b49STobias Grosser   /// Derive the bounds of an array.
207660f63b49STobias Grosser   ///
207760f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
207860f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
207960f63b49STobias Grosser   /// ScopArrayInfo.
208060f63b49STobias Grosser   ///
208160f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
208260f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
208360f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
208460f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
208502293ed7STobias Grosser       if (isl_set_is_empty(PPCGArray.extent)) {
208602293ed7STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
208702293ed7STobias Grosser         isl_local_space *LS = isl_local_space_from_space(
208802293ed7STobias Grosser             isl_space_params(isl_set_get_space(Dom)));
208902293ed7STobias Grosser         isl_set_free(Dom);
209002293ed7STobias Grosser         isl_aff *Zero = isl_aff_zero_on_domain(LS);
209102293ed7STobias Grosser         PPCGArray.bound[0] = isl_pw_aff_from_aff(Zero);
209202293ed7STobias Grosser       } else {
209360f63b49STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
209460f63b49STobias Grosser         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
209560f63b49STobias Grosser         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
209660f63b49STobias Grosser         isl_set_free(Dom);
209760f63b49STobias Grosser         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
209802293ed7STobias Grosser         isl_local_space *LS =
209902293ed7STobias Grosser             isl_local_space_from_space(isl_set_get_space(Dom));
210060f63b49STobias Grosser         isl_aff *One = isl_aff_zero_on_domain(LS);
210160f63b49STobias Grosser         One = isl_aff_add_constant_si(One, 1);
210260f63b49STobias Grosser         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
210360f63b49STobias Grosser         Bound = isl_pw_aff_gist(Bound, S->getContext());
210460f63b49STobias Grosser         PPCGArray.bound[0] = Bound;
210560f63b49STobias Grosser       }
210602293ed7STobias Grosser     }
210760f63b49STobias Grosser 
210860f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
210960f63b49STobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
211060f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
211160f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
211260f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
211360f63b49STobias Grosser       PPCGArray.bound[i] = Bound;
211460f63b49STobias Grosser     }
211560f63b49STobias Grosser   }
211660f63b49STobias Grosser 
211760f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
211860f63b49STobias Grosser   ///
211960f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
212060f63b49STobias Grosser   void createArrays(gpu_prog *PPCGProg) {
212160f63b49STobias Grosser     int i = 0;
2122d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
212360f63b49STobias Grosser       std::string TypeName;
212460f63b49STobias Grosser       raw_string_ostream OS(TypeName);
212560f63b49STobias Grosser 
212660f63b49STobias Grosser       OS << *Array->getElementType();
212760f63b49STobias Grosser       TypeName = OS.str();
212860f63b49STobias Grosser 
212960f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
213060f63b49STobias Grosser 
213160f63b49STobias Grosser       PPCGArray.space = Array->getSpace();
213260f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
213360f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
213460f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
213560f63b49STobias Grosser       PPCGArray.extent = nullptr;
213660f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
213760f63b49STobias Grosser       PPCGArray.bound =
213860f63b49STobias Grosser           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
213960f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
214060f63b49STobias Grosser       PPCGArray.n_ref = 0;
214160f63b49STobias Grosser       PPCGArray.refs = nullptr;
214260f63b49STobias Grosser       PPCGArray.accessed = true;
2143fe74a7a1STobias Grosser       PPCGArray.read_only_scalar =
2144fe74a7a1STobias Grosser           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
214560f63b49STobias Grosser       PPCGArray.has_compound_element = false;
214660f63b49STobias Grosser       PPCGArray.local = false;
214760f63b49STobias Grosser       PPCGArray.declare_local = false;
214860f63b49STobias Grosser       PPCGArray.global = false;
214960f63b49STobias Grosser       PPCGArray.linearize = false;
215060f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
215113c78e4dSTobias Grosser       PPCGArray.user = Array;
215260f63b49STobias Grosser 
215360f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
21542d010dafSTobias Grosser       i++;
2155b9fc860aSTobias Grosser 
2156b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
215760f63b49STobias Grosser     }
215860f63b49STobias Grosser   }
215960f63b49STobias Grosser 
216060f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
216160f63b49STobias Grosser   ///
216260f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
216360f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
216460f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
216560f63b49STobias Grosser 
2166d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
216760f63b49STobias Grosser       isl_space *Space = Array->getSpace();
216860f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
216960f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
217060f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
217160f63b49STobias Grosser     }
217260f63b49STobias Grosser 
217360f63b49STobias Grosser     return Maps;
217460f63b49STobias Grosser   }
217560f63b49STobias Grosser 
2176e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
2177e938517eSTobias Grosser   ///
2178e938517eSTobias Grosser   /// @returns A new gpu grogram description.
2179e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
2180e938517eSTobias Grosser 
2181e938517eSTobias Grosser     if (!PPCGScop)
2182e938517eSTobias Grosser       return nullptr;
2183e938517eSTobias Grosser 
2184e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
2185e938517eSTobias Grosser 
2186e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
2187e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
2188aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
218960f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
219060f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
219160f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
219260f63b49STobias Grosser     PPCGProg->tagged_must_kill =
219360f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
219460f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
219560f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
2196e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
2197e938517eSTobias Grosser     PPCGProg->array_order = nullptr;
219869b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
219969b46751STobias Grosser     PPCGProg->stmts = getStatements();
220060f63b49STobias Grosser     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
220160f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
220260f63b49STobias Grosser                                        PPCGProg->n_array);
220360f63b49STobias Grosser 
220460f63b49STobias Grosser     createArrays(PPCGProg);
2205e938517eSTobias Grosser 
2206d58acf86STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
2207d58acf86STobias Grosser 
2208e938517eSTobias Grosser     return PPCGProg;
2209e938517eSTobias Grosser   }
2210e938517eSTobias Grosser 
221169b46751STobias Grosser   struct PrintGPUUserData {
221269b46751STobias Grosser     struct cuda_info *CudaInfo;
221369b46751STobias Grosser     struct gpu_prog *PPCGProg;
221469b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
221569b46751STobias Grosser   };
221669b46751STobias Grosser 
221769b46751STobias Grosser   /// Print a user statement node in the host code.
221869b46751STobias Grosser   ///
221969b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
222069b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
222169b46751STobias Grosser   /// host ast.
222269b46751STobias Grosser   ///
222369b46751STobias Grosser   /// @param P The printer to print to
222469b46751STobias Grosser   /// @param Options The printing options to use
222569b46751STobias Grosser   /// @param Node The node to print
222669b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
222769b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
222869b46751STobias Grosser   ///
222969b46751STobias Grosser   /// @returns A printer to which the output has been printed.
223069b46751STobias Grosser   static __isl_give isl_printer *
223169b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
223269b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
223369b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
223469b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
223569b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
223669b46751STobias Grosser 
223769b46751STobias Grosser     if (Id) {
223820251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
223920251734STobias Grosser 
224020251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
224120251734STobias Grosser       // otherwise try to call pet functionality that is not available in
224220251734STobias Grosser       // Polly.
224320251734STobias Grosser       if (IsUser) {
224420251734STobias Grosser         P = isl_printer_start_line(P);
224520251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
224620251734STobias Grosser         P = isl_printer_end_line(P);
224720251734STobias Grosser         isl_id_free(Id);
224820251734STobias Grosser         isl_ast_print_options_free(Options);
224920251734STobias Grosser         return P;
225020251734STobias Grosser       }
225120251734STobias Grosser 
225269b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
225369b46751STobias Grosser       isl_id_free(Id);
225469b46751STobias Grosser       Data->Kernels.push_back(Kernel);
225569b46751STobias Grosser     }
225669b46751STobias Grosser 
225769b46751STobias Grosser     return print_host_user(P, Options, Node, User);
225869b46751STobias Grosser   }
225969b46751STobias Grosser 
226069b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
226169b46751STobias Grosser   ///
226269b46751STobias Grosser   /// @param Kernel The kernel to print
226369b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
226469b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
226569b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
226669b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
226769b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
226869b46751STobias Grosser     char *String = isl_printer_get_str(P);
226969b46751STobias Grosser     printf("%s\n", String);
227069b46751STobias Grosser     free(String);
227169b46751STobias Grosser     isl_printer_free(P);
227269b46751STobias Grosser   }
227369b46751STobias Grosser 
227469b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
227569b46751STobias Grosser   ///
227669b46751STobias Grosser   /// @param Tree An AST describing GPU code
227769b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
227869b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
227969b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
228069b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
228169b46751STobias Grosser 
228269b46751STobias Grosser     PrintGPUUserData Data;
228369b46751STobias Grosser     Data.PPCGProg = PPCGProg;
228469b46751STobias Grosser 
228569b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
228669b46751STobias Grosser     Options =
228769b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
228869b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
228969b46751STobias Grosser     char *String = isl_printer_get_str(P);
229069b46751STobias Grosser     printf("# host\n");
229169b46751STobias Grosser     printf("%s\n", String);
229269b46751STobias Grosser     free(String);
229369b46751STobias Grosser     isl_printer_free(P);
229469b46751STobias Grosser 
229569b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
229669b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
229769b46751STobias Grosser       printKernel(Kernel);
229869b46751STobias Grosser     }
229969b46751STobias Grosser   }
230069b46751STobias Grosser 
2301f384594dSTobias Grosser   // Generate a GPU program using PPCG.
2302f384594dSTobias Grosser   //
2303f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
2304f384594dSTobias Grosser   //
2305f384594dSTobias Grosser   //  1) Compute new schedule for the program.
2306f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
2307f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
2308f384594dSTobias Grosser   //
2309f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
2310f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
2311f384594dSTobias Grosser   // strategy directly from this pass.
2312f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
2313f384594dSTobias Grosser 
2314f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
2315f384594dSTobias Grosser 
2316f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
2317f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
2318f384594dSTobias Grosser     PPCGGen->print = nullptr;
2319f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
232060c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
2321f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
2322f384594dSTobias Grosser     PPCGGen->tree = nullptr;
2323f384594dSTobias Grosser     PPCGGen->types.n = 0;
2324f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
2325f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
2326f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
2327f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
2328f384594dSTobias Grosser 
2329f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
2330f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
2331f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
23322341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
2333f384594dSTobias Grosser 
2334f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
2335f384594dSTobias Grosser 
2336aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
2337aef5196fSTobias Grosser 
233869b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
2339aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
234069b46751STobias Grosser     } else {
2341aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
234269b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
234369b46751STobias Grosser     }
2344aef5196fSTobias Grosser 
2345f384594dSTobias Grosser     if (DumpSchedule) {
2346f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
2347f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
2348f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
2349f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
2350f384594dSTobias Grosser       if (Schedule)
2351f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
2352f384594dSTobias Grosser       else
2353f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
2354f384594dSTobias Grosser 
2355f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
2356f384594dSTobias Grosser       isl_printer_free(P);
2357f384594dSTobias Grosser     }
2358f384594dSTobias Grosser 
235969b46751STobias Grosser     if (DumpCode) {
236069b46751STobias Grosser       printf("Code\n");
236169b46751STobias Grosser       printf("====\n");
236269b46751STobias Grosser       if (PPCGGen->tree)
236369b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
236469b46751STobias Grosser       else
236569b46751STobias Grosser         printf("No code generated\n");
236669b46751STobias Grosser     }
236769b46751STobias Grosser 
2368f384594dSTobias Grosser     isl_schedule_free(Schedule);
2369f384594dSTobias Grosser 
2370f384594dSTobias Grosser     return PPCGGen;
2371f384594dSTobias Grosser   }
2372f384594dSTobias Grosser 
2373f384594dSTobias Grosser   /// Free gpu_gen structure.
2374f384594dSTobias Grosser   ///
2375f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
2376f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
2377f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
2378f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
2379f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
2380f384594dSTobias Grosser     free(PPCGGen);
2381f384594dSTobias Grosser   }
2382f384594dSTobias Grosser 
2383b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
2384b307ed4dSTobias Grosser   ///
2385b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
2386b307ed4dSTobias Grosser   /// ourselves.
2387b307ed4dSTobias Grosser   ///
2388b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
2389b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
2390b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
2391b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
2392b307ed4dSTobias Grosser     free(PPCGScop->options);
2393b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
2394b307ed4dSTobias Grosser   }
2395b307ed4dSTobias Grosser 
239682f2af35STobias Grosser   /// Approximate the number of points in the set.
239782f2af35STobias Grosser   ///
239882f2af35STobias Grosser   /// This function returns an ast expression that overapproximates the number
239982f2af35STobias Grosser   /// of points in an isl set through the rectangular hull surrounding this set.
240082f2af35STobias Grosser   ///
240182f2af35STobias Grosser   /// @param Set   The set to count.
240282f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
240382f2af35STobias Grosser   ///              expression.
240482f2af35STobias Grosser   ///
240582f2af35STobias Grosser   /// @returns An approximation of the number of points in the set.
240682f2af35STobias Grosser   __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set,
240782f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
240882f2af35STobias Grosser 
240982f2af35STobias Grosser     isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1);
241082f2af35STobias Grosser     auto *Expr = isl_ast_expr_from_val(isl_val_copy(One));
241182f2af35STobias Grosser 
241282f2af35STobias Grosser     isl_space *Space = isl_set_get_space(Set);
241382f2af35STobias Grosser     Space = isl_space_params(Space);
241482f2af35STobias Grosser     auto *Univ = isl_set_universe(Space);
241582f2af35STobias Grosser     isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One);
241682f2af35STobias Grosser 
241782f2af35STobias Grosser     for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) {
241882f2af35STobias Grosser       isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i);
241982f2af35STobias Grosser       isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i);
242082f2af35STobias Grosser       isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min);
242182f2af35STobias Grosser       DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff));
242282f2af35STobias Grosser       auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize);
242382f2af35STobias Grosser       Expr = isl_ast_expr_mul(Expr, DimSizeExpr);
242482f2af35STobias Grosser     }
242582f2af35STobias Grosser 
242682f2af35STobias Grosser     isl_set_free(Set);
242782f2af35STobias Grosser     isl_pw_aff_free(OneAff);
242882f2af35STobias Grosser 
242982f2af35STobias Grosser     return Expr;
243082f2af35STobias Grosser   }
243182f2af35STobias Grosser 
243282f2af35STobias Grosser   /// Approximate a number of dynamic instructions executed by a given
243382f2af35STobias Grosser   /// statement.
243482f2af35STobias Grosser   ///
243582f2af35STobias Grosser   /// @param Stmt  The statement for which to compute the number of dynamic
243682f2af35STobias Grosser   ///              instructions.
243782f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
243882f2af35STobias Grosser   ///              expression.
243982f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
244082f2af35STobias Grosser   ///          by @p Stmt.
244182f2af35STobias Grosser   __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt,
244282f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
244382f2af35STobias Grosser     auto Iterations = approxPointsInSet(Stmt.getDomain(), Build);
244482f2af35STobias Grosser 
244582f2af35STobias Grosser     long InstCount = 0;
244682f2af35STobias Grosser 
244782f2af35STobias Grosser     if (Stmt.isBlockStmt()) {
244882f2af35STobias Grosser       auto *BB = Stmt.getBasicBlock();
244982f2af35STobias Grosser       InstCount = std::distance(BB->begin(), BB->end());
245082f2af35STobias Grosser     } else {
245182f2af35STobias Grosser       auto *R = Stmt.getRegion();
245282f2af35STobias Grosser 
245382f2af35STobias Grosser       for (auto *BB : R->blocks()) {
245482f2af35STobias Grosser         InstCount += std::distance(BB->begin(), BB->end());
245582f2af35STobias Grosser       }
245682f2af35STobias Grosser     }
245782f2af35STobias Grosser 
245882f2af35STobias Grosser     isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount);
245982f2af35STobias Grosser     auto *InstExpr = isl_ast_expr_from_val(InstVal);
246082f2af35STobias Grosser     return isl_ast_expr_mul(InstExpr, Iterations);
246182f2af35STobias Grosser   }
246282f2af35STobias Grosser 
246382f2af35STobias Grosser   /// Approximate dynamic instructions executed in scop.
246482f2af35STobias Grosser   ///
246582f2af35STobias Grosser   /// @param S     The scop for which to approximate dynamic instructions.
246682f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
246782f2af35STobias Grosser   ///              expression.
246882f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
246982f2af35STobias Grosser   ///          in @p S.
247082f2af35STobias Grosser   __isl_give isl_ast_expr *
247182f2af35STobias Grosser   getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) {
247282f2af35STobias Grosser     isl_ast_expr *Instructions;
247382f2af35STobias Grosser 
247482f2af35STobias Grosser     isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0);
247582f2af35STobias Grosser     Instructions = isl_ast_expr_from_val(Zero);
247682f2af35STobias Grosser 
247782f2af35STobias Grosser     for (ScopStmt &Stmt : S) {
247882f2af35STobias Grosser       isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build);
247982f2af35STobias Grosser       Instructions = isl_ast_expr_add(Instructions, StmtInstructions);
248082f2af35STobias Grosser     }
248182f2af35STobias Grosser     return Instructions;
248282f2af35STobias Grosser   }
248382f2af35STobias Grosser 
248482f2af35STobias Grosser   /// Create a check that ensures sufficient compute in scop.
248582f2af35STobias Grosser   ///
248682f2af35STobias Grosser   /// @param S     The scop for which to ensure sufficient compute.
248782f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
248882f2af35STobias Grosser   ///              expression.
248982f2af35STobias Grosser   /// @returns An expression that evaluates to TRUE in case of sufficient
249082f2af35STobias Grosser   ///          compute and to FALSE, otherwise.
249182f2af35STobias Grosser   __isl_give isl_ast_expr *
249282f2af35STobias Grosser   createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) {
249382f2af35STobias Grosser     auto Iterations = getNumberOfIterations(S, Build);
249482f2af35STobias Grosser     auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute);
249582f2af35STobias Grosser     auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal);
249682f2af35STobias Grosser     return isl_ast_expr_ge(Iterations, MinComputeExpr);
249782f2af35STobias Grosser   }
249882f2af35STobias Grosser 
249938fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
250038fc0aedSTobias Grosser   ///
250132837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
250232837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
250332837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
250438fc0aedSTobias Grosser     ScopAnnotator Annotator;
250538fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
250638fc0aedSTobias Grosser 
250738fc0aedSTobias Grosser     Region *R = &S->getRegion();
250838fc0aedSTobias Grosser 
250938fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
251038fc0aedSTobias Grosser 
251138fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
251238fc0aedSTobias Grosser 
251338fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
251438fc0aedSTobias Grosser 
251538fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
251638fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
251738fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
251838fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
251938fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
252038fc0aedSTobias Grosser     // code generating this scop.
252138fc0aedSTobias Grosser     BasicBlock *StartBlock =
25222d950f36SPhilip Pfaffe         executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI);
252338fc0aedSTobias Grosser 
25242d950f36SPhilip Pfaffe     GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S,
2525acf80064SEli Friedman                                StartBlock, Prog);
2526acf80064SEli Friedman 
252738fc0aedSTobias Grosser     // TODO: Handle LICM
252838fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
252938fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
253038fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
2531cb1aef8dSTobias Grosser 
2532cb1aef8dSTobias Grosser     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx());
2533cb1aef8dSTobias Grosser     isl_ast_expr *Condition = IslAst::buildRunCondition(S, Build);
253482f2af35STobias Grosser     isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build);
253582f2af35STobias Grosser     Condition = isl_ast_expr_and(Condition, SufficientCompute);
2536cb1aef8dSTobias Grosser     isl_ast_build_free(Build);
2537cb1aef8dSTobias Grosser 
2538cb1aef8dSTobias Grosser     Value *RTC = NodeBuilder.createRTC(Condition);
2539cb1aef8dSTobias Grosser     Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
2540cb1aef8dSTobias Grosser 
254138fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
2542fa7b0802STobias Grosser 
2543fa7b0802STobias Grosser     NodeBuilder.initializeAfterRTH();
254438fc0aedSTobias Grosser     NodeBuilder.create(Root);
25458ed5e599STobias Grosser     NodeBuilder.finalize();
25465857b701STobias Grosser 
2547bc653f20STobias Grosser     /// In case a sequential kernel has more surrounding loops as any parallel
2548bc653f20STobias Grosser     /// kernel, the SCoP is probably mostly sequential. Hence, there is no
2549de244eb4STobias Grosser     /// point in running it on a GPU.
2550bc653f20STobias Grosser     if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel)
2551bc653f20STobias Grosser       SplitBlock->getTerminator()->setOperand(0, Builder.getFalse());
2552bc653f20STobias Grosser 
25535857b701STobias Grosser     if (!NodeBuilder.BuildSuccessful)
25545857b701STobias Grosser       SplitBlock->getTerminator()->setOperand(0, Builder.getFalse());
255538fc0aedSTobias Grosser   }
255638fc0aedSTobias Grosser 
2557e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
2558e938517eSTobias Grosser     S = &CurrentScop;
255938fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
256038fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
256138fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
25627b5a4dfdSTobias Grosser     DL = &S->getRegion().getEntry()->getModule()->getDataLayout();
256338fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
2564e938517eSTobias Grosser 
25652d58a64eSTobias Grosser     // We currently do not support scops with invariant loads.
25662d58a64eSTobias Grosser     if (S->hasInvariantAccesses())
25672d58a64eSTobias Grosser       return false;
25682d58a64eSTobias Grosser 
2569e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
2570e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
2571f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
257238fc0aedSTobias Grosser 
257338fc0aedSTobias Grosser     if (PPCGGen->tree)
257432837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
257538fc0aedSTobias Grosser 
2576b307ed4dSTobias Grosser     freeOptions(PPCGScop);
2577f384594dSTobias Grosser     freePPCGGen(PPCGGen);
2578e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
2579e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
2580e938517eSTobias Grosser 
2581e938517eSTobias Grosser     return true;
2582e938517eSTobias Grosser   }
25839dfe4e7cSTobias Grosser 
25849dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
25859dfe4e7cSTobias Grosser 
25869dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
25879dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
25889dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
25899dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
25909dfe4e7cSTobias Grosser     AU.addRequired<ScopDetection>();
25919dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
25929dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
25939dfe4e7cSTobias Grosser 
25949dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
25959dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
25969dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
25979dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
25989dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
25999dfe4e7cSTobias Grosser     AU.addPreserved<ScopDetection>();
26009dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
26019dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
26029dfe4e7cSTobias Grosser 
26039dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
26049dfe4e7cSTobias Grosser     //        region tree.
26059dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
26069dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
26079dfe4e7cSTobias Grosser   }
26089dfe4e7cSTobias Grosser };
260924222c73STobias Grosser } // namespace
26109dfe4e7cSTobias Grosser 
26119dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
26129dfe4e7cSTobias Grosser 
26139dfe4e7cSTobias Grosser Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
26149dfe4e7cSTobias Grosser 
26159dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
26169dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
26179dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
26189dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
26199dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
26209dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
26219dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
26229dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScopDetection);
26239dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
26249dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
2625