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 
1517f01968SSiddharth Bhat #include "polly/CodeGen/PPCGCodeGeneration.h"
16cb1aef8dSTobias Grosser #include "polly/CodeGen/IslAst.h"
179dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h"
1838fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h"
199dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h"
209dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h"
21f384594dSTobias Grosser #include "polly/Options.h"
22629109b6STobias Grosser #include "polly/ScopDetection.h"
239dfe4e7cSTobias Grosser #include "polly/ScopInfo.h"
24edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h"
2574dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h"
269dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h"
279dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h"
289dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h"
299dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
3074dc3cb4STobias Grosser #include "llvm/Analysis/TargetLibraryInfo.h"
3174dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h"
3274dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h"
33e1a98343STobias Grosser #include "llvm/IR/Verifier.h"
3474dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h"
3574dc3cb4STobias Grosser #include "llvm/Support/TargetSelect.h"
3674dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h"
379a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h"
38750160e2STobias Grosser #include "llvm/Transforms/Utils/BasicBlockUtils.h"
399dfe4e7cSTobias Grosser 
40f384594dSTobias Grosser #include "isl/union_map.h"
41f384594dSTobias Grosser 
42e938517eSTobias Grosser extern "C" {
43a56f8f8eSTobias Grosser #include "ppcg/cuda.h"
44a56f8f8eSTobias Grosser #include "ppcg/gpu.h"
45a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h"
46a56f8f8eSTobias Grosser #include "ppcg/ppcg.h"
47a56f8f8eSTobias Grosser #include "ppcg/schedule.h"
48e938517eSTobias Grosser }
49e938517eSTobias Grosser 
509dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h"
519dfe4e7cSTobias Grosser 
529dfe4e7cSTobias Grosser using namespace polly;
539dfe4e7cSTobias Grosser using namespace llvm;
549dfe4e7cSTobias Grosser 
559dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg"
569dfe4e7cSTobias Grosser 
57f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
58f384594dSTobias Grosser                                   cl::desc("Dump the computed GPU Schedule"),
59681bd568STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
60f384594dSTobias Grosser                                   cl::cat(PollyCategory));
6169b46751STobias Grosser 
6269b46751STobias Grosser static cl::opt<bool>
6369b46751STobias Grosser     DumpCode("polly-acc-dump-code",
6469b46751STobias Grosser              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
6569b46751STobias Grosser              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
6669b46751STobias Grosser 
6732837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
6832837fe3STobias Grosser                                   cl::desc("Dump the kernel LLVM-IR"),
6932837fe3STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
7032837fe3STobias Grosser                                   cl::cat(PollyCategory));
7132837fe3STobias Grosser 
7274dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
7374dc3cb4STobias Grosser                                    cl::desc("Dump the kernel assembly code"),
7474dc3cb4STobias Grosser                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
7574dc3cb4STobias Grosser                                    cl::cat(PollyCategory));
7674dc3cb4STobias Grosser 
7774dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath",
7874dc3cb4STobias Grosser                               cl::desc("Allow unsafe math optimizations"),
7974dc3cb4STobias Grosser                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
8074dc3cb4STobias Grosser                               cl::cat(PollyCategory));
81b513b491STobias Grosser static cl::opt<bool> SharedMemory("polly-acc-use-shared",
82b513b491STobias Grosser                                   cl::desc("Use shared memory"), cl::Hidden,
83b513b491STobias Grosser                                   cl::init(false), cl::ZeroOrMore,
84b513b491STobias Grosser                                   cl::cat(PollyCategory));
85130ca30fSTobias Grosser static cl::opt<bool> PrivateMemory("polly-acc-use-private",
86130ca30fSTobias Grosser                                    cl::desc("Use private memory"), cl::Hidden,
87130ca30fSTobias Grosser                                    cl::init(false), cl::ZeroOrMore,
88130ca30fSTobias Grosser                                    cl::cat(PollyCategory));
8974dc3cb4STobias Grosser 
90abed4969SSiddharth Bhat static cl::opt<bool> ManagedMemory("polly-acc-codegen-managed-memory",
91abed4969SSiddharth Bhat                                    cl::desc("Generate Host kernel code assuming"
92abed4969SSiddharth Bhat                                             " that all memory has been"
93abed4969SSiddharth Bhat                                             " declared as managed memory"),
94abed4969SSiddharth Bhat                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
95abed4969SSiddharth Bhat                                    cl::cat(PollyCategory));
96abed4969SSiddharth Bhat 
9765d7f72fSSiddharth Bhat static cl::opt<bool>
9865d7f72fSSiddharth Bhat     FailOnVerifyModuleFailure("polly-acc-fail-on-verify-module-failure",
9965d7f72fSSiddharth Bhat                               cl::desc("Fail and generate a backtrace if"
10065d7f72fSSiddharth Bhat                                        " verifyModule fails on the GPU "
10165d7f72fSSiddharth Bhat                                        " kernel module."),
10265d7f72fSSiddharth Bhat                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
10365d7f72fSSiddharth Bhat                               cl::cat(PollyCategory));
10465d7f72fSSiddharth Bhat 
10574dc3cb4STobias Grosser static cl::opt<std::string>
10674dc3cb4STobias Grosser     CudaVersion("polly-acc-cuda-version",
10774dc3cb4STobias Grosser                 cl::desc("The CUDA version to compile for"), cl::Hidden,
10874dc3cb4STobias Grosser                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
10974dc3cb4STobias Grosser 
11082f2af35STobias Grosser static cl::opt<int>
11182f2af35STobias Grosser     MinCompute("polly-acc-mincompute",
11282f2af35STobias Grosser                cl::desc("Minimal number of compute statements to run on GPU."),
11382f2af35STobias Grosser                cl::Hidden, cl::init(10 * 512 * 512));
11482f2af35STobias Grosser 
11560c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
11660c60025STobias Grosser ///
11760c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
11860c60025STobias Grosser /// of the scheduled ScopStmts.
11960c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
120edb885cbSTobias Grosser     void *StmtT, isl_ast_build *Build,
12160c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
12260c60025STobias Grosser                                        isl_id *Id, void *User),
12360c60025STobias Grosser     void *UserIndex,
12460c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
125edb885cbSTobias Grosser     void *UserExpr) {
12660c60025STobias Grosser 
127edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
12860c60025STobias Grosser 
129edb885cbSTobias Grosser   isl_ctx *Ctx;
130edb885cbSTobias Grosser 
131edb885cbSTobias Grosser   if (!Stmt || !Build)
132edb885cbSTobias Grosser     return NULL;
133edb885cbSTobias Grosser 
134edb885cbSTobias Grosser   Ctx = isl_ast_build_get_ctx(Build);
135edb885cbSTobias Grosser   isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0);
136edb885cbSTobias Grosser 
137edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
138edb885cbSTobias Grosser     isl_map *AddrFunc = Acc->getAddressFunction();
139edb885cbSTobias Grosser     AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain());
140edb885cbSTobias Grosser     isl_id *RefId = Acc->getId();
141edb885cbSTobias Grosser     isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc);
142edb885cbSTobias Grosser     isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA);
143edb885cbSTobias Grosser     MPA = isl_multi_pw_aff_coalesce(MPA);
144edb885cbSTobias Grosser     MPA = FunctionIndex(MPA, RefId, UserIndex);
145edb885cbSTobias Grosser     isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA);
146edb885cbSTobias Grosser     Access = FunctionExpr(Access, RefId, UserExpr);
147edb885cbSTobias Grosser     RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access);
148edb885cbSTobias Grosser   }
149edb885cbSTobias Grosser 
150edb885cbSTobias Grosser   return RefToExpr;
15160c60025STobias Grosser }
152f384594dSTobias Grosser 
153a90be207SSiddharth Bhat /// Given a LLVM Type, compute its size in bytes,
154a90be207SSiddharth Bhat static int computeSizeInBytes(const Type *T) {
155a90be207SSiddharth Bhat   int bytes = T->getPrimitiveSizeInBits() / 8;
156a90be207SSiddharth Bhat   if (bytes == 0)
157a90be207SSiddharth Bhat     bytes = T->getScalarSizeInBits() / 8;
158a90be207SSiddharth Bhat   return bytes;
159a90be207SSiddharth Bhat }
160a90be207SSiddharth Bhat 
16138fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
16238fc0aedSTobias Grosser ///
16338fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
164a6d48f59SMichael Kruse /// generates code for general-purpose AST nodes, with special functionality
16538fc0aedSTobias Grosser /// for generating GPU specific user nodes.
16638fc0aedSTobias Grosser ///
16738fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
16838fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
16938fc0aedSTobias Grosser public:
1702d950f36SPhilip Pfaffe   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator,
17138fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
172acf80064SEli Friedman                  DominatorTree &DT, Scop &S, BasicBlock *StartBlock,
17317f01968SSiddharth Bhat                  gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch)
1742d950f36SPhilip Pfaffe       : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock),
17517f01968SSiddharth Bhat         Prog(Prog), Runtime(Runtime), Arch(Arch) {
176edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
177edb885cbSTobias Grosser   }
17838fc0aedSTobias Grosser 
179fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
180fa7b0802STobias Grosser   void initializeAfterRTH();
181fa7b0802STobias Grosser 
182fa7b0802STobias Grosser   /// Finalize the generated scop.
183fa7b0802STobias Grosser   virtual void finalize();
184fa7b0802STobias Grosser 
1855857b701STobias Grosser   /// Track if the full build process was successful.
1865857b701STobias Grosser   ///
1875857b701STobias Grosser   /// This value is set to false, if throughout the build process an error
1885857b701STobias Grosser   /// occurred which prevents us from generating valid GPU code.
1895857b701STobias Grosser   bool BuildSuccessful = true;
1905857b701STobias Grosser 
191bc653f20STobias Grosser   /// The maximal number of loops surrounding a sequential kernel.
192bc653f20STobias Grosser   unsigned DeepestSequential = 0;
193bc653f20STobias Grosser 
194bc653f20STobias Grosser   /// The maximal number of loops surrounding a parallel kernel.
195bc653f20STobias Grosser   unsigned DeepestParallel = 0;
196bc653f20STobias Grosser 
19738fc0aedSTobias Grosser private:
19874dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
19974dc3cb4STobias Grosser   ///
20074dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
20174dc3cb4STobias Grosser   /// more.
20274dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
20374dc3cb4STobias Grosser 
20413c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
20513c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
2067287aeddSTobias Grosser 
207fa7b0802STobias Grosser   /// The current GPU context.
208fa7b0802STobias Grosser   Value *GPUContext;
209fa7b0802STobias Grosser 
210b513b491STobias Grosser   /// The set of isl_ids allocated in the kernel
211b513b491STobias Grosser   std::vector<isl_id *> KernelIds;
212b513b491STobias Grosser 
21332837fe3STobias Grosser   /// A module containing GPU code.
21432837fe3STobias Grosser   ///
21532837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
21632837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
21732837fe3STobias Grosser 
21832837fe3STobias Grosser   /// The GPU program we generate code for.
21932837fe3STobias Grosser   gpu_prog *Prog;
22032837fe3STobias Grosser 
22117f01968SSiddharth Bhat   /// The GPU Runtime implementation to use (OpenCL or CUDA).
22217f01968SSiddharth Bhat   GPURuntime Runtime;
22317f01968SSiddharth Bhat 
22417f01968SSiddharth Bhat   /// The GPU Architecture to target.
22517f01968SSiddharth Bhat   GPUArch Arch;
22617f01968SSiddharth Bhat 
227472f9654STobias Grosser   /// Class to free isl_ids.
228472f9654STobias Grosser   class IslIdDeleter {
229472f9654STobias Grosser   public:
230472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
231472f9654STobias Grosser   };
232472f9654STobias Grosser 
233472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
234472f9654STobias Grosser   ///
235472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
236472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
237472f9654STobias Grosser 
238edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
239edb885cbSTobias Grosser 
24038fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
24138fc0aedSTobias Grosser   ///
24238fc0aedSTobias Grosser   /// These AST nodes can be of type:
24338fc0aedSTobias Grosser   ///
24438fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
24538fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
24613c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
2475260c041STobias Grosser   ///   - In-kernel synchronization
2485260c041STobias Grosser   ///   - In-kernel memory copy statement
24938fc0aedSTobias Grosser   ///
2501fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
2511fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
25232837fe3STobias Grosser 
25313c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
25413c78e4dSTobias Grosser 
25513c78e4dSTobias Grosser   /// Create code for a data transfer statement
25613c78e4dSTobias Grosser   ///
25713c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
25813c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
25913c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
26013c78e4dSTobias Grosser                           enum DataDirection Direction);
26113c78e4dSTobias Grosser 
262edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
263edb885cbSTobias Grosser   ///
264edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
265edb885cbSTobias Grosser   ///
266f291c8d5SSiddharth Bhat   /// @returns A pair, whose first element contains the set of values
267f291c8d5SSiddharth Bhat   ///          referenced by the kernel, and whose second element contains the
268f291c8d5SSiddharth Bhat   ///          set of functions referenced by the kernel. All functions in the
269f291c8d5SSiddharth Bhat   ///          second set satisfy isValidFunctionInKernel.
270f291c8d5SSiddharth Bhat   std::pair<SetVector<Value *>, SetVector<Function *>>
271f291c8d5SSiddharth Bhat   getReferencesInKernel(ppcg_kernel *Kernel);
272edb885cbSTobias Grosser 
27379a947c2STobias Grosser   /// Compute the sizes of the execution grid for a given kernel.
27479a947c2STobias Grosser   ///
27579a947c2STobias Grosser   /// @param Kernel The kernel to compute grid sizes for.
27679a947c2STobias Grosser   ///
27779a947c2STobias Grosser   /// @returns A tuple with grid sizes for X and Y dimension
27879a947c2STobias Grosser   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
27979a947c2STobias Grosser 
280abed4969SSiddharth Bhat   /// Creates a array that can be sent to the kernel on the device using a
281abed4969SSiddharth Bhat   /// host pointer. This is required for managed memory, when we directly send
282abed4969SSiddharth Bhat   /// host pointers to the device.
283abed4969SSiddharth Bhat   /// \note
284abed4969SSiddharth Bhat   /// This is to be used only with managed memory
285abed4969SSiddharth Bhat   Value *getOrCreateManagedDeviceArray(gpu_array_info *Array,
286abed4969SSiddharth Bhat                                        ScopArrayInfo *ArrayInfo);
287abed4969SSiddharth Bhat 
28879a947c2STobias Grosser   /// Compute the sizes of the thread blocks for a given kernel.
28979a947c2STobias Grosser   ///
29079a947c2STobias Grosser   /// @param Kernel The kernel to compute thread block sizes for.
29179a947c2STobias Grosser   ///
29279a947c2STobias Grosser   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
29379a947c2STobias Grosser   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
29479a947c2STobias Grosser 
295a90be207SSiddharth Bhat   /// Store a specific kernel launch parameter in the array of kernel launch
296a90be207SSiddharth Bhat   /// parameters.
297a90be207SSiddharth Bhat   ///
298a90be207SSiddharth Bhat   /// @param Parameters The list of parameters in which to store.
299a90be207SSiddharth Bhat   /// @param Param      The kernel launch parameter to store.
300a90be207SSiddharth Bhat   /// @param Index      The index in the parameter list, at which to store the
301a90be207SSiddharth Bhat   ///                   parameter.
302a90be207SSiddharth Bhat   void insertStoreParameter(Instruction *Parameters, Instruction *Param,
303a90be207SSiddharth Bhat                             int Index);
304a90be207SSiddharth Bhat 
30579a947c2STobias Grosser   /// Create kernel launch parameters.
30679a947c2STobias Grosser   ///
30779a947c2STobias Grosser   /// @param Kernel        The kernel to create parameters for.
30879a947c2STobias Grosser   /// @param F             The kernel function that has been created.
30957693272STobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
31079a947c2STobias Grosser   ///
31179a947c2STobias Grosser   /// @returns A stack allocated array with pointers to the parameter
31279a947c2STobias Grosser   ///          values that are passed to the kernel.
31357693272STobias Grosser   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
31457693272STobias Grosser                                 SetVector<Value *> SubtreeValues);
31579a947c2STobias Grosser 
316b513b491STobias Grosser   /// Create declarations for kernel variable.
317b513b491STobias Grosser   ///
318b513b491STobias Grosser   /// This includes shared memory declarations.
319b513b491STobias Grosser   ///
320b513b491STobias Grosser   /// @param Kernel        The kernel definition to create variables for.
321b513b491STobias Grosser   /// @param FN            The function into which to generate the variables.
322b513b491STobias Grosser   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
323b513b491STobias Grosser 
324c1c6a2a6STobias Grosser   /// Add CUDA annotations to module.
325c1c6a2a6STobias Grosser   ///
326c1c6a2a6STobias Grosser   /// Add a set of CUDA annotations that declares the maximal block dimensions
327c1c6a2a6STobias Grosser   /// that will be used to execute the CUDA kernel. This allows the NVIDIA
328c1c6a2a6STobias Grosser   /// PTX compiler to bound the number of allocated registers to ensure the
329c1c6a2a6STobias Grosser   /// resulting kernel is known to run with up to as many block dimensions
330c1c6a2a6STobias Grosser   /// as specified here.
331c1c6a2a6STobias Grosser   ///
332c1c6a2a6STobias Grosser   /// @param M         The module to add the annotations to.
333c1c6a2a6STobias Grosser   /// @param BlockDimX The size of block dimension X.
334c1c6a2a6STobias Grosser   /// @param BlockDimY The size of block dimension Y.
335c1c6a2a6STobias Grosser   /// @param BlockDimZ The size of block dimension Z.
336c1c6a2a6STobias Grosser   void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY,
337c1c6a2a6STobias Grosser                           Value *BlockDimZ);
338c1c6a2a6STobias Grosser 
33932837fe3STobias Grosser   /// Create GPU kernel.
34032837fe3STobias Grosser   ///
34132837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
34232837fe3STobias Grosser   ///
34332837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
34432837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
34532837fe3STobias Grosser 
34613c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
34713c78e4dSTobias Grosser   ///
34813c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
34913c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
35013c78e4dSTobias Grosser 
351aaabbbf8STobias Grosser   /// Generate code to compute the minimal offset at which an array is accessed.
352aaabbbf8STobias Grosser   ///
353aaabbbf8STobias Grosser   /// The offset of an array is the minimal array location accessed in a scop.
354aaabbbf8STobias Grosser   ///
355aaabbbf8STobias Grosser   /// Example:
356aaabbbf8STobias Grosser   ///
357aaabbbf8STobias Grosser   ///   for (long i = 0; i < 100; i++)
358aaabbbf8STobias Grosser   ///     A[i + 42] += ...
359aaabbbf8STobias Grosser   ///
360aaabbbf8STobias Grosser   ///   getArrayOffset(A) results in 42.
361aaabbbf8STobias Grosser   ///
362aaabbbf8STobias Grosser   /// @param Array The array for which to compute the offset.
363aaabbbf8STobias Grosser   /// @returns An llvm::Value that contains the offset of the array.
364aaabbbf8STobias Grosser   Value *getArrayOffset(gpu_array_info *Array);
365aaabbbf8STobias Grosser 
36600bb5a99STobias Grosser   /// Prepare the kernel arguments for kernel code generation
36700bb5a99STobias Grosser   ///
36800bb5a99STobias Grosser   /// @param Kernel The kernel to generate code for.
36900bb5a99STobias Grosser   /// @param FN     The function created for the kernel.
37000bb5a99STobias Grosser   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
37100bb5a99STobias Grosser 
37232837fe3STobias Grosser   /// Create kernel function.
37332837fe3STobias Grosser   ///
37432837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
37532837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
37632837fe3STobias Grosser   /// start block of this newly created function.
37732837fe3STobias Grosser   ///
37832837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
379edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
380f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by this
381f291c8d5SSiddharth Bhat   ///                         kernel.
382edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
383f291c8d5SSiddharth Bhat                             SetVector<Value *> &SubtreeValues,
384f291c8d5SSiddharth Bhat                             SetVector<Function *> &SubtreeFunctions);
38532837fe3STobias Grosser 
38632837fe3STobias Grosser   /// Create the declaration of a kernel function.
38732837fe3STobias Grosser   ///
38832837fe3STobias Grosser   /// The kernel function takes as arguments:
38932837fe3STobias Grosser   ///
39032837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
391f6044bd0STobias Grosser   ///   - Host iterators
392c84a1995STobias Grosser   ///   - Parameters
39332837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
39432837fe3STobias Grosser   ///
39532837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
396edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
397edb885cbSTobias Grosser   ///
39832837fe3STobias Grosser   /// @returns The newly declared function.
399edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
400edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
40132837fe3STobias Grosser 
402472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
403472f9654STobias Grosser   ///
404472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
405472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
406472f9654STobias Grosser 
407f291c8d5SSiddharth Bhat   /// Setup the creation of functions referenced by the GPU kernel.
408f291c8d5SSiddharth Bhat   ///
409f291c8d5SSiddharth Bhat   /// 1. Create new function declarations in GPUModule which are the same as
410f291c8d5SSiddharth Bhat   /// SubtreeFunctions.
411f291c8d5SSiddharth Bhat   ///
412f291c8d5SSiddharth Bhat   /// 2. Populate IslNodeBuilder::ValueMap with mappings from
413f291c8d5SSiddharth Bhat   /// old functions (that come from the original module) to new functions
414f291c8d5SSiddharth Bhat   /// (that are created within GPUModule). That way, we generate references
415f291c8d5SSiddharth Bhat   /// to the correct function (in GPUModule) in BlockGenerator.
416f291c8d5SSiddharth Bhat   ///
417f291c8d5SSiddharth Bhat   /// @see IslNodeBuilder::ValueMap
418f291c8d5SSiddharth Bhat   /// @see BlockGenerator::GlobalMap
419f291c8d5SSiddharth Bhat   /// @see BlockGenerator::getNewValue
420f291c8d5SSiddharth Bhat   /// @see GPUNodeBuilder::getReferencesInKernel.
421f291c8d5SSiddharth Bhat   ///
422f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by
423f291c8d5SSiddharth Bhat   ///                         this kernel.
424f291c8d5SSiddharth Bhat   void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions);
425f291c8d5SSiddharth Bhat 
426b513b491STobias Grosser   /// Create a global-to-shared or shared-to-global copy statement.
427b513b491STobias Grosser   ///
428b513b491STobias Grosser   /// @param CopyStmt The copy statement to generate code for
429b513b491STobias Grosser   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
430b513b491STobias Grosser 
431edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
432edb885cbSTobias Grosser   ///
433edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
434edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
435edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
436edb885cbSTobias Grosser 
4375260c041STobias Grosser   /// Create an in-kernel synchronization call.
4385260c041STobias Grosser   void createKernelSync();
4395260c041STobias Grosser 
44074dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
44174dc3cb4STobias Grosser   ///
44274dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
44374dc3cb4STobias Grosser   std::string createKernelASM();
44474dc3cb4STobias Grosser 
44574dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
44674dc3cb4STobias Grosser   ///
44774dc3cb4STobias Grosser   /// @param F The function to remove references to.
44874dc3cb4STobias Grosser   void clearDominators(Function *F);
44974dc3cb4STobias Grosser 
45074dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
45174dc3cb4STobias Grosser   ///
45274dc3cb4STobias Grosser   /// @param F The function to remove references to.
45374dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
45474dc3cb4STobias Grosser 
45574dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
45674dc3cb4STobias Grosser   ///
45774dc3cb4STobias Grosser   /// @param F The function to remove references to.
45874dc3cb4STobias Grosser   void clearLoops(Function *F);
45974dc3cb4STobias Grosser 
46032837fe3STobias Grosser   /// Finalize the generation of the kernel function.
46132837fe3STobias Grosser   ///
46232837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
46332837fe3STobias Grosser   /// dump its IR to stderr.
46457793596STobias Grosser   ///
46557793596STobias Grosser   /// @returns The Assembly string of the kernel.
46657793596STobias Grosser   std::string finalizeKernelFunction();
467fa7b0802STobias Grosser 
46851dfc275STobias Grosser   /// Finalize the generation of the kernel arguments.
46951dfc275STobias Grosser   ///
47051dfc275STobias Grosser   /// This function ensures that not-read-only scalars used in a kernel are
471a6d48f59SMichael Kruse   /// stored back to the global memory location they are backed with before
47251dfc275STobias Grosser   /// the kernel terminates.
47351dfc275STobias Grosser   ///
47451dfc275STobias Grosser   /// @params Kernel The kernel to finalize kernel arguments for.
47551dfc275STobias Grosser   void finalizeKernelArguments(ppcg_kernel *Kernel);
47651dfc275STobias Grosser 
4777287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
478fa7b0802STobias Grosser   void allocateDeviceArrays();
479fa7b0802STobias Grosser 
4807287aeddSTobias Grosser   /// Free all allocated device arrays.
4817287aeddSTobias Grosser   void freeDeviceArrays();
4827287aeddSTobias Grosser 
483fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
484fa7b0802STobias Grosser   ///
485fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
486fa7b0802STobias Grosser   Value *createCallInitContext();
487fa7b0802STobias Grosser 
48879a947c2STobias Grosser   /// Create a call to get the device pointer for a kernel allocation.
48979a947c2STobias Grosser   ///
49079a947c2STobias Grosser   /// @param Allocation The Polly GPU allocation
49179a947c2STobias Grosser   ///
49279a947c2STobias Grosser   /// @returns The device parameter corresponding to this allocation.
49379a947c2STobias Grosser   Value *createCallGetDevicePtr(Value *Allocation);
49479a947c2STobias Grosser 
495fa7b0802STobias Grosser   /// Create a call to free the GPU context.
496fa7b0802STobias Grosser   ///
497fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
498fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
499fa7b0802STobias Grosser 
5007287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
5017287aeddSTobias Grosser   ///
5027287aeddSTobias Grosser   /// @param Size The size of memory to allocate
5037287aeddSTobias Grosser   ///
5047287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
505fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
5067287aeddSTobias Grosser 
5077287aeddSTobias Grosser   /// Create a call to free a device array.
5087287aeddSTobias Grosser   ///
5097287aeddSTobias Grosser   /// @param Array The device array to free.
5107287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
51113c78e4dSTobias Grosser 
51213c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
51313c78e4dSTobias Grosser   ///
51413c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
51513c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
51613c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
51713c78e4dSTobias Grosser                                       Value *Size);
51813c78e4dSTobias Grosser 
51913c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
52013c78e4dSTobias Grosser   ///
52113c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
52213c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
52313c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
52413c78e4dSTobias Grosser                                       Value *Size);
52557793596STobias Grosser 
526abed4969SSiddharth Bhat   /// Create a call to synchronize Host & Device.
527abed4969SSiddharth Bhat   /// \note
528abed4969SSiddharth Bhat   /// This is to be used only with managed memory.
529abed4969SSiddharth Bhat   void createCallSynchronizeDevice();
530abed4969SSiddharth Bhat 
53157793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
53257793596STobias Grosser   ///
53357793596STobias Grosser   /// @param Buffer The string describing the kernel.
53457793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
53557793596STobias Grosser   ///
53657793596STobias Grosser   /// @returns A pointer to a kernel object
53757793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
53857793596STobias Grosser 
53957793596STobias Grosser   /// Create a call to free a GPU kernel.
54057793596STobias Grosser   ///
54157793596STobias Grosser   /// @param GPUKernel THe kernel to free.
54257793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
54379a947c2STobias Grosser 
54479a947c2STobias Grosser   /// Create a call to launch a GPU kernel.
54579a947c2STobias Grosser   ///
54679a947c2STobias Grosser   /// @param GPUKernel  The kernel to launch.
54779a947c2STobias Grosser   /// @param GridDimX   The size of the first grid dimension.
54879a947c2STobias Grosser   /// @param GridDimY   The size of the second grid dimension.
54979a947c2STobias Grosser   /// @param GridBlockX The size of the first block dimension.
55079a947c2STobias Grosser   /// @param GridBlockY The size of the second block dimension.
55179a947c2STobias Grosser   /// @param GridBlockZ The size of the third block dimension.
552a6d48f59SMichael Kruse   /// @param Parameters A pointer to an array that contains itself pointers to
55379a947c2STobias Grosser   ///                   the parameter values passed for each kernel argument.
55479a947c2STobias Grosser   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
55579a947c2STobias Grosser                               Value *GridDimY, Value *BlockDimX,
55679a947c2STobias Grosser                               Value *BlockDimY, Value *BlockDimZ,
55779a947c2STobias Grosser                               Value *Parameters);
5581fb9b64dSTobias Grosser };
5591fb9b64dSTobias Grosser 
560fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
561750160e2STobias Grosser   BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(),
562750160e2STobias Grosser                                  &*Builder.GetInsertPoint(), &DT, &LI);
563750160e2STobias Grosser   NewBB->setName("polly.acc.initialize");
564750160e2STobias Grosser   Builder.SetInsertPoint(&NewBB->front());
565750160e2STobias Grosser 
566fa7b0802STobias Grosser   GPUContext = createCallInitContext();
567abed4969SSiddharth Bhat 
568abed4969SSiddharth Bhat   if (!ManagedMemory)
569fa7b0802STobias Grosser     allocateDeviceArrays();
570fa7b0802STobias Grosser }
571fa7b0802STobias Grosser 
572fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
573abed4969SSiddharth Bhat   if (!ManagedMemory)
5747287aeddSTobias Grosser     freeDeviceArrays();
575abed4969SSiddharth Bhat 
576fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
577fa7b0802STobias Grosser   IslNodeBuilder::finalize();
578fa7b0802STobias Grosser }
579fa7b0802STobias Grosser 
580fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
581abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory will directly send host pointers "
582abed4969SSiddharth Bhat                            "to the kernel. There is no need for device arrays");
583fa7b0802STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
584fa7b0802STobias Grosser 
585fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
586fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
58713c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
5887287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
5897287aeddSTobias Grosser     DevArrayName.append(Array->name);
590fa7b0802STobias Grosser 
59113c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
592aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(Array);
593aaabbbf8STobias Grosser     if (Offset)
594aaabbbf8STobias Grosser       ArraySize = Builder.CreateSub(
595aaabbbf8STobias Grosser           ArraySize,
596aaabbbf8STobias Grosser           Builder.CreateMul(Offset,
597aaabbbf8STobias Grosser                             Builder.getInt64(ScopArray->getElemSizeInBytes())));
5987287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
5997287aeddSTobias Grosser     DevArray->setName(DevArrayName);
60013c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
601fa7b0802STobias Grosser   }
602fa7b0802STobias Grosser 
603fa7b0802STobias Grosser   isl_ast_build_free(Build);
604fa7b0802STobias Grosser }
605fa7b0802STobias Grosser 
606c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX,
607c1c6a2a6STobias Grosser                                         Value *BlockDimY, Value *BlockDimZ) {
608c1c6a2a6STobias Grosser   auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations");
609c1c6a2a6STobias Grosser 
610c1c6a2a6STobias Grosser   for (auto &F : *M) {
611c1c6a2a6STobias Grosser     if (F.getCallingConv() != CallingConv::PTX_Kernel)
612c1c6a2a6STobias Grosser       continue;
613c1c6a2a6STobias Grosser 
614c1c6a2a6STobias Grosser     Value *V[] = {BlockDimX, BlockDimY, BlockDimZ};
615c1c6a2a6STobias Grosser 
616c1c6a2a6STobias Grosser     Metadata *Elements[] = {
617c1c6a2a6STobias Grosser         ValueAsMetadata::get(&F),   MDString::get(M->getContext(), "maxntidx"),
618c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"),
619c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"),
620c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[2]),
621c1c6a2a6STobias Grosser     };
622c1c6a2a6STobias Grosser     MDNode *Node = MDNode::get(M->getContext(), Elements);
623c1c6a2a6STobias Grosser     AnnotationNode->addOperand(Node);
624c1c6a2a6STobias Grosser   }
625c1c6a2a6STobias Grosser }
626c1c6a2a6STobias Grosser 
6277287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
628abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not use device arrays");
62913c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
63013c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
6317287aeddSTobias Grosser }
6327287aeddSTobias Grosser 
63357793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
63457793596STobias Grosser   const char *Name = "polly_getKernel";
63557793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
63657793596STobias Grosser   Function *F = M->getFunction(Name);
63757793596STobias Grosser 
63857793596STobias Grosser   // If F is not available, declare it.
63957793596STobias Grosser   if (!F) {
64057793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
64157793596STobias Grosser     std::vector<Type *> Args;
64257793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
64357793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
64457793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
64557793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
64657793596STobias Grosser   }
64757793596STobias Grosser 
64857793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
64957793596STobias Grosser }
65057793596STobias Grosser 
65179a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
65279a947c2STobias Grosser   const char *Name = "polly_getDevicePtr";
65379a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
65479a947c2STobias Grosser   Function *F = M->getFunction(Name);
65579a947c2STobias Grosser 
65679a947c2STobias Grosser   // If F is not available, declare it.
65779a947c2STobias Grosser   if (!F) {
65879a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
65979a947c2STobias Grosser     std::vector<Type *> Args;
66079a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
66179a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
66279a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
66379a947c2STobias Grosser   }
66479a947c2STobias Grosser 
66579a947c2STobias Grosser   return Builder.CreateCall(F, {Allocation});
66679a947c2STobias Grosser }
66779a947c2STobias Grosser 
66879a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
66979a947c2STobias Grosser                                             Value *GridDimY, Value *BlockDimX,
67079a947c2STobias Grosser                                             Value *BlockDimY, Value *BlockDimZ,
67179a947c2STobias Grosser                                             Value *Parameters) {
67279a947c2STobias Grosser   const char *Name = "polly_launchKernel";
67379a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
67479a947c2STobias Grosser   Function *F = M->getFunction(Name);
67579a947c2STobias Grosser 
67679a947c2STobias Grosser   // If F is not available, declare it.
67779a947c2STobias Grosser   if (!F) {
67879a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
67979a947c2STobias Grosser     std::vector<Type *> Args;
68079a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
68179a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
68279a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
68379a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
68479a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
68579a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
68679a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
68779a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
68879a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
68979a947c2STobias Grosser   }
69079a947c2STobias Grosser 
691ff40087aSTobias Grosser   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
69279a947c2STobias Grosser                          BlockDimZ, Parameters});
69379a947c2STobias Grosser }
69479a947c2STobias Grosser 
69557793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
69657793596STobias Grosser   const char *Name = "polly_freeKernel";
69757793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
69857793596STobias Grosser   Function *F = M->getFunction(Name);
69957793596STobias Grosser 
70057793596STobias Grosser   // If F is not available, declare it.
70157793596STobias Grosser   if (!F) {
70257793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
70357793596STobias Grosser     std::vector<Type *> Args;
70457793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
70557793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
70657793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
70757793596STobias Grosser   }
70857793596STobias Grosser 
70957793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
71057793596STobias Grosser }
71157793596STobias Grosser 
7127287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
713abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not allocate or free memory "
714abed4969SSiddharth Bhat                            "for device");
7157287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
7167287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7177287aeddSTobias Grosser   Function *F = M->getFunction(Name);
7187287aeddSTobias Grosser 
7197287aeddSTobias Grosser   // If F is not available, declare it.
7207287aeddSTobias Grosser   if (!F) {
7217287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
7227287aeddSTobias Grosser     std::vector<Type *> Args;
7237287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
7247287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
7257287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
7267287aeddSTobias Grosser   }
7277287aeddSTobias Grosser 
7287287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
7297287aeddSTobias Grosser }
7307287aeddSTobias Grosser 
731fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
732abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not allocate or free memory "
733abed4969SSiddharth Bhat                            "for device");
734fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
735fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
736fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
737fa7b0802STobias Grosser 
738fa7b0802STobias Grosser   // If F is not available, declare it.
739fa7b0802STobias Grosser   if (!F) {
740fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
741fa7b0802STobias Grosser     std::vector<Type *> Args;
742fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
743fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
744fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
745fa7b0802STobias Grosser   }
746fa7b0802STobias Grosser 
747fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
748fa7b0802STobias Grosser }
749fa7b0802STobias Grosser 
75013c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
75113c78e4dSTobias Grosser                                                     Value *DeviceData,
75213c78e4dSTobias Grosser                                                     Value *Size) {
753abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not transfer memory between "
754abed4969SSiddharth Bhat                            "device and host");
75513c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
75613c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
75713c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
75813c78e4dSTobias Grosser 
75913c78e4dSTobias Grosser   // If F is not available, declare it.
76013c78e4dSTobias Grosser   if (!F) {
76113c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
76213c78e4dSTobias Grosser     std::vector<Type *> Args;
76313c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
76413c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
76513c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
76613c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
76713c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
76813c78e4dSTobias Grosser   }
76913c78e4dSTobias Grosser 
77013c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
77113c78e4dSTobias Grosser }
77213c78e4dSTobias Grosser 
77313c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
77413c78e4dSTobias Grosser                                                     Value *HostData,
77513c78e4dSTobias Grosser                                                     Value *Size) {
776abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not transfer memory between "
777abed4969SSiddharth Bhat                            "device and host");
77813c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
77913c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
78013c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
78113c78e4dSTobias Grosser 
78213c78e4dSTobias Grosser   // If F is not available, declare it.
78313c78e4dSTobias Grosser   if (!F) {
78413c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
78513c78e4dSTobias Grosser     std::vector<Type *> Args;
78613c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
78713c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
78813c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
78913c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
79013c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
79113c78e4dSTobias Grosser   }
79213c78e4dSTobias Grosser 
79313c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
79413c78e4dSTobias Grosser }
79513c78e4dSTobias Grosser 
796abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() {
797abed4969SSiddharth Bhat   assert(ManagedMemory && "explicit synchronization is only necessary for "
798abed4969SSiddharth Bhat                           "managed memory");
799abed4969SSiddharth Bhat   const char *Name = "polly_synchronizeDevice";
800abed4969SSiddharth Bhat   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
801abed4969SSiddharth Bhat   Function *F = M->getFunction(Name);
802abed4969SSiddharth Bhat 
803abed4969SSiddharth Bhat   // If F is not available, declare it.
804abed4969SSiddharth Bhat   if (!F) {
805abed4969SSiddharth Bhat     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
806abed4969SSiddharth Bhat     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
807abed4969SSiddharth Bhat     F = Function::Create(Ty, Linkage, Name, M);
808abed4969SSiddharth Bhat   }
809abed4969SSiddharth Bhat 
810abed4969SSiddharth Bhat   Builder.CreateCall(F);
811abed4969SSiddharth Bhat }
812abed4969SSiddharth Bhat 
813fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
81417f01968SSiddharth Bhat   const char *Name;
81517f01968SSiddharth Bhat 
81617f01968SSiddharth Bhat   switch (Runtime) {
81717f01968SSiddharth Bhat   case GPURuntime::CUDA:
81817f01968SSiddharth Bhat     Name = "polly_initContextCUDA";
81917f01968SSiddharth Bhat     break;
82017f01968SSiddharth Bhat   case GPURuntime::OpenCL:
82117f01968SSiddharth Bhat     Name = "polly_initContextCL";
82217f01968SSiddharth Bhat     break;
82317f01968SSiddharth Bhat   }
82417f01968SSiddharth Bhat 
825fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
826fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
827fa7b0802STobias Grosser 
828fa7b0802STobias Grosser   // If F is not available, declare it.
829fa7b0802STobias Grosser   if (!F) {
830fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
831fa7b0802STobias Grosser     std::vector<Type *> Args;
832fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
833fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
834fa7b0802STobias Grosser   }
835fa7b0802STobias Grosser 
836fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
837fa7b0802STobias Grosser }
838fa7b0802STobias Grosser 
839fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
840fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
841fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
842fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
843fa7b0802STobias Grosser 
844fa7b0802STobias Grosser   // If F is not available, declare it.
845fa7b0802STobias Grosser   if (!F) {
846fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
847fa7b0802STobias Grosser     std::vector<Type *> Args;
848fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
849fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
850fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
851fa7b0802STobias Grosser   }
852fa7b0802STobias Grosser 
853fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
854fa7b0802STobias Grosser }
855fa7b0802STobias Grosser 
8565260c041STobias Grosser /// Check if one string is a prefix of another.
8575260c041STobias Grosser ///
8585260c041STobias Grosser /// @param String The string in which to look for the prefix.
8595260c041STobias Grosser /// @param Prefix The prefix to look for.
8605260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
8615260c041STobias Grosser   return String.find(Prefix) == 0;
8625260c041STobias Grosser }
8635260c041STobias Grosser 
86413c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
86513c78e4dSTobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
86613c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
86713c78e4dSTobias Grosser 
86813c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
86913c78e4dSTobias Grosser     auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]);
87013c78e4dSTobias Grosser     isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero);
87113c78e4dSTobias Grosser 
87213c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
87313c78e4dSTobias Grosser       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]);
87413c78e4dSTobias Grosser       isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
87513c78e4dSTobias Grosser       Res = isl_ast_expr_mul(Res, Expr);
87613c78e4dSTobias Grosser     }
87713c78e4dSTobias Grosser 
87813c78e4dSTobias Grosser     Value *NumElements = ExprBuilder.create(Res);
879b79f4d39STobias Grosser     if (NumElements->getType() != ArraySize->getType())
880b79f4d39STobias Grosser       NumElements = Builder.CreateSExt(NumElements, ArraySize->getType());
88113c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
88213c78e4dSTobias Grosser   }
88313c78e4dSTobias Grosser   isl_ast_build_free(Build);
88413c78e4dSTobias Grosser   return ArraySize;
88513c78e4dSTobias Grosser }
88613c78e4dSTobias Grosser 
887aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) {
888aaabbbf8STobias Grosser   if (gpu_array_is_scalar(Array))
889aaabbbf8STobias Grosser     return nullptr;
890aaabbbf8STobias Grosser 
891aaabbbf8STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
892aaabbbf8STobias Grosser 
893aaabbbf8STobias Grosser   isl_set *Min = isl_set_lexmin(isl_set_copy(Array->extent));
894aaabbbf8STobias Grosser 
895aaabbbf8STobias Grosser   isl_set *ZeroSet = isl_set_universe(isl_set_get_space(Min));
896aaabbbf8STobias Grosser 
897aaabbbf8STobias Grosser   for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++)
898aaabbbf8STobias Grosser     ZeroSet = isl_set_fix_si(ZeroSet, isl_dim_set, i, 0);
899aaabbbf8STobias Grosser 
900aaabbbf8STobias Grosser   if (isl_set_is_subset(Min, ZeroSet)) {
901aaabbbf8STobias Grosser     isl_set_free(Min);
902aaabbbf8STobias Grosser     isl_set_free(ZeroSet);
903aaabbbf8STobias Grosser     isl_ast_build_free(Build);
904aaabbbf8STobias Grosser     return nullptr;
905aaabbbf8STobias Grosser   }
906aaabbbf8STobias Grosser   isl_set_free(ZeroSet);
907aaabbbf8STobias Grosser 
908aaabbbf8STobias Grosser   isl_ast_expr *Result =
909aaabbbf8STobias Grosser       isl_ast_expr_from_val(isl_val_int_from_si(isl_set_get_ctx(Min), 0));
910aaabbbf8STobias Grosser 
911aaabbbf8STobias Grosser   for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) {
912aaabbbf8STobias Grosser     if (i > 0) {
913aaabbbf8STobias Grosser       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i - 1]);
914aaabbbf8STobias Grosser       isl_ast_expr *BExpr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
915aaabbbf8STobias Grosser       Result = isl_ast_expr_mul(Result, BExpr);
916aaabbbf8STobias Grosser     }
917aaabbbf8STobias Grosser     isl_pw_aff *DimMin = isl_set_dim_min(isl_set_copy(Min), i);
918aaabbbf8STobias Grosser     isl_ast_expr *MExpr = isl_ast_build_expr_from_pw_aff(Build, DimMin);
919aaabbbf8STobias Grosser     Result = isl_ast_expr_add(Result, MExpr);
920aaabbbf8STobias Grosser   }
921aaabbbf8STobias Grosser 
922aaabbbf8STobias Grosser   Value *ResultValue = ExprBuilder.create(Result);
923aaabbbf8STobias Grosser   isl_set_free(Min);
924aaabbbf8STobias Grosser   isl_ast_build_free(Build);
925aaabbbf8STobias Grosser 
926aaabbbf8STobias Grosser   return ResultValue;
927aaabbbf8STobias Grosser }
928aaabbbf8STobias Grosser 
929abed4969SSiddharth Bhat Value *GPUNodeBuilder::getOrCreateManagedDeviceArray(gpu_array_info *Array,
930abed4969SSiddharth Bhat                                                      ScopArrayInfo *ArrayInfo) {
931abed4969SSiddharth Bhat 
932abed4969SSiddharth Bhat   assert(ManagedMemory && "Only used when you wish to get a host "
933abed4969SSiddharth Bhat                           "pointer for sending data to the kernel, "
934abed4969SSiddharth Bhat                           "with managed memory");
935abed4969SSiddharth Bhat   std::map<ScopArrayInfo *, Value *>::iterator it;
936abed4969SSiddharth Bhat   if ((it = DeviceAllocations.find(ArrayInfo)) != DeviceAllocations.end()) {
937abed4969SSiddharth Bhat     return it->second;
938abed4969SSiddharth Bhat   } else {
939abed4969SSiddharth Bhat     Value *HostPtr;
940abed4969SSiddharth Bhat 
941abed4969SSiddharth Bhat     if (gpu_array_is_scalar(Array))
942abed4969SSiddharth Bhat       HostPtr = BlockGen.getOrCreateAlloca(ArrayInfo);
943abed4969SSiddharth Bhat     else
944abed4969SSiddharth Bhat       HostPtr = ArrayInfo->getBasePtr();
945abed4969SSiddharth Bhat 
946abed4969SSiddharth Bhat     Value *Offset = getArrayOffset(Array);
947abed4969SSiddharth Bhat     if (Offset) {
948abed4969SSiddharth Bhat       HostPtr = Builder.CreatePointerCast(
949abed4969SSiddharth Bhat           HostPtr, ArrayInfo->getElementType()->getPointerTo());
950abed4969SSiddharth Bhat       HostPtr = Builder.CreateGEP(HostPtr, Offset);
951abed4969SSiddharth Bhat     }
952abed4969SSiddharth Bhat 
953abed4969SSiddharth Bhat     HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
954abed4969SSiddharth Bhat     DeviceAllocations[ArrayInfo] = HostPtr;
955abed4969SSiddharth Bhat     return HostPtr;
956abed4969SSiddharth Bhat   }
957abed4969SSiddharth Bhat }
958abed4969SSiddharth Bhat 
95913c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
96013c78e4dSTobias Grosser                                         enum DataDirection Direction) {
961abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory needs no data transfers");
96213c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
96313c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
96413c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
96513c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
96613c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
96713c78e4dSTobias Grosser 
96813c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
969aaabbbf8STobias Grosser   Value *Offset = getArrayOffset(Array);
97013c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
97113c78e4dSTobias Grosser 
972b06ff457STobias Grosser   Value *HostPtr;
973b06ff457STobias Grosser 
974b06ff457STobias Grosser   if (gpu_array_is_scalar(Array))
975b06ff457STobias Grosser     HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
976b06ff457STobias Grosser   else
977b06ff457STobias Grosser     HostPtr = ScopArray->getBasePtr();
97813c78e4dSTobias Grosser 
979aaabbbf8STobias Grosser   if (Offset) {
980aaabbbf8STobias Grosser     HostPtr = Builder.CreatePointerCast(
981aaabbbf8STobias Grosser         HostPtr, ScopArray->getElementType()->getPointerTo());
982aaabbbf8STobias Grosser     HostPtr = Builder.CreateGEP(HostPtr, Offset);
983aaabbbf8STobias Grosser   }
984aaabbbf8STobias Grosser 
98513c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
98613c78e4dSTobias Grosser 
987aaabbbf8STobias Grosser   if (Offset) {
988aaabbbf8STobias Grosser     Size = Builder.CreateSub(
989ff40087aSTobias Grosser         Size, Builder.CreateMul(
990ff40087aSTobias Grosser                   Offset, Builder.getInt64(ScopArray->getElemSizeInBytes())));
991aaabbbf8STobias Grosser   }
992aaabbbf8STobias Grosser 
99313c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
99413c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
99513c78e4dSTobias Grosser   else
99613c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
99713c78e4dSTobias Grosser 
99813c78e4dSTobias Grosser   isl_id_free(Id);
99913c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
100013c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
100113c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
100213c78e4dSTobias Grosser }
100313c78e4dSTobias Grosser 
10041fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
100532837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
100632837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
100732837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
100832837fe3STobias Grosser   isl_id_free(Id);
100932837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
101032837fe3STobias Grosser 
101132837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
101232837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
101332837fe3STobias Grosser     createKernel(UserStmt);
101432837fe3STobias Grosser     isl_ast_expr_free(Expr);
101532837fe3STobias Grosser     return;
101632837fe3STobias Grosser   }
101732837fe3STobias Grosser 
101813c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
1019abed4969SSiddharth Bhat     if (!ManagedMemory)
102013c78e4dSTobias Grosser       createDataTransfer(UserStmt, HOST_TO_DEVICE);
1021abed4969SSiddharth Bhat     else
1022abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1023abed4969SSiddharth Bhat 
102432837fe3STobias Grosser     isl_ast_expr_free(Expr);
102513c78e4dSTobias Grosser     return;
102613c78e4dSTobias Grosser   }
102713c78e4dSTobias Grosser 
102813c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
1029abed4969SSiddharth Bhat     if (!ManagedMemory) {
103013c78e4dSTobias Grosser       createDataTransfer(UserStmt, DEVICE_TO_HOST);
1031abed4969SSiddharth Bhat     } else {
1032abed4969SSiddharth Bhat       createCallSynchronizeDevice();
1033abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1034abed4969SSiddharth Bhat     }
103513c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
103638fc0aedSTobias Grosser     return;
103738fc0aedSTobias Grosser   }
103838fc0aedSTobias Grosser 
10395260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
10405260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
10415260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
10425260c041STobias Grosser   isl_id_free(Anno);
10435260c041STobias Grosser 
10445260c041STobias Grosser   switch (KernelStmt->type) {
10455260c041STobias Grosser   case ppcg_kernel_domain:
1046edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
10475260c041STobias Grosser     isl_ast_node_free(UserStmt);
10485260c041STobias Grosser     return;
10495260c041STobias Grosser   case ppcg_kernel_copy:
1050b513b491STobias Grosser     createKernelCopy(KernelStmt);
10515260c041STobias Grosser     isl_ast_expr_free(Expr);
10525260c041STobias Grosser     isl_ast_node_free(UserStmt);
10535260c041STobias Grosser     return;
10545260c041STobias Grosser   case ppcg_kernel_sync:
10555260c041STobias Grosser     createKernelSync();
10565260c041STobias Grosser     isl_ast_expr_free(Expr);
10575260c041STobias Grosser     isl_ast_node_free(UserStmt);
10585260c041STobias Grosser     return;
10595260c041STobias Grosser   }
10605260c041STobias Grosser 
10615260c041STobias Grosser   isl_ast_expr_free(Expr);
10625260c041STobias Grosser   isl_ast_node_free(UserStmt);
10635260c041STobias Grosser   return;
10645260c041STobias Grosser }
1065b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
1066b513b491STobias Grosser   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
1067b513b491STobias Grosser   LocalIndex = isl_ast_expr_address_of(LocalIndex);
1068b513b491STobias Grosser   Value *LocalAddr = ExprBuilder.create(LocalIndex);
1069b513b491STobias Grosser   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
1070b513b491STobias Grosser   Index = isl_ast_expr_address_of(Index);
1071b513b491STobias Grosser   Value *GlobalAddr = ExprBuilder.create(Index);
1072b513b491STobias Grosser 
1073b513b491STobias Grosser   if (KernelStmt->u.c.read) {
1074b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read");
1075b513b491STobias Grosser     Builder.CreateStore(Load, LocalAddr);
1076b513b491STobias Grosser   } else {
1077b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write");
1078b513b491STobias Grosser     Builder.CreateStore(Load, GlobalAddr);
1079b513b491STobias Grosser   }
1080b513b491STobias Grosser }
10815260c041STobias Grosser 
1082edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
1083edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
1084edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1085edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
1086edb885cbSTobias Grosser 
1087edb885cbSTobias Grosser   LoopToScevMapT LTS;
1088edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
1089edb885cbSTobias Grosser 
1090edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
1091edb885cbSTobias Grosser 
1092edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
1093edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
1094edb885cbSTobias Grosser   else
1095a82c4b5dSTobias Grosser     RegionGen.copyStmt(*Stmt, LTS, Indexes);
1096edb885cbSTobias Grosser }
1097edb885cbSTobias Grosser 
10985260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
10995260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
110017f01968SSiddharth Bhat 
110117f01968SSiddharth Bhat   Function *Sync;
110217f01968SSiddharth Bhat 
110317f01968SSiddharth Bhat   switch (Arch) {
110417f01968SSiddharth Bhat   case GPUArch::NVPTX64:
110517f01968SSiddharth Bhat     Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
110617f01968SSiddharth Bhat     break;
110717f01968SSiddharth Bhat   }
110817f01968SSiddharth Bhat 
11095260c041STobias Grosser   Builder.CreateCall(Sync, {});
11105260c041STobias Grosser }
11115260c041STobias Grosser 
1112edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
1113edb885cbSTobias Grosser ///
1114edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
1115edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
1116edb885cbSTobias Grosser ///
1117edb885cbSTobias Grosser /// @param Node The node to collect references for.
1118edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
1119edb885cbSTobias Grosser ///
1120edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
1121edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
1122edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
1123edb885cbSTobias Grosser     return isl_bool_true;
1124edb885cbSTobias Grosser 
1125edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
1126edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
1127edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
1128edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
1129edb885cbSTobias Grosser   isl_id_free(Id);
1130edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
1131edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
1132edb885cbSTobias Grosser 
1133edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
1134edb885cbSTobias Grosser     return isl_bool_true;
1135edb885cbSTobias Grosser 
1136edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
1137edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
1138edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1139edb885cbSTobias Grosser   isl_id_free(Id);
1140edb885cbSTobias Grosser 
114100bb5a99STobias Grosser   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
1142edb885cbSTobias Grosser 
1143edb885cbSTobias Grosser   return isl_bool_true;
1144edb885cbSTobias Grosser }
1145edb885cbSTobias Grosser 
1146f291c8d5SSiddharth Bhat /// Check if F is a function that we can code-generate in a GPU kernel.
1147f291c8d5SSiddharth Bhat static bool isValidFunctionInKernel(llvm::Function *F) {
1148f291c8d5SSiddharth Bhat   assert(F && "F is an invalid pointer");
1149f291c8d5SSiddharth Bhat   // We string compare against the name of the function to allow
1150f291c8d5SSiddharth Bhat   // all variants of the intrinsic "llvm.sqrt.*"
1151f291c8d5SSiddharth Bhat   return F->isIntrinsic() && F->getName().startswith("llvm.sqrt");
1152f291c8d5SSiddharth Bhat }
1153f291c8d5SSiddharth Bhat 
1154f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value.
1155f291c8d5SSiddharth Bhat ///
1156f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along
1157f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and
1158f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not
1159f291c8d5SSiddharth Bhat /// `Function`s.
1160f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); }
1161f291c8d5SSiddharth Bhat 
1162f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`.
1163f291c8d5SSiddharth Bhat static SetVector<Function *>
1164f291c8d5SSiddharth Bhat getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues) {
1165f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1166f291c8d5SSiddharth Bhat   for (Value *It : RawSubtreeValues) {
1167f291c8d5SSiddharth Bhat     Function *F = dyn_cast<Function>(It);
1168f291c8d5SSiddharth Bhat     if (F) {
1169f291c8d5SSiddharth Bhat       assert(isValidFunctionInKernel(F) && "Code should have bailed out by "
1170f291c8d5SSiddharth Bhat                                            "this point if an invalid function "
1171f291c8d5SSiddharth Bhat                                            "were present in a kernel.");
1172f291c8d5SSiddharth Bhat       SubtreeFunctions.insert(F);
1173f291c8d5SSiddharth Bhat     }
1174f291c8d5SSiddharth Bhat   }
1175f291c8d5SSiddharth Bhat   return SubtreeFunctions;
1176f291c8d5SSiddharth Bhat }
1177f291c8d5SSiddharth Bhat 
1178f291c8d5SSiddharth Bhat std::pair<SetVector<Value *>, SetVector<Function *>>
1179f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
1180edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
1181edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
1182edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1183edb885cbSTobias Grosser   SubtreeReferences References = {
1184edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
1185edb885cbSTobias Grosser 
1186edb885cbSTobias Grosser   for (const auto &I : IDToValue)
1187edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
1188edb885cbSTobias Grosser 
1189edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
1190edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
1191edb885cbSTobias Grosser 
1192edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
1193edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
1194edb885cbSTobias Grosser 
1195edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
1196d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
1197edb885cbSTobias Grosser 
1198edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
1199edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1200edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
1201edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1202edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1203edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1204edb885cbSTobias Grosser     isl_id_free(Id);
1205edb885cbSTobias Grosser   }
1206edb885cbSTobias Grosser   isl_space_free(Space);
1207edb885cbSTobias Grosser 
1208edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
1209edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1210edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1211edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1212edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1213edb885cbSTobias Grosser     isl_id_free(Id);
1214edb885cbSTobias Grosser   }
1215edb885cbSTobias Grosser 
1216f291c8d5SSiddharth Bhat   // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions
1217f291c8d5SSiddharth Bhat   // SubtreeValues. This is important, because we should not lose any
1218f291c8d5SSiddharth Bhat   // SubtreeValues in the process of constructing the
1219f291c8d5SSiddharth Bhat   // "ValidSubtree{Values, Functions} sets. Nor should the set
1220f291c8d5SSiddharth Bhat   // ValidSubtree{Values, Functions} have any common element.
1221f291c8d5SSiddharth Bhat   auto ValidSubtreeValuesIt =
1222f291c8d5SSiddharth Bhat       make_filter_range(SubtreeValues, isValidSubtreeValue);
1223f291c8d5SSiddharth Bhat   SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(),
1224f291c8d5SSiddharth Bhat                                         ValidSubtreeValuesIt.end());
1225f291c8d5SSiddharth Bhat   SetVector<Function *> ValidSubtreeFunctions(
1226f291c8d5SSiddharth Bhat       getFunctionsFromRawSubtreeValues(SubtreeValues));
1227f291c8d5SSiddharth Bhat 
1228f291c8d5SSiddharth Bhat   return std::make_pair(ValidSubtreeValues, ValidSubtreeFunctions);
1229edb885cbSTobias Grosser }
1230edb885cbSTobias Grosser 
123174dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
123274dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
123374dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
123474dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
123574dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
123674dc3cb4STobias Grosser 
123774dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
123874dc3cb4STobias Grosser     DT.eraseNode(BB);
123974dc3cb4STobias Grosser }
124074dc3cb4STobias Grosser 
124174dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
124274dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
124374dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
124474dc3cb4STobias Grosser     if (L)
124574dc3cb4STobias Grosser       SE.forgetLoop(L);
124674dc3cb4STobias Grosser   }
124774dc3cb4STobias Grosser }
124874dc3cb4STobias Grosser 
124974dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
125074dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
125174dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
125274dc3cb4STobias Grosser     if (L)
125374dc3cb4STobias Grosser       SE.forgetLoop(L);
125474dc3cb4STobias Grosser     LI.removeBlock(&BB);
125574dc3cb4STobias Grosser   }
125674dc3cb4STobias Grosser }
125774dc3cb4STobias Grosser 
125879a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
125979a947c2STobias Grosser   std::vector<Value *> Sizes;
126079a947c2STobias Grosser   isl_ast_build *Context = isl_ast_build_from_context(S.getContext());
126179a947c2STobias Grosser 
126279a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
126379a947c2STobias Grosser     isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i);
126479a947c2STobias Grosser     isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size);
126579a947c2STobias Grosser     Value *Res = ExprBuilder.create(GridSize);
126679a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
126779a947c2STobias Grosser     Sizes.push_back(Res);
126879a947c2STobias Grosser   }
126979a947c2STobias Grosser   isl_ast_build_free(Context);
127079a947c2STobias Grosser 
127179a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
127279a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
127379a947c2STobias Grosser 
127479a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
127579a947c2STobias Grosser }
127679a947c2STobias Grosser 
127779a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
127879a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
127979a947c2STobias Grosser   std::vector<Value *> Sizes;
128079a947c2STobias Grosser 
128179a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
128279a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
128379a947c2STobias Grosser     Sizes.push_back(Res);
128479a947c2STobias Grosser   }
128579a947c2STobias Grosser 
128679a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
128779a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
128879a947c2STobias Grosser 
128979a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
129079a947c2STobias Grosser }
129179a947c2STobias Grosser 
1292a90be207SSiddharth Bhat void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters,
1293a90be207SSiddharth Bhat                                           Instruction *Param, int Index) {
1294a90be207SSiddharth Bhat   Value *Slot = Builder.CreateGEP(
1295a90be207SSiddharth Bhat       Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1296a90be207SSiddharth Bhat   Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1297a90be207SSiddharth Bhat   Builder.CreateStore(ParamTyped, Slot);
1298a90be207SSiddharth Bhat }
1299a90be207SSiddharth Bhat 
130057693272STobias Grosser Value *
130157693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
130257693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
1303a90be207SSiddharth Bhat   const int NumArgs = F->arg_size();
1304a90be207SSiddharth Bhat   std::vector<int> ArgSizes(NumArgs);
1305a90be207SSiddharth Bhat 
1306a90be207SSiddharth Bhat   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs);
130779a947c2STobias Grosser 
130879a947c2STobias Grosser   BasicBlock *EntryBlock =
130979a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
131067726b32STobias Grosser   auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace();
131179a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
131267726b32STobias Grosser   Instruction *Parameters = new AllocaInst(
131367726b32STobias Grosser       ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator());
131479a947c2STobias Grosser 
131579a947c2STobias Grosser   int Index = 0;
131679a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
131779a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
131879a947c2STobias Grosser       continue;
131979a947c2STobias Grosser 
132079a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
132179a947c2STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
132279a947c2STobias Grosser 
1323a90be207SSiddharth Bhat     ArgSizes[Index] = SAI->getElemSizeInBytes();
1324a90be207SSiddharth Bhat 
1325abed4969SSiddharth Bhat     Value *DevArray = nullptr;
1326abed4969SSiddharth Bhat     if (ManagedMemory) {
1327abed4969SSiddharth Bhat       DevArray = getOrCreateManagedDeviceArray(
1328abed4969SSiddharth Bhat           &Prog->array[i], const_cast<ScopArrayInfo *>(SAI));
1329abed4969SSiddharth Bhat     } else {
1330abed4969SSiddharth Bhat       DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
133179a947c2STobias Grosser       DevArray = createCallGetDevicePtr(DevArray);
1332abed4969SSiddharth Bhat     }
1333abed4969SSiddharth Bhat     assert(DevArray != nullptr && "Array to be offloaded to device not "
1334abed4969SSiddharth Bhat                                   "initialized");
1335aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(&Prog->array[i]);
1336aaabbbf8STobias Grosser 
1337aaabbbf8STobias Grosser     if (Offset) {
1338aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(
1339aaabbbf8STobias Grosser           DevArray, SAI->getElementType()->getPointerTo());
1340aaabbbf8STobias Grosser       DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset));
1341aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1342aaabbbf8STobias Grosser     }
1343fe74a7a1STobias Grosser     Value *Slot = Builder.CreateGEP(
1344fe74a7a1STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1345aaabbbf8STobias Grosser 
1346fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1347abed4969SSiddharth Bhat       Value *ValPtr = nullptr;
1348abed4969SSiddharth Bhat       if (ManagedMemory)
1349abed4969SSiddharth Bhat         ValPtr = DevArray;
1350abed4969SSiddharth Bhat       else
1351abed4969SSiddharth Bhat         ValPtr = BlockGen.getOrCreateAlloca(SAI);
1352abed4969SSiddharth Bhat 
1353abed4969SSiddharth Bhat       assert(ValPtr != nullptr && "ValPtr that should point to a valid object"
1354abed4969SSiddharth Bhat                                   " to be stored into Parameters");
1355fe74a7a1STobias Grosser       Value *ValPtrCast =
1356fe74a7a1STobias Grosser           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1357fe74a7a1STobias Grosser       Builder.CreateStore(ValPtrCast, Slot);
1358fe74a7a1STobias Grosser     } else {
135967726b32STobias Grosser       Instruction *Param =
136067726b32STobias Grosser           new AllocaInst(Builder.getInt8PtrTy(), AddressSpace,
136167726b32STobias Grosser                          Launch + "_param_" + std::to_string(Index),
136279a947c2STobias Grosser                          EntryBlock->getTerminator());
136379a947c2STobias Grosser       Builder.CreateStore(DevArray, Param);
136479a947c2STobias Grosser       Value *ParamTyped =
136579a947c2STobias Grosser           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
136679a947c2STobias Grosser       Builder.CreateStore(ParamTyped, Slot);
1367fe74a7a1STobias Grosser     }
136879a947c2STobias Grosser     Index++;
136979a947c2STobias Grosser   }
137079a947c2STobias Grosser 
1371a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1372a490147cSTobias Grosser 
1373a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1374a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1375a490147cSTobias Grosser     Value *Val = IDToValue[Id];
1376a490147cSTobias Grosser     isl_id_free(Id);
1377a90be207SSiddharth Bhat 
1378a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1379a90be207SSiddharth Bhat 
138067726b32STobias Grosser     Instruction *Param =
138167726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
138267726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1383a490147cSTobias Grosser                        EntryBlock->getTerminator());
1384a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
1385a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1386a490147cSTobias Grosser     Index++;
1387a490147cSTobias Grosser   }
1388a490147cSTobias Grosser 
1389d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1390d8b94bcaSTobias Grosser 
1391d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
1392d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1393d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
1394d8b94bcaSTobias Grosser     isl_id_free(Id);
1395a90be207SSiddharth Bhat 
1396a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1397a90be207SSiddharth Bhat 
139867726b32STobias Grosser     Instruction *Param =
139967726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
140067726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1401d8b94bcaSTobias Grosser                        EntryBlock->getTerminator());
1402d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
1403a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1404d8b94bcaSTobias Grosser     Index++;
1405d8b94bcaSTobias Grosser   }
1406d8b94bcaSTobias Grosser 
140757693272STobias Grosser   for (auto Val : SubtreeValues) {
1408a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1409a90be207SSiddharth Bhat 
141067726b32STobias Grosser     Instruction *Param =
141167726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
141267726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
141357693272STobias Grosser                        EntryBlock->getTerminator());
141457693272STobias Grosser     Builder.CreateStore(Val, Param);
1415a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1416a90be207SSiddharth Bhat     Index++;
1417a90be207SSiddharth Bhat   }
1418a90be207SSiddharth Bhat 
1419a90be207SSiddharth Bhat   for (int i = 0; i < NumArgs; i++) {
1420a90be207SSiddharth Bhat     Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]);
1421a90be207SSiddharth Bhat     Instruction *Param =
1422a90be207SSiddharth Bhat         new AllocaInst(Builder.getInt32Ty(), AddressSpace,
1423a90be207SSiddharth Bhat                        Launch + "_param_size_" + std::to_string(i),
1424a90be207SSiddharth Bhat                        EntryBlock->getTerminator());
1425a90be207SSiddharth Bhat     Builder.CreateStore(Val, Param);
1426a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
142757693272STobias Grosser     Index++;
142857693272STobias Grosser   }
142957693272STobias Grosser 
143079a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
143179a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
143279a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
143379a947c2STobias Grosser }
143479a947c2STobias Grosser 
1435f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions(
1436f291c8d5SSiddharth Bhat     SetVector<Function *> SubtreeFunctions) {
1437f291c8d5SSiddharth Bhat   for (auto Fn : SubtreeFunctions) {
1438f291c8d5SSiddharth Bhat     const std::string ClonedFnName = Fn->getName();
1439f291c8d5SSiddharth Bhat     Function *Clone = GPUModule->getFunction(ClonedFnName);
1440f291c8d5SSiddharth Bhat     if (!Clone)
1441f291c8d5SSiddharth Bhat       Clone =
1442f291c8d5SSiddharth Bhat           Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage,
1443f291c8d5SSiddharth Bhat                            ClonedFnName, GPUModule.get());
1444f291c8d5SSiddharth Bhat     assert(Clone && "Expected cloned function to be initialized.");
1445f291c8d5SSiddharth Bhat     assert(ValueMap.find(Fn) == ValueMap.end() &&
1446f291c8d5SSiddharth Bhat            "Fn already present in ValueMap");
1447f291c8d5SSiddharth Bhat     ValueMap[Fn] = Clone;
1448f291c8d5SSiddharth Bhat   }
1449f291c8d5SSiddharth Bhat }
145032837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
145132837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
145232837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
145332837fe3STobias Grosser   isl_id_free(Id);
145432837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
145532837fe3STobias Grosser 
1456bc653f20STobias Grosser   if (Kernel->n_grid > 1)
1457bc653f20STobias Grosser     DeepestParallel =
1458bc653f20STobias Grosser         std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set));
1459bc653f20STobias Grosser   else
1460bc653f20STobias Grosser     DeepestSequential =
1461bc653f20STobias Grosser         std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set));
1462bc653f20STobias Grosser 
1463c1c6a2a6STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1464c1c6a2a6STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1465c1c6a2a6STobias Grosser 
1466f291c8d5SSiddharth Bhat   SetVector<Value *> SubtreeValues;
1467f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1468f291c8d5SSiddharth Bhat   std::tie(SubtreeValues, SubtreeFunctions) = getReferencesInKernel(Kernel);
1469edb885cbSTobias Grosser 
147032837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
147132837fe3STobias Grosser 
147232837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1473472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1474edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
1475587f1f57STobias Grosser   BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap;
1476b06ff457STobias Grosser   ScalarMap.clear();
147732837fe3STobias Grosser 
1478edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1479edb885cbSTobias Grosser 
1480edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
1481edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
1482edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
1483edb885cbSTobias Grosser   for (const Loop *L : Loops) {
1484edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1485edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1486edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1487edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1488edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1489edb885cbSTobias Grosser     SubtreeValues.insert(V);
1490edb885cbSTobias Grosser   }
1491edb885cbSTobias Grosser 
1492f291c8d5SSiddharth Bhat   createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions);
1493f291c8d5SSiddharth Bhat   setupKernelSubtreeFunctions(SubtreeFunctions);
149432837fe3STobias Grosser 
149559ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
149659ab0705STobias Grosser 
149751dfc275STobias Grosser   finalizeKernelArguments(Kernel);
149874dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
1499c1c6a2a6STobias Grosser   addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
150074dc3cb4STobias Grosser   clearDominators(F);
150174dc3cb4STobias Grosser   clearScalarEvolution(F);
150274dc3cb4STobias Grosser   clearLoops(F);
150374dc3cb4STobias Grosser 
1504472f9654STobias Grosser   IDToValue = HostIDs;
150532837fe3STobias Grosser 
1506b06ff457STobias Grosser   ValueMap = std::move(HostValueMap);
1507b06ff457STobias Grosser   ScalarMap = std::move(HostScalarMap);
1508edb885cbSTobias Grosser   EscapeMap.clear();
1509edb885cbSTobias Grosser   IDToSAI.clear();
151074dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
151174dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
15124d5a9172STobias Grosser     S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array);
151374dc3cb4STobias Grosser   LocalArrays.clear();
1514edb885cbSTobias Grosser 
151551dfc275STobias Grosser   std::string ASMString = finalizeKernelFunction();
151651dfc275STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
151757693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
151879a947c2STobias Grosser 
151957793596STobias Grosser   std::string Name = "kernel_" + std::to_string(Kernel->id);
152057793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
152157793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
152257793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
152379a947c2STobias Grosser 
152479a947c2STobias Grosser   Value *GridDimX, *GridDimY;
152579a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
152679a947c2STobias Grosser 
152779a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
152879a947c2STobias Grosser                          BlockDimZ, Parameters);
152957793596STobias Grosser   createCallFreeKernel(GPUKernel);
1530b513b491STobias Grosser 
1531b513b491STobias Grosser   for (auto Id : KernelIds)
1532b513b491STobias Grosser     isl_id_free(Id);
1533b513b491STobias Grosser 
1534b513b491STobias Grosser   KernelIds.clear();
153532837fe3STobias Grosser }
153632837fe3STobias Grosser 
153732837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
153832837fe3STobias Grosser ///
153932837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
154032837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
1541d277fedaSSiddharth Bhat   std::string Ret = "";
154232837fe3STobias Grosser 
1543d277fedaSSiddharth Bhat   if (!is64Bit) {
1544d277fedaSSiddharth Bhat     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
1545d277fedaSSiddharth Bhat            "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1546d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1547d277fedaSSiddharth Bhat   } else {
1548d277fedaSSiddharth Bhat     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
1549d277fedaSSiddharth Bhat            "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1550d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1551d277fedaSSiddharth Bhat   }
155232837fe3STobias Grosser 
155332837fe3STobias Grosser   return Ret;
155432837fe3STobias Grosser }
155532837fe3STobias Grosser 
1556edb885cbSTobias Grosser Function *
1557edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1558edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
155932837fe3STobias Grosser   std::vector<Type *> Args;
156032837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
156132837fe3STobias Grosser 
156232837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
156332837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
156432837fe3STobias Grosser       continue;
156532837fe3STobias Grosser 
1566fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1567fe74a7a1STobias Grosser       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1568fe74a7a1STobias Grosser       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
1569fe74a7a1STobias Grosser       Args.push_back(SAI->getElementType());
1570fe74a7a1STobias Grosser     } else {
1571d277fedaSSiddharth Bhat       static const int UseGlobalMemory = 1;
1572d277fedaSSiddharth Bhat       Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory));
157332837fe3STobias Grosser     }
1574fe74a7a1STobias Grosser   }
157532837fe3STobias Grosser 
1576f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1577f6044bd0STobias Grosser 
1578f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++)
1579f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
1580f6044bd0STobias Grosser 
1581c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1582c84a1995STobias Grosser 
1583cf66ef26STobias Grosser   for (long i = 0; i < NumVars; i++) {
1584cf66ef26STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1585cf66ef26STobias Grosser     Value *Val = IDToValue[Id];
1586cf66ef26STobias Grosser     isl_id_free(Id);
1587cf66ef26STobias Grosser     Args.push_back(Val->getType());
1588cf66ef26STobias Grosser   }
1589c84a1995STobias Grosser 
1590edb885cbSTobias Grosser   for (auto *V : SubtreeValues)
1591edb885cbSTobias Grosser     Args.push_back(V->getType());
1592edb885cbSTobias Grosser 
159332837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
159432837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
159532837fe3STobias Grosser                               GPUModule.get());
159617f01968SSiddharth Bhat 
159717f01968SSiddharth Bhat   switch (Arch) {
159817f01968SSiddharth Bhat   case GPUArch::NVPTX64:
159932837fe3STobias Grosser     FN->setCallingConv(CallingConv::PTX_Kernel);
160017f01968SSiddharth Bhat     break;
160117f01968SSiddharth Bhat   }
160232837fe3STobias Grosser 
160332837fe3STobias Grosser   auto Arg = FN->arg_begin();
160432837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
160532837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
160632837fe3STobias Grosser       continue;
160732837fe3STobias Grosser 
1608edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
1609edb885cbSTobias Grosser 
1610edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1611edb885cbSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1612edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
1613edb885cbSTobias Grosser     Value *Val = &*Arg;
1614edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1615edb885cbSTobias Grosser     isl_ast_build *Build =
1616edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
1617f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1618edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1619edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
1620edb885cbSTobias Grosser           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
1621edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
1622edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
1623edb885cbSTobias Grosser     }
1624edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
16254d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array);
162674dc3cb4STobias Grosser     LocalArrays.push_back(Val);
1627edb885cbSTobias Grosser 
1628edb885cbSTobias Grosser     isl_ast_build_free(Build);
1629b513b491STobias Grosser     KernelIds.push_back(Id);
1630edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
163132837fe3STobias Grosser     Arg++;
163232837fe3STobias Grosser   }
163332837fe3STobias Grosser 
1634f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1635f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1636f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
1637f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
1638f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1639f6044bd0STobias Grosser     Arg++;
1640f6044bd0STobias Grosser   }
1641f6044bd0STobias Grosser 
1642c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
1643c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1644c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
164512453403STobias Grosser     Value *Val = IDToValue[Id];
164612453403STobias Grosser     ValueMap[Val] = &*Arg;
1647c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
1648c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1649c84a1995STobias Grosser     Arg++;
1650c84a1995STobias Grosser   }
1651c84a1995STobias Grosser 
1652edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
1653edb885cbSTobias Grosser     Arg->setName(V->getName());
1654edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
1655edb885cbSTobias Grosser     Arg++;
1656edb885cbSTobias Grosser   }
1657edb885cbSTobias Grosser 
165832837fe3STobias Grosser   return FN;
165932837fe3STobias Grosser }
166032837fe3STobias Grosser 
1661472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
166217f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsBID[2];
166317f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsTID[3];
1664472f9654STobias Grosser 
166517f01968SSiddharth Bhat   switch (Arch) {
166617f01968SSiddharth Bhat   case GPUArch::NVPTX64:
166717f01968SSiddharth Bhat     IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x;
166817f01968SSiddharth Bhat     IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y;
166917f01968SSiddharth Bhat 
167017f01968SSiddharth Bhat     IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x;
167117f01968SSiddharth Bhat     IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y;
167217f01968SSiddharth Bhat     IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z;
167317f01968SSiddharth Bhat     break;
167417f01968SSiddharth Bhat   }
1675472f9654STobias Grosser 
1676472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1677472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
1678472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1679472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1680472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1681472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1682472f9654STobias Grosser     IDToValue[Id] = Val;
1683472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1684472f9654STobias Grosser   };
1685472f9654STobias Grosser 
1686472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
1687472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1688472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
1689472f9654STobias Grosser   }
1690472f9654STobias Grosser 
1691472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
1692472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1693472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
1694472f9654STobias Grosser   }
1695472f9654STobias Grosser }
1696472f9654STobias Grosser 
169700bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
169800bb5a99STobias Grosser   auto Arg = FN->arg_begin();
169900bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
170000bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
170100bb5a99STobias Grosser       continue;
170200bb5a99STobias Grosser 
170300bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
170400bb5a99STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
170500bb5a99STobias Grosser     isl_id_free(Id);
170600bb5a99STobias Grosser 
170700bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
170800bb5a99STobias Grosser       Arg++;
170900bb5a99STobias Grosser       continue;
171000bb5a99STobias Grosser     }
171100bb5a99STobias Grosser 
1712fe74a7a1STobias Grosser     Value *Val = &*Arg;
1713fe74a7a1STobias Grosser 
1714fe74a7a1STobias Grosser     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
171500bb5a99STobias Grosser       Type *TypePtr = SAI->getElementType()->getPointerTo();
1716fe74a7a1STobias Grosser       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
1717fe74a7a1STobias Grosser       Val = Builder.CreateLoad(TypedArgPtr);
1718fe74a7a1STobias Grosser     }
1719fe74a7a1STobias Grosser 
1720fe74a7a1STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
172100bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
172200bb5a99STobias Grosser 
172300bb5a99STobias Grosser     Arg++;
172400bb5a99STobias Grosser   }
172500bb5a99STobias Grosser }
172600bb5a99STobias Grosser 
172751dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) {
172851dfc275STobias Grosser   auto *FN = Builder.GetInsertBlock()->getParent();
172951dfc275STobias Grosser   auto Arg = FN->arg_begin();
173051dfc275STobias Grosser 
173151dfc275STobias Grosser   bool StoredScalar = false;
173251dfc275STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
173351dfc275STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
173451dfc275STobias Grosser       continue;
173551dfc275STobias Grosser 
173651dfc275STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
173751dfc275STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
173851dfc275STobias Grosser     isl_id_free(Id);
173951dfc275STobias Grosser 
174051dfc275STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
174151dfc275STobias Grosser       Arg++;
174251dfc275STobias Grosser       continue;
174351dfc275STobias Grosser     }
174451dfc275STobias Grosser 
174551dfc275STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
174651dfc275STobias Grosser       Arg++;
174751dfc275STobias Grosser       continue;
174851dfc275STobias Grosser     }
174951dfc275STobias Grosser 
175051dfc275STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
175151dfc275STobias Grosser     Value *ArgPtr = &*Arg;
175251dfc275STobias Grosser     Type *TypePtr = SAI->getElementType()->getPointerTo();
175351dfc275STobias Grosser     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
175451dfc275STobias Grosser     Value *Val = Builder.CreateLoad(Alloca);
175551dfc275STobias Grosser     Builder.CreateStore(Val, TypedArgPtr);
175651dfc275STobias Grosser     StoredScalar = true;
175751dfc275STobias Grosser 
175851dfc275STobias Grosser     Arg++;
175951dfc275STobias Grosser   }
176051dfc275STobias Grosser 
176151dfc275STobias Grosser   if (StoredScalar)
176251dfc275STobias Grosser     /// In case more than one thread contains scalar stores, the generated
176351dfc275STobias Grosser     /// code might be incorrect, if we only store at the end of the kernel.
176451dfc275STobias Grosser     /// To support this case we need to store these scalars back at each
176551dfc275STobias Grosser     /// memory store or at least before each kernel barrier.
176651dfc275STobias Grosser     if (Kernel->n_block != 0 || Kernel->n_grid != 0)
176751dfc275STobias Grosser       BuildSuccessful = 0;
176851dfc275STobias Grosser }
176951dfc275STobias Grosser 
1770b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
1771b513b491STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1772b513b491STobias Grosser 
1773b513b491STobias Grosser   for (int i = 0; i < Kernel->n_var; ++i) {
1774b513b491STobias Grosser     struct ppcg_kernel_var &Var = Kernel->var[i];
1775b513b491STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
1776b513b491STobias Grosser     Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType();
1777b513b491STobias Grosser 
1778f919d8b3STobias Grosser     Type *ArrayTy = EleTy;
1779b513b491STobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1780b513b491STobias Grosser 
1781f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1782928d7573STobias Grosser     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
1783b513b491STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1784f919d8b3STobias Grosser       long Bound = isl_val_get_num_si(Val);
1785b513b491STobias Grosser       isl_val_free(Val);
1786b513b491STobias Grosser       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
1787928d7573STobias Grosser     }
1788928d7573STobias Grosser 
1789928d7573STobias Grosser     for (int j = Var.array->n_index - 1; j >= 0; --j) {
1790928d7573STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1791928d7573STobias Grosser       long Bound = isl_val_get_num_si(Val);
1792928d7573STobias Grosser       isl_val_free(Val);
1793b513b491STobias Grosser       ArrayTy = ArrayType::get(ArrayTy, Bound);
1794b513b491STobias Grosser     }
1795b513b491STobias Grosser 
1796130ca30fSTobias Grosser     const ScopArrayInfo *SAI;
1797130ca30fSTobias Grosser     Value *Allocation;
1798130ca30fSTobias Grosser     if (Var.type == ppcg_access_shared) {
1799130ca30fSTobias Grosser       auto GlobalVar = new GlobalVariable(
1800130ca30fSTobias Grosser           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
1801130ca30fSTobias Grosser           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
1802130ca30fSTobias Grosser       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
1803f919d8b3STobias Grosser       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
1804f919d8b3STobias Grosser 
1805130ca30fSTobias Grosser       Allocation = GlobalVar;
1806130ca30fSTobias Grosser     } else if (Var.type == ppcg_access_private) {
1807130ca30fSTobias Grosser       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
1808130ca30fSTobias Grosser     } else {
1809130ca30fSTobias Grosser       llvm_unreachable("unknown variable type");
1810130ca30fSTobias Grosser     }
18114d5a9172STobias Grosser     SAI =
18124d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array);
1813b513b491STobias Grosser     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
1814130ca30fSTobias Grosser     IDToValue[Id] = Allocation;
1815130ca30fSTobias Grosser     LocalArrays.push_back(Allocation);
1816b513b491STobias Grosser     KernelIds.push_back(Id);
1817b513b491STobias Grosser     IDToSAI[Id] = SAI;
1818b513b491STobias Grosser   }
1819b513b491STobias Grosser }
1820b513b491STobias Grosser 
1821f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction(
1822f291c8d5SSiddharth Bhat     ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues,
1823f291c8d5SSiddharth Bhat     SetVector<Function *> &SubtreeFunctions) {
182432837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
182532837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
182617f01968SSiddharth Bhat 
182717f01968SSiddharth Bhat   switch (Arch) {
182817f01968SSiddharth Bhat   case GPUArch::NVPTX64:
182917f01968SSiddharth Bhat     if (Runtime == GPURuntime::CUDA)
183032837fe3STobias Grosser       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
183117f01968SSiddharth Bhat     else if (Runtime == GPURuntime::OpenCL)
183217f01968SSiddharth Bhat       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl"));
183332837fe3STobias Grosser     GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
183417f01968SSiddharth Bhat     break;
183517f01968SSiddharth Bhat   }
183632837fe3STobias Grosser 
1837edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
183832837fe3STobias Grosser 
183959ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
184032837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
184132837fe3STobias Grosser 
184259ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
184359ab0705STobias Grosser 
184432837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
184532837fe3STobias Grosser   Builder.CreateRetVoid();
184632837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
1847472f9654STobias Grosser 
1848629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
1849629109b6STobias Grosser 
185000bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
1851b513b491STobias Grosser   createKernelVariables(Kernel, FN);
1852472f9654STobias Grosser   insertKernelIntrinsics(Kernel);
185332837fe3STobias Grosser }
185432837fe3STobias Grosser 
185574dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
185617f01968SSiddharth Bhat   llvm::Triple GPUTriple;
185717f01968SSiddharth Bhat 
185817f01968SSiddharth Bhat   switch (Arch) {
185917f01968SSiddharth Bhat   case GPUArch::NVPTX64:
186017f01968SSiddharth Bhat     switch (Runtime) {
186117f01968SSiddharth Bhat     case GPURuntime::CUDA:
186217f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda"));
186317f01968SSiddharth Bhat       break;
186417f01968SSiddharth Bhat     case GPURuntime::OpenCL:
186517f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl"));
186617f01968SSiddharth Bhat       break;
186717f01968SSiddharth Bhat     }
186817f01968SSiddharth Bhat     break;
186917f01968SSiddharth Bhat   }
187017f01968SSiddharth Bhat 
187174dc3cb4STobias Grosser   std::string ErrMsg;
187274dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
187374dc3cb4STobias Grosser 
187474dc3cb4STobias Grosser   if (!GPUTarget) {
187574dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
187674dc3cb4STobias Grosser     return "";
187774dc3cb4STobias Grosser   }
187874dc3cb4STobias Grosser 
187974dc3cb4STobias Grosser   TargetOptions Options;
188074dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
188117f01968SSiddharth Bhat 
188217f01968SSiddharth Bhat   std::string subtarget;
188317f01968SSiddharth Bhat 
188417f01968SSiddharth Bhat   switch (Arch) {
188517f01968SSiddharth Bhat   case GPUArch::NVPTX64:
188617f01968SSiddharth Bhat     subtarget = CudaVersion;
188717f01968SSiddharth Bhat     break;
188817f01968SSiddharth Bhat   }
188917f01968SSiddharth Bhat 
189017f01968SSiddharth Bhat   std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine(
189117f01968SSiddharth Bhat       GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>()));
189274dc3cb4STobias Grosser 
189374dc3cb4STobias Grosser   SmallString<0> ASMString;
189474dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
189574dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
189674dc3cb4STobias Grosser 
189774dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
189874dc3cb4STobias Grosser 
189974dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
190074dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
190174dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
190274dc3cb4STobias Grosser     return "";
190374dc3cb4STobias Grosser   }
190474dc3cb4STobias Grosser 
190574dc3cb4STobias Grosser   PM.run(*GPUModule);
190674dc3cb4STobias Grosser 
190774dc3cb4STobias Grosser   return ASMStream.str();
190874dc3cb4STobias Grosser }
190974dc3cb4STobias Grosser 
191057793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
191165d7f72fSSiddharth Bhat 
19125857b701STobias Grosser   if (verifyModule(*GPUModule)) {
191365d7f72fSSiddharth Bhat     DEBUG(dbgs() << "verifyModule failed on module:\n";
191465d7f72fSSiddharth Bhat           GPUModule->print(dbgs(), nullptr); dbgs() << "\n";);
191565d7f72fSSiddharth Bhat 
191665d7f72fSSiddharth Bhat     if (FailOnVerifyModuleFailure)
191765d7f72fSSiddharth Bhat       llvm_unreachable("VerifyModule failed.");
191865d7f72fSSiddharth Bhat 
19195857b701STobias Grosser     BuildSuccessful = false;
19205857b701STobias Grosser     return "";
19215857b701STobias Grosser   }
192232837fe3STobias Grosser 
192332837fe3STobias Grosser   if (DumpKernelIR)
192432837fe3STobias Grosser     outs() << *GPUModule << "\n";
192532837fe3STobias Grosser 
19269a18d559STobias Grosser   // Optimize module.
19279a18d559STobias Grosser   llvm::legacy::PassManager OptPasses;
19289a18d559STobias Grosser   PassManagerBuilder PassBuilder;
19299a18d559STobias Grosser   PassBuilder.OptLevel = 3;
19309a18d559STobias Grosser   PassBuilder.SizeLevel = 0;
19319a18d559STobias Grosser   PassBuilder.populateModulePassManager(OptPasses);
19329a18d559STobias Grosser   OptPasses.run(*GPUModule);
19339a18d559STobias Grosser 
193474dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
193574dc3cb4STobias Grosser 
193674dc3cb4STobias Grosser   if (DumpKernelASM)
193774dc3cb4STobias Grosser     outs() << Assembly << "\n";
193874dc3cb4STobias Grosser 
193932837fe3STobias Grosser   GPUModule.release();
1940472f9654STobias Grosser   KernelIDs.clear();
194157793596STobias Grosser 
194257793596STobias Grosser   return Assembly;
194332837fe3STobias Grosser }
194432837fe3STobias Grosser 
19459dfe4e7cSTobias Grosser namespace {
19469dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
19479dfe4e7cSTobias Grosser public:
19489dfe4e7cSTobias Grosser   static char ID;
19499dfe4e7cSTobias Grosser 
195017f01968SSiddharth Bhat   GPURuntime Runtime = GPURuntime::CUDA;
195117f01968SSiddharth Bhat 
195217f01968SSiddharth Bhat   GPUArch Architecture = GPUArch::NVPTX64;
195317f01968SSiddharth Bhat 
1954e938517eSTobias Grosser   /// The scop that is currently processed.
1955e938517eSTobias Grosser   Scop *S;
1956e938517eSTobias Grosser 
195738fc0aedSTobias Grosser   LoopInfo *LI;
195838fc0aedSTobias Grosser   DominatorTree *DT;
195938fc0aedSTobias Grosser   ScalarEvolution *SE;
196038fc0aedSTobias Grosser   const DataLayout *DL;
196138fc0aedSTobias Grosser   RegionInfo *RI;
196238fc0aedSTobias Grosser 
19639dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
19649dfe4e7cSTobias Grosser 
1965e938517eSTobias Grosser   /// Construct compilation options for PPCG.
1966e938517eSTobias Grosser   ///
1967e938517eSTobias Grosser   /// @returns The compilation options.
1968e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
1969e938517eSTobias Grosser     auto DebugOptions =
1970e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
1971e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
1972e938517eSTobias Grosser 
1973e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
1974e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
1975e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
1976e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
19778950ceadSTobias Grosser     DebugOptions->verbose = false;
1978e938517eSTobias Grosser 
1979e938517eSTobias Grosser     Options->debug = DebugOptions;
1980e938517eSTobias Grosser 
1981e938517eSTobias Grosser     Options->reschedule = true;
1982e938517eSTobias Grosser     Options->scale_tile_loops = false;
1983e938517eSTobias Grosser     Options->wrap = false;
1984e938517eSTobias Grosser 
1985e938517eSTobias Grosser     Options->non_negative_parameters = false;
1986e938517eSTobias Grosser     Options->ctx = nullptr;
1987e938517eSTobias Grosser     Options->sizes = nullptr;
1988e938517eSTobias Grosser 
19894eaedde5STobias Grosser     Options->tile_size = 32;
19904eaedde5STobias Grosser 
1991130ca30fSTobias Grosser     Options->use_private_memory = PrivateMemory;
1992b513b491STobias Grosser     Options->use_shared_memory = SharedMemory;
1993b513b491STobias Grosser     Options->max_shared_memory = 48 * 1024;
1994e938517eSTobias Grosser 
1995e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
1996e938517eSTobias Grosser     Options->openmp = false;
1997e938517eSTobias Grosser     Options->linearize_device_arrays = true;
1998e938517eSTobias Grosser     Options->live_range_reordering = false;
1999e938517eSTobias Grosser 
2000e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
2001e938517eSTobias Grosser     Options->opencl_use_gpu = false;
2002e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
2003e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
2004e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
2005e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
2006e938517eSTobias Grosser 
2007e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
2008e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
2009e938517eSTobias Grosser 
2010e938517eSTobias Grosser     return Options;
2011e938517eSTobias Grosser   }
2012e938517eSTobias Grosser 
2013f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
2014f384594dSTobias Grosser   ///
2015f384594dSTobias Grosser   /// Instead of a normal access of the form:
2016f384594dSTobias Grosser   ///
2017f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
2018f384594dSTobias Grosser   ///
2019f384594dSTobias Grosser   /// a tagged access has the form
2020f384594dSTobias Grosser   ///
2021f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
2022f384594dSTobias Grosser   ///
2023f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
2024f384594dSTobias Grosser   /// triggered the access.
2025f384594dSTobias Grosser   ///
2026f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
2027f384594dSTobias Grosser   ///
2028f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
2029f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
2030f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
2031f384594dSTobias Grosser 
2032f384594dSTobias Grosser     for (auto &Stmt : *S)
2033f384594dSTobias Grosser       for (auto &Acc : Stmt)
2034f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
2035f384594dSTobias Grosser           isl_map *Relation = Acc->getAccessRelation();
2036f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
2037f384594dSTobias Grosser 
2038f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
2039f384594dSTobias Grosser           Space = isl_space_range(Space);
2040f384594dSTobias Grosser           Space = isl_space_from_range(Space);
20416293ba69STobias Grosser           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
2042f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
2043f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
2044f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
2045f384594dSTobias Grosser         }
2046f384594dSTobias Grosser 
2047f384594dSTobias Grosser     return Accesses;
2048f384594dSTobias Grosser   }
2049f384594dSTobias Grosser 
2050f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
2051f384594dSTobias Grosser   ///
2052f384594dSTobias Grosser   /// @see getTaggedAccesses
2053f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
2054f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
2055f384594dSTobias Grosser   }
2056f384594dSTobias Grosser 
2057f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
2058f384594dSTobias Grosser   ///
2059f384594dSTobias Grosser   /// @see getTaggedAccesses
2060f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
2061f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
2062f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
2063f384594dSTobias Grosser   }
2064f384594dSTobias Grosser 
2065f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
2066f384594dSTobias Grosser   ///
2067f384594dSTobias Grosser   /// @see getTaggedAccesses
2068f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
2069f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
2070f384594dSTobias Grosser   }
2071f384594dSTobias Grosser 
2072aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
2073aef5196fSTobias Grosser   ///
2074aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
2075aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
2076aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
2077aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
2078aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
2079aef5196fSTobias Grosser   /// the data format that ppcg expects.
2080aef5196fSTobias Grosser   ///
2081aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
2082aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
2083aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
2084bd81a7eeSTobias Grosser         S->getIslCtx(),
2085bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
2086aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
2087aef5196fSTobias Grosser     auto *Space = S->getParamSpace();
2088aef5196fSTobias Grosser 
2089aef5196fSTobias Grosser     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
2090aef5196fSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
2091aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2092aef5196fSTobias Grosser     }
2093aef5196fSTobias Grosser 
2094aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
2095d7754a12SRoman Gareev       auto Id = Array->getBasePtrId();
2096aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2097aef5196fSTobias Grosser     }
2098aef5196fSTobias Grosser 
2099aef5196fSTobias Grosser     isl_space_free(Space);
2100aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
2101aef5196fSTobias Grosser 
2102aef5196fSTobias Grosser     return Names;
2103aef5196fSTobias Grosser   }
2104aef5196fSTobias Grosser 
2105e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
2106e938517eSTobias Grosser   ///
2107f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
2108f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
2109f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
2110f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
2111e938517eSTobias Grosser   ///
2112e938517eSTobias Grosser   /// @returns A new ppcg scop.
2113e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
2114e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
2115e938517eSTobias Grosser 
2116e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
2117e938517eSTobias Grosser 
2118e938517eSTobias Grosser     PPCGScop->start = 0;
2119e938517eSTobias Grosser     PPCGScop->end = 0;
2120e938517eSTobias Grosser 
2121f384594dSTobias Grosser     PPCGScop->context = S->getContext();
2122f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
2123e938517eSTobias Grosser     PPCGScop->call = nullptr;
2124f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
2125f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
2126e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
2127f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
2128f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
2129f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
2130f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
2131e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
2132f384594dSTobias Grosser     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
2133e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
2134e938517eSTobias Grosser 
2135e938517eSTobias Grosser     PPCGScop->independence = nullptr;
2136e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
2137e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
2138e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
2139e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
2140e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
2141e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
2142e938517eSTobias Grosser 
2143f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
2144aef5196fSTobias Grosser     PPCGScop->names = getNames();
2145e938517eSTobias Grosser 
2146e938517eSTobias Grosser     PPCGScop->pet = nullptr;
2147e938517eSTobias Grosser 
2148f384594dSTobias Grosser     compute_tagger(PPCGScop);
2149f384594dSTobias Grosser     compute_dependences(PPCGScop);
2150f384594dSTobias Grosser 
2151e938517eSTobias Grosser     return PPCGScop;
2152e938517eSTobias Grosser   }
2153e938517eSTobias Grosser 
2154a6d48f59SMichael Kruse   /// Collect the array accesses in a statement.
215560f63b49STobias Grosser   ///
215660f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
215760f63b49STobias Grosser   ///
215860f63b49STobias Grosser   /// @returns A list of array accesses.
215960f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
216060f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
216160f63b49STobias Grosser 
216260f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
216360f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
216460f63b49STobias Grosser       Access->read = Acc->isRead();
216560f63b49STobias Grosser       Access->write = Acc->isWrite();
216660f63b49STobias Grosser       Access->access = Acc->getAccessRelation();
216760f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
216860f63b49STobias Grosser       Space = isl_space_range(Space);
216960f63b49STobias Grosser       Space = isl_space_from_range(Space);
21706293ba69STobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
217160f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
217260f63b49STobias Grosser       Access->tagged_access =
217360f63b49STobias Grosser           isl_map_domain_product(Acc->getAccessRelation(), Universe);
2174b513b491STobias Grosser       Access->exact_write = !Acc->isMayWrite();
217560f63b49STobias Grosser       Access->ref_id = Acc->getId();
217660f63b49STobias Grosser       Access->next = Accesses;
2177b513b491STobias Grosser       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
217860f63b49STobias Grosser       Accesses = Access;
217960f63b49STobias Grosser     }
218060f63b49STobias Grosser 
218160f63b49STobias Grosser     return Accesses;
218260f63b49STobias Grosser   }
218360f63b49STobias Grosser 
218469b46751STobias Grosser   /// Collect the list of GPU statements.
218569b46751STobias Grosser   ///
218669b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
218769b46751STobias Grosser   /// as well as a list with all memory accesses.
218869b46751STobias Grosser   ///
218969b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
219069b46751STobias Grosser   ///
219169b46751STobias Grosser   /// @returns A linked-list of statements.
219269b46751STobias Grosser   gpu_stmt *getStatements() {
219369b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
219469b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
219569b46751STobias Grosser 
219669b46751STobias Grosser     int i = 0;
219769b46751STobias Grosser     for (auto &Stmt : *S) {
219869b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
219969b46751STobias Grosser 
220069b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
220169b46751STobias Grosser 
220269b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
220369b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
220460f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
220569b46751STobias Grosser       i++;
220669b46751STobias Grosser     }
220769b46751STobias Grosser 
220869b46751STobias Grosser     return Stmts;
220969b46751STobias Grosser   }
221069b46751STobias Grosser 
221160f63b49STobias Grosser   /// Derive the extent of an array.
221260f63b49STobias Grosser   ///
2213d58acf86STobias Grosser   /// The extent of an array is the set of elements that are within the
2214d58acf86STobias Grosser   /// accessed array. For the inner dimensions, the extent constraints are
2215d58acf86STobias Grosser   /// 0 and the size of the corresponding array dimension. For the first
2216d58acf86STobias Grosser   /// (outermost) dimension, the extent constraints are the minimal and maximal
2217d58acf86STobias Grosser   /// subscript value for the first dimension.
221860f63b49STobias Grosser   ///
221960f63b49STobias Grosser   /// @param Array The array to derive the extent for.
222060f63b49STobias Grosser   ///
222160f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
222260f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
2223d58acf86STobias Grosser     unsigned NumDims = Array->getNumberOfDimensions();
222460f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
222560f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
2226d58acf86STobias Grosser     Accesses = isl_union_map_detect_equalities(Accesses);
222760f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
2228d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2229d58acf86STobias Grosser     AccessUSet = isl_union_set_detect_equalities(AccessUSet);
2230d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2231d58acf86STobias Grosser 
2232d58acf86STobias Grosser     if (isl_union_set_is_empty(AccessUSet)) {
2233d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
2234d58acf86STobias Grosser       return isl_set_empty(Array->getSpace());
2235d58acf86STobias Grosser     }
2236d58acf86STobias Grosser 
2237d58acf86STobias Grosser     if (Array->getNumberOfDimensions() == 0) {
2238d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
2239d58acf86STobias Grosser       return isl_set_universe(Array->getSpace());
2240d58acf86STobias Grosser     }
2241d58acf86STobias Grosser 
224260f63b49STobias Grosser     isl_set *AccessSet =
224360f63b49STobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace());
224460f63b49STobias Grosser 
2245d58acf86STobias Grosser     isl_union_set_free(AccessUSet);
2246d58acf86STobias Grosser     isl_local_space *LS = isl_local_space_from_space(Array->getSpace());
2247d58acf86STobias Grosser 
2248d58acf86STobias Grosser     isl_pw_aff *Val =
2249d58acf86STobias Grosser         isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0));
2250d58acf86STobias Grosser 
2251d58acf86STobias Grosser     isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0);
2252d58acf86STobias Grosser     isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0);
2253d58acf86STobias Grosser     OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in,
2254d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
2255d58acf86STobias Grosser     OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in,
2256d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
2257d58acf86STobias Grosser     OuterMin =
2258d58acf86STobias Grosser         isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, Array->getBasePtrId());
2259d58acf86STobias Grosser     OuterMax =
2260d58acf86STobias Grosser         isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, Array->getBasePtrId());
2261d58acf86STobias Grosser 
2262d58acf86STobias Grosser     isl_set *Extent = isl_set_universe(Array->getSpace());
2263d58acf86STobias Grosser 
2264d58acf86STobias Grosser     Extent = isl_set_intersect(
2265d58acf86STobias Grosser         Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val)));
2266d58acf86STobias Grosser     Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val));
2267d58acf86STobias Grosser 
2268d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i)
2269d58acf86STobias Grosser       Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0);
2270d58acf86STobias Grosser 
2271b7f68b8cSSiddharth Bhat     for (unsigned i = 0; i < NumDims; ++i) {
2272d58acf86STobias Grosser       isl_pw_aff *PwAff =
2273d58acf86STobias Grosser           const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i));
2274b7f68b8cSSiddharth Bhat 
2275b7f68b8cSSiddharth Bhat       // isl_pw_aff can be NULL for zero dimension. Only in the case of a
2276b7f68b8cSSiddharth Bhat       // Fortran array will we have a legitimate dimension.
2277b7f68b8cSSiddharth Bhat       if (!PwAff) {
2278b7f68b8cSSiddharth Bhat         assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension");
2279b7f68b8cSSiddharth Bhat         continue;
2280b7f68b8cSSiddharth Bhat       }
2281b7f68b8cSSiddharth Bhat 
2282d58acf86STobias Grosser       isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain(
2283d58acf86STobias Grosser           isl_local_space_from_space(Array->getSpace()), isl_dim_set, i));
2284d58acf86STobias Grosser       PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in,
2285d58acf86STobias Grosser                                   isl_pw_aff_dim(Val, isl_dim_in));
2286d58acf86STobias Grosser       PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in,
2287d58acf86STobias Grosser                                       isl_pw_aff_get_tuple_id(Val, isl_dim_in));
2288d58acf86STobias Grosser       auto *Set = isl_pw_aff_gt_set(PwAff, Val);
2289d58acf86STobias Grosser       Extent = isl_set_intersect(Set, Extent);
2290d58acf86STobias Grosser     }
2291d58acf86STobias Grosser 
2292d58acf86STobias Grosser     return Extent;
229360f63b49STobias Grosser   }
229460f63b49STobias Grosser 
229560f63b49STobias Grosser   /// Derive the bounds of an array.
229660f63b49STobias Grosser   ///
229760f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
229860f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
229960f63b49STobias Grosser   /// ScopArrayInfo.
230060f63b49STobias Grosser   ///
230160f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
230260f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
230360f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
230460f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
230502293ed7STobias Grosser       if (isl_set_is_empty(PPCGArray.extent)) {
230602293ed7STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
230702293ed7STobias Grosser         isl_local_space *LS = isl_local_space_from_space(
230802293ed7STobias Grosser             isl_space_params(isl_set_get_space(Dom)));
230902293ed7STobias Grosser         isl_set_free(Dom);
231002293ed7STobias Grosser         isl_aff *Zero = isl_aff_zero_on_domain(LS);
231102293ed7STobias Grosser         PPCGArray.bound[0] = isl_pw_aff_from_aff(Zero);
231202293ed7STobias Grosser       } else {
231360f63b49STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
231460f63b49STobias Grosser         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
231560f63b49STobias Grosser         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
231660f63b49STobias Grosser         isl_set_free(Dom);
231760f63b49STobias Grosser         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
231802293ed7STobias Grosser         isl_local_space *LS =
231902293ed7STobias Grosser             isl_local_space_from_space(isl_set_get_space(Dom));
232060f63b49STobias Grosser         isl_aff *One = isl_aff_zero_on_domain(LS);
232160f63b49STobias Grosser         One = isl_aff_add_constant_si(One, 1);
232260f63b49STobias Grosser         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
232360f63b49STobias Grosser         Bound = isl_pw_aff_gist(Bound, S->getContext());
232460f63b49STobias Grosser         PPCGArray.bound[0] = Bound;
232560f63b49STobias Grosser       }
232602293ed7STobias Grosser     }
232760f63b49STobias Grosser 
232860f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
232960f63b49STobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
233060f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
233160f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
233260f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
233360f63b49STobias Grosser       PPCGArray.bound[i] = Bound;
233460f63b49STobias Grosser     }
233560f63b49STobias Grosser   }
233660f63b49STobias Grosser 
233760f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
233860f63b49STobias Grosser   ///
233960f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
234060f63b49STobias Grosser   void createArrays(gpu_prog *PPCGProg) {
234160f63b49STobias Grosser     int i = 0;
2342d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
234360f63b49STobias Grosser       std::string TypeName;
234460f63b49STobias Grosser       raw_string_ostream OS(TypeName);
234560f63b49STobias Grosser 
234660f63b49STobias Grosser       OS << *Array->getElementType();
234760f63b49STobias Grosser       TypeName = OS.str();
234860f63b49STobias Grosser 
234960f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
235060f63b49STobias Grosser 
235160f63b49STobias Grosser       PPCGArray.space = Array->getSpace();
235260f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
235360f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
235460f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
235560f63b49STobias Grosser       PPCGArray.extent = nullptr;
235660f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
235760f63b49STobias Grosser       PPCGArray.bound =
235860f63b49STobias Grosser           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
235960f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
236060f63b49STobias Grosser       PPCGArray.n_ref = 0;
236160f63b49STobias Grosser       PPCGArray.refs = nullptr;
236260f63b49STobias Grosser       PPCGArray.accessed = true;
2363fe74a7a1STobias Grosser       PPCGArray.read_only_scalar =
2364fe74a7a1STobias Grosser           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
236560f63b49STobias Grosser       PPCGArray.has_compound_element = false;
236660f63b49STobias Grosser       PPCGArray.local = false;
236760f63b49STobias Grosser       PPCGArray.declare_local = false;
236860f63b49STobias Grosser       PPCGArray.global = false;
236960f63b49STobias Grosser       PPCGArray.linearize = false;
237060f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
237113c78e4dSTobias Grosser       PPCGArray.user = Array;
237260f63b49STobias Grosser 
237360f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
23742d010dafSTobias Grosser       i++;
2375b9fc860aSTobias Grosser 
2376b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
237760f63b49STobias Grosser     }
237860f63b49STobias Grosser   }
237960f63b49STobias Grosser 
238060f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
238160f63b49STobias Grosser   ///
238260f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
238360f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
238460f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
238560f63b49STobias Grosser 
2386d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
238760f63b49STobias Grosser       isl_space *Space = Array->getSpace();
238860f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
238960f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
239060f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
239160f63b49STobias Grosser     }
239260f63b49STobias Grosser 
239360f63b49STobias Grosser     return Maps;
239460f63b49STobias Grosser   }
239560f63b49STobias Grosser 
2396e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
2397e938517eSTobias Grosser   ///
2398a6d48f59SMichael Kruse   /// @returns A new gpu program description.
2399e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
2400e938517eSTobias Grosser 
2401e938517eSTobias Grosser     if (!PPCGScop)
2402e938517eSTobias Grosser       return nullptr;
2403e938517eSTobias Grosser 
2404e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
2405e938517eSTobias Grosser 
2406e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
2407e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
2408aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
240960f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
241060f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
241160f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
241260f63b49STobias Grosser     PPCGProg->tagged_must_kill =
241360f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
241460f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
241560f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
2416e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
2417e938517eSTobias Grosser     PPCGProg->array_order = nullptr;
241869b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
241969b46751STobias Grosser     PPCGProg->stmts = getStatements();
242060f63b49STobias Grosser     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
242160f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
242260f63b49STobias Grosser                                        PPCGProg->n_array);
242360f63b49STobias Grosser 
242460f63b49STobias Grosser     createArrays(PPCGProg);
2425e938517eSTobias Grosser 
2426d58acf86STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
2427d58acf86STobias Grosser 
2428e938517eSTobias Grosser     return PPCGProg;
2429e938517eSTobias Grosser   }
2430e938517eSTobias Grosser 
243169b46751STobias Grosser   struct PrintGPUUserData {
243269b46751STobias Grosser     struct cuda_info *CudaInfo;
243369b46751STobias Grosser     struct gpu_prog *PPCGProg;
243469b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
243569b46751STobias Grosser   };
243669b46751STobias Grosser 
243769b46751STobias Grosser   /// Print a user statement node in the host code.
243869b46751STobias Grosser   ///
243969b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
244069b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
244169b46751STobias Grosser   /// host ast.
244269b46751STobias Grosser   ///
244369b46751STobias Grosser   /// @param P The printer to print to
244469b46751STobias Grosser   /// @param Options The printing options to use
244569b46751STobias Grosser   /// @param Node The node to print
244669b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
244769b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
244869b46751STobias Grosser   ///
244969b46751STobias Grosser   /// @returns A printer to which the output has been printed.
245069b46751STobias Grosser   static __isl_give isl_printer *
245169b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
245269b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
245369b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
245469b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
245569b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
245669b46751STobias Grosser 
245769b46751STobias Grosser     if (Id) {
245820251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
245920251734STobias Grosser 
246020251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
246120251734STobias Grosser       // otherwise try to call pet functionality that is not available in
246220251734STobias Grosser       // Polly.
246320251734STobias Grosser       if (IsUser) {
246420251734STobias Grosser         P = isl_printer_start_line(P);
246520251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
246620251734STobias Grosser         P = isl_printer_end_line(P);
246720251734STobias Grosser         isl_id_free(Id);
246820251734STobias Grosser         isl_ast_print_options_free(Options);
246920251734STobias Grosser         return P;
247020251734STobias Grosser       }
247120251734STobias Grosser 
247269b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
247369b46751STobias Grosser       isl_id_free(Id);
247469b46751STobias Grosser       Data->Kernels.push_back(Kernel);
247569b46751STobias Grosser     }
247669b46751STobias Grosser 
247769b46751STobias Grosser     return print_host_user(P, Options, Node, User);
247869b46751STobias Grosser   }
247969b46751STobias Grosser 
248069b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
248169b46751STobias Grosser   ///
248269b46751STobias Grosser   /// @param Kernel The kernel to print
248369b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
248469b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
248569b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
248669b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
248769b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
248869b46751STobias Grosser     char *String = isl_printer_get_str(P);
248969b46751STobias Grosser     printf("%s\n", String);
249069b46751STobias Grosser     free(String);
249169b46751STobias Grosser     isl_printer_free(P);
249269b46751STobias Grosser   }
249369b46751STobias Grosser 
249469b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
249569b46751STobias Grosser   ///
249669b46751STobias Grosser   /// @param Tree An AST describing GPU code
249769b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
249869b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
249969b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
250069b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
250169b46751STobias Grosser 
250269b46751STobias Grosser     PrintGPUUserData Data;
250369b46751STobias Grosser     Data.PPCGProg = PPCGProg;
250469b46751STobias Grosser 
250569b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
250669b46751STobias Grosser     Options =
250769b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
250869b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
250969b46751STobias Grosser     char *String = isl_printer_get_str(P);
251069b46751STobias Grosser     printf("# host\n");
251169b46751STobias Grosser     printf("%s\n", String);
251269b46751STobias Grosser     free(String);
251369b46751STobias Grosser     isl_printer_free(P);
251469b46751STobias Grosser 
251569b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
251669b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
251769b46751STobias Grosser       printKernel(Kernel);
251869b46751STobias Grosser     }
251969b46751STobias Grosser   }
252069b46751STobias Grosser 
2521f384594dSTobias Grosser   // Generate a GPU program using PPCG.
2522f384594dSTobias Grosser   //
2523f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
2524f384594dSTobias Grosser   //
2525f384594dSTobias Grosser   //  1) Compute new schedule for the program.
2526f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
2527f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
2528f384594dSTobias Grosser   //
2529f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
2530f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
2531f384594dSTobias Grosser   // strategy directly from this pass.
2532f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
2533f384594dSTobias Grosser 
2534f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
2535f384594dSTobias Grosser 
2536f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
2537f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
2538f384594dSTobias Grosser     PPCGGen->print = nullptr;
2539f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
254060c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
2541f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
2542f384594dSTobias Grosser     PPCGGen->tree = nullptr;
2543f384594dSTobias Grosser     PPCGGen->types.n = 0;
2544f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
2545f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
2546f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
2547f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
2548f384594dSTobias Grosser 
2549f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
2550f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
2551f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
25522341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
2553f384594dSTobias Grosser 
2554f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
2555f384594dSTobias Grosser 
2556aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
2557aef5196fSTobias Grosser 
255869b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
2559aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
256069b46751STobias Grosser     } else {
2561aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
256269b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
256369b46751STobias Grosser     }
2564aef5196fSTobias Grosser 
2565f384594dSTobias Grosser     if (DumpSchedule) {
2566f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
2567f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
2568f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
2569f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
2570f384594dSTobias Grosser       if (Schedule)
2571f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
2572f384594dSTobias Grosser       else
2573f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
2574f384594dSTobias Grosser 
2575f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
2576f384594dSTobias Grosser       isl_printer_free(P);
2577f384594dSTobias Grosser     }
2578f384594dSTobias Grosser 
257969b46751STobias Grosser     if (DumpCode) {
258069b46751STobias Grosser       printf("Code\n");
258169b46751STobias Grosser       printf("====\n");
258269b46751STobias Grosser       if (PPCGGen->tree)
258369b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
258469b46751STobias Grosser       else
258569b46751STobias Grosser         printf("No code generated\n");
258669b46751STobias Grosser     }
258769b46751STobias Grosser 
2588f384594dSTobias Grosser     isl_schedule_free(Schedule);
2589f384594dSTobias Grosser 
2590f384594dSTobias Grosser     return PPCGGen;
2591f384594dSTobias Grosser   }
2592f384594dSTobias Grosser 
2593f384594dSTobias Grosser   /// Free gpu_gen structure.
2594f384594dSTobias Grosser   ///
2595f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
2596f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
2597f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
2598f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
2599f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
2600f384594dSTobias Grosser     free(PPCGGen);
2601f384594dSTobias Grosser   }
2602f384594dSTobias Grosser 
2603b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
2604b307ed4dSTobias Grosser   ///
2605b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
2606b307ed4dSTobias Grosser   /// ourselves.
2607b307ed4dSTobias Grosser   ///
2608b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
2609b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
2610b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
2611b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
2612b307ed4dSTobias Grosser     free(PPCGScop->options);
2613b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
2614b307ed4dSTobias Grosser   }
2615b307ed4dSTobias Grosser 
261682f2af35STobias Grosser   /// Approximate the number of points in the set.
261782f2af35STobias Grosser   ///
261882f2af35STobias Grosser   /// This function returns an ast expression that overapproximates the number
261982f2af35STobias Grosser   /// of points in an isl set through the rectangular hull surrounding this set.
262082f2af35STobias Grosser   ///
262182f2af35STobias Grosser   /// @param Set   The set to count.
262282f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
262382f2af35STobias Grosser   ///              expression.
262482f2af35STobias Grosser   ///
262582f2af35STobias Grosser   /// @returns An approximation of the number of points in the set.
262682f2af35STobias Grosser   __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set,
262782f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
262882f2af35STobias Grosser 
262982f2af35STobias Grosser     isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1);
263082f2af35STobias Grosser     auto *Expr = isl_ast_expr_from_val(isl_val_copy(One));
263182f2af35STobias Grosser 
263282f2af35STobias Grosser     isl_space *Space = isl_set_get_space(Set);
263382f2af35STobias Grosser     Space = isl_space_params(Space);
263482f2af35STobias Grosser     auto *Univ = isl_set_universe(Space);
263582f2af35STobias Grosser     isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One);
263682f2af35STobias Grosser 
263782f2af35STobias Grosser     for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) {
263882f2af35STobias Grosser       isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i);
263982f2af35STobias Grosser       isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i);
264082f2af35STobias Grosser       isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min);
264182f2af35STobias Grosser       DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff));
264282f2af35STobias Grosser       auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize);
264382f2af35STobias Grosser       Expr = isl_ast_expr_mul(Expr, DimSizeExpr);
264482f2af35STobias Grosser     }
264582f2af35STobias Grosser 
264682f2af35STobias Grosser     isl_set_free(Set);
264782f2af35STobias Grosser     isl_pw_aff_free(OneAff);
264882f2af35STobias Grosser 
264982f2af35STobias Grosser     return Expr;
265082f2af35STobias Grosser   }
265182f2af35STobias Grosser 
265282f2af35STobias Grosser   /// Approximate a number of dynamic instructions executed by a given
265382f2af35STobias Grosser   /// statement.
265482f2af35STobias Grosser   ///
265582f2af35STobias Grosser   /// @param Stmt  The statement for which to compute the number of dynamic
265682f2af35STobias Grosser   ///              instructions.
265782f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
265882f2af35STobias Grosser   ///              expression.
265982f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
266082f2af35STobias Grosser   ///          by @p Stmt.
266182f2af35STobias Grosser   __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt,
266282f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
266382f2af35STobias Grosser     auto Iterations = approxPointsInSet(Stmt.getDomain(), Build);
266482f2af35STobias Grosser 
266582f2af35STobias Grosser     long InstCount = 0;
266682f2af35STobias Grosser 
266782f2af35STobias Grosser     if (Stmt.isBlockStmt()) {
266882f2af35STobias Grosser       auto *BB = Stmt.getBasicBlock();
266982f2af35STobias Grosser       InstCount = std::distance(BB->begin(), BB->end());
267082f2af35STobias Grosser     } else {
267182f2af35STobias Grosser       auto *R = Stmt.getRegion();
267282f2af35STobias Grosser 
267382f2af35STobias Grosser       for (auto *BB : R->blocks()) {
267482f2af35STobias Grosser         InstCount += std::distance(BB->begin(), BB->end());
267582f2af35STobias Grosser       }
267682f2af35STobias Grosser     }
267782f2af35STobias Grosser 
267882f2af35STobias Grosser     isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount);
267982f2af35STobias Grosser     auto *InstExpr = isl_ast_expr_from_val(InstVal);
268082f2af35STobias Grosser     return isl_ast_expr_mul(InstExpr, Iterations);
268182f2af35STobias Grosser   }
268282f2af35STobias Grosser 
268382f2af35STobias Grosser   /// Approximate dynamic instructions executed in scop.
268482f2af35STobias Grosser   ///
268582f2af35STobias Grosser   /// @param S     The scop for which to approximate dynamic instructions.
268682f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
268782f2af35STobias Grosser   ///              expression.
268882f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
268982f2af35STobias Grosser   ///          in @p S.
269082f2af35STobias Grosser   __isl_give isl_ast_expr *
269182f2af35STobias Grosser   getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) {
269282f2af35STobias Grosser     isl_ast_expr *Instructions;
269382f2af35STobias Grosser 
269482f2af35STobias Grosser     isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0);
269582f2af35STobias Grosser     Instructions = isl_ast_expr_from_val(Zero);
269682f2af35STobias Grosser 
269782f2af35STobias Grosser     for (ScopStmt &Stmt : S) {
269882f2af35STobias Grosser       isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build);
269982f2af35STobias Grosser       Instructions = isl_ast_expr_add(Instructions, StmtInstructions);
270082f2af35STobias Grosser     }
270182f2af35STobias Grosser     return Instructions;
270282f2af35STobias Grosser   }
270382f2af35STobias Grosser 
270482f2af35STobias Grosser   /// Create a check that ensures sufficient compute in scop.
270582f2af35STobias Grosser   ///
270682f2af35STobias Grosser   /// @param S     The scop for which to ensure sufficient compute.
270782f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
270882f2af35STobias Grosser   ///              expression.
270982f2af35STobias Grosser   /// @returns An expression that evaluates to TRUE in case of sufficient
271082f2af35STobias Grosser   ///          compute and to FALSE, otherwise.
271182f2af35STobias Grosser   __isl_give isl_ast_expr *
271282f2af35STobias Grosser   createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) {
271382f2af35STobias Grosser     auto Iterations = getNumberOfIterations(S, Build);
271482f2af35STobias Grosser     auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute);
271582f2af35STobias Grosser     auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal);
271682f2af35STobias Grosser     return isl_ast_expr_ge(Iterations, MinComputeExpr);
271782f2af35STobias Grosser   }
271882f2af35STobias Grosser 
2719f291c8d5SSiddharth Bhat   /// Check if the basic block contains a function we cannot codegen for GPU
2720f291c8d5SSiddharth Bhat   /// kernels.
2721f291c8d5SSiddharth Bhat   ///
2722f291c8d5SSiddharth Bhat   /// If this basic block does something with a `Function` other than calling
2723f291c8d5SSiddharth Bhat   /// a function that we support in a kernel, return true.
2724f291c8d5SSiddharth Bhat   bool containsInvalidKernelFunctionInBllock(const BasicBlock *BB) {
2725f291c8d5SSiddharth Bhat     for (const Instruction &Inst : *BB) {
2726f291c8d5SSiddharth Bhat       const CallInst *Call = dyn_cast<CallInst>(&Inst);
2727f291c8d5SSiddharth Bhat       if (Call && isValidFunctionInKernel(Call->getCalledFunction())) {
2728f291c8d5SSiddharth Bhat         continue;
2729f291c8d5SSiddharth Bhat       }
2730f291c8d5SSiddharth Bhat 
2731bccaea57SSiddharth Bhat       for (Value *SrcVal : Inst.operands()) {
2732bccaea57SSiddharth Bhat         PointerType *p = dyn_cast<PointerType>(SrcVal->getType());
2733bccaea57SSiddharth Bhat         if (!p)
2734bccaea57SSiddharth Bhat           continue;
2735bccaea57SSiddharth Bhat         if (isa<FunctionType>(p->getElementType()))
2736bccaea57SSiddharth Bhat           return true;
2737bccaea57SSiddharth Bhat       }
2738f291c8d5SSiddharth Bhat     }
2739bccaea57SSiddharth Bhat     return false;
2740bccaea57SSiddharth Bhat   }
2741bccaea57SSiddharth Bhat 
2742f291c8d5SSiddharth Bhat   /// Return whether the Scop S uses functions in a way that we do not support.
2743f291c8d5SSiddharth Bhat   bool containsInvalidKernelFunction(const Scop &S) {
2744bccaea57SSiddharth Bhat     for (auto &Stmt : S) {
2745bccaea57SSiddharth Bhat       if (Stmt.isBlockStmt()) {
2746f291c8d5SSiddharth Bhat         if (containsInvalidKernelFunctionInBllock(Stmt.getBasicBlock()))
2747bccaea57SSiddharth Bhat           return true;
2748bccaea57SSiddharth Bhat       } else {
2749bccaea57SSiddharth Bhat         assert(Stmt.isRegionStmt() &&
2750bccaea57SSiddharth Bhat                "Stmt was neither block nor region statement");
2751bccaea57SSiddharth Bhat         for (const BasicBlock *BB : Stmt.getRegion()->blocks())
2752f291c8d5SSiddharth Bhat           if (containsInvalidKernelFunctionInBllock(BB))
2753bccaea57SSiddharth Bhat             return true;
2754bccaea57SSiddharth Bhat       }
2755bccaea57SSiddharth Bhat     }
2756bccaea57SSiddharth Bhat     return false;
2757bccaea57SSiddharth Bhat   }
2758bccaea57SSiddharth Bhat 
275938fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
276038fc0aedSTobias Grosser   ///
276132837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
276232837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
276332837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
276438fc0aedSTobias Grosser     ScopAnnotator Annotator;
276538fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
276638fc0aedSTobias Grosser 
276738fc0aedSTobias Grosser     Region *R = &S->getRegion();
276838fc0aedSTobias Grosser 
276938fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
277038fc0aedSTobias Grosser 
277138fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
277238fc0aedSTobias Grosser 
277338fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
277438fc0aedSTobias Grosser 
277538fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
277638fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
277738fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
277838fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
277938fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
278038fc0aedSTobias Grosser     // code generating this scop.
2781256070d8SAndreas Simbuerger     BBPair StartExitBlocks =
27822d950f36SPhilip Pfaffe         executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI);
2783256070d8SAndreas Simbuerger     BasicBlock *StartBlock = std::get<0>(StartExitBlocks);
278438fc0aedSTobias Grosser 
27852d950f36SPhilip Pfaffe     GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S,
278617f01968SSiddharth Bhat                                StartBlock, Prog, Runtime, Architecture);
2787acf80064SEli Friedman 
278838fc0aedSTobias Grosser     // TODO: Handle LICM
278938fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
279038fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
279138fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
2792cb1aef8dSTobias Grosser 
2793cb1aef8dSTobias Grosser     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx());
27942b852e2eSPhilip Pfaffe     isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build);
279582f2af35STobias Grosser     isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build);
279682f2af35STobias Grosser     Condition = isl_ast_expr_and(Condition, SufficientCompute);
2797cb1aef8dSTobias Grosser     isl_ast_build_free(Build);
2798cb1aef8dSTobias Grosser 
2799cb1aef8dSTobias Grosser     Value *RTC = NodeBuilder.createRTC(Condition);
2800cb1aef8dSTobias Grosser     Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
2801cb1aef8dSTobias Grosser 
280238fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
2803fa7b0802STobias Grosser 
2804fa7b0802STobias Grosser     NodeBuilder.initializeAfterRTH();
280538fc0aedSTobias Grosser     NodeBuilder.create(Root);
28068ed5e599STobias Grosser     NodeBuilder.finalize();
28075857b701STobias Grosser 
2808bc653f20STobias Grosser     /// In case a sequential kernel has more surrounding loops as any parallel
2809bc653f20STobias Grosser     /// kernel, the SCoP is probably mostly sequential. Hence, there is no
2810de244eb4STobias Grosser     /// point in running it on a GPU.
2811bc653f20STobias Grosser     if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel)
2812bc653f20STobias Grosser       SplitBlock->getTerminator()->setOperand(0, Builder.getFalse());
2813bc653f20STobias Grosser 
28145857b701STobias Grosser     if (!NodeBuilder.BuildSuccessful)
28155857b701STobias Grosser       SplitBlock->getTerminator()->setOperand(0, Builder.getFalse());
281638fc0aedSTobias Grosser   }
281738fc0aedSTobias Grosser 
2818e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
2819e938517eSTobias Grosser     S = &CurrentScop;
282038fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
282138fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
282238fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
28237b5a4dfdSTobias Grosser     DL = &S->getRegion().getEntry()->getModule()->getDataLayout();
282438fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
2825e938517eSTobias Grosser 
2826f291c8d5SSiddharth Bhat     // We currently do not support functions other than intrinsics inside
2827f291c8d5SSiddharth Bhat     // kernels, as code generation will need to offload function calls to the
2828f291c8d5SSiddharth Bhat     // kernel. This may lead to a kernel trying to call a function on the host.
2829bccaea57SSiddharth Bhat     // This also allows us to prevent codegen from trying to take the
2830bccaea57SSiddharth Bhat     // address of an intrinsic function to send to the kernel.
2831f291c8d5SSiddharth Bhat     if (containsInvalidKernelFunction(CurrentScop)) {
2832f291c8d5SSiddharth Bhat       DEBUG(
2833f291c8d5SSiddharth Bhat           dbgs()
2834f291c8d5SSiddharth Bhat               << "Scop contains function which cannot be materialised in a GPU "
2835f291c8d5SSiddharth Bhat                  "kernel. Bailing out.\n";);
2836bccaea57SSiddharth Bhat       return false;
2837f291c8d5SSiddharth Bhat     }
2838bccaea57SSiddharth Bhat 
2839e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
2840e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
2841f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
284238fc0aedSTobias Grosser 
2843*02ca346eSSingapuram Sanjay Srivallabh     if (PPCGGen->tree) {
284432837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
2845*02ca346eSSingapuram Sanjay Srivallabh       CurrentScop.markAsToBeSkipped();
2846*02ca346eSSingapuram Sanjay Srivallabh     }
284738fc0aedSTobias Grosser 
2848b307ed4dSTobias Grosser     freeOptions(PPCGScop);
2849f384594dSTobias Grosser     freePPCGGen(PPCGGen);
2850e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
2851e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
2852e938517eSTobias Grosser 
2853e938517eSTobias Grosser     return true;
2854e938517eSTobias Grosser   }
28559dfe4e7cSTobias Grosser 
28569dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
28579dfe4e7cSTobias Grosser 
28589dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
28599dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
28609dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
28619dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
28625cc87e3aSPhilip Pfaffe     AU.addRequired<ScopDetectionWrapperPass>();
28639dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
28649dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
28659dfe4e7cSTobias Grosser 
28669dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
28679dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
28689dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
28699dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
28709dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
28715cc87e3aSPhilip Pfaffe     AU.addPreserved<ScopDetectionWrapperPass>();
28729dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
28739dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
28749dfe4e7cSTobias Grosser 
28759dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
28769dfe4e7cSTobias Grosser     //        region tree.
28779dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
28789dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
28799dfe4e7cSTobias Grosser   }
28809dfe4e7cSTobias Grosser };
288124222c73STobias Grosser } // namespace
28829dfe4e7cSTobias Grosser 
28839dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
28849dfe4e7cSTobias Grosser 
288517f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) {
288617f01968SSiddharth Bhat   PPCGCodeGeneration *generator = new PPCGCodeGeneration();
288717f01968SSiddharth Bhat   generator->Runtime = Runtime;
288817f01968SSiddharth Bhat   generator->Architecture = Arch;
288917f01968SSiddharth Bhat   return generator;
289017f01968SSiddharth Bhat }
28919dfe4e7cSTobias Grosser 
28929dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
28939dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
28949dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
28959dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
28969dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
28979dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
28989dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
28995cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
29009dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
29019dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
2902