19dfe4e7cSTobias Grosser //===------ PPCGCodeGeneration.cpp - Polly Accelerator Code Generation. ---===//
29dfe4e7cSTobias Grosser //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
69dfe4e7cSTobias Grosser //
79dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===//
89dfe4e7cSTobias Grosser //
99dfe4e7cSTobias Grosser // Take a scop created by ScopInfo and map it to GPU code using the ppcg
109dfe4e7cSTobias Grosser // GPU mapping strategy.
119dfe4e7cSTobias Grosser //
129dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===//
139dfe4e7cSTobias Grosser 
1417f01968SSiddharth Bhat #include "polly/CodeGen/PPCGCodeGeneration.h"
1571dfb3ebSSiddharth Bhat #include "polly/CodeGen/CodeGeneration.h"
16cb1aef8dSTobias Grosser #include "polly/CodeGen/IslAst.h"
179dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h"
187b9f5ca2SSiddharth Bhat #include "polly/CodeGen/PerfMonitor.h"
1938fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h"
209dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h"
219dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h"
22f384594dSTobias Grosser #include "polly/Options.h"
23629109b6STobias Grosser #include "polly/ScopDetection.h"
249dfe4e7cSTobias Grosser #include "polly/ScopInfo.h"
25edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h"
2674dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h"
2774dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h"
280133dc39SHeejin Ahn #include "llvm/IR/IntrinsicsNVPTX.h"
2974dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h"
30e1a98343STobias Grosser #include "llvm/IR/Verifier.h"
318fc6cdfbSTobias Grosser #include "llvm/IRReader/IRReader.h"
322c831971SMichael Kruse #include "llvm/InitializePasses.h"
338fc6cdfbSTobias Grosser #include "llvm/Linker/Linker.h"
34031bb165SMichael Kruse #include "llvm/Support/SourceMgr.h"
3574dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h"
3674dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h"
379a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h"
38750160e2STobias Grosser #include "llvm/Transforms/Utils/BasicBlockUtils.h"
39f384594dSTobias Grosser #include "isl/union_map.h"
40f384594dSTobias Grosser 
41e938517eSTobias Grosser extern "C" {
42a56f8f8eSTobias Grosser #include "ppcg/cuda.h"
43a56f8f8eSTobias Grosser #include "ppcg/gpu.h"
44a56f8f8eSTobias Grosser #include "ppcg/ppcg.h"
45e938517eSTobias Grosser }
46e938517eSTobias Grosser 
479dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h"
489dfe4e7cSTobias Grosser 
499dfe4e7cSTobias Grosser using namespace polly;
509dfe4e7cSTobias Grosser using namespace llvm;
519dfe4e7cSTobias Grosser 
529dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg"
539dfe4e7cSTobias Grosser 
54f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
55f384594dSTobias Grosser                                   cl::desc("Dump the computed GPU Schedule"),
56681bd568STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
57f384594dSTobias Grosser                                   cl::cat(PollyCategory));
5869b46751STobias Grosser 
5969b46751STobias Grosser static cl::opt<bool>
6069b46751STobias Grosser     DumpCode("polly-acc-dump-code",
6169b46751STobias Grosser              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
6269b46751STobias Grosser              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
6369b46751STobias Grosser 
6432837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
6532837fe3STobias Grosser                                   cl::desc("Dump the kernel LLVM-IR"),
6632837fe3STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
6732837fe3STobias Grosser                                   cl::cat(PollyCategory));
6832837fe3STobias Grosser 
6974dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
7074dc3cb4STobias Grosser                                    cl::desc("Dump the kernel assembly code"),
7174dc3cb4STobias Grosser                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
7274dc3cb4STobias Grosser                                    cl::cat(PollyCategory));
7374dc3cb4STobias Grosser 
7474dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath",
7574dc3cb4STobias Grosser                               cl::desc("Allow unsafe math optimizations"),
7674dc3cb4STobias Grosser                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
7774dc3cb4STobias Grosser                               cl::cat(PollyCategory));
78b513b491STobias Grosser static cl::opt<bool> SharedMemory("polly-acc-use-shared",
79b513b491STobias Grosser                                   cl::desc("Use shared memory"), cl::Hidden,
80b513b491STobias Grosser                                   cl::init(false), cl::ZeroOrMore,
81b513b491STobias Grosser                                   cl::cat(PollyCategory));
82130ca30fSTobias Grosser static cl::opt<bool> PrivateMemory("polly-acc-use-private",
83130ca30fSTobias Grosser                                    cl::desc("Use private memory"), cl::Hidden,
84130ca30fSTobias Grosser                                    cl::init(false), cl::ZeroOrMore,
85130ca30fSTobias Grosser                                    cl::cat(PollyCategory));
8674dc3cb4STobias Grosser 
87c4a4af47SSiddharth Bhat bool polly::PollyManagedMemory;
88c4a4af47SSiddharth Bhat static cl::opt<bool, true>
89c4a4af47SSiddharth Bhat     XManagedMemory("polly-acc-codegen-managed-memory",
90abed4969SSiddharth Bhat                    cl::desc("Generate Host kernel code assuming"
91abed4969SSiddharth Bhat                             " that all memory has been"
92abed4969SSiddharth Bhat                             " declared as managed memory"),
93c4a4af47SSiddharth Bhat                    cl::location(PollyManagedMemory), cl::Hidden,
94c4a4af47SSiddharth Bhat                    cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
95abed4969SSiddharth Bhat 
9665d7f72fSSiddharth Bhat static cl::opt<bool>
9765d7f72fSSiddharth Bhat     FailOnVerifyModuleFailure("polly-acc-fail-on-verify-module-failure",
9865d7f72fSSiddharth Bhat                               cl::desc("Fail and generate a backtrace if"
9965d7f72fSSiddharth Bhat                                        " verifyModule fails on the GPU "
10065d7f72fSSiddharth Bhat                                        " kernel module."),
10165d7f72fSSiddharth Bhat                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
10265d7f72fSSiddharth Bhat                               cl::cat(PollyCategory));
10365d7f72fSSiddharth Bhat 
1048fc6cdfbSTobias Grosser static cl::opt<std::string> CUDALibDevice(
1058fc6cdfbSTobias Grosser     "polly-acc-libdevice", cl::desc("Path to CUDA libdevice"), cl::Hidden,
1068fc6cdfbSTobias Grosser     cl::init("/usr/local/cuda/nvvm/libdevice/libdevice.compute_20.10.ll"),
1078fc6cdfbSTobias Grosser     cl::ZeroOrMore, cl::cat(PollyCategory));
1088fc6cdfbSTobias Grosser 
10974dc3cb4STobias Grosser static cl::opt<std::string>
11074dc3cb4STobias Grosser     CudaVersion("polly-acc-cuda-version",
11174dc3cb4STobias Grosser                 cl::desc("The CUDA version to compile for"), cl::Hidden,
11274dc3cb4STobias Grosser                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
11374dc3cb4STobias Grosser 
11482f2af35STobias Grosser static cl::opt<int>
11582f2af35STobias Grosser     MinCompute("polly-acc-mincompute",
11682f2af35STobias Grosser                cl::desc("Minimal number of compute statements to run on GPU."),
11782f2af35STobias Grosser                cl::Hidden, cl::init(10 * 512 * 512));
11882f2af35STobias Grosser 
1197b9f5ca2SSiddharth Bhat extern bool polly::PerfMonitoring;
1207b9f5ca2SSiddharth Bhat 
121638316daSSiddharth Bhat /// Return  a unique name for a Scop, which is the scop region with the
122638316daSSiddharth Bhat /// function name.
123638316daSSiddharth Bhat std::string getUniqueScopName(const Scop *S) {
124638316daSSiddharth Bhat   return "Scop Region: " + S->getNameStr() +
125638316daSSiddharth Bhat          " | Function: " + std::string(S->getFunction().getName());
126638316daSSiddharth Bhat }
127638316daSSiddharth Bhat 
128a82f2d26SSiddharth Bhat /// Used to store information PPCG wants for kills. This information is
129a82f2d26SSiddharth Bhat /// used by live range reordering.
130a82f2d26SSiddharth Bhat ///
131a82f2d26SSiddharth Bhat /// @see computeLiveRangeReordering
132a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGScop
133a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGProg
134a82f2d26SSiddharth Bhat struct MustKillsInfo {
135a82f2d26SSiddharth Bhat   /// Collection of all kill statements that will be sequenced at the end of
136a82f2d26SSiddharth Bhat   /// PPCGScop->schedule.
137a82f2d26SSiddharth Bhat   ///
138a82f2d26SSiddharth Bhat   /// The nodes in `KillsSchedule` will be merged using `isl_schedule_set`
139a82f2d26SSiddharth Bhat   /// which merges schedules in *arbitrary* order.
140a82f2d26SSiddharth Bhat   /// (we don't care about the order of the kills anyway).
141a82f2d26SSiddharth Bhat   isl::schedule KillsSchedule;
142a82f2d26SSiddharth Bhat   /// Map from kill statement instances to scalars that need to be
143a82f2d26SSiddharth Bhat   /// killed.
144a82f2d26SSiddharth Bhat   ///
145edfef5aeSSiddharth Bhat   /// We currently derive kill information for:
146edfef5aeSSiddharth Bhat   ///  1. phi nodes. PHI nodes are not alive outside the scop and can
147edfef5aeSSiddharth Bhat   ///     consequently all be killed.
148edfef5aeSSiddharth Bhat   ///  2. Scalar arrays that are not used outside the Scop. This is
149edfef5aeSSiddharth Bhat   ///     checked by `isScalarUsesContainedInScop`.
150edfef5aeSSiddharth Bhat   /// [params] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] }
151a82f2d26SSiddharth Bhat   isl::union_map TaggedMustKills;
152a82f2d26SSiddharth Bhat 
1539e3db2b7SSiddharth Bhat   /// Tagged must kills stripped of the tags.
1549e3db2b7SSiddharth Bhat   /// [params] -> { Stmt_phantom[]  -> scalar_to_kill[] }
1559e3db2b7SSiddharth Bhat   isl::union_map MustKills;
1569e3db2b7SSiddharth Bhat 
1579e3db2b7SSiddharth Bhat   MustKillsInfo() : KillsSchedule(nullptr) {}
158a82f2d26SSiddharth Bhat };
159a82f2d26SSiddharth Bhat 
160761e5b93SSiddharth Bhat /// Check if SAI's uses are entirely contained within Scop S.
161761e5b93SSiddharth Bhat /// If a scalar is used only with a Scop, we are free to kill it, as no data
162761e5b93SSiddharth Bhat /// can flow in/out of the value any more.
163761e5b93SSiddharth Bhat /// @see computeMustKillsInfo
164761e5b93SSiddharth Bhat static bool isScalarUsesContainedInScop(const Scop &S,
165761e5b93SSiddharth Bhat                                         const ScopArrayInfo *SAI) {
166761e5b93SSiddharth Bhat   assert(SAI->isValueKind() && "this function only deals with scalars."
167761e5b93SSiddharth Bhat                                " Dealing with arrays required alias analysis");
168761e5b93SSiddharth Bhat 
169761e5b93SSiddharth Bhat   const Region &R = S.getRegion();
170761e5b93SSiddharth Bhat   for (User *U : SAI->getBasePtr()->users()) {
171761e5b93SSiddharth Bhat     Instruction *I = dyn_cast<Instruction>(U);
172761e5b93SSiddharth Bhat     assert(I && "invalid user of scop array info");
173761e5b93SSiddharth Bhat     if (!R.contains(I))
174761e5b93SSiddharth Bhat       return false;
175761e5b93SSiddharth Bhat   }
176761e5b93SSiddharth Bhat   return true;
177761e5b93SSiddharth Bhat }
178761e5b93SSiddharth Bhat 
179a82f2d26SSiddharth Bhat /// Compute must-kills needed to enable live range reordering with PPCG.
180a82f2d26SSiddharth Bhat ///
181a82f2d26SSiddharth Bhat /// @params S The Scop to compute live range reordering information
182a82f2d26SSiddharth Bhat /// @returns live range reordering information that can be used to setup
183a82f2d26SSiddharth Bhat /// PPCG.
184a82f2d26SSiddharth Bhat static MustKillsInfo computeMustKillsInfo(const Scop &S) {
185b65ccc43STobias Grosser   const isl::space ParamSpace = S.getParamSpace();
186a82f2d26SSiddharth Bhat   MustKillsInfo Info;
187a82f2d26SSiddharth Bhat 
188761e5b93SSiddharth Bhat   // 1. Collect all ScopArrayInfo that satisfy *any* of the criteria:
189761e5b93SSiddharth Bhat   //      1.1 phi nodes in scop.
190761e5b93SSiddharth Bhat   //      1.2 scalars that are only used within the scop
191a82f2d26SSiddharth Bhat   SmallVector<isl::id, 4> KillMemIds;
192a82f2d26SSiddharth Bhat   for (ScopArrayInfo *SAI : S.arrays()) {
193761e5b93SSiddharth Bhat     if (SAI->isPHIKind() ||
194761e5b93SSiddharth Bhat         (SAI->isValueKind() && isScalarUsesContainedInScop(S, SAI)))
19577eef90fSTobias Grosser       KillMemIds.push_back(isl::manage(SAI->getBasePtrId().release()));
196a82f2d26SSiddharth Bhat   }
197a82f2d26SSiddharth Bhat 
198d70ea7feSTobias Grosser   Info.TaggedMustKills = isl::union_map::empty(ParamSpace);
199d70ea7feSTobias Grosser   Info.MustKills = isl::union_map::empty(ParamSpace);
200a82f2d26SSiddharth Bhat 
201a82f2d26SSiddharth Bhat   // Initialising KillsSchedule to `isl_set_empty` creates an empty node in the
202a82f2d26SSiddharth Bhat   // schedule:
203a82f2d26SSiddharth Bhat   //     - filter: "[control] -> { }"
204a82f2d26SSiddharth Bhat   // So, we choose to not create this to keep the output a little nicer,
205a82f2d26SSiddharth Bhat   // at the cost of some code complexity.
206a82f2d26SSiddharth Bhat   Info.KillsSchedule = nullptr;
207a82f2d26SSiddharth Bhat 
208edfef5aeSSiddharth Bhat   for (isl::id &ToKillId : KillMemIds) {
209a82f2d26SSiddharth Bhat     isl::id KillStmtId = isl::id::alloc(
210edfef5aeSSiddharth Bhat         S.getIslCtx(),
211edfef5aeSSiddharth Bhat         std::string("SKill_phantom_").append(ToKillId.get_name()), nullptr);
212a82f2d26SSiddharth Bhat 
213a82f2d26SSiddharth Bhat     // NOTE: construction of tagged_must_kill:
214a82f2d26SSiddharth Bhat     // 2. We need to construct a map:
215edfef5aeSSiddharth Bhat     //     [param] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] }
216a82f2d26SSiddharth Bhat     // To construct this, we use `isl_map_domain_product` on 2 maps`:
217edfef5aeSSiddharth Bhat     // 2a. StmtToScalar:
218edfef5aeSSiddharth Bhat     //         [param] -> { Stmt_phantom[] -> scalar_to_kill[] }
219edfef5aeSSiddharth Bhat     // 2b. PhantomRefToScalar:
220edfef5aeSSiddharth Bhat     //         [param] -> { ref_phantom[] -> scalar_to_kill[] }
221a82f2d26SSiddharth Bhat     //
222a82f2d26SSiddharth Bhat     // Combining these with `isl_map_domain_product` gives us
223a82f2d26SSiddharth Bhat     // TaggedMustKill:
224edfef5aeSSiddharth Bhat     //     [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] }
225a82f2d26SSiddharth Bhat 
226edfef5aeSSiddharth Bhat     // 2a. [param] -> { Stmt[] -> scalar_to_kill[] }
227d70ea7feSTobias Grosser     isl::map StmtToScalar = isl::map::universe(ParamSpace);
228edfef5aeSSiddharth Bhat     StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::in, isl::id(KillStmtId));
229edfef5aeSSiddharth Bhat     StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::out, isl::id(ToKillId));
230a82f2d26SSiddharth Bhat 
231a82f2d26SSiddharth Bhat     isl::id PhantomRefId = isl::id::alloc(
232edfef5aeSSiddharth Bhat         S.getIslCtx(), std::string("ref_phantom") + ToKillId.get_name(),
233edfef5aeSSiddharth Bhat         nullptr);
234a82f2d26SSiddharth Bhat 
235edfef5aeSSiddharth Bhat     // 2b. [param] -> { phantom_ref[] -> scalar_to_kill[] }
236d70ea7feSTobias Grosser     isl::map PhantomRefToScalar = isl::map::universe(ParamSpace);
237edfef5aeSSiddharth Bhat     PhantomRefToScalar =
238edfef5aeSSiddharth Bhat         PhantomRefToScalar.set_tuple_id(isl::dim::in, PhantomRefId);
239edfef5aeSSiddharth Bhat     PhantomRefToScalar =
240edfef5aeSSiddharth Bhat         PhantomRefToScalar.set_tuple_id(isl::dim::out, ToKillId);
241a82f2d26SSiddharth Bhat 
242edfef5aeSSiddharth Bhat     // 2. [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] }
243edfef5aeSSiddharth Bhat     isl::map TaggedMustKill = StmtToScalar.domain_product(PhantomRefToScalar);
244a82f2d26SSiddharth Bhat     Info.TaggedMustKills = Info.TaggedMustKills.unite(TaggedMustKill);
245a82f2d26SSiddharth Bhat 
2469e3db2b7SSiddharth Bhat     // 2. [param] -> { Stmt[] -> scalar_to_kill[] }
2479e3db2b7SSiddharth Bhat     Info.MustKills = Info.TaggedMustKills.domain_factor_domain();
2489e3db2b7SSiddharth Bhat 
249a82f2d26SSiddharth Bhat     // 3. Create the kill schedule of the form:
250a82f2d26SSiddharth Bhat     //     "[param] -> { Stmt_phantom[] }"
251a82f2d26SSiddharth Bhat     // Then add this to Info.KillsSchedule.
252a82f2d26SSiddharth Bhat     isl::space KillStmtSpace = ParamSpace;
253a82f2d26SSiddharth Bhat     KillStmtSpace = KillStmtSpace.set_tuple_id(isl::dim::set, KillStmtId);
254a82f2d26SSiddharth Bhat     isl::union_set KillStmtDomain = isl::set::universe(KillStmtSpace);
255a82f2d26SSiddharth Bhat 
256a82f2d26SSiddharth Bhat     isl::schedule KillSchedule = isl::schedule::from_domain(KillStmtDomain);
257a82f2d26SSiddharth Bhat     if (Info.KillsSchedule)
2585f865032STobias Grosser       Info.KillsSchedule = isl::manage(
2595f865032STobias Grosser           isl_schedule_set(Info.KillsSchedule.release(), KillSchedule.copy()));
260a82f2d26SSiddharth Bhat     else
261a82f2d26SSiddharth Bhat       Info.KillsSchedule = KillSchedule;
262a82f2d26SSiddharth Bhat   }
263a82f2d26SSiddharth Bhat 
264a82f2d26SSiddharth Bhat   return Info;
265a82f2d26SSiddharth Bhat }
266a82f2d26SSiddharth Bhat 
26760c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
26860c60025STobias Grosser ///
26960c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
27060c60025STobias Grosser /// of the scheduled ScopStmts.
27160c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
27235de9009SSiddharth Bhat     void *StmtT, __isl_take isl_ast_build *Build_C,
27360c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
27460c60025STobias Grosser                                        isl_id *Id, void *User),
27560c60025STobias Grosser     void *UserIndex,
27660c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
277edb885cbSTobias Grosser     void *UserExpr) {
27860c60025STobias Grosser 
279edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
28060c60025STobias Grosser 
28135de9009SSiddharth Bhat   if (!Stmt || !Build_C)
282edb885cbSTobias Grosser     return NULL;
283edb885cbSTobias Grosser 
284718d04c6STobias Grosser   isl::ast_build Build = isl::manage_copy(Build_C);
28535de9009SSiddharth Bhat   isl::ctx Ctx = Build.get_ctx();
28635de9009SSiddharth Bhat   isl::id_to_ast_expr RefToExpr = isl::id_to_ast_expr::alloc(Ctx, 0);
287edb885cbSTobias Grosser 
288cff9696eSTobias Grosser   Stmt->setAstBuild(Build);
289cff9696eSTobias Grosser 
290edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
29135de9009SSiddharth Bhat     isl::map AddrFunc = Acc->getAddressFunction();
292dcf8d696STobias Grosser     AddrFunc = AddrFunc.intersect_domain(Stmt->getDomain());
29335de9009SSiddharth Bhat 
29435de9009SSiddharth Bhat     isl::id RefId = Acc->getId();
29535de9009SSiddharth Bhat     isl::pw_multi_aff PMA = isl::pw_multi_aff::from_map(AddrFunc);
29635de9009SSiddharth Bhat 
29735de9009SSiddharth Bhat     isl::multi_pw_aff MPA = isl::multi_pw_aff(PMA);
29835de9009SSiddharth Bhat     MPA = MPA.coalesce();
29935de9009SSiddharth Bhat     MPA = isl::manage(FunctionIndex(MPA.release(), RefId.get(), UserIndex));
30035de9009SSiddharth Bhat 
30135de9009SSiddharth Bhat     isl::ast_expr Access = Build.access_from(MPA);
30235de9009SSiddharth Bhat     Access = isl::manage(FunctionExpr(Access.release(), RefId.get(), UserExpr));
30335de9009SSiddharth Bhat     RefToExpr = RefToExpr.set(RefId, Access);
304edb885cbSTobias Grosser   }
305edb885cbSTobias Grosser 
30635de9009SSiddharth Bhat   return RefToExpr.release();
30760c60025STobias Grosser }
308f384594dSTobias Grosser 
309a90be207SSiddharth Bhat /// Given a LLVM Type, compute its size in bytes,
310a90be207SSiddharth Bhat static int computeSizeInBytes(const Type *T) {
311a90be207SSiddharth Bhat   int bytes = T->getPrimitiveSizeInBits() / 8;
312a90be207SSiddharth Bhat   if (bytes == 0)
313a90be207SSiddharth Bhat     bytes = T->getScalarSizeInBits() / 8;
314a90be207SSiddharth Bhat   return bytes;
315a90be207SSiddharth Bhat }
316a90be207SSiddharth Bhat 
31738fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
31838fc0aedSTobias Grosser ///
31938fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
320a6d48f59SMichael Kruse /// generates code for general-purpose AST nodes, with special functionality
32138fc0aedSTobias Grosser /// for generating GPU specific user nodes.
32238fc0aedSTobias Grosser ///
32338fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
32438fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
32538fc0aedSTobias Grosser public:
3262d950f36SPhilip Pfaffe   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator,
32738fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
328acf80064SEli Friedman                  DominatorTree &DT, Scop &S, BasicBlock *StartBlock,
32917f01968SSiddharth Bhat                  gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch)
3302d950f36SPhilip Pfaffe       : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock),
33117f01968SSiddharth Bhat         Prog(Prog), Runtime(Runtime), Arch(Arch) {
332edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
333edb885cbSTobias Grosser   }
33438fc0aedSTobias Grosser 
335fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
336fa7b0802STobias Grosser   void initializeAfterRTH();
337fa7b0802STobias Grosser 
338fa7b0802STobias Grosser   /// Finalize the generated scop.
339fa7b0802STobias Grosser   virtual void finalize();
340fa7b0802STobias Grosser 
3415857b701STobias Grosser   /// Track if the full build process was successful.
3425857b701STobias Grosser   ///
3435857b701STobias Grosser   /// This value is set to false, if throughout the build process an error
3445857b701STobias Grosser   /// occurred which prevents us from generating valid GPU code.
3455857b701STobias Grosser   bool BuildSuccessful = true;
3465857b701STobias Grosser 
347bc653f20STobias Grosser   /// The maximal number of loops surrounding a sequential kernel.
348bc653f20STobias Grosser   unsigned DeepestSequential = 0;
349bc653f20STobias Grosser 
350bc653f20STobias Grosser   /// The maximal number of loops surrounding a parallel kernel.
351bc653f20STobias Grosser   unsigned DeepestParallel = 0;
352bc653f20STobias Grosser 
35379f13b9aSSingapuram Sanjay Srivallabh   /// Return the name to set for the ptx_kernel.
35479f13b9aSSingapuram Sanjay Srivallabh   std::string getKernelFuncName(int Kernel_id);
35579f13b9aSSingapuram Sanjay Srivallabh 
35638fc0aedSTobias Grosser private:
35774dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
35874dc3cb4STobias Grosser   ///
35974dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
36074dc3cb4STobias Grosser   /// more.
36174dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
36274dc3cb4STobias Grosser 
36313c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
36413c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
3657287aeddSTobias Grosser 
366fa7b0802STobias Grosser   /// The current GPU context.
367fa7b0802STobias Grosser   Value *GPUContext;
368fa7b0802STobias Grosser 
369b513b491STobias Grosser   /// The set of isl_ids allocated in the kernel
370b513b491STobias Grosser   std::vector<isl_id *> KernelIds;
371b513b491STobias Grosser 
37232837fe3STobias Grosser   /// A module containing GPU code.
37332837fe3STobias Grosser   ///
37432837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
37532837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
37632837fe3STobias Grosser 
37732837fe3STobias Grosser   /// The GPU program we generate code for.
37832837fe3STobias Grosser   gpu_prog *Prog;
37932837fe3STobias Grosser 
38017f01968SSiddharth Bhat   /// The GPU Runtime implementation to use (OpenCL or CUDA).
38117f01968SSiddharth Bhat   GPURuntime Runtime;
38217f01968SSiddharth Bhat 
38317f01968SSiddharth Bhat   /// The GPU Architecture to target.
38417f01968SSiddharth Bhat   GPUArch Arch;
38517f01968SSiddharth Bhat 
386472f9654STobias Grosser   /// Class to free isl_ids.
387472f9654STobias Grosser   class IslIdDeleter {
388472f9654STobias Grosser   public:
389472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
390472f9654STobias Grosser   };
391472f9654STobias Grosser 
392472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
393472f9654STobias Grosser   ///
394472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
395472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
396472f9654STobias Grosser 
397edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
398edb885cbSTobias Grosser 
39938fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
40038fc0aedSTobias Grosser   ///
40138fc0aedSTobias Grosser   /// These AST nodes can be of type:
40238fc0aedSTobias Grosser   ///
40338fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
40438fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
40513c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
4065260c041STobias Grosser   ///   - In-kernel synchronization
4075260c041STobias Grosser   ///   - In-kernel memory copy statement
40838fc0aedSTobias Grosser   ///
4091fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
4101fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
41132837fe3STobias Grosser 
41253c80387SPhilip Pfaffe   virtual void createFor(__isl_take isl_ast_node *Node);
41353c80387SPhilip Pfaffe 
41413c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
41513c78e4dSTobias Grosser 
41613c78e4dSTobias Grosser   /// Create code for a data transfer statement
41713c78e4dSTobias Grosser   ///
41813c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
41913c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
42013c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
42113c78e4dSTobias Grosser                           enum DataDirection Direction);
42213c78e4dSTobias Grosser 
423edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
424edb885cbSTobias Grosser   ///
425edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
426edb885cbSTobias Grosser   ///
427e53c924bSSiddharth Bhat   /// @returns A tuple, whose:
428e53c924bSSiddharth Bhat   ///          - First element contains the set of values referenced by the
429e53c924bSSiddharth Bhat   ///            kernel
430e53c924bSSiddharth Bhat   ///          - Second element contains the set of functions referenced by the
431e53c924bSSiddharth Bhat   ///             kernel. All functions in the set satisfy
432e53c924bSSiddharth Bhat   ///             `isValidFunctionInKernel`.
433e53c924bSSiddharth Bhat   ///          - Third element contains loops that have induction variables
434e53c924bSSiddharth Bhat   ///            which are used in the kernel, *and* these loops are *neither*
435e53c924bSSiddharth Bhat   ///            in the scop, nor do they immediately surroung the Scop.
436e53c924bSSiddharth Bhat   ///            See [Code generation of induction variables of loops outside
437e53c924bSSiddharth Bhat   ///            Scops]
43843df2020STobias Grosser   std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>,
43943df2020STobias Grosser              isl::space>
440f291c8d5SSiddharth Bhat   getReferencesInKernel(ppcg_kernel *Kernel);
441edb885cbSTobias Grosser 
44279a947c2STobias Grosser   /// Compute the sizes of the execution grid for a given kernel.
44379a947c2STobias Grosser   ///
44479a947c2STobias Grosser   /// @param Kernel The kernel to compute grid sizes for.
44579a947c2STobias Grosser   ///
44679a947c2STobias Grosser   /// @returns A tuple with grid sizes for X and Y dimension
44779a947c2STobias Grosser   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
44879a947c2STobias Grosser 
449b99c1171STobias Grosser   /// Get the managed array pointer for sending host pointers to the device.
450abed4969SSiddharth Bhat   /// \note
451abed4969SSiddharth Bhat   /// This is to be used only with managed memory
452b99c1171STobias Grosser   Value *getManagedDeviceArray(gpu_array_info *Array, ScopArrayInfo *ArrayInfo);
453abed4969SSiddharth Bhat 
45479a947c2STobias Grosser   /// Compute the sizes of the thread blocks for a given kernel.
45579a947c2STobias Grosser   ///
45679a947c2STobias Grosser   /// @param Kernel The kernel to compute thread block sizes for.
45779a947c2STobias Grosser   ///
45879a947c2STobias Grosser   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
45979a947c2STobias Grosser   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
46079a947c2STobias Grosser 
461a90be207SSiddharth Bhat   /// Store a specific kernel launch parameter in the array of kernel launch
462a90be207SSiddharth Bhat   /// parameters.
463a90be207SSiddharth Bhat   ///
464a90be207SSiddharth Bhat   /// @param Parameters The list of parameters in which to store.
465a90be207SSiddharth Bhat   /// @param Param      The kernel launch parameter to store.
466a90be207SSiddharth Bhat   /// @param Index      The index in the parameter list, at which to store the
467a90be207SSiddharth Bhat   ///                   parameter.
468a90be207SSiddharth Bhat   void insertStoreParameter(Instruction *Parameters, Instruction *Param,
469a90be207SSiddharth Bhat                             int Index);
470a90be207SSiddharth Bhat 
47179a947c2STobias Grosser   /// Create kernel launch parameters.
47279a947c2STobias Grosser   ///
47379a947c2STobias Grosser   /// @param Kernel        The kernel to create parameters for.
47479a947c2STobias Grosser   /// @param F             The kernel function that has been created.
47557693272STobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
47679a947c2STobias Grosser   ///
47779a947c2STobias Grosser   /// @returns A stack allocated array with pointers to the parameter
47879a947c2STobias Grosser   ///          values that are passed to the kernel.
47957693272STobias Grosser   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
48057693272STobias Grosser                                 SetVector<Value *> SubtreeValues);
48179a947c2STobias Grosser 
482b513b491STobias Grosser   /// Create declarations for kernel variable.
483b513b491STobias Grosser   ///
484b513b491STobias Grosser   /// This includes shared memory declarations.
485b513b491STobias Grosser   ///
486b513b491STobias Grosser   /// @param Kernel        The kernel definition to create variables for.
487b513b491STobias Grosser   /// @param FN            The function into which to generate the variables.
488b513b491STobias Grosser   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
489b513b491STobias Grosser 
490c1c6a2a6STobias Grosser   /// Add CUDA annotations to module.
491c1c6a2a6STobias Grosser   ///
492c1c6a2a6STobias Grosser   /// Add a set of CUDA annotations that declares the maximal block dimensions
493c1c6a2a6STobias Grosser   /// that will be used to execute the CUDA kernel. This allows the NVIDIA
494c1c6a2a6STobias Grosser   /// PTX compiler to bound the number of allocated registers to ensure the
495c1c6a2a6STobias Grosser   /// resulting kernel is known to run with up to as many block dimensions
496c1c6a2a6STobias Grosser   /// as specified here.
497c1c6a2a6STobias Grosser   ///
498c1c6a2a6STobias Grosser   /// @param M         The module to add the annotations to.
499c1c6a2a6STobias Grosser   /// @param BlockDimX The size of block dimension X.
500c1c6a2a6STobias Grosser   /// @param BlockDimY The size of block dimension Y.
501c1c6a2a6STobias Grosser   /// @param BlockDimZ The size of block dimension Z.
502c1c6a2a6STobias Grosser   void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY,
503c1c6a2a6STobias Grosser                           Value *BlockDimZ);
504c1c6a2a6STobias Grosser 
50532837fe3STobias Grosser   /// Create GPU kernel.
50632837fe3STobias Grosser   ///
50732837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
50832837fe3STobias Grosser   ///
50932837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
51032837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
51132837fe3STobias Grosser 
51213c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
51313c78e4dSTobias Grosser   ///
51413c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
51513c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
51613c78e4dSTobias Grosser 
517aaabbbf8STobias Grosser   /// Generate code to compute the minimal offset at which an array is accessed.
518aaabbbf8STobias Grosser   ///
519aaabbbf8STobias Grosser   /// The offset of an array is the minimal array location accessed in a scop.
520aaabbbf8STobias Grosser   ///
521aaabbbf8STobias Grosser   /// Example:
522aaabbbf8STobias Grosser   ///
523aaabbbf8STobias Grosser   ///   for (long i = 0; i < 100; i++)
524aaabbbf8STobias Grosser   ///     A[i + 42] += ...
525aaabbbf8STobias Grosser   ///
526aaabbbf8STobias Grosser   ///   getArrayOffset(A) results in 42.
527aaabbbf8STobias Grosser   ///
528aaabbbf8STobias Grosser   /// @param Array The array for which to compute the offset.
529aaabbbf8STobias Grosser   /// @returns An llvm::Value that contains the offset of the array.
530aaabbbf8STobias Grosser   Value *getArrayOffset(gpu_array_info *Array);
531aaabbbf8STobias Grosser 
53200bb5a99STobias Grosser   /// Prepare the kernel arguments for kernel code generation
53300bb5a99STobias Grosser   ///
53400bb5a99STobias Grosser   /// @param Kernel The kernel to generate code for.
53500bb5a99STobias Grosser   /// @param FN     The function created for the kernel.
53600bb5a99STobias Grosser   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
53700bb5a99STobias Grosser 
53832837fe3STobias Grosser   /// Create kernel function.
53932837fe3STobias Grosser   ///
54032837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
54132837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
54232837fe3STobias Grosser   /// start block of this newly created function.
54332837fe3STobias Grosser   ///
54432837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
545edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
546f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by this
547f291c8d5SSiddharth Bhat   ///                         kernel.
548edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
549f291c8d5SSiddharth Bhat                             SetVector<Value *> &SubtreeValues,
550f291c8d5SSiddharth Bhat                             SetVector<Function *> &SubtreeFunctions);
55132837fe3STobias Grosser 
55232837fe3STobias Grosser   /// Create the declaration of a kernel function.
55332837fe3STobias Grosser   ///
55432837fe3STobias Grosser   /// The kernel function takes as arguments:
55532837fe3STobias Grosser   ///
55632837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
557f6044bd0STobias Grosser   ///   - Host iterators
558c84a1995STobias Grosser   ///   - Parameters
55932837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
56032837fe3STobias Grosser   ///
56132837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
562edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
563edb885cbSTobias Grosser   ///
56432837fe3STobias Grosser   /// @returns The newly declared function.
565edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
566edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
56732837fe3STobias Grosser 
568472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
569472f9654STobias Grosser   ///
570472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
571472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
572472f9654STobias Grosser 
5732f3073b5SPhilipp Schaad   /// Insert function calls to retrieve the SPIR group/local ids.
5742f3073b5SPhilipp Schaad   ///
575d71493cbSPhilip Pfaffe   /// @param Kernel The kernel to generate the function calls for.
576d71493cbSPhilip Pfaffe   /// @param SizeTypeIs64Bit Whether size_t of the openCl device is 64bit.
577d71493cbSPhilip Pfaffe   void insertKernelCallsSPIR(ppcg_kernel *Kernel, bool SizeTypeIs64bit);
5782f3073b5SPhilipp Schaad 
579f291c8d5SSiddharth Bhat   /// Setup the creation of functions referenced by the GPU kernel.
580f291c8d5SSiddharth Bhat   ///
581f291c8d5SSiddharth Bhat   /// 1. Create new function declarations in GPUModule which are the same as
582f291c8d5SSiddharth Bhat   /// SubtreeFunctions.
583f291c8d5SSiddharth Bhat   ///
584f291c8d5SSiddharth Bhat   /// 2. Populate IslNodeBuilder::ValueMap with mappings from
585f291c8d5SSiddharth Bhat   /// old functions (that come from the original module) to new functions
586f291c8d5SSiddharth Bhat   /// (that are created within GPUModule). That way, we generate references
587f291c8d5SSiddharth Bhat   /// to the correct function (in GPUModule) in BlockGenerator.
588f291c8d5SSiddharth Bhat   ///
589f291c8d5SSiddharth Bhat   /// @see IslNodeBuilder::ValueMap
590f291c8d5SSiddharth Bhat   /// @see BlockGenerator::GlobalMap
591f291c8d5SSiddharth Bhat   /// @see BlockGenerator::getNewValue
592f291c8d5SSiddharth Bhat   /// @see GPUNodeBuilder::getReferencesInKernel.
593f291c8d5SSiddharth Bhat   ///
594f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by
595f291c8d5SSiddharth Bhat   ///                         this kernel.
596f291c8d5SSiddharth Bhat   void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions);
597f291c8d5SSiddharth Bhat 
598b513b491STobias Grosser   /// Create a global-to-shared or shared-to-global copy statement.
599b513b491STobias Grosser   ///
600b513b491STobias Grosser   /// @param CopyStmt The copy statement to generate code for
601b513b491STobias Grosser   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
602b513b491STobias Grosser 
603edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
604edb885cbSTobias Grosser   ///
605edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
606edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
607edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
608edb885cbSTobias Grosser 
6095260c041STobias Grosser   /// Create an in-kernel synchronization call.
6105260c041STobias Grosser   void createKernelSync();
6115260c041STobias Grosser 
61274dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
61374dc3cb4STobias Grosser   ///
61474dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
61574dc3cb4STobias Grosser   std::string createKernelASM();
61674dc3cb4STobias Grosser 
61774dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
61874dc3cb4STobias Grosser   ///
61974dc3cb4STobias Grosser   /// @param F The function to remove references to.
62074dc3cb4STobias Grosser   void clearDominators(Function *F);
62174dc3cb4STobias Grosser 
62274dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
62374dc3cb4STobias Grosser   ///
62474dc3cb4STobias Grosser   /// @param F The function to remove references to.
62574dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
62674dc3cb4STobias Grosser 
62774dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
62874dc3cb4STobias Grosser   ///
62974dc3cb4STobias Grosser   /// @param F The function to remove references to.
63074dc3cb4STobias Grosser   void clearLoops(Function *F);
63174dc3cb4STobias Grosser 
6328fc6cdfbSTobias Grosser   /// Check if the scop requires to be linked with CUDA's libdevice.
6338fc6cdfbSTobias Grosser   bool requiresCUDALibDevice();
6348fc6cdfbSTobias Grosser 
6358fc6cdfbSTobias Grosser   /// Link with the NVIDIA libdevice library (if needed and available).
6368fc6cdfbSTobias Grosser   void addCUDALibDevice();
6378fc6cdfbSTobias Grosser 
63832837fe3STobias Grosser   /// Finalize the generation of the kernel function.
63932837fe3STobias Grosser   ///
64032837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
64132837fe3STobias Grosser   /// dump its IR to stderr.
64257793596STobias Grosser   ///
64357793596STobias Grosser   /// @returns The Assembly string of the kernel.
64457793596STobias Grosser   std::string finalizeKernelFunction();
645fa7b0802STobias Grosser 
64651dfc275STobias Grosser   /// Finalize the generation of the kernel arguments.
64751dfc275STobias Grosser   ///
64851dfc275STobias Grosser   /// This function ensures that not-read-only scalars used in a kernel are
649a6d48f59SMichael Kruse   /// stored back to the global memory location they are backed with before
65051dfc275STobias Grosser   /// the kernel terminates.
65151dfc275STobias Grosser   ///
65251dfc275STobias Grosser   /// @params Kernel The kernel to finalize kernel arguments for.
65351dfc275STobias Grosser   void finalizeKernelArguments(ppcg_kernel *Kernel);
65451dfc275STobias Grosser 
6557287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
656fa7b0802STobias Grosser   void allocateDeviceArrays();
657fa7b0802STobias Grosser 
658b99c1171STobias Grosser   /// Create code to prepare the managed device pointers.
659b99c1171STobias Grosser   void prepareManagedDeviceArrays();
660b99c1171STobias Grosser 
6617287aeddSTobias Grosser   /// Free all allocated device arrays.
6627287aeddSTobias Grosser   void freeDeviceArrays();
6637287aeddSTobias Grosser 
664fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
665fa7b0802STobias Grosser   ///
666fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
667fa7b0802STobias Grosser   Value *createCallInitContext();
668fa7b0802STobias Grosser 
66979a947c2STobias Grosser   /// Create a call to get the device pointer for a kernel allocation.
67079a947c2STobias Grosser   ///
67179a947c2STobias Grosser   /// @param Allocation The Polly GPU allocation
67279a947c2STobias Grosser   ///
67379a947c2STobias Grosser   /// @returns The device parameter corresponding to this allocation.
67479a947c2STobias Grosser   Value *createCallGetDevicePtr(Value *Allocation);
67579a947c2STobias Grosser 
676fa7b0802STobias Grosser   /// Create a call to free the GPU context.
677fa7b0802STobias Grosser   ///
678fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
679fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
680fa7b0802STobias Grosser 
6817287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
6827287aeddSTobias Grosser   ///
6837287aeddSTobias Grosser   /// @param Size The size of memory to allocate
6847287aeddSTobias Grosser   ///
6857287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
686fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
6877287aeddSTobias Grosser 
6887287aeddSTobias Grosser   /// Create a call to free a device array.
6897287aeddSTobias Grosser   ///
6907287aeddSTobias Grosser   /// @param Array The device array to free.
6917287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
69213c78e4dSTobias Grosser 
69313c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
69413c78e4dSTobias Grosser   ///
69513c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
69613c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
69713c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
69813c78e4dSTobias Grosser                                       Value *Size);
69913c78e4dSTobias Grosser 
70013c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
70113c78e4dSTobias Grosser   ///
70213c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
70313c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
70413c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
70513c78e4dSTobias Grosser                                       Value *Size);
70657793596STobias Grosser 
707abed4969SSiddharth Bhat   /// Create a call to synchronize Host & Device.
708abed4969SSiddharth Bhat   /// \note
709abed4969SSiddharth Bhat   /// This is to be used only with managed memory.
710abed4969SSiddharth Bhat   void createCallSynchronizeDevice();
711abed4969SSiddharth Bhat 
71257793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
71357793596STobias Grosser   ///
71457793596STobias Grosser   /// @param Buffer The string describing the kernel.
71557793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
71657793596STobias Grosser   ///
71757793596STobias Grosser   /// @returns A pointer to a kernel object
71857793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
71957793596STobias Grosser 
72057793596STobias Grosser   /// Create a call to free a GPU kernel.
72157793596STobias Grosser   ///
72257793596STobias Grosser   /// @param GPUKernel THe kernel to free.
72357793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
72479a947c2STobias Grosser 
72579a947c2STobias Grosser   /// Create a call to launch a GPU kernel.
72679a947c2STobias Grosser   ///
72779a947c2STobias Grosser   /// @param GPUKernel  The kernel to launch.
72879a947c2STobias Grosser   /// @param GridDimX   The size of the first grid dimension.
72979a947c2STobias Grosser   /// @param GridDimY   The size of the second grid dimension.
73079a947c2STobias Grosser   /// @param GridBlockX The size of the first block dimension.
73179a947c2STobias Grosser   /// @param GridBlockY The size of the second block dimension.
73279a947c2STobias Grosser   /// @param GridBlockZ The size of the third block dimension.
733a6d48f59SMichael Kruse   /// @param Parameters A pointer to an array that contains itself pointers to
73479a947c2STobias Grosser   ///                   the parameter values passed for each kernel argument.
73579a947c2STobias Grosser   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
73679a947c2STobias Grosser                               Value *GridDimY, Value *BlockDimX,
73779a947c2STobias Grosser                               Value *BlockDimY, Value *BlockDimZ,
73879a947c2STobias Grosser                               Value *Parameters);
7391fb9b64dSTobias Grosser };
7401fb9b64dSTobias Grosser 
74179f13b9aSSingapuram Sanjay Srivallabh std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) {
7421abd9ffaSSingapuram Sanjay Srivallabh   return "FUNC_" + S.getFunction().getName().str() + "_SCOP_" +
7431abd9ffaSSingapuram Sanjay Srivallabh          std::to_string(S.getID()) + "_KERNEL_" + std::to_string(Kernel_id);
74479f13b9aSSingapuram Sanjay Srivallabh }
74579f13b9aSSingapuram Sanjay Srivallabh 
746fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
747750160e2STobias Grosser   BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(),
748750160e2STobias Grosser                                  &*Builder.GetInsertPoint(), &DT, &LI);
749750160e2STobias Grosser   NewBB->setName("polly.acc.initialize");
750750160e2STobias Grosser   Builder.SetInsertPoint(&NewBB->front());
751750160e2STobias Grosser 
752fa7b0802STobias Grosser   GPUContext = createCallInitContext();
753abed4969SSiddharth Bhat 
754c4a4af47SSiddharth Bhat   if (!PollyManagedMemory)
755fa7b0802STobias Grosser     allocateDeviceArrays();
756b99c1171STobias Grosser   else
757b99c1171STobias Grosser     prepareManagedDeviceArrays();
758fa7b0802STobias Grosser }
759fa7b0802STobias Grosser 
760fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
761c4a4af47SSiddharth Bhat   if (!PollyManagedMemory)
7627287aeddSTobias Grosser     freeDeviceArrays();
763abed4969SSiddharth Bhat 
764fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
765fa7b0802STobias Grosser   IslNodeBuilder::finalize();
766fa7b0802STobias Grosser }
767fa7b0802STobias Grosser 
768fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
769c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory &&
770c4a4af47SSiddharth Bhat          "Managed memory will directly send host pointers "
771abed4969SSiddharth Bhat          "to the kernel. There is no need for device arrays");
7728ea1fc19STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext().release());
773fa7b0802STobias Grosser 
774fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
775fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
77613c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
7777287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
7787287aeddSTobias Grosser     DevArrayName.append(Array->name);
779fa7b0802STobias Grosser 
78013c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
781aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(Array);
782aaabbbf8STobias Grosser     if (Offset)
783aaabbbf8STobias Grosser       ArraySize = Builder.CreateSub(
784aaabbbf8STobias Grosser           ArraySize,
785aaabbbf8STobias Grosser           Builder.CreateMul(Offset,
786aaabbbf8STobias Grosser                             Builder.getInt64(ScopArray->getElemSizeInBytes())));
78734eeabbcSSiddharth Bhat     const SCEV *SizeSCEV = SE.getSCEV(ArraySize);
78834eeabbcSSiddharth Bhat     // It makes no sense to have an array of size 0. The CUDA API will
78934eeabbcSSiddharth Bhat     // throw an error anyway if we invoke `cuMallocManaged` with size `0`. We
79034eeabbcSSiddharth Bhat     // choose to be defensive and catch this at the compile phase. It is
79134eeabbcSSiddharth Bhat     // most likely that we are doing something wrong with size computation.
79234eeabbcSSiddharth Bhat     if (SizeSCEV->isZero()) {
79334eeabbcSSiddharth Bhat       errs() << getUniqueScopName(&S)
79434eeabbcSSiddharth Bhat              << " has computed array size 0: " << *ArraySize
79534eeabbcSSiddharth Bhat              << " | for array: " << *(ScopArray->getBasePtr())
79634eeabbcSSiddharth Bhat              << ". This is illegal, exiting.\n";
79734eeabbcSSiddharth Bhat       report_fatal_error("array size was computed to be 0");
79834eeabbcSSiddharth Bhat     }
79934eeabbcSSiddharth Bhat 
8007287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
8017287aeddSTobias Grosser     DevArray->setName(DevArrayName);
80213c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
803fa7b0802STobias Grosser   }
804fa7b0802STobias Grosser 
805fa7b0802STobias Grosser   isl_ast_build_free(Build);
806fa7b0802STobias Grosser }
807fa7b0802STobias Grosser 
808b99c1171STobias Grosser void GPUNodeBuilder::prepareManagedDeviceArrays() {
809c4a4af47SSiddharth Bhat   assert(PollyManagedMemory &&
810b99c1171STobias Grosser          "Device array most only be prepared in managed-memory mode");
811b99c1171STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
812b99c1171STobias Grosser     gpu_array_info *Array = &Prog->array[i];
813b99c1171STobias Grosser     ScopArrayInfo *ScopArray = (ScopArrayInfo *)Array->user;
814b99c1171STobias Grosser     Value *HostPtr;
815b99c1171STobias Grosser 
816b99c1171STobias Grosser     if (gpu_array_is_scalar(Array))
817b99c1171STobias Grosser       HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
818b99c1171STobias Grosser     else
819b99c1171STobias Grosser       HostPtr = ScopArray->getBasePtr();
820b99c1171STobias Grosser     HostPtr = getLatestValue(HostPtr);
821b99c1171STobias Grosser 
822b99c1171STobias Grosser     Value *Offset = getArrayOffset(Array);
823b99c1171STobias Grosser     if (Offset) {
824b99c1171STobias Grosser       HostPtr = Builder.CreatePointerCast(
825b99c1171STobias Grosser           HostPtr, ScopArray->getElementType()->getPointerTo());
826b99c1171STobias Grosser       HostPtr = Builder.CreateGEP(HostPtr, Offset);
827b99c1171STobias Grosser     }
828b99c1171STobias Grosser 
829b99c1171STobias Grosser     HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
830b99c1171STobias Grosser     DeviceAllocations[ScopArray] = HostPtr;
831b99c1171STobias Grosser   }
832b99c1171STobias Grosser }
833b99c1171STobias Grosser 
834c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX,
835c1c6a2a6STobias Grosser                                         Value *BlockDimY, Value *BlockDimZ) {
836c1c6a2a6STobias Grosser   auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations");
837c1c6a2a6STobias Grosser 
838c1c6a2a6STobias Grosser   for (auto &F : *M) {
839c1c6a2a6STobias Grosser     if (F.getCallingConv() != CallingConv::PTX_Kernel)
840c1c6a2a6STobias Grosser       continue;
841c1c6a2a6STobias Grosser 
842c1c6a2a6STobias Grosser     Value *V[] = {BlockDimX, BlockDimY, BlockDimZ};
843c1c6a2a6STobias Grosser 
844c1c6a2a6STobias Grosser     Metadata *Elements[] = {
845c1c6a2a6STobias Grosser         ValueAsMetadata::get(&F),   MDString::get(M->getContext(), "maxntidx"),
846c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"),
847c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"),
848c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[2]),
849c1c6a2a6STobias Grosser     };
850c1c6a2a6STobias Grosser     MDNode *Node = MDNode::get(M->getContext(), Elements);
851c1c6a2a6STobias Grosser     AnnotationNode->addOperand(Node);
852c1c6a2a6STobias Grosser   }
853c1c6a2a6STobias Grosser }
854c1c6a2a6STobias Grosser 
8557287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
856c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory && "Managed memory does not use device arrays");
85713c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
85813c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
8597287aeddSTobias Grosser }
8607287aeddSTobias Grosser 
86157793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
86257793596STobias Grosser   const char *Name = "polly_getKernel";
86357793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
86457793596STobias Grosser   Function *F = M->getFunction(Name);
86557793596STobias Grosser 
86657793596STobias Grosser   // If F is not available, declare it.
86757793596STobias Grosser   if (!F) {
86857793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
86957793596STobias Grosser     std::vector<Type *> Args;
87057793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
87157793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
87257793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
87357793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
87457793596STobias Grosser   }
87557793596STobias Grosser 
87657793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
87757793596STobias Grosser }
87857793596STobias Grosser 
87979a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
88079a947c2STobias Grosser   const char *Name = "polly_getDevicePtr";
88179a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
88279a947c2STobias Grosser   Function *F = M->getFunction(Name);
88379a947c2STobias Grosser 
88479a947c2STobias Grosser   // If F is not available, declare it.
88579a947c2STobias Grosser   if (!F) {
88679a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
88779a947c2STobias Grosser     std::vector<Type *> Args;
88879a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
88979a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
89079a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
89179a947c2STobias Grosser   }
89279a947c2STobias Grosser 
89379a947c2STobias Grosser   return Builder.CreateCall(F, {Allocation});
89479a947c2STobias Grosser }
89579a947c2STobias Grosser 
89679a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
89779a947c2STobias Grosser                                             Value *GridDimY, Value *BlockDimX,
89879a947c2STobias Grosser                                             Value *BlockDimY, Value *BlockDimZ,
89979a947c2STobias Grosser                                             Value *Parameters) {
90079a947c2STobias Grosser   const char *Name = "polly_launchKernel";
90179a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
90279a947c2STobias Grosser   Function *F = M->getFunction(Name);
90379a947c2STobias Grosser 
90479a947c2STobias Grosser   // If F is not available, declare it.
90579a947c2STobias Grosser   if (!F) {
90679a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
90779a947c2STobias Grosser     std::vector<Type *> Args;
90879a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
90979a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
91079a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
91179a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
91279a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
91379a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
91479a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
91579a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
91679a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
91779a947c2STobias Grosser   }
91879a947c2STobias Grosser 
919ff40087aSTobias Grosser   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
92079a947c2STobias Grosser                          BlockDimZ, Parameters});
92179a947c2STobias Grosser }
92279a947c2STobias Grosser 
92357793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
92457793596STobias Grosser   const char *Name = "polly_freeKernel";
92557793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
92657793596STobias Grosser   Function *F = M->getFunction(Name);
92757793596STobias Grosser 
92857793596STobias Grosser   // If F is not available, declare it.
92957793596STobias Grosser   if (!F) {
93057793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
93157793596STobias Grosser     std::vector<Type *> Args;
93257793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
93357793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
93457793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
93557793596STobias Grosser   }
93657793596STobias Grosser 
93757793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
93857793596STobias Grosser }
93957793596STobias Grosser 
9407287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
941c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory &&
942c4a4af47SSiddharth Bhat          "Managed memory does not allocate or free memory "
943abed4969SSiddharth Bhat          "for device");
9447287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
9457287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9467287aeddSTobias Grosser   Function *F = M->getFunction(Name);
9477287aeddSTobias Grosser 
9487287aeddSTobias Grosser   // If F is not available, declare it.
9497287aeddSTobias Grosser   if (!F) {
9507287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
9517287aeddSTobias Grosser     std::vector<Type *> Args;
9527287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
9537287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
9547287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
9557287aeddSTobias Grosser   }
9567287aeddSTobias Grosser 
9577287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
9587287aeddSTobias Grosser }
9597287aeddSTobias Grosser 
960fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
961c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory &&
962c4a4af47SSiddharth Bhat          "Managed memory does not allocate or free memory "
963abed4969SSiddharth Bhat          "for device");
964fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
965fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
966fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
967fa7b0802STobias Grosser 
968fa7b0802STobias Grosser   // If F is not available, declare it.
969fa7b0802STobias Grosser   if (!F) {
970fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
971fa7b0802STobias Grosser     std::vector<Type *> Args;
972fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
973fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
974fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
975fa7b0802STobias Grosser   }
976fa7b0802STobias Grosser 
977fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
978fa7b0802STobias Grosser }
979fa7b0802STobias Grosser 
98013c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
98113c78e4dSTobias Grosser                                                     Value *DeviceData,
98213c78e4dSTobias Grosser                                                     Value *Size) {
983c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory &&
984c4a4af47SSiddharth Bhat          "Managed memory does not transfer memory between "
985abed4969SSiddharth Bhat          "device and host");
98613c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
98713c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
98813c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
98913c78e4dSTobias Grosser 
99013c78e4dSTobias Grosser   // If F is not available, declare it.
99113c78e4dSTobias Grosser   if (!F) {
99213c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
99313c78e4dSTobias Grosser     std::vector<Type *> Args;
99413c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
99513c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
99613c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
99713c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
99813c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
99913c78e4dSTobias Grosser   }
100013c78e4dSTobias Grosser 
100113c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
100213c78e4dSTobias Grosser }
100313c78e4dSTobias Grosser 
100413c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
100513c78e4dSTobias Grosser                                                     Value *HostData,
100613c78e4dSTobias Grosser                                                     Value *Size) {
1007c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory &&
1008c4a4af47SSiddharth Bhat          "Managed memory does not transfer memory between "
1009abed4969SSiddharth Bhat          "device and host");
101013c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
101113c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
101213c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
101313c78e4dSTobias Grosser 
101413c78e4dSTobias Grosser   // If F is not available, declare it.
101513c78e4dSTobias Grosser   if (!F) {
101613c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
101713c78e4dSTobias Grosser     std::vector<Type *> Args;
101813c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
101913c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
102013c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
102113c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
102213c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
102313c78e4dSTobias Grosser   }
102413c78e4dSTobias Grosser 
102513c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
102613c78e4dSTobias Grosser }
102713c78e4dSTobias Grosser 
1028abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() {
1029c4a4af47SSiddharth Bhat   assert(PollyManagedMemory && "explicit synchronization is only necessary for "
1030abed4969SSiddharth Bhat                                "managed memory");
1031abed4969SSiddharth Bhat   const char *Name = "polly_synchronizeDevice";
1032abed4969SSiddharth Bhat   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1033abed4969SSiddharth Bhat   Function *F = M->getFunction(Name);
1034abed4969SSiddharth Bhat 
1035abed4969SSiddharth Bhat   // If F is not available, declare it.
1036abed4969SSiddharth Bhat   if (!F) {
1037abed4969SSiddharth Bhat     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1038abed4969SSiddharth Bhat     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
1039abed4969SSiddharth Bhat     F = Function::Create(Ty, Linkage, Name, M);
1040abed4969SSiddharth Bhat   }
1041abed4969SSiddharth Bhat 
1042abed4969SSiddharth Bhat   Builder.CreateCall(F);
1043abed4969SSiddharth Bhat }
1044abed4969SSiddharth Bhat 
1045fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
104617f01968SSiddharth Bhat   const char *Name;
104717f01968SSiddharth Bhat 
104817f01968SSiddharth Bhat   switch (Runtime) {
104917f01968SSiddharth Bhat   case GPURuntime::CUDA:
105017f01968SSiddharth Bhat     Name = "polly_initContextCUDA";
105117f01968SSiddharth Bhat     break;
105217f01968SSiddharth Bhat   case GPURuntime::OpenCL:
105317f01968SSiddharth Bhat     Name = "polly_initContextCL";
105417f01968SSiddharth Bhat     break;
105517f01968SSiddharth Bhat   }
105617f01968SSiddharth Bhat 
1057fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1058fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
1059fa7b0802STobias Grosser 
1060fa7b0802STobias Grosser   // If F is not available, declare it.
1061fa7b0802STobias Grosser   if (!F) {
1062fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1063fa7b0802STobias Grosser     std::vector<Type *> Args;
1064fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
1065fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
1066fa7b0802STobias Grosser   }
1067fa7b0802STobias Grosser 
1068fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
1069fa7b0802STobias Grosser }
1070fa7b0802STobias Grosser 
1071fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
1072fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
1073fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1074fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
1075fa7b0802STobias Grosser 
1076fa7b0802STobias Grosser   // If F is not available, declare it.
1077fa7b0802STobias Grosser   if (!F) {
1078fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1079fa7b0802STobias Grosser     std::vector<Type *> Args;
1080fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
1081fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
1082fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
1083fa7b0802STobias Grosser   }
1084fa7b0802STobias Grosser 
1085fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
1086fa7b0802STobias Grosser }
1087fa7b0802STobias Grosser 
10885260c041STobias Grosser /// Check if one string is a prefix of another.
10895260c041STobias Grosser ///
10905260c041STobias Grosser /// @param String The string in which to look for the prefix.
10915260c041STobias Grosser /// @param Prefix The prefix to look for.
10925260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
10935260c041STobias Grosser   return String.find(Prefix) == 0;
10945260c041STobias Grosser }
10955260c041STobias Grosser 
109613c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
1097b65ccc43STobias Grosser   isl::ast_build Build = isl::ast_build::from_context(S.getContext());
109813c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
109913c78e4dSTobias Grosser 
110013c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
1101718d04c6STobias Grosser     isl::multi_pw_aff ArrayBound = isl::manage_copy(Array->bound);
1102f7face4bSSiddharth Bhat 
1103f7face4bSSiddharth Bhat     isl::pw_aff OffsetDimZero = ArrayBound.get_pw_aff(0);
1104f7face4bSSiddharth Bhat     isl::ast_expr Res = Build.expr_from(OffsetDimZero);
110513c78e4dSTobias Grosser 
110613c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
1107f7face4bSSiddharth Bhat       isl::pw_aff Bound_I = ArrayBound.get_pw_aff(i);
1108f7face4bSSiddharth Bhat       isl::ast_expr Expr = Build.expr_from(Bound_I);
1109f7face4bSSiddharth Bhat       Res = Res.mul(Expr);
111013c78e4dSTobias Grosser     }
111113c78e4dSTobias Grosser 
1112f7face4bSSiddharth Bhat     Value *NumElements = ExprBuilder.create(Res.release());
1113b79f4d39STobias Grosser     if (NumElements->getType() != ArraySize->getType())
1114b79f4d39STobias Grosser       NumElements = Builder.CreateSExt(NumElements, ArraySize->getType());
111513c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
111613c78e4dSTobias Grosser   }
111713c78e4dSTobias Grosser   return ArraySize;
111813c78e4dSTobias Grosser }
111913c78e4dSTobias Grosser 
1120aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) {
1121aaabbbf8STobias Grosser   if (gpu_array_is_scalar(Array))
1122aaabbbf8STobias Grosser     return nullptr;
1123aaabbbf8STobias Grosser 
1124b65ccc43STobias Grosser   isl::ast_build Build = isl::ast_build::from_context(S.getContext());
1125aaabbbf8STobias Grosser 
1126718d04c6STobias Grosser   isl::set Min = isl::manage_copy(Array->extent).lexmin();
1127aaabbbf8STobias Grosser 
1128ccbf4b50SSiddharth Bhat   isl::set ZeroSet = isl::set::universe(Min.get_space());
1129aaabbbf8STobias Grosser 
11303044dc51SMichael Kruse   for (long i = 0, n = Min.dim(isl::dim::set); i < n; i++)
1131ccbf4b50SSiddharth Bhat     ZeroSet = ZeroSet.fix_si(isl::dim::set, i, 0);
1132aaabbbf8STobias Grosser 
1133ccbf4b50SSiddharth Bhat   if (Min.is_subset(ZeroSet)) {
1134aaabbbf8STobias Grosser     return nullptr;
1135aaabbbf8STobias Grosser   }
1136aaabbbf8STobias Grosser 
1137ccbf4b50SSiddharth Bhat   isl::ast_expr Result = isl::ast_expr::from_val(isl::val(Min.get_ctx(), 0));
1138aaabbbf8STobias Grosser 
11393044dc51SMichael Kruse   for (long i = 0, n = Min.dim(isl::dim::set); i < n; i++) {
1140aaabbbf8STobias Grosser     if (i > 0) {
1141ccbf4b50SSiddharth Bhat       isl::pw_aff Bound_I =
1142ccbf4b50SSiddharth Bhat           isl::manage(isl_multi_pw_aff_get_pw_aff(Array->bound, i - 1));
1143ccbf4b50SSiddharth Bhat       isl::ast_expr BExpr = Build.expr_from(Bound_I);
1144ccbf4b50SSiddharth Bhat       Result = Result.mul(BExpr);
1145aaabbbf8STobias Grosser     }
1146ccbf4b50SSiddharth Bhat     isl::pw_aff DimMin = Min.dim_min(i);
1147ccbf4b50SSiddharth Bhat     isl::ast_expr MExpr = Build.expr_from(DimMin);
1148ccbf4b50SSiddharth Bhat     Result = Result.add(MExpr);
1149aaabbbf8STobias Grosser   }
1150aaabbbf8STobias Grosser 
1151ccbf4b50SSiddharth Bhat   return ExprBuilder.create(Result.release());
1152aaabbbf8STobias Grosser }
1153aaabbbf8STobias Grosser 
1154b99c1171STobias Grosser Value *GPUNodeBuilder::getManagedDeviceArray(gpu_array_info *Array,
1155abed4969SSiddharth Bhat                                              ScopArrayInfo *ArrayInfo) {
1156c4a4af47SSiddharth Bhat   assert(PollyManagedMemory && "Only used when you wish to get a host "
1157abed4969SSiddharth Bhat                                "pointer for sending data to the kernel, "
1158abed4969SSiddharth Bhat                                "with managed memory");
1159abed4969SSiddharth Bhat   std::map<ScopArrayInfo *, Value *>::iterator it;
1160b99c1171STobias Grosser   it = DeviceAllocations.find(ArrayInfo);
1161b99c1171STobias Grosser   assert(it != DeviceAllocations.end() &&
1162b99c1171STobias Grosser          "Device array expected to be available");
1163abed4969SSiddharth Bhat   return it->second;
1164abed4969SSiddharth Bhat }
1165abed4969SSiddharth Bhat 
116613c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
116713c78e4dSTobias Grosser                                         enum DataDirection Direction) {
1168c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory && "Managed memory needs no data transfers");
116913c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
117013c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
117113c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
117213c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
117313c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
117413c78e4dSTobias Grosser 
117513c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
1176aaabbbf8STobias Grosser   Value *Offset = getArrayOffset(Array);
117713c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
117813c78e4dSTobias Grosser 
1179b06ff457STobias Grosser   Value *HostPtr;
1180b06ff457STobias Grosser 
1181b06ff457STobias Grosser   if (gpu_array_is_scalar(Array))
1182b06ff457STobias Grosser     HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
1183b06ff457STobias Grosser   else
1184b06ff457STobias Grosser     HostPtr = ScopArray->getBasePtr();
1185edf9581eSSiddharth Bhat   HostPtr = getLatestValue(HostPtr);
118613c78e4dSTobias Grosser 
1187aaabbbf8STobias Grosser   if (Offset) {
1188aaabbbf8STobias Grosser     HostPtr = Builder.CreatePointerCast(
1189aaabbbf8STobias Grosser         HostPtr, ScopArray->getElementType()->getPointerTo());
1190aaabbbf8STobias Grosser     HostPtr = Builder.CreateGEP(HostPtr, Offset);
1191aaabbbf8STobias Grosser   }
1192aaabbbf8STobias Grosser 
119313c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
119413c78e4dSTobias Grosser 
1195aaabbbf8STobias Grosser   if (Offset) {
1196aaabbbf8STobias Grosser     Size = Builder.CreateSub(
1197ff40087aSTobias Grosser         Size, Builder.CreateMul(
1198ff40087aSTobias Grosser                   Offset, Builder.getInt64(ScopArray->getElemSizeInBytes())));
1199aaabbbf8STobias Grosser   }
1200aaabbbf8STobias Grosser 
120113c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
120213c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
120313c78e4dSTobias Grosser   else
120413c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
120513c78e4dSTobias Grosser 
120613c78e4dSTobias Grosser   isl_id_free(Id);
120713c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
120813c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
120913c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
121013c78e4dSTobias Grosser }
121113c78e4dSTobias Grosser 
12121fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
121332837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
121432837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
121532837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
121632837fe3STobias Grosser   isl_id_free(Id);
121732837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
121832837fe3STobias Grosser 
121932837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
122032837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
122132837fe3STobias Grosser     createKernel(UserStmt);
122262acb344STobias Grosser     if (PollyManagedMemory)
122362acb344STobias Grosser       createCallSynchronizeDevice();
122432837fe3STobias Grosser     isl_ast_expr_free(Expr);
122532837fe3STobias Grosser     return;
122632837fe3STobias Grosser   }
12279e3db2b7SSiddharth Bhat   if (!strcmp(Str, "init_device")) {
12289e3db2b7SSiddharth Bhat     initializeAfterRTH();
12299e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
12309e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
12319e3db2b7SSiddharth Bhat     return;
12329e3db2b7SSiddharth Bhat   }
12339e3db2b7SSiddharth Bhat   if (!strcmp(Str, "clear_device")) {
12349e3db2b7SSiddharth Bhat     finalize();
12359e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
12369e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
12379e3db2b7SSiddharth Bhat     return;
12389e3db2b7SSiddharth Bhat   }
123913c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
1240c4a4af47SSiddharth Bhat     if (!PollyManagedMemory)
124113c78e4dSTobias Grosser       createDataTransfer(UserStmt, HOST_TO_DEVICE);
1242abed4969SSiddharth Bhat     else
1243abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1244abed4969SSiddharth Bhat 
124532837fe3STobias Grosser     isl_ast_expr_free(Expr);
124613c78e4dSTobias Grosser     return;
124713c78e4dSTobias Grosser   }
124813c78e4dSTobias Grosser 
124913c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
1250c4a4af47SSiddharth Bhat     if (!PollyManagedMemory) {
125113c78e4dSTobias Grosser       createDataTransfer(UserStmt, DEVICE_TO_HOST);
1252abed4969SSiddharth Bhat     } else {
1253abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1254abed4969SSiddharth Bhat     }
125513c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
125638fc0aedSTobias Grosser     return;
125738fc0aedSTobias Grosser   }
125838fc0aedSTobias Grosser 
12595260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
12605260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
12615260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
12625260c041STobias Grosser   isl_id_free(Anno);
12635260c041STobias Grosser 
12645260c041STobias Grosser   switch (KernelStmt->type) {
12655260c041STobias Grosser   case ppcg_kernel_domain:
1266edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
12675260c041STobias Grosser     isl_ast_node_free(UserStmt);
12685260c041STobias Grosser     return;
12695260c041STobias Grosser   case ppcg_kernel_copy:
1270b513b491STobias Grosser     createKernelCopy(KernelStmt);
12715260c041STobias Grosser     isl_ast_expr_free(Expr);
12725260c041STobias Grosser     isl_ast_node_free(UserStmt);
12735260c041STobias Grosser     return;
12745260c041STobias Grosser   case ppcg_kernel_sync:
12755260c041STobias Grosser     createKernelSync();
12765260c041STobias Grosser     isl_ast_expr_free(Expr);
12775260c041STobias Grosser     isl_ast_node_free(UserStmt);
12785260c041STobias Grosser     return;
12795260c041STobias Grosser   }
12805260c041STobias Grosser 
12815260c041STobias Grosser   isl_ast_expr_free(Expr);
12825260c041STobias Grosser   isl_ast_node_free(UserStmt);
12835260c041STobias Grosser }
128453c80387SPhilip Pfaffe 
128553c80387SPhilip Pfaffe void GPUNodeBuilder::createFor(__isl_take isl_ast_node *Node) {
128642ad8182SMichael Kruse   createForSequential(isl::manage(Node), false);
128753c80387SPhilip Pfaffe }
128853c80387SPhilip Pfaffe 
1289b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
1290b513b491STobias Grosser   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
1291b513b491STobias Grosser   LocalIndex = isl_ast_expr_address_of(LocalIndex);
1292b513b491STobias Grosser   Value *LocalAddr = ExprBuilder.create(LocalIndex);
1293b513b491STobias Grosser   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
1294b513b491STobias Grosser   Index = isl_ast_expr_address_of(Index);
1295b513b491STobias Grosser   Value *GlobalAddr = ExprBuilder.create(Index);
1296b513b491STobias Grosser 
1297b513b491STobias Grosser   if (KernelStmt->u.c.read) {
1298b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read");
1299b513b491STobias Grosser     Builder.CreateStore(Load, LocalAddr);
1300b513b491STobias Grosser   } else {
1301b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write");
1302b513b491STobias Grosser     Builder.CreateStore(Load, GlobalAddr);
1303b513b491STobias Grosser   }
1304b513b491STobias Grosser }
13055260c041STobias Grosser 
1306edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
1307edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
1308edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1309edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
1310edb885cbSTobias Grosser 
1311edb885cbSTobias Grosser   LoopToScevMapT LTS;
1312edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
1313edb885cbSTobias Grosser 
1314edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
1315edb885cbSTobias Grosser 
1316edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
1317edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
1318edb885cbSTobias Grosser   else
1319a82c4b5dSTobias Grosser     RegionGen.copyStmt(*Stmt, LTS, Indexes);
1320edb885cbSTobias Grosser }
1321edb885cbSTobias Grosser 
13225260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
13235260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13242f3073b5SPhilipp Schaad   const char *SpirName = "__gen_ocl_barrier_global";
132517f01968SSiddharth Bhat 
132617f01968SSiddharth Bhat   Function *Sync;
132717f01968SSiddharth Bhat 
132817f01968SSiddharth Bhat   switch (Arch) {
13292f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
13302f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
13312f3073b5SPhilipp Schaad     Sync = M->getFunction(SpirName);
13322f3073b5SPhilipp Schaad 
13332f3073b5SPhilipp Schaad     // If Sync is not available, declare it.
13342f3073b5SPhilipp Schaad     if (!Sync) {
13352f3073b5SPhilipp Schaad       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
13362f3073b5SPhilipp Schaad       std::vector<Type *> Args;
13372f3073b5SPhilipp Schaad       FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
13382f3073b5SPhilipp Schaad       Sync = Function::Create(Ty, Linkage, SpirName, M);
13392f3073b5SPhilipp Schaad       Sync->setCallingConv(CallingConv::SPIR_FUNC);
13402f3073b5SPhilipp Schaad     }
13412f3073b5SPhilipp Schaad     break;
134217f01968SSiddharth Bhat   case GPUArch::NVPTX64:
134317f01968SSiddharth Bhat     Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
134417f01968SSiddharth Bhat     break;
134517f01968SSiddharth Bhat   }
134617f01968SSiddharth Bhat 
13475260c041STobias Grosser   Builder.CreateCall(Sync, {});
13485260c041STobias Grosser }
13495260c041STobias Grosser 
1350edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
1351edb885cbSTobias Grosser ///
1352edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
1353edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
1354edb885cbSTobias Grosser ///
1355edb885cbSTobias Grosser /// @param Node The node to collect references for.
1356edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
1357edb885cbSTobias Grosser ///
1358edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
1359edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
1360edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
1361edb885cbSTobias Grosser     return isl_bool_true;
1362edb885cbSTobias Grosser 
1363edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
1364edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
1365edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
1366edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
1367edb885cbSTobias Grosser   isl_id_free(Id);
1368edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
1369edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
1370edb885cbSTobias Grosser 
1371edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
1372edb885cbSTobias Grosser     return isl_bool_true;
1373edb885cbSTobias Grosser 
1374edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
1375edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
1376edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1377edb885cbSTobias Grosser   isl_id_free(Id);
1378edb885cbSTobias Grosser 
137900bb5a99STobias Grosser   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
1380edb885cbSTobias Grosser 
1381edb885cbSTobias Grosser   return isl_bool_true;
1382edb885cbSTobias Grosser }
1383edb885cbSTobias Grosser 
13848fc6cdfbSTobias Grosser /// A list of functions that are available in NVIDIA's libdevice.
13858fc6cdfbSTobias Grosser const std::set<std::string> CUDALibDeviceFunctions = {
138656572c6aSSiddharth Bhat     "exp",      "expf",      "expl",      "cos", "cosf", "sqrt", "sqrtf",
138756572c6aSSiddharth Bhat     "copysign", "copysignf", "copysignl", "log", "logf", "powi", "powif"};
138856572c6aSSiddharth Bhat 
138956572c6aSSiddharth Bhat // A map from intrinsics to their corresponding libdevice functions.
139056572c6aSSiddharth Bhat const std::map<std::string, std::string> IntrinsicToLibdeviceFunc = {
139156572c6aSSiddharth Bhat     {"llvm.exp.f64", "exp"},
139256572c6aSSiddharth Bhat     {"llvm.exp.f32", "expf"},
139356572c6aSSiddharth Bhat     {"llvm.powi.f64", "powi"},
139456572c6aSSiddharth Bhat     {"llvm.powi.f32", "powif"}};
13958fc6cdfbSTobias Grosser 
139666a05ad6SPhilip Pfaffe /// Return the corresponding CUDA libdevice function name @p Name.
139756572c6aSSiddharth Bhat /// Note that this function will try to convert instrinsics in the list
139856572c6aSSiddharth Bhat /// IntrinsicToLibdeviceFunc into libdevice functions.
139956572c6aSSiddharth Bhat /// This is because some intrinsics such as `exp`
140056572c6aSSiddharth Bhat /// are not supported by the NVPTX backend.
140156572c6aSSiddharth Bhat /// If this restriction of the backend is lifted, we should refactor our code
140256572c6aSSiddharth Bhat /// so that we use intrinsics whenever possible.
14038fc6cdfbSTobias Grosser ///
14048fc6cdfbSTobias Grosser /// Return "" if we are not compiling for CUDA.
1405*1a53b732SMichael Kruse std::string getCUDALibDeviceFuntion(StringRef NameRef) {
1406*1a53b732SMichael Kruse   std::string Name = NameRef.str();
140766a05ad6SPhilip Pfaffe   auto It = IntrinsicToLibdeviceFunc.find(Name);
140856572c6aSSiddharth Bhat   if (It != IntrinsicToLibdeviceFunc.end())
140966a05ad6SPhilip Pfaffe     return getCUDALibDeviceFuntion(It->second);
141056572c6aSSiddharth Bhat 
141166a05ad6SPhilip Pfaffe   if (CUDALibDeviceFunctions.count(Name))
1412*1a53b732SMichael Kruse     return ("__nv_" + Name);
14138fc6cdfbSTobias Grosser 
14148fc6cdfbSTobias Grosser   return "";
14158fc6cdfbSTobias Grosser }
14168fc6cdfbSTobias Grosser 
1417f291c8d5SSiddharth Bhat /// Check if F is a function that we can code-generate in a GPU kernel.
14188fc6cdfbSTobias Grosser static bool isValidFunctionInKernel(llvm::Function *F, bool AllowLibDevice) {
1419f291c8d5SSiddharth Bhat   assert(F && "F is an invalid pointer");
1420f291c8d5SSiddharth Bhat   // We string compare against the name of the function to allow
142154491db6STobias Grosser   // all variants of the intrinsic "llvm.sqrt.*", "llvm.fabs", and
142254491db6STobias Grosser   // "llvm.copysign".
142354491db6STobias Grosser   const StringRef Name = F->getName();
14248fc6cdfbSTobias Grosser 
142566a05ad6SPhilip Pfaffe   if (AllowLibDevice && getCUDALibDeviceFuntion(Name).length() > 0)
14268fc6cdfbSTobias Grosser     return true;
14278fc6cdfbSTobias Grosser 
142854491db6STobias Grosser   return F->isIntrinsic() &&
142954491db6STobias Grosser          (Name.startswith("llvm.sqrt") || Name.startswith("llvm.fabs") ||
143056572c6aSSiddharth Bhat           Name.startswith("llvm.copysign"));
1431f291c8d5SSiddharth Bhat }
1432f291c8d5SSiddharth Bhat 
1433f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value.
1434f291c8d5SSiddharth Bhat ///
1435f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along
1436f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and
1437f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not
1438f291c8d5SSiddharth Bhat /// `Function`s.
1439f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); }
1440f291c8d5SSiddharth Bhat 
1441f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`.
1442f291c8d5SSiddharth Bhat static SetVector<Function *>
14438fc6cdfbSTobias Grosser getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues,
14448fc6cdfbSTobias Grosser                                  bool AllowCUDALibDevice) {
1445f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1446f291c8d5SSiddharth Bhat   for (Value *It : RawSubtreeValues) {
1447f291c8d5SSiddharth Bhat     Function *F = dyn_cast<Function>(It);
1448f291c8d5SSiddharth Bhat     if (F) {
14498fc6cdfbSTobias Grosser       assert(isValidFunctionInKernel(F, AllowCUDALibDevice) &&
14508fc6cdfbSTobias Grosser              "Code should have bailed out by "
1451f291c8d5SSiddharth Bhat              "this point if an invalid function "
1452f291c8d5SSiddharth Bhat              "were present in a kernel.");
1453f291c8d5SSiddharth Bhat       SubtreeFunctions.insert(F);
1454f291c8d5SSiddharth Bhat     }
1455f291c8d5SSiddharth Bhat   }
1456f291c8d5SSiddharth Bhat   return SubtreeFunctions;
1457f291c8d5SSiddharth Bhat }
1458f291c8d5SSiddharth Bhat 
145943df2020STobias Grosser std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>,
146043df2020STobias Grosser            isl::space>
1461f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
1462edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
1463edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
1464edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
146543df2020STobias Grosser   isl::space ParamSpace = isl::space(S.getIslCtx(), 0, 0).params();
1466edb885cbSTobias Grosser   SubtreeReferences References = {
146743df2020STobias Grosser       LI,         SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator(),
146843df2020STobias Grosser       &ParamSpace};
1469edb885cbSTobias Grosser 
1470edb885cbSTobias Grosser   for (const auto &I : IDToValue)
1471edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
1472edb885cbSTobias Grosser 
1473e53c924bSSiddharth Bhat   // NOTE: this is populated in IslNodeBuilder::addParameters
1474e53c924bSSiddharth Bhat   // See [Code generation of induction variables of loops outside Scops].
1475e53c924bSSiddharth Bhat   for (const auto &I : OutsideLoopIterations)
1476e53c924bSSiddharth Bhat     SubtreeValues.insert(cast<SCEVUnknown>(I.second)->getValue());
1477e53c924bSSiddharth Bhat 
1478edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
1479edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
1480edb885cbSTobias Grosser 
1481e53c924bSSiddharth Bhat   for (const SCEV *Expr : SCEVs) {
1482edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
1483e53c924bSSiddharth Bhat     findLoops(Expr, Loops);
1484e53c924bSSiddharth Bhat   }
1485e53c924bSSiddharth Bhat 
1486e53c924bSSiddharth Bhat   Loops.remove_if([this](const Loop *L) {
1487e53c924bSSiddharth Bhat     return S.contains(L) || L->contains(S.getEntry());
1488e53c924bSSiddharth Bhat   });
1489edb885cbSTobias Grosser 
1490edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
1491d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
1492edb885cbSTobias Grosser 
1493b65ccc43STobias Grosser   isl_space *Space = S.getParamSpace().release();
14943044dc51SMichael Kruse   for (long i = 0, n = isl_space_dim(Space, isl_dim_param); i < n; i++) {
1495edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
1496edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1497edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1498edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1499edb885cbSTobias Grosser     isl_id_free(Id);
1500edb885cbSTobias Grosser   }
1501edb885cbSTobias Grosser   isl_space_free(Space);
1502edb885cbSTobias Grosser 
15033044dc51SMichael Kruse   for (long i = 0, n = isl_space_dim(Kernel->space, isl_dim_set); i < n; i++) {
1504edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1505edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1506edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1507edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1508edb885cbSTobias Grosser     isl_id_free(Id);
1509edb885cbSTobias Grosser   }
1510edb885cbSTobias Grosser 
1511f291c8d5SSiddharth Bhat   // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions
1512f291c8d5SSiddharth Bhat   // SubtreeValues. This is important, because we should not lose any
1513f291c8d5SSiddharth Bhat   // SubtreeValues in the process of constructing the
1514f291c8d5SSiddharth Bhat   // "ValidSubtree{Values, Functions} sets. Nor should the set
1515f291c8d5SSiddharth Bhat   // ValidSubtree{Values, Functions} have any common element.
1516f291c8d5SSiddharth Bhat   auto ValidSubtreeValuesIt =
1517f291c8d5SSiddharth Bhat       make_filter_range(SubtreeValues, isValidSubtreeValue);
1518f291c8d5SSiddharth Bhat   SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(),
1519f291c8d5SSiddharth Bhat                                         ValidSubtreeValuesIt.end());
15208fc6cdfbSTobias Grosser 
15218fc6cdfbSTobias Grosser   bool AllowCUDALibDevice = Arch == GPUArch::NVPTX64;
15228fc6cdfbSTobias Grosser 
1523f291c8d5SSiddharth Bhat   SetVector<Function *> ValidSubtreeFunctions(
15248fc6cdfbSTobias Grosser       getFunctionsFromRawSubtreeValues(SubtreeValues, AllowCUDALibDevice));
1525f291c8d5SSiddharth Bhat 
1526a1b2086aSSiddharth Bhat   // @see IslNodeBuilder::getReferencesInSubtree
1527a1b2086aSSiddharth Bhat   SetVector<Value *> ReplacedValues;
1528a1b2086aSSiddharth Bhat   for (Value *V : ValidSubtreeValues) {
1529a1b2086aSSiddharth Bhat     auto It = ValueMap.find(V);
1530a1b2086aSSiddharth Bhat     if (It == ValueMap.end())
1531a1b2086aSSiddharth Bhat       ReplacedValues.insert(V);
1532a1b2086aSSiddharth Bhat     else
1533a1b2086aSSiddharth Bhat       ReplacedValues.insert(It->second);
1534a1b2086aSSiddharth Bhat   }
153543df2020STobias Grosser   return std::make_tuple(ReplacedValues, ValidSubtreeFunctions, Loops,
153643df2020STobias Grosser                          ParamSpace);
1537edb885cbSTobias Grosser }
1538edb885cbSTobias Grosser 
153974dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
154074dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
154174dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
154274dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
154374dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
154474dc3cb4STobias Grosser 
154574dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
154674dc3cb4STobias Grosser     DT.eraseNode(BB);
154774dc3cb4STobias Grosser }
154874dc3cb4STobias Grosser 
154974dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
15504d50ab86SPhilip Pfaffe   for (BasicBlock &BB : *F) {
15514d50ab86SPhilip Pfaffe     Loop *L = LI.getLoopFor(&BB);
155274dc3cb4STobias Grosser     if (L)
155374dc3cb4STobias Grosser       SE.forgetLoop(L);
155474dc3cb4STobias Grosser   }
15554d50ab86SPhilip Pfaffe }
155674dc3cb4STobias Grosser 
155774dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
1558c06a6380SPhilip Pfaffe   SmallSet<Loop *, 1> WorkList;
15594d50ab86SPhilip Pfaffe   for (BasicBlock &BB : *F) {
15604d50ab86SPhilip Pfaffe     Loop *L = LI.getLoopFor(&BB);
15614d50ab86SPhilip Pfaffe     if (L)
1562c06a6380SPhilip Pfaffe       WorkList.insert(L);
15634d50ab86SPhilip Pfaffe   }
1564c06a6380SPhilip Pfaffe   for (auto *L : WorkList)
1565c06a6380SPhilip Pfaffe     LI.erase(L);
156674dc3cb4STobias Grosser }
156774dc3cb4STobias Grosser 
156879a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
156979a947c2STobias Grosser   std::vector<Value *> Sizes;
15708ea1fc19STobias Grosser   isl::ast_build Context = isl::ast_build::from_context(S.getContext());
157179a947c2STobias Grosser 
1572718d04c6STobias Grosser   isl::multi_pw_aff GridSizePwAffs = isl::manage_copy(Kernel->grid_size);
157379a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
15744d5820d1SSiddharth Bhat     isl::pw_aff Size = GridSizePwAffs.get_pw_aff(i);
15754d5820d1SSiddharth Bhat     isl::ast_expr GridSize = Context.expr_from(Size);
15764d5820d1SSiddharth Bhat     Value *Res = ExprBuilder.create(GridSize.release());
157779a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
157879a947c2STobias Grosser     Sizes.push_back(Res);
157979a947c2STobias Grosser   }
158079a947c2STobias Grosser 
158179a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
158279a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
158379a947c2STobias Grosser 
158479a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
158579a947c2STobias Grosser }
158679a947c2STobias Grosser 
158779a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
158879a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
158979a947c2STobias Grosser   std::vector<Value *> Sizes;
159079a947c2STobias Grosser 
159179a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
159279a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
159379a947c2STobias Grosser     Sizes.push_back(Res);
159479a947c2STobias Grosser   }
159579a947c2STobias Grosser 
159679a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
159779a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
159879a947c2STobias Grosser 
159979a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
160079a947c2STobias Grosser }
160179a947c2STobias Grosser 
1602a90be207SSiddharth Bhat void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters,
1603a90be207SSiddharth Bhat                                           Instruction *Param, int Index) {
1604a90be207SSiddharth Bhat   Value *Slot = Builder.CreateGEP(
1605a90be207SSiddharth Bhat       Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1606a90be207SSiddharth Bhat   Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1607a90be207SSiddharth Bhat   Builder.CreateStore(ParamTyped, Slot);
1608a90be207SSiddharth Bhat }
1609a90be207SSiddharth Bhat 
161057693272STobias Grosser Value *
161157693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
161257693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
1613a90be207SSiddharth Bhat   const int NumArgs = F->arg_size();
1614a90be207SSiddharth Bhat   std::vector<int> ArgSizes(NumArgs);
1615a90be207SSiddharth Bhat 
161650139f0fSPhilipp Schaad   // If we are using the OpenCL Runtime, we need to add the kernel argument
161750139f0fSPhilipp Schaad   // sizes to the end of the launch-parameter list, so OpenCL can determine
161850139f0fSPhilipp Schaad   // how big the respective kernel arguments are.
161950139f0fSPhilipp Schaad   // Here we need to reserve adequate space for that.
162050139f0fSPhilipp Schaad   Type *ArrayTy;
162150139f0fSPhilipp Schaad   if (Runtime == GPURuntime::OpenCL)
162250139f0fSPhilipp Schaad     ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs);
162350139f0fSPhilipp Schaad   else
162450139f0fSPhilipp Schaad     ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), NumArgs);
162579a947c2STobias Grosser 
162679a947c2STobias Grosser   BasicBlock *EntryBlock =
162779a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
162867726b32STobias Grosser   auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace();
162979a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
163067726b32STobias Grosser   Instruction *Parameters = new AllocaInst(
163167726b32STobias Grosser       ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator());
163279a947c2STobias Grosser 
163379a947c2STobias Grosser   int Index = 0;
163479a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
163579a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
163679a947c2STobias Grosser       continue;
163779a947c2STobias Grosser 
163879a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1639206e9e3bSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
164079a947c2STobias Grosser 
164150139f0fSPhilipp Schaad     if (Runtime == GPURuntime::OpenCL)
1642a90be207SSiddharth Bhat       ArgSizes[Index] = SAI->getElemSizeInBytes();
1643a90be207SSiddharth Bhat 
1644abed4969SSiddharth Bhat     Value *DevArray = nullptr;
1645c4a4af47SSiddharth Bhat     if (PollyManagedMemory) {
1646b99c1171STobias Grosser       DevArray = getManagedDeviceArray(&Prog->array[i],
1647b99c1171STobias Grosser                                        const_cast<ScopArrayInfo *>(SAI));
1648abed4969SSiddharth Bhat     } else {
1649abed4969SSiddharth Bhat       DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
165079a947c2STobias Grosser       DevArray = createCallGetDevicePtr(DevArray);
1651abed4969SSiddharth Bhat     }
1652abed4969SSiddharth Bhat     assert(DevArray != nullptr && "Array to be offloaded to device not "
1653abed4969SSiddharth Bhat                                   "initialized");
1654aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(&Prog->array[i]);
1655aaabbbf8STobias Grosser 
1656aaabbbf8STobias Grosser     if (Offset) {
1657aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(
1658aaabbbf8STobias Grosser           DevArray, SAI->getElementType()->getPointerTo());
1659aaabbbf8STobias Grosser       DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset));
1660aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1661aaabbbf8STobias Grosser     }
1662fe74a7a1STobias Grosser     Value *Slot = Builder.CreateGEP(
1663fe74a7a1STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1664aaabbbf8STobias Grosser 
1665fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1666abed4969SSiddharth Bhat       Value *ValPtr = nullptr;
1667c4a4af47SSiddharth Bhat       if (PollyManagedMemory)
1668abed4969SSiddharth Bhat         ValPtr = DevArray;
1669abed4969SSiddharth Bhat       else
1670abed4969SSiddharth Bhat         ValPtr = BlockGen.getOrCreateAlloca(SAI);
1671abed4969SSiddharth Bhat 
1672abed4969SSiddharth Bhat       assert(ValPtr != nullptr && "ValPtr that should point to a valid object"
1673abed4969SSiddharth Bhat                                   " to be stored into Parameters");
1674fe74a7a1STobias Grosser       Value *ValPtrCast =
1675fe74a7a1STobias Grosser           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1676fe74a7a1STobias Grosser       Builder.CreateStore(ValPtrCast, Slot);
1677fe74a7a1STobias Grosser     } else {
167867726b32STobias Grosser       Instruction *Param =
167967726b32STobias Grosser           new AllocaInst(Builder.getInt8PtrTy(), AddressSpace,
168067726b32STobias Grosser                          Launch + "_param_" + std::to_string(Index),
168179a947c2STobias Grosser                          EntryBlock->getTerminator());
168279a947c2STobias Grosser       Builder.CreateStore(DevArray, Param);
168379a947c2STobias Grosser       Value *ParamTyped =
168479a947c2STobias Grosser           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
168579a947c2STobias Grosser       Builder.CreateStore(ParamTyped, Slot);
1686fe74a7a1STobias Grosser     }
168779a947c2STobias Grosser     Index++;
168879a947c2STobias Grosser   }
168979a947c2STobias Grosser 
1690a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1691a490147cSTobias Grosser 
1692a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1693a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1694a490147cSTobias Grosser     Value *Val = IDToValue[Id];
1695a490147cSTobias Grosser     isl_id_free(Id);
1696a90be207SSiddharth Bhat 
169750139f0fSPhilipp Schaad     if (Runtime == GPURuntime::OpenCL)
1698a90be207SSiddharth Bhat       ArgSizes[Index] = computeSizeInBytes(Val->getType());
1699a90be207SSiddharth Bhat 
170067726b32STobias Grosser     Instruction *Param =
170167726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
170267726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1703a490147cSTobias Grosser                        EntryBlock->getTerminator());
1704a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
1705a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1706a490147cSTobias Grosser     Index++;
1707a490147cSTobias Grosser   }
1708a490147cSTobias Grosser 
1709d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1710d8b94bcaSTobias Grosser 
1711d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
1712d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1713d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
1714a1b2086aSSiddharth Bhat     if (ValueMap.count(Val))
1715a1b2086aSSiddharth Bhat       Val = ValueMap[Val];
1716d8b94bcaSTobias Grosser     isl_id_free(Id);
1717a90be207SSiddharth Bhat 
171850139f0fSPhilipp Schaad     if (Runtime == GPURuntime::OpenCL)
1719a90be207SSiddharth Bhat       ArgSizes[Index] = computeSizeInBytes(Val->getType());
1720a90be207SSiddharth Bhat 
172167726b32STobias Grosser     Instruction *Param =
172267726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
172367726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1724d8b94bcaSTobias Grosser                        EntryBlock->getTerminator());
1725d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
1726a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1727d8b94bcaSTobias Grosser     Index++;
1728d8b94bcaSTobias Grosser   }
1729d8b94bcaSTobias Grosser 
173057693272STobias Grosser   for (auto Val : SubtreeValues) {
173150139f0fSPhilipp Schaad     if (Runtime == GPURuntime::OpenCL)
1732a90be207SSiddharth Bhat       ArgSizes[Index] = computeSizeInBytes(Val->getType());
1733a90be207SSiddharth Bhat 
173467726b32STobias Grosser     Instruction *Param =
173567726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
173667726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
173757693272STobias Grosser                        EntryBlock->getTerminator());
173857693272STobias Grosser     Builder.CreateStore(Val, Param);
1739a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1740a90be207SSiddharth Bhat     Index++;
1741a90be207SSiddharth Bhat   }
1742a90be207SSiddharth Bhat 
174350139f0fSPhilipp Schaad   if (Runtime == GPURuntime::OpenCL) {
1744a90be207SSiddharth Bhat     for (int i = 0; i < NumArgs; i++) {
1745a90be207SSiddharth Bhat       Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]);
1746a90be207SSiddharth Bhat       Instruction *Param =
1747a90be207SSiddharth Bhat           new AllocaInst(Builder.getInt32Ty(), AddressSpace,
1748a90be207SSiddharth Bhat                          Launch + "_param_size_" + std::to_string(i),
1749a90be207SSiddharth Bhat                          EntryBlock->getTerminator());
1750a90be207SSiddharth Bhat       Builder.CreateStore(Val, Param);
1751a90be207SSiddharth Bhat       insertStoreParameter(Parameters, Param, Index);
175257693272STobias Grosser       Index++;
175357693272STobias Grosser     }
175450139f0fSPhilipp Schaad   }
175557693272STobias Grosser 
175679a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
175779a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
175879a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
175979a947c2STobias Grosser }
176079a947c2STobias Grosser 
1761f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions(
1762f291c8d5SSiddharth Bhat     SetVector<Function *> SubtreeFunctions) {
1763f291c8d5SSiddharth Bhat   for (auto Fn : SubtreeFunctions) {
1764*1a53b732SMichael Kruse     const std::string ClonedFnName = Fn->getName().str();
1765f291c8d5SSiddharth Bhat     Function *Clone = GPUModule->getFunction(ClonedFnName);
1766f291c8d5SSiddharth Bhat     if (!Clone)
1767f291c8d5SSiddharth Bhat       Clone =
1768f291c8d5SSiddharth Bhat           Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage,
1769f291c8d5SSiddharth Bhat                            ClonedFnName, GPUModule.get());
1770f291c8d5SSiddharth Bhat     assert(Clone && "Expected cloned function to be initialized.");
1771f291c8d5SSiddharth Bhat     assert(ValueMap.find(Fn) == ValueMap.end() &&
1772f291c8d5SSiddharth Bhat            "Fn already present in ValueMap");
1773f291c8d5SSiddharth Bhat     ValueMap[Fn] = Clone;
1774f291c8d5SSiddharth Bhat   }
1775f291c8d5SSiddharth Bhat }
177632837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
177732837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
177832837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
177932837fe3STobias Grosser   isl_id_free(Id);
178032837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
178132837fe3STobias Grosser 
1782bc653f20STobias Grosser   if (Kernel->n_grid > 1)
1783bc653f20STobias Grosser     DeepestParallel =
1784bc653f20STobias Grosser         std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set));
1785bc653f20STobias Grosser   else
1786bc653f20STobias Grosser     DeepestSequential =
1787bc653f20STobias Grosser         std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set));
1788bc653f20STobias Grosser 
1789c1c6a2a6STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1790c1c6a2a6STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1791c1c6a2a6STobias Grosser 
1792f291c8d5SSiddharth Bhat   SetVector<Value *> SubtreeValues;
1793f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1794e53c924bSSiddharth Bhat   SetVector<const Loop *> Loops;
179543df2020STobias Grosser   isl::space ParamSpace;
179643df2020STobias Grosser   std::tie(SubtreeValues, SubtreeFunctions, Loops, ParamSpace) =
1797e53c924bSSiddharth Bhat       getReferencesInKernel(Kernel);
1798edb885cbSTobias Grosser 
179943df2020STobias Grosser   // Add parameters that appear only in the access function to the kernel
180043df2020STobias Grosser   // space. This is important to make sure that all isl_ids are passed as
180143df2020STobias Grosser   // parameters to the kernel, even though we may not have all parameters
180243df2020STobias Grosser   // in the context to improve compile time.
180343df2020STobias Grosser   Kernel->space = isl_space_align_params(Kernel->space, ParamSpace.release());
180443df2020STobias Grosser 
180532837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
180632837fe3STobias Grosser 
180732837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1808472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1809edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
1810587f1f57STobias Grosser   BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap;
1811b06ff457STobias Grosser   ScalarMap.clear();
1812c52b71dbSTobias Grosser   BlockGenerator::EscapeUsersAllocaMapTy HostEscapeMap = EscapeMap;
1813c52b71dbSTobias Grosser   EscapeMap.clear();
181432837fe3STobias Grosser 
1815edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
1816edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
1817edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
1818edb885cbSTobias Grosser   for (const Loop *L : Loops) {
1819edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1820edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1821edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1822edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1823edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1824edb885cbSTobias Grosser     SubtreeValues.insert(V);
1825edb885cbSTobias Grosser   }
1826edb885cbSTobias Grosser 
1827f291c8d5SSiddharth Bhat   createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions);
1828f291c8d5SSiddharth Bhat   setupKernelSubtreeFunctions(SubtreeFunctions);
182932837fe3STobias Grosser 
183059ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
183159ab0705STobias Grosser 
183251dfc275STobias Grosser   finalizeKernelArguments(Kernel);
183374dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
18342f3073b5SPhilipp Schaad   if (Arch == GPUArch::NVPTX64)
1835c1c6a2a6STobias Grosser     addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
183674dc3cb4STobias Grosser   clearDominators(F);
183774dc3cb4STobias Grosser   clearScalarEvolution(F);
183874dc3cb4STobias Grosser   clearLoops(F);
183974dc3cb4STobias Grosser 
1840472f9654STobias Grosser   IDToValue = HostIDs;
184132837fe3STobias Grosser 
1842b06ff457STobias Grosser   ValueMap = std::move(HostValueMap);
1843b06ff457STobias Grosser   ScalarMap = std::move(HostScalarMap);
1844c52b71dbSTobias Grosser   EscapeMap = std::move(HostEscapeMap);
1845edb885cbSTobias Grosser   IDToSAI.clear();
184674dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
184774dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
18484d5a9172STobias Grosser     S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array);
184974dc3cb4STobias Grosser   LocalArrays.clear();
1850edb885cbSTobias Grosser 
185151dfc275STobias Grosser   std::string ASMString = finalizeKernelFunction();
185251dfc275STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
185357693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
185479a947c2STobias Grosser 
185579f13b9aSSingapuram Sanjay Srivallabh   std::string Name = getKernelFuncName(Kernel->id);
185657793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
185757793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
185857793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
185979a947c2STobias Grosser 
186079a947c2STobias Grosser   Value *GridDimX, *GridDimY;
186179a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
186279a947c2STobias Grosser 
186379a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
186479a947c2STobias Grosser                          BlockDimZ, Parameters);
186557793596STobias Grosser   createCallFreeKernel(GPUKernel);
1866b513b491STobias Grosser 
1867b513b491STobias Grosser   for (auto Id : KernelIds)
1868b513b491STobias Grosser     isl_id_free(Id);
1869b513b491STobias Grosser 
1870b513b491STobias Grosser   KernelIds.clear();
187132837fe3STobias Grosser }
187232837fe3STobias Grosser 
187332837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
187432837fe3STobias Grosser ///
187532837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
187632837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
1877d277fedaSSiddharth Bhat   std::string Ret = "";
187832837fe3STobias Grosser 
1879d277fedaSSiddharth Bhat   if (!is64Bit) {
1880d277fedaSSiddharth Bhat     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
188130caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1882d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1883d277fedaSSiddharth Bhat   } else {
1884d277fedaSSiddharth Bhat     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
188530caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1886d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1887d277fedaSSiddharth Bhat   }
188832837fe3STobias Grosser 
188932837fe3STobias Grosser   return Ret;
189032837fe3STobias Grosser }
189132837fe3STobias Grosser 
18922f3073b5SPhilipp Schaad /// Compute the DataLayout string for a SPIR kernel.
18932f3073b5SPhilipp Schaad ///
18942f3073b5SPhilipp Schaad /// @param is64Bit Are we looking for a 64 bit architecture?
18952f3073b5SPhilipp Schaad static std::string computeSPIRDataLayout(bool is64Bit) {
18962f3073b5SPhilipp Schaad   std::string Ret = "";
18972f3073b5SPhilipp Schaad 
18982f3073b5SPhilipp Schaad   if (!is64Bit) {
18992f3073b5SPhilipp Schaad     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
190030caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
19012f3073b5SPhilipp Schaad            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
19022f3073b5SPhilipp Schaad            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
19032f3073b5SPhilipp Schaad   } else {
19042f3073b5SPhilipp Schaad     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
190530caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
19062f3073b5SPhilipp Schaad            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
19072f3073b5SPhilipp Schaad            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
19082f3073b5SPhilipp Schaad   }
19092f3073b5SPhilipp Schaad 
19102f3073b5SPhilipp Schaad   return Ret;
19112f3073b5SPhilipp Schaad }
19122f3073b5SPhilipp Schaad 
1913edb885cbSTobias Grosser Function *
1914edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1915edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
191632837fe3STobias Grosser   std::vector<Type *> Args;
191779f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
191832837fe3STobias Grosser 
19192f3073b5SPhilipp Schaad   std::vector<Metadata *> MemoryType;
19202f3073b5SPhilipp Schaad 
192132837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
192232837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
192332837fe3STobias Grosser       continue;
192432837fe3STobias Grosser 
1925fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1926fe74a7a1STobias Grosser       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1927206e9e3bSTobias Grosser       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
1928fe74a7a1STobias Grosser       Args.push_back(SAI->getElementType());
19292f3073b5SPhilipp Schaad       MemoryType.push_back(
19302f3073b5SPhilipp Schaad           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1931fe74a7a1STobias Grosser     } else {
1932d277fedaSSiddharth Bhat       static const int UseGlobalMemory = 1;
1933d277fedaSSiddharth Bhat       Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory));
19342f3073b5SPhilipp Schaad       MemoryType.push_back(
19352f3073b5SPhilipp Schaad           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 1)));
193632837fe3STobias Grosser     }
1937fe74a7a1STobias Grosser   }
193832837fe3STobias Grosser 
1939f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1940f6044bd0STobias Grosser 
19412f3073b5SPhilipp Schaad   for (long i = 0; i < NumHostIters; i++) {
1942f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
19432f3073b5SPhilipp Schaad     MemoryType.push_back(
19442f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
19452f3073b5SPhilipp Schaad   }
1946f6044bd0STobias Grosser 
1947c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1948c84a1995STobias Grosser 
1949cf66ef26STobias Grosser   for (long i = 0; i < NumVars; i++) {
1950cf66ef26STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1951cf66ef26STobias Grosser     Value *Val = IDToValue[Id];
1952cf66ef26STobias Grosser     isl_id_free(Id);
1953cf66ef26STobias Grosser     Args.push_back(Val->getType());
19542f3073b5SPhilipp Schaad     MemoryType.push_back(
19552f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1956cf66ef26STobias Grosser   }
1957c84a1995STobias Grosser 
19582f3073b5SPhilipp Schaad   for (auto *V : SubtreeValues) {
1959edb885cbSTobias Grosser     Args.push_back(V->getType());
19602f3073b5SPhilipp Schaad     MemoryType.push_back(
19612f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
19622f3073b5SPhilipp Schaad   }
1963edb885cbSTobias Grosser 
196432837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
196532837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
196632837fe3STobias Grosser                               GPUModule.get());
196717f01968SSiddharth Bhat 
19682f3073b5SPhilipp Schaad   std::vector<Metadata *> EmptyStrings;
19692f3073b5SPhilipp Schaad 
19702f3073b5SPhilipp Schaad   for (unsigned int i = 0; i < MemoryType.size(); i++) {
19712f3073b5SPhilipp Schaad     EmptyStrings.push_back(MDString::get(FN->getContext(), ""));
19722f3073b5SPhilipp Schaad   }
19732f3073b5SPhilipp Schaad 
19742f3073b5SPhilipp Schaad   if (Arch == GPUArch::SPIR32 || Arch == GPUArch::SPIR64) {
19752f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_addr_space",
19762f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), MemoryType));
19772f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_name",
19782f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
19792f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_access_qual",
19802f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
19812f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_type",
19822f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
19832f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_type_qual",
19842f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
19852f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_base_type",
19862f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
19872f3073b5SPhilipp Schaad   }
19882f3073b5SPhilipp Schaad 
198917f01968SSiddharth Bhat   switch (Arch) {
199017f01968SSiddharth Bhat   case GPUArch::NVPTX64:
199132837fe3STobias Grosser     FN->setCallingConv(CallingConv::PTX_Kernel);
199217f01968SSiddharth Bhat     break;
19932f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
19942f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
19952f3073b5SPhilipp Schaad     FN->setCallingConv(CallingConv::SPIR_KERNEL);
19962f3073b5SPhilipp Schaad     break;
199717f01968SSiddharth Bhat   }
199832837fe3STobias Grosser 
199932837fe3STobias Grosser   auto Arg = FN->arg_begin();
200032837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
200132837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
200232837fe3STobias Grosser       continue;
200332837fe3STobias Grosser 
2004edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
2005edb885cbSTobias Grosser 
2006edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2007718d04c6STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage_copy(Id));
2008edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
2009edb885cbSTobias Grosser     Value *Val = &*Arg;
2010edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
2011edb885cbSTobias Grosser     isl_ast_build *Build =
2012edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
2013f5aff704SRoman Gareev     Sizes.push_back(nullptr);
20143044dc51SMichael Kruse     for (long j = 1, n = Kernel->array[i].array->n_index; j < n; j++) {
2015edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
20169e3db2b7SSiddharth Bhat           Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j));
2017edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
2018edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
2019edb885cbSTobias Grosser     }
2020edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
20214d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array);
202274dc3cb4STobias Grosser     LocalArrays.push_back(Val);
2023edb885cbSTobias Grosser 
2024edb885cbSTobias Grosser     isl_ast_build_free(Build);
2025b513b491STobias Grosser     KernelIds.push_back(Id);
2026edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
202732837fe3STobias Grosser     Arg++;
202832837fe3STobias Grosser   }
202932837fe3STobias Grosser 
2030f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
2031f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
2032f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
2033f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
2034f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
2035f6044bd0STobias Grosser     Arg++;
2036f6044bd0STobias Grosser   }
2037f6044bd0STobias Grosser 
2038c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
2039c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
2040c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
204112453403STobias Grosser     Value *Val = IDToValue[Id];
204212453403STobias Grosser     ValueMap[Val] = &*Arg;
2043c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
2044c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
2045c84a1995STobias Grosser     Arg++;
2046c84a1995STobias Grosser   }
2047c84a1995STobias Grosser 
2048edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
2049edb885cbSTobias Grosser     Arg->setName(V->getName());
2050edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
2051edb885cbSTobias Grosser     Arg++;
2052edb885cbSTobias Grosser   }
2053edb885cbSTobias Grosser 
205432837fe3STobias Grosser   return FN;
205532837fe3STobias Grosser }
205632837fe3STobias Grosser 
2057472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
205817f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsBID[2];
205917f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsTID[3];
2060472f9654STobias Grosser 
206117f01968SSiddharth Bhat   switch (Arch) {
20622f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
20632f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
20642f3073b5SPhilipp Schaad     llvm_unreachable("Cannot generate NVVM intrinsics for SPIR");
206517f01968SSiddharth Bhat   case GPUArch::NVPTX64:
206617f01968SSiddharth Bhat     IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x;
206717f01968SSiddharth Bhat     IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y;
206817f01968SSiddharth Bhat 
206917f01968SSiddharth Bhat     IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x;
207017f01968SSiddharth Bhat     IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y;
207117f01968SSiddharth Bhat     IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z;
207217f01968SSiddharth Bhat     break;
207317f01968SSiddharth Bhat   }
2074472f9654STobias Grosser 
2075472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
2076472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
2077472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
2078472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
2079472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
2080472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
2081472f9654STobias Grosser     IDToValue[Id] = Val;
2082472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
2083472f9654STobias Grosser   };
2084472f9654STobias Grosser 
2085472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
2086472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
2087472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
2088472f9654STobias Grosser   }
2089472f9654STobias Grosser 
2090472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
2091472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
2092472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
2093472f9654STobias Grosser   }
2094472f9654STobias Grosser }
2095472f9654STobias Grosser 
2096d71493cbSPhilip Pfaffe void GPUNodeBuilder::insertKernelCallsSPIR(ppcg_kernel *Kernel,
2097d71493cbSPhilip Pfaffe                                            bool SizeTypeIs64bit) {
20982f3073b5SPhilipp Schaad   const char *GroupName[3] = {"__gen_ocl_get_group_id0",
20992f3073b5SPhilipp Schaad                               "__gen_ocl_get_group_id1",
21002f3073b5SPhilipp Schaad                               "__gen_ocl_get_group_id2"};
21012f3073b5SPhilipp Schaad 
21022f3073b5SPhilipp Schaad   const char *LocalName[3] = {"__gen_ocl_get_local_id0",
21032f3073b5SPhilipp Schaad                               "__gen_ocl_get_local_id1",
21042f3073b5SPhilipp Schaad                               "__gen_ocl_get_local_id2"};
2105d71493cbSPhilip Pfaffe   IntegerType *SizeT =
2106d71493cbSPhilip Pfaffe       SizeTypeIs64bit ? Builder.getInt64Ty() : Builder.getInt32Ty();
21072f3073b5SPhilipp Schaad 
2108d71493cbSPhilip Pfaffe   auto createFunc = [this](const char *Name, __isl_take isl_id *Id,
2109d71493cbSPhilip Pfaffe                            IntegerType *SizeT) mutable {
21102f3073b5SPhilipp Schaad     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
21112f3073b5SPhilipp Schaad     Function *FN = M->getFunction(Name);
21122f3073b5SPhilipp Schaad 
21132f3073b5SPhilipp Schaad     // If FN is not available, declare it.
21142f3073b5SPhilipp Schaad     if (!FN) {
21152f3073b5SPhilipp Schaad       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
21162f3073b5SPhilipp Schaad       std::vector<Type *> Args;
2117d71493cbSPhilip Pfaffe       FunctionType *Ty = FunctionType::get(SizeT, Args, false);
21182f3073b5SPhilipp Schaad       FN = Function::Create(Ty, Linkage, Name, M);
21192f3073b5SPhilipp Schaad       FN->setCallingConv(CallingConv::SPIR_FUNC);
21202f3073b5SPhilipp Schaad     }
21212f3073b5SPhilipp Schaad 
21222f3073b5SPhilipp Schaad     Value *Val = Builder.CreateCall(FN, {});
2123d71493cbSPhilip Pfaffe     if (SizeT == Builder.getInt32Ty())
21242f3073b5SPhilipp Schaad       Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
21252f3073b5SPhilipp Schaad     IDToValue[Id] = Val;
21262f3073b5SPhilipp Schaad     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
21272f3073b5SPhilipp Schaad   };
21282f3073b5SPhilipp Schaad 
21292f3073b5SPhilipp Schaad   for (int i = 0; i < Kernel->n_grid; ++i)
2130d71493cbSPhilip Pfaffe     createFunc(GroupName[i], isl_id_list_get_id(Kernel->block_ids, i), SizeT);
21312f3073b5SPhilipp Schaad 
21322f3073b5SPhilipp Schaad   for (int i = 0; i < Kernel->n_block; ++i)
2133d71493cbSPhilip Pfaffe     createFunc(LocalName[i], isl_id_list_get_id(Kernel->thread_ids, i), SizeT);
21342f3073b5SPhilipp Schaad }
21352f3073b5SPhilipp Schaad 
213600bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
213700bb5a99STobias Grosser   auto Arg = FN->arg_begin();
213800bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
213900bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
214000bb5a99STobias Grosser       continue;
214100bb5a99STobias Grosser 
214200bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2143718d04c6STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage_copy(Id));
214400bb5a99STobias Grosser     isl_id_free(Id);
214500bb5a99STobias Grosser 
214600bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
214700bb5a99STobias Grosser       Arg++;
214800bb5a99STobias Grosser       continue;
214900bb5a99STobias Grosser     }
215000bb5a99STobias Grosser 
2151fe74a7a1STobias Grosser     Value *Val = &*Arg;
2152fe74a7a1STobias Grosser 
2153fe74a7a1STobias Grosser     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
215400bb5a99STobias Grosser       Type *TypePtr = SAI->getElementType()->getPointerTo();
2155fe74a7a1STobias Grosser       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
2156fe74a7a1STobias Grosser       Val = Builder.CreateLoad(TypedArgPtr);
2157fe74a7a1STobias Grosser     }
2158fe74a7a1STobias Grosser 
2159fe74a7a1STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
216000bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
216100bb5a99STobias Grosser 
216200bb5a99STobias Grosser     Arg++;
216300bb5a99STobias Grosser   }
216400bb5a99STobias Grosser }
216500bb5a99STobias Grosser 
216651dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) {
216751dfc275STobias Grosser   auto *FN = Builder.GetInsertBlock()->getParent();
216851dfc275STobias Grosser   auto Arg = FN->arg_begin();
216951dfc275STobias Grosser 
217051dfc275STobias Grosser   bool StoredScalar = false;
217151dfc275STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
217251dfc275STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
217351dfc275STobias Grosser       continue;
217451dfc275STobias Grosser 
217551dfc275STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2176718d04c6STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage_copy(Id));
217751dfc275STobias Grosser     isl_id_free(Id);
217851dfc275STobias Grosser 
217951dfc275STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
218051dfc275STobias Grosser       Arg++;
218151dfc275STobias Grosser       continue;
218251dfc275STobias Grosser     }
218351dfc275STobias Grosser 
218451dfc275STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
218551dfc275STobias Grosser       Arg++;
218651dfc275STobias Grosser       continue;
218751dfc275STobias Grosser     }
218851dfc275STobias Grosser 
218951dfc275STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
219051dfc275STobias Grosser     Value *ArgPtr = &*Arg;
219151dfc275STobias Grosser     Type *TypePtr = SAI->getElementType()->getPointerTo();
219251dfc275STobias Grosser     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
219351dfc275STobias Grosser     Value *Val = Builder.CreateLoad(Alloca);
219451dfc275STobias Grosser     Builder.CreateStore(Val, TypedArgPtr);
219551dfc275STobias Grosser     StoredScalar = true;
219651dfc275STobias Grosser 
219751dfc275STobias Grosser     Arg++;
219851dfc275STobias Grosser   }
219951dfc275STobias Grosser 
2200638316daSSiddharth Bhat   if (StoredScalar) {
220151dfc275STobias Grosser     /// In case more than one thread contains scalar stores, the generated
220251dfc275STobias Grosser     /// code might be incorrect, if we only store at the end of the kernel.
220351dfc275STobias Grosser     /// To support this case we need to store these scalars back at each
220451dfc275STobias Grosser     /// memory store or at least before each kernel barrier.
2205638316daSSiddharth Bhat     if (Kernel->n_block != 0 || Kernel->n_grid != 0) {
220651dfc275STobias Grosser       BuildSuccessful = 0;
2207349506a9SNicola Zaghen       LLVM_DEBUG(
2208638316daSSiddharth Bhat           dbgs() << getUniqueScopName(&S)
2209638316daSSiddharth Bhat                  << " has a store to a scalar value that"
2210638316daSSiddharth Bhat                     " would be undefined to run in parallel. Bailing out.\n";);
2211638316daSSiddharth Bhat     }
2212638316daSSiddharth Bhat   }
221351dfc275STobias Grosser }
221451dfc275STobias Grosser 
2215b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
2216b513b491STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
2217b513b491STobias Grosser 
2218b513b491STobias Grosser   for (int i = 0; i < Kernel->n_var; ++i) {
2219b513b491STobias Grosser     struct ppcg_kernel_var &Var = Kernel->var[i];
2220b513b491STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
2221206e9e3bSTobias Grosser     Type *EleTy = ScopArrayInfo::getFromId(isl::manage(Id))->getElementType();
2222b513b491STobias Grosser 
2223f919d8b3STobias Grosser     Type *ArrayTy = EleTy;
2224b513b491STobias Grosser     SmallVector<const SCEV *, 4> Sizes;
2225b513b491STobias Grosser 
2226f5aff704SRoman Gareev     Sizes.push_back(nullptr);
2227928d7573STobias Grosser     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
2228b513b491STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2229f919d8b3STobias Grosser       long Bound = isl_val_get_num_si(Val);
2230b513b491STobias Grosser       isl_val_free(Val);
2231b513b491STobias Grosser       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
2232928d7573STobias Grosser     }
2233928d7573STobias Grosser 
2234928d7573STobias Grosser     for (int j = Var.array->n_index - 1; j >= 0; --j) {
2235928d7573STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2236928d7573STobias Grosser       long Bound = isl_val_get_num_si(Val);
2237928d7573STobias Grosser       isl_val_free(Val);
2238b513b491STobias Grosser       ArrayTy = ArrayType::get(ArrayTy, Bound);
2239b513b491STobias Grosser     }
2240b513b491STobias Grosser 
2241130ca30fSTobias Grosser     const ScopArrayInfo *SAI;
2242130ca30fSTobias Grosser     Value *Allocation;
2243130ca30fSTobias Grosser     if (Var.type == ppcg_access_shared) {
2244130ca30fSTobias Grosser       auto GlobalVar = new GlobalVariable(
2245130ca30fSTobias Grosser           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
2246130ca30fSTobias Grosser           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
2247f7b3ae65SMichael Kruse       GlobalVar->setAlignment(llvm::Align(EleTy->getPrimitiveSizeInBits() / 8));
2248f919d8b3STobias Grosser       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
2249f919d8b3STobias Grosser 
2250130ca30fSTobias Grosser       Allocation = GlobalVar;
2251130ca30fSTobias Grosser     } else if (Var.type == ppcg_access_private) {
2252130ca30fSTobias Grosser       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
2253130ca30fSTobias Grosser     } else {
2254130ca30fSTobias Grosser       llvm_unreachable("unknown variable type");
2255130ca30fSTobias Grosser     }
22564d5a9172STobias Grosser     SAI =
22574d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array);
225800fd43b3SPhilip Pfaffe     Id = isl_id_alloc(S.getIslCtx().get(), Var.name, nullptr);
2259130ca30fSTobias Grosser     IDToValue[Id] = Allocation;
2260130ca30fSTobias Grosser     LocalArrays.push_back(Allocation);
2261b513b491STobias Grosser     KernelIds.push_back(Id);
2262b513b491STobias Grosser     IDToSAI[Id] = SAI;
2263b513b491STobias Grosser   }
2264b513b491STobias Grosser }
2265b513b491STobias Grosser 
2266f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction(
2267f291c8d5SSiddharth Bhat     ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues,
2268f291c8d5SSiddharth Bhat     SetVector<Function *> &SubtreeFunctions) {
226979f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
227032837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
227117f01968SSiddharth Bhat 
227217f01968SSiddharth Bhat   switch (Arch) {
227317f01968SSiddharth Bhat   case GPUArch::NVPTX64:
227417f01968SSiddharth Bhat     if (Runtime == GPURuntime::CUDA)
227532837fe3STobias Grosser       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
227617f01968SSiddharth Bhat     else if (Runtime == GPURuntime::OpenCL)
227717f01968SSiddharth Bhat       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl"));
227832837fe3STobias Grosser     GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
227917f01968SSiddharth Bhat     break;
22802f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
22812f3073b5SPhilipp Schaad     GPUModule->setTargetTriple(Triple::normalize("spir-unknown-unknown"));
22822f3073b5SPhilipp Schaad     GPUModule->setDataLayout(computeSPIRDataLayout(false /* is64Bit */));
22832f3073b5SPhilipp Schaad     break;
22842f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
22852f3073b5SPhilipp Schaad     GPUModule->setTargetTriple(Triple::normalize("spir64-unknown-unknown"));
22862f3073b5SPhilipp Schaad     GPUModule->setDataLayout(computeSPIRDataLayout(true /* is64Bit */));
22872f3073b5SPhilipp Schaad     break;
228817f01968SSiddharth Bhat   }
228932837fe3STobias Grosser 
2290edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
229132837fe3STobias Grosser 
229259ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
229332837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
229432837fe3STobias Grosser 
229559ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
229659ab0705STobias Grosser 
229732837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
229832837fe3STobias Grosser   Builder.CreateRetVoid();
229932837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
2300472f9654STobias Grosser 
2301629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
2302629109b6STobias Grosser 
230300bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
2304b513b491STobias Grosser   createKernelVariables(Kernel, FN);
23052f3073b5SPhilipp Schaad 
23062f3073b5SPhilipp Schaad   switch (Arch) {
23072f3073b5SPhilipp Schaad   case GPUArch::NVPTX64:
2308472f9654STobias Grosser     insertKernelIntrinsics(Kernel);
23092f3073b5SPhilipp Schaad     break;
23102f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
2311d71493cbSPhilip Pfaffe     insertKernelCallsSPIR(Kernel, false);
2312d71493cbSPhilip Pfaffe     break;
23132f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
2314d71493cbSPhilip Pfaffe     insertKernelCallsSPIR(Kernel, true);
23152f3073b5SPhilipp Schaad     break;
23162f3073b5SPhilipp Schaad   }
231732837fe3STobias Grosser }
231832837fe3STobias Grosser 
231974dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
232017f01968SSiddharth Bhat   llvm::Triple GPUTriple;
232117f01968SSiddharth Bhat 
232217f01968SSiddharth Bhat   switch (Arch) {
232317f01968SSiddharth Bhat   case GPUArch::NVPTX64:
232417f01968SSiddharth Bhat     switch (Runtime) {
232517f01968SSiddharth Bhat     case GPURuntime::CUDA:
232617f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda"));
232717f01968SSiddharth Bhat       break;
232817f01968SSiddharth Bhat     case GPURuntime::OpenCL:
232917f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl"));
233017f01968SSiddharth Bhat       break;
233117f01968SSiddharth Bhat     }
233217f01968SSiddharth Bhat     break;
23332f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
23342f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
23352f3073b5SPhilipp Schaad     std::string SPIRAssembly;
23362f3073b5SPhilipp Schaad     raw_string_ostream IROstream(SPIRAssembly);
23372f3073b5SPhilipp Schaad     IROstream << *GPUModule;
23382f3073b5SPhilipp Schaad     IROstream.flush();
23392f3073b5SPhilipp Schaad     return SPIRAssembly;
234017f01968SSiddharth Bhat   }
234117f01968SSiddharth Bhat 
234274dc3cb4STobias Grosser   std::string ErrMsg;
234374dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
234474dc3cb4STobias Grosser 
234574dc3cb4STobias Grosser   if (!GPUTarget) {
234674dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
234774dc3cb4STobias Grosser     return "";
234874dc3cb4STobias Grosser   }
234974dc3cb4STobias Grosser 
235074dc3cb4STobias Grosser   TargetOptions Options;
235174dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
235217f01968SSiddharth Bhat 
235317f01968SSiddharth Bhat   std::string subtarget;
235417f01968SSiddharth Bhat 
235517f01968SSiddharth Bhat   switch (Arch) {
235617f01968SSiddharth Bhat   case GPUArch::NVPTX64:
235717f01968SSiddharth Bhat     subtarget = CudaVersion;
235817f01968SSiddharth Bhat     break;
23592f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
23602f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
23612f3073b5SPhilipp Schaad     llvm_unreachable("No subtarget for SPIR architecture");
236217f01968SSiddharth Bhat   }
236317f01968SSiddharth Bhat 
236417f01968SSiddharth Bhat   std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine(
236517f01968SSiddharth Bhat       GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>()));
236674dc3cb4STobias Grosser 
236774dc3cb4STobias Grosser   SmallString<0> ASMString;
236874dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
236974dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
237074dc3cb4STobias Grosser 
237174dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
237274dc3cb4STobias Grosser 
23731dfede31SReid Kleckner   if (TargetM->addPassesToEmitFile(PM, ASMStream, nullptr, CGFT_AssemblyFile,
23749a45114bSPeter Collingbourne                                    true /* verify */)) {
237574dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
237674dc3cb4STobias Grosser     return "";
237774dc3cb4STobias Grosser   }
237874dc3cb4STobias Grosser 
237974dc3cb4STobias Grosser   PM.run(*GPUModule);
238074dc3cb4STobias Grosser 
2381*1a53b732SMichael Kruse   return ASMStream.str().str();
238274dc3cb4STobias Grosser }
238374dc3cb4STobias Grosser 
23848fc6cdfbSTobias Grosser bool GPUNodeBuilder::requiresCUDALibDevice() {
23855b307cdbSTobias Grosser   bool RequiresLibDevice = false;
23868fc6cdfbSTobias Grosser   for (Function &F : GPUModule->functions()) {
23878fc6cdfbSTobias Grosser     if (!F.isDeclaration())
23888fc6cdfbSTobias Grosser       continue;
23898fc6cdfbSTobias Grosser 
239066a05ad6SPhilip Pfaffe     const std::string CUDALibDeviceFunc = getCUDALibDeviceFuntion(F.getName());
23918fc6cdfbSTobias Grosser     if (CUDALibDeviceFunc.length() != 0) {
239256572c6aSSiddharth Bhat       // We need to handle the case where a module looks like this:
239356572c6aSSiddharth Bhat       // @expf(..)
239456572c6aSSiddharth Bhat       // @llvm.exp.f64(..)
239556572c6aSSiddharth Bhat       // Both of these functions would be renamed to `__nv_expf`.
239656572c6aSSiddharth Bhat       //
239756572c6aSSiddharth Bhat       // So, we must first check for the existence of the libdevice function.
239856572c6aSSiddharth Bhat       // If this exists, we replace our current function with it.
239956572c6aSSiddharth Bhat       //
240056572c6aSSiddharth Bhat       // If it does not exist, we rename the current function to the
240156572c6aSSiddharth Bhat       // libdevice functiono name.
240256572c6aSSiddharth Bhat       if (Function *Replacement = F.getParent()->getFunction(CUDALibDeviceFunc))
240356572c6aSSiddharth Bhat         F.replaceAllUsesWith(Replacement);
240456572c6aSSiddharth Bhat       else
24058fc6cdfbSTobias Grosser         F.setName(CUDALibDeviceFunc);
24065b307cdbSTobias Grosser       RequiresLibDevice = true;
24078fc6cdfbSTobias Grosser     }
24088fc6cdfbSTobias Grosser   }
24098fc6cdfbSTobias Grosser 
24105b307cdbSTobias Grosser   return RequiresLibDevice;
24118fc6cdfbSTobias Grosser }
24128fc6cdfbSTobias Grosser 
24138fc6cdfbSTobias Grosser void GPUNodeBuilder::addCUDALibDevice() {
24148fc6cdfbSTobias Grosser   if (Arch != GPUArch::NVPTX64)
24158fc6cdfbSTobias Grosser     return;
24168fc6cdfbSTobias Grosser 
24178fc6cdfbSTobias Grosser   if (requiresCUDALibDevice()) {
24188fc6cdfbSTobias Grosser     SMDiagnostic Error;
24198fc6cdfbSTobias Grosser 
24208fc6cdfbSTobias Grosser     errs() << CUDALibDevice << "\n";
24218fc6cdfbSTobias Grosser     auto LibDeviceModule =
24228fc6cdfbSTobias Grosser         parseIRFile(CUDALibDevice, Error, GPUModule->getContext());
24238fc6cdfbSTobias Grosser 
24248fc6cdfbSTobias Grosser     if (!LibDeviceModule) {
24258fc6cdfbSTobias Grosser       BuildSuccessful = false;
24268fc6cdfbSTobias Grosser       report_fatal_error("Could not find or load libdevice. Skipping GPU "
24278fc6cdfbSTobias Grosser                          "kernel generation. Please set -polly-acc-libdevice "
24288fc6cdfbSTobias Grosser                          "accordingly.\n");
24298fc6cdfbSTobias Grosser       return;
24308fc6cdfbSTobias Grosser     }
24318fc6cdfbSTobias Grosser 
24328fc6cdfbSTobias Grosser     Linker L(*GPUModule);
24338fc6cdfbSTobias Grosser 
24348fc6cdfbSTobias Grosser     // Set an nvptx64 target triple to avoid linker warnings. The original
24358fc6cdfbSTobias Grosser     // triple of the libdevice files are nvptx-unknown-unknown.
24368fc6cdfbSTobias Grosser     LibDeviceModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
24378fc6cdfbSTobias Grosser     L.linkInModule(std::move(LibDeviceModule), Linker::LinkOnlyNeeded);
24388fc6cdfbSTobias Grosser   }
24398fc6cdfbSTobias Grosser }
24408fc6cdfbSTobias Grosser 
244157793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
244265d7f72fSSiddharth Bhat 
24435857b701STobias Grosser   if (verifyModule(*GPUModule)) {
2444349506a9SNicola Zaghen     LLVM_DEBUG(dbgs() << "verifyModule failed on module:\n";
244565d7f72fSSiddharth Bhat                GPUModule->print(dbgs(), nullptr); dbgs() << "\n";);
2446349506a9SNicola Zaghen     LLVM_DEBUG(dbgs() << "verifyModule Error:\n";
2447a0fb8b23SSiddharth Bhat                verifyModule(*GPUModule, &dbgs()););
244865d7f72fSSiddharth Bhat 
244965d7f72fSSiddharth Bhat     if (FailOnVerifyModuleFailure)
245065d7f72fSSiddharth Bhat       llvm_unreachable("VerifyModule failed.");
245165d7f72fSSiddharth Bhat 
24525857b701STobias Grosser     BuildSuccessful = false;
24535857b701STobias Grosser     return "";
24545857b701STobias Grosser   }
245532837fe3STobias Grosser 
24568fc6cdfbSTobias Grosser   addCUDALibDevice();
24578fc6cdfbSTobias Grosser 
245832837fe3STobias Grosser   if (DumpKernelIR)
245932837fe3STobias Grosser     outs() << *GPUModule << "\n";
246032837fe3STobias Grosser 
24612f3073b5SPhilipp Schaad   if (Arch != GPUArch::SPIR32 && Arch != GPUArch::SPIR64) {
24629a18d559STobias Grosser     // Optimize module.
24639a18d559STobias Grosser     llvm::legacy::PassManager OptPasses;
24649a18d559STobias Grosser     PassManagerBuilder PassBuilder;
24659a18d559STobias Grosser     PassBuilder.OptLevel = 3;
24669a18d559STobias Grosser     PassBuilder.SizeLevel = 0;
24679a18d559STobias Grosser     PassBuilder.populateModulePassManager(OptPasses);
24689a18d559STobias Grosser     OptPasses.run(*GPUModule);
24692f3073b5SPhilipp Schaad   }
24709a18d559STobias Grosser 
247174dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
247274dc3cb4STobias Grosser 
247374dc3cb4STobias Grosser   if (DumpKernelASM)
247474dc3cb4STobias Grosser     outs() << Assembly << "\n";
247574dc3cb4STobias Grosser 
247632837fe3STobias Grosser   GPUModule.release();
2477472f9654STobias Grosser   KernelIDs.clear();
247857793596STobias Grosser 
247957793596STobias Grosser   return Assembly;
248032837fe3STobias Grosser }
2481eadf76d3SSiddharth Bhat /// Construct an `isl_pw_aff_list` from a vector of `isl_pw_aff`
2482eadf76d3SSiddharth Bhat /// @param PwAffs The list of piecewise affine functions to create an
2483eadf76d3SSiddharth Bhat ///               `isl_pw_aff_list` from. We expect an rvalue ref because
2484eadf76d3SSiddharth Bhat ///               all the isl_pw_aff are used up by this function.
2485eadf76d3SSiddharth Bhat ///
2486eadf76d3SSiddharth Bhat /// @returns  The `isl_pw_aff_list`.
2487eadf76d3SSiddharth Bhat __isl_give isl_pw_aff_list *
2488eadf76d3SSiddharth Bhat createPwAffList(isl_ctx *Context,
2489eadf76d3SSiddharth Bhat                 const std::vector<__isl_take isl_pw_aff *> &&PwAffs) {
2490eadf76d3SSiddharth Bhat   isl_pw_aff_list *List = isl_pw_aff_list_alloc(Context, PwAffs.size());
2491eadf76d3SSiddharth Bhat 
2492eadf76d3SSiddharth Bhat   for (unsigned i = 0; i < PwAffs.size(); i++) {
2493eadf76d3SSiddharth Bhat     List = isl_pw_aff_list_insert(List, i, PwAffs[i]);
2494eadf76d3SSiddharth Bhat   }
2495eadf76d3SSiddharth Bhat   return List;
2496eadf76d3SSiddharth Bhat }
2497eadf76d3SSiddharth Bhat 
2498eadf76d3SSiddharth Bhat /// Align all the `PwAffs` such that they have the same parameter dimensions.
2499eadf76d3SSiddharth Bhat ///
2500eadf76d3SSiddharth Bhat /// We loop over all `pw_aff` and align all of their spaces together to
2501eadf76d3SSiddharth Bhat /// create a common space for all the `pw_aff`. This common space is the
2502eadf76d3SSiddharth Bhat /// `AlignSpace`. We then align all the `pw_aff` to this space. We start
2503eadf76d3SSiddharth Bhat /// with the given `SeedSpace`.
2504eadf76d3SSiddharth Bhat /// @param PwAffs    The list of piecewise affine functions we want to align.
2505eadf76d3SSiddharth Bhat ///                  This is an rvalue reference because the entire vector is
2506eadf76d3SSiddharth Bhat ///                  used up by the end of the operation.
2507eadf76d3SSiddharth Bhat /// @param SeedSpace The space to start the alignment process with.
2508eadf76d3SSiddharth Bhat /// @returns         A std::pair, whose first element is the aligned space,
2509eadf76d3SSiddharth Bhat ///                  whose second element is the vector of aligned piecewise
2510eadf76d3SSiddharth Bhat ///                  affines.
2511eadf76d3SSiddharth Bhat static std::pair<__isl_give isl_space *, std::vector<__isl_give isl_pw_aff *>>
2512eadf76d3SSiddharth Bhat alignPwAffs(const std::vector<__isl_take isl_pw_aff *> &&PwAffs,
2513eadf76d3SSiddharth Bhat             __isl_take isl_space *SeedSpace) {
2514eadf76d3SSiddharth Bhat   assert(SeedSpace && "Invalid seed space given.");
2515eadf76d3SSiddharth Bhat 
2516eadf76d3SSiddharth Bhat   isl_space *AlignSpace = SeedSpace;
2517eadf76d3SSiddharth Bhat   for (isl_pw_aff *PwAff : PwAffs) {
2518eadf76d3SSiddharth Bhat     isl_space *PwAffSpace = isl_pw_aff_get_domain_space(PwAff);
2519eadf76d3SSiddharth Bhat     AlignSpace = isl_space_align_params(AlignSpace, PwAffSpace);
2520eadf76d3SSiddharth Bhat   }
2521eadf76d3SSiddharth Bhat   std::vector<isl_pw_aff *> AdjustedPwAffs;
2522eadf76d3SSiddharth Bhat 
2523eadf76d3SSiddharth Bhat   for (unsigned i = 0; i < PwAffs.size(); i++) {
2524eadf76d3SSiddharth Bhat     isl_pw_aff *Adjusted = PwAffs[i];
2525eadf76d3SSiddharth Bhat     assert(Adjusted && "Invalid pw_aff given.");
2526eadf76d3SSiddharth Bhat     Adjusted = isl_pw_aff_align_params(Adjusted, isl_space_copy(AlignSpace));
2527eadf76d3SSiddharth Bhat     AdjustedPwAffs.push_back(Adjusted);
2528eadf76d3SSiddharth Bhat   }
2529eadf76d3SSiddharth Bhat   return std::make_pair(AlignSpace, AdjustedPwAffs);
2530eadf76d3SSiddharth Bhat }
253132837fe3STobias Grosser 
25329dfe4e7cSTobias Grosser namespace {
25339dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
25349dfe4e7cSTobias Grosser public:
25359dfe4e7cSTobias Grosser   static char ID;
25369dfe4e7cSTobias Grosser 
253717f01968SSiddharth Bhat   GPURuntime Runtime = GPURuntime::CUDA;
253817f01968SSiddharth Bhat 
253917f01968SSiddharth Bhat   GPUArch Architecture = GPUArch::NVPTX64;
254017f01968SSiddharth Bhat 
2541e938517eSTobias Grosser   /// The scop that is currently processed.
2542e938517eSTobias Grosser   Scop *S;
2543e938517eSTobias Grosser 
254438fc0aedSTobias Grosser   LoopInfo *LI;
254538fc0aedSTobias Grosser   DominatorTree *DT;
254638fc0aedSTobias Grosser   ScalarEvolution *SE;
254738fc0aedSTobias Grosser   const DataLayout *DL;
254838fc0aedSTobias Grosser   RegionInfo *RI;
254938fc0aedSTobias Grosser 
25509dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
25519dfe4e7cSTobias Grosser 
2552e938517eSTobias Grosser   /// Construct compilation options for PPCG.
2553e938517eSTobias Grosser   ///
2554e938517eSTobias Grosser   /// @returns The compilation options.
2555e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
2556e938517eSTobias Grosser     auto DebugOptions =
2557e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
2558e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
2559e938517eSTobias Grosser 
2560e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
2561e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
2562e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
2563e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
25648950ceadSTobias Grosser     DebugOptions->verbose = false;
2565e938517eSTobias Grosser 
2566e938517eSTobias Grosser     Options->debug = DebugOptions;
2567e938517eSTobias Grosser 
25689e3db2b7SSiddharth Bhat     Options->group_chains = false;
2569e938517eSTobias Grosser     Options->reschedule = true;
2570e938517eSTobias Grosser     Options->scale_tile_loops = false;
2571e938517eSTobias Grosser     Options->wrap = false;
2572e938517eSTobias Grosser 
2573e938517eSTobias Grosser     Options->non_negative_parameters = false;
2574e938517eSTobias Grosser     Options->ctx = nullptr;
2575e938517eSTobias Grosser     Options->sizes = nullptr;
2576e938517eSTobias Grosser 
25779e3db2b7SSiddharth Bhat     Options->tile = true;
25784eaedde5STobias Grosser     Options->tile_size = 32;
25794eaedde5STobias Grosser 
25809e3db2b7SSiddharth Bhat     Options->isolate_full_tiles = false;
25819e3db2b7SSiddharth Bhat 
2582130ca30fSTobias Grosser     Options->use_private_memory = PrivateMemory;
2583b513b491STobias Grosser     Options->use_shared_memory = SharedMemory;
2584b513b491STobias Grosser     Options->max_shared_memory = 48 * 1024;
2585e938517eSTobias Grosser 
2586e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
2587e938517eSTobias Grosser     Options->openmp = false;
2588e938517eSTobias Grosser     Options->linearize_device_arrays = true;
25899e3db2b7SSiddharth Bhat     Options->allow_gnu_extensions = false;
2590e938517eSTobias Grosser 
25919e3db2b7SSiddharth Bhat     Options->unroll_copy_shared = false;
25929e3db2b7SSiddharth Bhat     Options->unroll_gpu_tile = false;
25939e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
25949e3db2b7SSiddharth Bhat 
25959e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
25969e3db2b7SSiddharth Bhat     Options->hybrid = false;
2597e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
2598e938517eSTobias Grosser     Options->opencl_use_gpu = false;
2599e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
2600e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
2601e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
2602e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
2603e938517eSTobias Grosser 
2604e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
2605e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
2606e938517eSTobias Grosser 
2607e938517eSTobias Grosser     return Options;
2608e938517eSTobias Grosser   }
2609e938517eSTobias Grosser 
2610f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
2611f384594dSTobias Grosser   ///
2612f384594dSTobias Grosser   /// Instead of a normal access of the form:
2613f384594dSTobias Grosser   ///
2614f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
2615f384594dSTobias Grosser   ///
2616f384594dSTobias Grosser   /// a tagged access has the form
2617f384594dSTobias Grosser   ///
2618f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
2619f384594dSTobias Grosser   ///
2620f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
2621f384594dSTobias Grosser   /// triggered the access.
2622f384594dSTobias Grosser   ///
2623f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
2624f384594dSTobias Grosser   ///
2625f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
2626f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
2627b65ccc43STobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace().release());
2628f384594dSTobias Grosser 
2629f384594dSTobias Grosser     for (auto &Stmt : *S)
2630f384594dSTobias Grosser       for (auto &Acc : Stmt)
2631f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
26321515f6b9STobias Grosser           isl_map *Relation = Acc->getAccessRelation().release();
2633dcf8d696STobias Grosser           Relation =
2634dcf8d696STobias Grosser               isl_map_intersect_domain(Relation, Stmt.getDomain().release());
2635f384594dSTobias Grosser 
2636f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
2637f384594dSTobias Grosser           Space = isl_space_range(Space);
2638f384594dSTobias Grosser           Space = isl_space_from_range(Space);
2639fe46c3ffSTobias Grosser           Space =
2640fe46c3ffSTobias Grosser               isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
2641f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
2642f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
2643f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
2644f384594dSTobias Grosser         }
2645f384594dSTobias Grosser 
2646f384594dSTobias Grosser     return Accesses;
2647f384594dSTobias Grosser   }
2648f384594dSTobias Grosser 
2649f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
2650f384594dSTobias Grosser   ///
2651f384594dSTobias Grosser   /// @see getTaggedAccesses
2652f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
2653f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
2654f384594dSTobias Grosser   }
2655f384594dSTobias Grosser 
2656f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
2657f384594dSTobias Grosser   ///
2658f384594dSTobias Grosser   /// @see getTaggedAccesses
2659f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
2660f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
2661f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
2662f384594dSTobias Grosser   }
2663f384594dSTobias Grosser 
2664f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
2665f384594dSTobias Grosser   ///
2666f384594dSTobias Grosser   /// @see getTaggedAccesses
2667f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
2668f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
2669f384594dSTobias Grosser   }
2670f384594dSTobias Grosser 
2671aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
2672aef5196fSTobias Grosser   ///
2673aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
2674aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
2675aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
2676aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
2677aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
2678aef5196fSTobias Grosser   /// the data format that ppcg expects.
2679aef5196fSTobias Grosser   ///
2680aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
2681aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
2682aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
268300fd43b3SPhilip Pfaffe         S->getIslCtx().get(),
2684bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
268500fd43b3SPhilip Pfaffe     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx().get()));
2686aef5196fSTobias Grosser 
268725271b91STobias Grosser     for (const SCEV *P : S->parameters()) {
26889a63570bSTobias Grosser       isl_id *Id = S->getIdForParam(P).release();
2689aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2690aef5196fSTobias Grosser     }
2691aef5196fSTobias Grosser 
2692aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
269377eef90fSTobias Grosser       auto Id = Array->getBasePtrId().release();
2694aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2695aef5196fSTobias Grosser     }
2696aef5196fSTobias Grosser 
2697aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
2698aef5196fSTobias Grosser 
2699aef5196fSTobias Grosser     return Names;
2700aef5196fSTobias Grosser   }
2701aef5196fSTobias Grosser 
2702e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
2703e938517eSTobias Grosser   ///
2704f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
2705f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
2706f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
2707f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
2708e938517eSTobias Grosser   ///
2709e938517eSTobias Grosser   /// @returns A new ppcg scop.
2710e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
27119e3db2b7SSiddharth Bhat     MustKillsInfo KillsInfo = computeMustKillsInfo(*S);
27129e3db2b7SSiddharth Bhat 
2713e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
2714e938517eSTobias Grosser 
2715e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
2716a82f2d26SSiddharth Bhat     // enable live range reordering
2717a82f2d26SSiddharth Bhat     PPCGScop->options->live_range_reordering = 1;
2718e938517eSTobias Grosser 
2719e938517eSTobias Grosser     PPCGScop->start = 0;
2720e938517eSTobias Grosser     PPCGScop->end = 0;
2721e938517eSTobias Grosser 
27228ea1fc19STobias Grosser     PPCGScop->context = S->getContext().release();
272331df6f31STobias Grosser     PPCGScop->domain = S->getDomains().release();
27249e3db2b7SSiddharth Bhat     // TODO: investigate this further. PPCG calls collect_call_domains.
27258ea1fc19STobias Grosser     PPCGScop->call = isl_union_set_from_set(S->getContext().release());
2726f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
27275ab39ff2STobias Grosser     PPCGScop->reads = S->getReads().release();
2728e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
2729f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
27305ab39ff2STobias Grosser     PPCGScop->may_writes = S->getWrites().release();
2731f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
27325ab39ff2STobias Grosser     PPCGScop->must_writes = S->getMustWrites().release();
2733e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
27348dae41a1STobias Grosser     PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.release();
27358dae41a1STobias Grosser     PPCGScop->must_kills = KillsInfo.MustKills.release();
27369e3db2b7SSiddharth Bhat 
2737e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
2738a82f2d26SSiddharth Bhat     PPCGScop->independence =
2739a82f2d26SSiddharth Bhat         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
2740e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
2741e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
2742e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
2743e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
2744e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
2745e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
2746e938517eSTobias Grosser 
274761bd3a48STobias Grosser     PPCGScop->schedule = S->getScheduleTree().release();
2748a82f2d26SSiddharth Bhat     // If we have something non-trivial to kill, add it to the schedule
2749a82f2d26SSiddharth Bhat     if (KillsInfo.KillsSchedule.get())
2750a82f2d26SSiddharth Bhat       PPCGScop->schedule = isl_schedule_sequence(
27518dae41a1STobias Grosser           PPCGScop->schedule, KillsInfo.KillsSchedule.release());
2752a82f2d26SSiddharth Bhat 
2753a82f2d26SSiddharth Bhat     PPCGScop->names = getNames();
2754e938517eSTobias Grosser     PPCGScop->pet = nullptr;
2755e938517eSTobias Grosser 
2756f384594dSTobias Grosser     compute_tagger(PPCGScop);
2757f384594dSTobias Grosser     compute_dependences(PPCGScop);
27589e3db2b7SSiddharth Bhat     eliminate_dead_code(PPCGScop);
2759f384594dSTobias Grosser 
2760e938517eSTobias Grosser     return PPCGScop;
2761e938517eSTobias Grosser   }
2762e938517eSTobias Grosser 
2763a6d48f59SMichael Kruse   /// Collect the array accesses in a statement.
276460f63b49STobias Grosser   ///
276560f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
276660f63b49STobias Grosser   ///
276760f63b49STobias Grosser   /// @returns A list of array accesses.
276860f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
276960f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
277060f63b49STobias Grosser 
277160f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
277200fd43b3SPhilip Pfaffe       auto Access =
277300fd43b3SPhilip Pfaffe           isl_alloc_type(S->getIslCtx().get(), struct gpu_stmt_access);
277460f63b49STobias Grosser       Access->read = Acc->isRead();
277560f63b49STobias Grosser       Access->write = Acc->isWrite();
27761515f6b9STobias Grosser       Access->access = Acc->getAccessRelation().release();
277760f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
277860f63b49STobias Grosser       Space = isl_space_range(Space);
277960f63b49STobias Grosser       Space = isl_space_from_range(Space);
2780fe46c3ffSTobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
278160f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
278260f63b49STobias Grosser       Access->tagged_access =
27831515f6b9STobias Grosser           isl_map_domain_product(Acc->getAccessRelation().release(), Universe);
2784b513b491STobias Grosser       Access->exact_write = !Acc->isMayWrite();
2785fe46c3ffSTobias Grosser       Access->ref_id = Acc->getId().release();
278660f63b49STobias Grosser       Access->next = Accesses;
2787b513b491STobias Grosser       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
2788ecb94a03STobias Grosser       // TODO: Also mark one-element accesses to arrays as fixed-element.
2789ecb94a03STobias Grosser       Access->fixed_element =
2790ecb94a03STobias Grosser           Acc->isLatestScalarKind() ? isl_bool_true : isl_bool_false;
279160f63b49STobias Grosser       Accesses = Access;
279260f63b49STobias Grosser     }
279360f63b49STobias Grosser 
279460f63b49STobias Grosser     return Accesses;
279560f63b49STobias Grosser   }
279660f63b49STobias Grosser 
279769b46751STobias Grosser   /// Collect the list of GPU statements.
279869b46751STobias Grosser   ///
279969b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
280069b46751STobias Grosser   /// as well as a list with all memory accesses.
280169b46751STobias Grosser   ///
280269b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
280369b46751STobias Grosser   ///
280469b46751STobias Grosser   /// @returns A linked-list of statements.
280569b46751STobias Grosser   gpu_stmt *getStatements() {
280600fd43b3SPhilip Pfaffe     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx().get(), struct gpu_stmt,
280769b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
280869b46751STobias Grosser 
280969b46751STobias Grosser     int i = 0;
281069b46751STobias Grosser     for (auto &Stmt : *S) {
281169b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
281269b46751STobias Grosser 
2813dcf8d696STobias Grosser       GPUStmt->id = Stmt.getDomainId().release();
281469b46751STobias Grosser 
281569b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
281669b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
281760f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
281869b46751STobias Grosser       i++;
281969b46751STobias Grosser     }
282069b46751STobias Grosser 
282169b46751STobias Grosser     return Stmts;
282269b46751STobias Grosser   }
282369b46751STobias Grosser 
282460f63b49STobias Grosser   /// Derive the extent of an array.
282560f63b49STobias Grosser   ///
2826d58acf86STobias Grosser   /// The extent of an array is the set of elements that are within the
2827d58acf86STobias Grosser   /// accessed array. For the inner dimensions, the extent constraints are
2828d58acf86STobias Grosser   /// 0 and the size of the corresponding array dimension. For the first
2829d58acf86STobias Grosser   /// (outermost) dimension, the extent constraints are the minimal and maximal
2830d58acf86STobias Grosser   /// subscript value for the first dimension.
283160f63b49STobias Grosser   ///
283260f63b49STobias Grosser   /// @param Array The array to derive the extent for.
283360f63b49STobias Grosser   ///
283460f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
2835d2e57981STobias Grosser   isl::set getExtent(ScopArrayInfo *Array) {
2836d58acf86STobias Grosser     unsigned NumDims = Array->getNumberOfDimensions();
2837fa03cb76STobias Grosser 
2838fa03cb76STobias Grosser     if (Array->getNumberOfDimensions() == 0)
2839fa03cb76STobias Grosser       return isl::set::universe(Array->getSpace());
2840fa03cb76STobias Grosser 
2841fa03cb76STobias Grosser     isl::union_map Accesses = S->getAccesses(Array);
2842d2e57981STobias Grosser     isl::union_set AccessUSet = Accesses.range();
2843d2e57981STobias Grosser     AccessUSet = AccessUSet.coalesce();
2844d2e57981STobias Grosser     AccessUSet = AccessUSet.detect_equalities();
2845d2e57981STobias Grosser     AccessUSet = AccessUSet.coalesce();
2846d58acf86STobias Grosser 
2847d2e57981STobias Grosser     if (AccessUSet.is_empty())
2848d2e57981STobias Grosser       return isl::set::empty(Array->getSpace());
2849d58acf86STobias Grosser 
2850d2e57981STobias Grosser     isl::set AccessSet = AccessUSet.extract_set(Array->getSpace());
285160f63b49STobias Grosser 
2852d2e57981STobias Grosser     isl::local_space LS = isl::local_space(Array->getSpace());
2853d58acf86STobias Grosser 
2854d2e57981STobias Grosser     isl::pw_aff Val = isl::aff::var_on_domain(LS, isl::dim::set, 0);
2855d2e57981STobias Grosser     isl::pw_aff OuterMin = AccessSet.dim_min(0);
2856d2e57981STobias Grosser     isl::pw_aff OuterMax = AccessSet.dim_max(0);
2857d2e57981STobias Grosser     OuterMin = OuterMin.add_dims(isl::dim::in, Val.dim(isl::dim::in));
2858d2e57981STobias Grosser     OuterMax = OuterMax.add_dims(isl::dim::in, Val.dim(isl::dim::in));
2859d2e57981STobias Grosser     OuterMin = OuterMin.set_tuple_id(isl::dim::in, Array->getBasePtrId());
2860d2e57981STobias Grosser     OuterMax = OuterMax.set_tuple_id(isl::dim::in, Array->getBasePtrId());
2861d58acf86STobias Grosser 
2862d2e57981STobias Grosser     isl::set Extent = isl::set::universe(Array->getSpace());
2863d58acf86STobias Grosser 
2864d2e57981STobias Grosser     Extent = Extent.intersect(OuterMin.le_set(Val));
2865d2e57981STobias Grosser     Extent = Extent.intersect(OuterMax.ge_set(Val));
2866d58acf86STobias Grosser 
2867d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i)
2868d2e57981STobias Grosser       Extent = Extent.lower_bound_si(isl::dim::set, i, 0);
2869d58acf86STobias Grosser 
2870b7f68b8cSSiddharth Bhat     for (unsigned i = 0; i < NumDims; ++i) {
2871d2e57981STobias Grosser       isl::pw_aff PwAff = Array->getDimensionSizePw(i);
2872b7f68b8cSSiddharth Bhat 
2873b7f68b8cSSiddharth Bhat       // isl_pw_aff can be NULL for zero dimension. Only in the case of a
2874b7f68b8cSSiddharth Bhat       // Fortran array will we have a legitimate dimension.
2875d2e57981STobias Grosser       if (PwAff.is_null()) {
2876b7f68b8cSSiddharth Bhat         assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension");
2877b7f68b8cSSiddharth Bhat         continue;
2878b7f68b8cSSiddharth Bhat       }
2879b7f68b8cSSiddharth Bhat 
2880d2e57981STobias Grosser       isl::pw_aff Val = isl::aff::var_on_domain(
2881d2e57981STobias Grosser           isl::local_space(Array->getSpace()), isl::dim::set, i);
2882d2e57981STobias Grosser       PwAff = PwAff.add_dims(isl::dim::in, Val.dim(isl::dim::in));
2883d2e57981STobias Grosser       PwAff = PwAff.set_tuple_id(isl::dim::in, Val.get_tuple_id(isl::dim::in));
2884d2e57981STobias Grosser       isl::set Set = PwAff.gt_set(Val);
2885d2e57981STobias Grosser       Extent = Set.intersect(Extent);
2886d58acf86STobias Grosser     }
2887d58acf86STobias Grosser 
2888d58acf86STobias Grosser     return Extent;
288960f63b49STobias Grosser   }
289060f63b49STobias Grosser 
289160f63b49STobias Grosser   /// Derive the bounds of an array.
289260f63b49STobias Grosser   ///
289360f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
289460f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
289560f63b49STobias Grosser   /// ScopArrayInfo.
289660f63b49STobias Grosser   ///
289760f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
289860f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
289960f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
2900eadf76d3SSiddharth Bhat     std::vector<isl_pw_aff *> Bounds;
29019e3db2b7SSiddharth Bhat 
290260f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
290302293ed7STobias Grosser       if (isl_set_is_empty(PPCGArray.extent)) {
290402293ed7STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
290502293ed7STobias Grosser         isl_local_space *LS = isl_local_space_from_space(
290602293ed7STobias Grosser             isl_space_params(isl_set_get_space(Dom)));
290702293ed7STobias Grosser         isl_set_free(Dom);
29089e3db2b7SSiddharth Bhat         isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS));
2909eadf76d3SSiddharth Bhat         Bounds.push_back(Zero);
291002293ed7STobias Grosser       } else {
291160f63b49STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
291260f63b49STobias Grosser         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
291360f63b49STobias Grosser         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
291460f63b49STobias Grosser         isl_set_free(Dom);
291560f63b49STobias Grosser         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
291602293ed7STobias Grosser         isl_local_space *LS =
291702293ed7STobias Grosser             isl_local_space_from_space(isl_set_get_space(Dom));
291860f63b49STobias Grosser         isl_aff *One = isl_aff_zero_on_domain(LS);
291960f63b49STobias Grosser         One = isl_aff_add_constant_si(One, 1);
292060f63b49STobias Grosser         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
29218ea1fc19STobias Grosser         Bound = isl_pw_aff_gist(Bound, S->getContext().release());
2922eadf76d3SSiddharth Bhat         Bounds.push_back(Bound);
292360f63b49STobias Grosser       }
292402293ed7STobias Grosser     }
292560f63b49STobias Grosser 
292660f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
292777eef90fSTobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i).release();
292860f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
292960f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
2930e2950f46SSiddharth Bhat 
2931e2950f46SSiddharth Bhat       // We need types to work out, which is why we perform this weird dance
2932e2950f46SSiddharth Bhat       // with `Aff` and `Bound`. Consider this example:
2933e2950f46SSiddharth Bhat 
2934e2950f46SSiddharth Bhat       // LS: [p] -> { [] }
2935e2950f46SSiddharth Bhat       // Zero: [p] -> { [] } | Implicitly, is [p] -> { ~ -> [] }.
2936e2950f46SSiddharth Bhat       // This `~` is used to denote a "null space" (which is different from
2937e2950f46SSiddharth Bhat       // a *zero dimensional* space), which is something that ISL does not
2938e2950f46SSiddharth Bhat       // show you when pretty printing.
2939e2950f46SSiddharth Bhat 
2940e2950f46SSiddharth Bhat       // Bound: [p] -> { [] -> [(10p)] } | Here, the [] is a *zero dimensional*
2941e2950f46SSiddharth Bhat       // space, not a "null space" which does not exist at all.
2942e2950f46SSiddharth Bhat 
2943e2950f46SSiddharth Bhat       // When we pullback (precompose) `Bound` with `Zero`, we get:
2944e2950f46SSiddharth Bhat       // Bound . Zero =
2945e2950f46SSiddharth Bhat       //     ([p] -> { [] -> [(10p)] }) . ([p] -> {~ -> [] }) =
2946e2950f46SSiddharth Bhat       //     [p] -> { ~ -> [(10p)] } =
2947e2950f46SSiddharth Bhat       //     [p] -> [(10p)] (as ISL pretty prints it)
2948e2950f46SSiddharth Bhat       // Bound Pullback: [p] -> { [(10p)] }
2949e2950f46SSiddharth Bhat 
2950e2950f46SSiddharth Bhat       // We want this kind of an expression for Bound, without a
2951e2950f46SSiddharth Bhat       // zero dimensional input, but with a "null space" input for the types
2952e2950f46SSiddharth Bhat       // to work out later on, as far as I (Siddharth Bhat) understand.
2953e2950f46SSiddharth Bhat       // I was unable to find a reference to this in the ISL manual.
2954e2950f46SSiddharth Bhat       // References: Tobias Grosser.
2955e2950f46SSiddharth Bhat 
295660f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
2957eadf76d3SSiddharth Bhat       Bounds.push_back(Bound);
295860f63b49STobias Grosser     }
29599e3db2b7SSiddharth Bhat 
2960eadf76d3SSiddharth Bhat     /// To construct a `isl_multi_pw_aff`, we need all the indivisual `pw_aff`
2961eadf76d3SSiddharth Bhat     /// to have the same parameter dimensions. So, we need to align them to an
2962eadf76d3SSiddharth Bhat     /// appropriate space.
2963eadf76d3SSiddharth Bhat     /// Scop::Context is _not_ an appropriate space, because when we have
2964eadf76d3SSiddharth Bhat     /// `-polly-ignore-parameter-bounds` enabled, the Scop::Context does not
2965eadf76d3SSiddharth Bhat     /// contain all parameter dimensions.
2966eadf76d3SSiddharth Bhat     /// So, use the helper `alignPwAffs` to align all the `isl_pw_aff` together.
2967b65ccc43STobias Grosser     isl_space *SeedAlignSpace = S->getParamSpace().release();
2968eadf76d3SSiddharth Bhat     SeedAlignSpace = isl_space_add_dims(SeedAlignSpace, isl_dim_set, 1);
2969eadf76d3SSiddharth Bhat 
2970eadf76d3SSiddharth Bhat     isl_space *AlignSpace = nullptr;
2971eadf76d3SSiddharth Bhat     std::vector<isl_pw_aff *> AlignedBounds;
2972eadf76d3SSiddharth Bhat     std::tie(AlignSpace, AlignedBounds) =
2973eadf76d3SSiddharth Bhat         alignPwAffs(std::move(Bounds), SeedAlignSpace);
2974eadf76d3SSiddharth Bhat 
2975eadf76d3SSiddharth Bhat     assert(AlignSpace && "alignPwAffs did not initialise AlignSpace");
2976eadf76d3SSiddharth Bhat 
2977eadf76d3SSiddharth Bhat     isl_pw_aff_list *BoundsList =
297800fd43b3SPhilip Pfaffe         createPwAffList(S->getIslCtx().get(), std::move(AlignedBounds));
2979eadf76d3SSiddharth Bhat 
29809e3db2b7SSiddharth Bhat     isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent);
2981eadf76d3SSiddharth Bhat     BoundsSpace = isl_space_align_params(BoundsSpace, AlignSpace);
29829e3db2b7SSiddharth Bhat 
29839e3db2b7SSiddharth Bhat     assert(BoundsSpace && "Unable to access space of array.");
29849e3db2b7SSiddharth Bhat     assert(BoundsList && "Unable to access list of bounds.");
29859e3db2b7SSiddharth Bhat 
29869e3db2b7SSiddharth Bhat     PPCGArray.bound =
29879e3db2b7SSiddharth Bhat         isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList);
29889e3db2b7SSiddharth Bhat     assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly.");
298960f63b49STobias Grosser   }
299060f63b49STobias Grosser 
299160f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
299260f63b49STobias Grosser   ///
299360f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
299443f178bbSSiddharth Bhat   void createArrays(gpu_prog *PPCGProg,
299543f178bbSSiddharth Bhat                     const SmallVector<ScopArrayInfo *, 4> &ValidSAIs) {
299660f63b49STobias Grosser     int i = 0;
299743f178bbSSiddharth Bhat     for (auto &Array : ValidSAIs) {
299860f63b49STobias Grosser       std::string TypeName;
299960f63b49STobias Grosser       raw_string_ostream OS(TypeName);
300060f63b49STobias Grosser 
300160f63b49STobias Grosser       OS << *Array->getElementType();
300260f63b49STobias Grosser       TypeName = OS.str();
300360f63b49STobias Grosser 
300460f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
300560f63b49STobias Grosser 
300677eef90fSTobias Grosser       PPCGArray.space = Array->getSpace().release();
300760f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
300834eeabbcSSiddharth Bhat       PPCGArray.size = DL->getTypeAllocSize(Array->getElementType());
300960f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
301060f63b49STobias Grosser       PPCGArray.extent = nullptr;
301160f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
3012d2e57981STobias Grosser       PPCGArray.extent = getExtent(Array).release();
301360f63b49STobias Grosser       PPCGArray.n_ref = 0;
301460f63b49STobias Grosser       PPCGArray.refs = nullptr;
301560f63b49STobias Grosser       PPCGArray.accessed = true;
3016fe74a7a1STobias Grosser       PPCGArray.read_only_scalar =
3017fe74a7a1STobias Grosser           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
301860f63b49STobias Grosser       PPCGArray.has_compound_element = false;
301960f63b49STobias Grosser       PPCGArray.local = false;
302060f63b49STobias Grosser       PPCGArray.declare_local = false;
302160f63b49STobias Grosser       PPCGArray.global = false;
302260f63b49STobias Grosser       PPCGArray.linearize = false;
302360f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
302413c78e4dSTobias Grosser       PPCGArray.user = Array;
302560f63b49STobias Grosser 
30269e3db2b7SSiddharth Bhat       PPCGArray.bound = nullptr;
302760f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
30282d010dafSTobias Grosser       i++;
3029b9fc860aSTobias Grosser 
3030b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
3031ecb94a03STobias Grosser       PPCGArray.only_fixed_element = only_fixed_element_accessed(&PPCGArray);
303260f63b49STobias Grosser     }
303360f63b49STobias Grosser   }
303460f63b49STobias Grosser 
303560f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
303660f63b49STobias Grosser   ///
303760f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
303860f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
3039b65ccc43STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace().release());
304060f63b49STobias Grosser 
3041d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
304277eef90fSTobias Grosser       isl_space *Space = Array->getSpace().release();
304360f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
304460f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
304560f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
304660f63b49STobias Grosser     }
304760f63b49STobias Grosser 
304860f63b49STobias Grosser     return Maps;
304960f63b49STobias Grosser   }
305060f63b49STobias Grosser 
3051e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
3052e938517eSTobias Grosser   ///
3053a6d48f59SMichael Kruse   /// @returns A new gpu program description.
3054e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
3055e938517eSTobias Grosser 
3056e938517eSTobias Grosser     if (!PPCGScop)
3057e938517eSTobias Grosser       return nullptr;
3058e938517eSTobias Grosser 
305900fd43b3SPhilip Pfaffe     auto PPCGProg = isl_calloc_type(S->getIslCtx().get(), struct gpu_prog);
3060e938517eSTobias Grosser 
306100fd43b3SPhilip Pfaffe     PPCGProg->ctx = S->getIslCtx().get();
3062e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
3063aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
306460f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
306560f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
306660f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
306760f63b49STobias Grosser     PPCGProg->tagged_must_kill =
306860f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
306960f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
307060f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
30719e3db2b7SSiddharth Bhat     // TODO: verify that this assignment is correct.
3072e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
307369b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
307469b46751STobias Grosser     PPCGProg->stmts = getStatements();
307543f178bbSSiddharth Bhat 
307643f178bbSSiddharth Bhat     // Only consider arrays that have a non-empty extent.
307743f178bbSSiddharth Bhat     // Otherwise, this will cause us to consider the following kinds of
307843f178bbSSiddharth Bhat     // empty arrays:
307943f178bbSSiddharth Bhat     //     1. Invariant loads that are represented by SAI objects.
308043f178bbSSiddharth Bhat     //     2. Arrays with statically known zero size.
308143f178bbSSiddharth Bhat     auto ValidSAIsRange =
308243f178bbSSiddharth Bhat         make_filter_range(S->arrays(), [this](ScopArrayInfo *SAI) -> bool {
3083d2e57981STobias Grosser           return !getExtent(SAI).is_empty();
308443f178bbSSiddharth Bhat         });
308543f178bbSSiddharth Bhat     SmallVector<ScopArrayInfo *, 4> ValidSAIs(ValidSAIsRange.begin(),
308643f178bbSSiddharth Bhat                                               ValidSAIsRange.end());
308743f178bbSSiddharth Bhat 
308843f178bbSSiddharth Bhat     PPCGProg->n_array =
308943f178bbSSiddharth Bhat         ValidSAIs.size(); // std::distance(S->array_begin(), S->array_end());
309058166b13SMichael Kruse     PPCGProg->array = isl_calloc_array(
309158166b13SMichael Kruse         S->getIslCtx().get(), struct gpu_array_info, PPCGProg->n_array);
309260f63b49STobias Grosser 
309343f178bbSSiddharth Bhat     createArrays(PPCGProg, ValidSAIs);
3094e938517eSTobias Grosser 
3095ecb94a03STobias Grosser     PPCGProg->array_order = nullptr;
3096ecb94a03STobias Grosser     collect_order_dependences(PPCGProg);
3097ecb94a03STobias Grosser 
3098d58acf86STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
3099e938517eSTobias Grosser     return PPCGProg;
3100e938517eSTobias Grosser   }
3101e938517eSTobias Grosser 
310269b46751STobias Grosser   struct PrintGPUUserData {
310369b46751STobias Grosser     struct cuda_info *CudaInfo;
310469b46751STobias Grosser     struct gpu_prog *PPCGProg;
310569b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
310669b46751STobias Grosser   };
310769b46751STobias Grosser 
310869b46751STobias Grosser   /// Print a user statement node in the host code.
310969b46751STobias Grosser   ///
311069b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
311169b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
311269b46751STobias Grosser   /// host ast.
311369b46751STobias Grosser   ///
311469b46751STobias Grosser   /// @param P The printer to print to
311569b46751STobias Grosser   /// @param Options The printing options to use
311669b46751STobias Grosser   /// @param Node The node to print
311769b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
311869b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
311969b46751STobias Grosser   ///
312069b46751STobias Grosser   /// @returns A printer to which the output has been printed.
312169b46751STobias Grosser   static __isl_give isl_printer *
312269b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
312369b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
312469b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
312569b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
312669b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
312769b46751STobias Grosser 
312869b46751STobias Grosser     if (Id) {
312920251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
313020251734STobias Grosser 
313120251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
313220251734STobias Grosser       // otherwise try to call pet functionality that is not available in
313320251734STobias Grosser       // Polly.
313420251734STobias Grosser       if (IsUser) {
313520251734STobias Grosser         P = isl_printer_start_line(P);
313620251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
313720251734STobias Grosser         P = isl_printer_end_line(P);
313820251734STobias Grosser         isl_id_free(Id);
313920251734STobias Grosser         isl_ast_print_options_free(Options);
314020251734STobias Grosser         return P;
314120251734STobias Grosser       }
314220251734STobias Grosser 
314369b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
314469b46751STobias Grosser       isl_id_free(Id);
314569b46751STobias Grosser       Data->Kernels.push_back(Kernel);
314669b46751STobias Grosser     }
314769b46751STobias Grosser 
314869b46751STobias Grosser     return print_host_user(P, Options, Node, User);
314969b46751STobias Grosser   }
315069b46751STobias Grosser 
315169b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
315269b46751STobias Grosser   ///
315369b46751STobias Grosser   /// @param Kernel The kernel to print
315469b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
315500fd43b3SPhilip Pfaffe     auto *P = isl_printer_to_str(S->getIslCtx().get());
315669b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
315700fd43b3SPhilip Pfaffe     auto *Options = isl_ast_print_options_alloc(S->getIslCtx().get());
315869b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
315969b46751STobias Grosser     char *String = isl_printer_get_str(P);
3160936c74adSSiddharth Bhat     outs() << String << "\n";
316169b46751STobias Grosser     free(String);
316269b46751STobias Grosser     isl_printer_free(P);
316369b46751STobias Grosser   }
316469b46751STobias Grosser 
316569b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
316669b46751STobias Grosser   ///
316769b46751STobias Grosser   /// @param Tree An AST describing GPU code
316869b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
316969b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
317000fd43b3SPhilip Pfaffe     auto *P = isl_printer_to_str(S->getIslCtx().get());
317169b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
317269b46751STobias Grosser 
317369b46751STobias Grosser     PrintGPUUserData Data;
317469b46751STobias Grosser     Data.PPCGProg = PPCGProg;
317569b46751STobias Grosser 
317600fd43b3SPhilip Pfaffe     auto *Options = isl_ast_print_options_alloc(S->getIslCtx().get());
317769b46751STobias Grosser     Options =
317869b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
317969b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
318069b46751STobias Grosser     char *String = isl_printer_get_str(P);
3181936c74adSSiddharth Bhat     outs() << "# host\n";
3182936c74adSSiddharth Bhat     outs() << String << "\n";
318369b46751STobias Grosser     free(String);
318469b46751STobias Grosser     isl_printer_free(P);
318569b46751STobias Grosser 
318669b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
3187936c74adSSiddharth Bhat       outs() << "# kernel" << Kernel->id << "\n";
318869b46751STobias Grosser       printKernel(Kernel);
318969b46751STobias Grosser     }
319069b46751STobias Grosser   }
319169b46751STobias Grosser 
3192f384594dSTobias Grosser   // Generate a GPU program using PPCG.
3193f384594dSTobias Grosser   //
3194f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
3195f384594dSTobias Grosser   //
3196f384594dSTobias Grosser   //  1) Compute new schedule for the program.
3197f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
3198f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
3199f384594dSTobias Grosser   //
3200f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
3201f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
3202f384594dSTobias Grosser   // strategy directly from this pass.
3203f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
3204f384594dSTobias Grosser 
320500fd43b3SPhilip Pfaffe     auto PPCGGen = isl_calloc_type(S->getIslCtx().get(), struct gpu_gen);
3206f384594dSTobias Grosser 
320700fd43b3SPhilip Pfaffe     PPCGGen->ctx = S->getIslCtx().get();
3208f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
3209f384594dSTobias Grosser     PPCGGen->print = nullptr;
3210f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
321160c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
3212f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
3213f384594dSTobias Grosser     PPCGGen->tree = nullptr;
3214f384594dSTobias Grosser     PPCGGen->types.n = 0;
3215f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
3216f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
3217f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
3218f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
3219f384594dSTobias Grosser 
3220f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
3221f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
3222f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
32232341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
3224f384594dSTobias Grosser 
3225f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
3226f384594dSTobias Grosser 
3227e32498c9STobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
3228e32498c9STobias Grosser 
3229b5563c68STobias Grosser     Schedule =
3230b5563c68STobias Grosser         isl_schedule_align_params(Schedule, S->getFullParamSpace().release());
3231b5563c68STobias Grosser 
323269b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
3233aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
3234349506a9SNicola Zaghen       LLVM_DEBUG(dbgs() << getUniqueScopName(S)
3235638316daSSiddharth Bhat                         << " does not have permutable bands. Bailing out\n";);
323669b46751STobias Grosser     } else {
3237861a387fSTobias Grosser       const bool CreateTransferToFromDevice = !PollyManagedMemory;
3238861a387fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule, CreateTransferToFromDevice);
323969b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
324069b46751STobias Grosser     }
3241aef5196fSTobias Grosser 
3242f384594dSTobias Grosser     if (DumpSchedule) {
324300fd43b3SPhilip Pfaffe       isl_printer *P = isl_printer_to_str(S->getIslCtx().get());
3244f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
3245f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
3246f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
3247f384594dSTobias Grosser       if (Schedule)
3248f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
3249f384594dSTobias Grosser       else
3250f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
3251f384594dSTobias Grosser 
3252936c74adSSiddharth Bhat       outs() << isl_printer_get_str(P) << "\n";
3253f384594dSTobias Grosser       isl_printer_free(P);
3254f384594dSTobias Grosser     }
3255f384594dSTobias Grosser 
325669b46751STobias Grosser     if (DumpCode) {
3257936c74adSSiddharth Bhat       outs() << "Code\n";
3258936c74adSSiddharth Bhat       outs() << "====\n";
325969b46751STobias Grosser       if (PPCGGen->tree)
326069b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
326169b46751STobias Grosser       else
3262936c74adSSiddharth Bhat         outs() << "No code generated\n";
326369b46751STobias Grosser     }
326469b46751STobias Grosser 
3265f384594dSTobias Grosser     isl_schedule_free(Schedule);
3266f384594dSTobias Grosser 
3267f384594dSTobias Grosser     return PPCGGen;
3268f384594dSTobias Grosser   }
3269f384594dSTobias Grosser 
3270f384594dSTobias Grosser   /// Free gpu_gen structure.
3271f384594dSTobias Grosser   ///
3272f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
3273f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
3274f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
3275f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
3276f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
3277f384594dSTobias Grosser     free(PPCGGen);
3278f384594dSTobias Grosser   }
3279f384594dSTobias Grosser 
3280b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
3281b307ed4dSTobias Grosser   ///
3282b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
3283b307ed4dSTobias Grosser   /// ourselves.
3284b307ed4dSTobias Grosser   ///
3285b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
3286b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
3287b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
3288b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
3289b307ed4dSTobias Grosser     free(PPCGScop->options);
3290b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
3291b307ed4dSTobias Grosser   }
3292b307ed4dSTobias Grosser 
329382f2af35STobias Grosser   /// Approximate the number of points in the set.
329482f2af35STobias Grosser   ///
329582f2af35STobias Grosser   /// This function returns an ast expression that overapproximates the number
329682f2af35STobias Grosser   /// of points in an isl set through the rectangular hull surrounding this set.
329782f2af35STobias Grosser   ///
329882f2af35STobias Grosser   /// @param Set   The set to count.
329982f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
330082f2af35STobias Grosser   ///              expression.
330182f2af35STobias Grosser   ///
330282f2af35STobias Grosser   /// @returns An approximation of the number of points in the set.
330382f2af35STobias Grosser   __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set,
330482f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
330582f2af35STobias Grosser 
330682f2af35STobias Grosser     isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1);
330782f2af35STobias Grosser     auto *Expr = isl_ast_expr_from_val(isl_val_copy(One));
330882f2af35STobias Grosser 
330982f2af35STobias Grosser     isl_space *Space = isl_set_get_space(Set);
331082f2af35STobias Grosser     Space = isl_space_params(Space);
331182f2af35STobias Grosser     auto *Univ = isl_set_universe(Space);
331282f2af35STobias Grosser     isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One);
331382f2af35STobias Grosser 
33143044dc51SMichael Kruse     for (long i = 0, n = isl_set_dim(Set, isl_dim_set); i < n; i++) {
331582f2af35STobias Grosser       isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i);
331682f2af35STobias Grosser       isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i);
331782f2af35STobias Grosser       isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min);
331882f2af35STobias Grosser       DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff));
331982f2af35STobias Grosser       auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize);
332082f2af35STobias Grosser       Expr = isl_ast_expr_mul(Expr, DimSizeExpr);
332182f2af35STobias Grosser     }
332282f2af35STobias Grosser 
332382f2af35STobias Grosser     isl_set_free(Set);
332482f2af35STobias Grosser     isl_pw_aff_free(OneAff);
332582f2af35STobias Grosser 
332682f2af35STobias Grosser     return Expr;
332782f2af35STobias Grosser   }
332882f2af35STobias Grosser 
332982f2af35STobias Grosser   /// Approximate a number of dynamic instructions executed by a given
333082f2af35STobias Grosser   /// statement.
333182f2af35STobias Grosser   ///
333282f2af35STobias Grosser   /// @param Stmt  The statement for which to compute the number of dynamic
333382f2af35STobias Grosser   ///              instructions.
333482f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
333582f2af35STobias Grosser   ///              expression.
333682f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
333782f2af35STobias Grosser   ///          by @p Stmt.
333882f2af35STobias Grosser   __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt,
333982f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
3340dcf8d696STobias Grosser     auto Iterations = approxPointsInSet(Stmt.getDomain().release(), Build);
334182f2af35STobias Grosser 
334282f2af35STobias Grosser     long InstCount = 0;
334382f2af35STobias Grosser 
334482f2af35STobias Grosser     if (Stmt.isBlockStmt()) {
334582f2af35STobias Grosser       auto *BB = Stmt.getBasicBlock();
334682f2af35STobias Grosser       InstCount = std::distance(BB->begin(), BB->end());
334782f2af35STobias Grosser     } else {
334882f2af35STobias Grosser       auto *R = Stmt.getRegion();
334982f2af35STobias Grosser 
335082f2af35STobias Grosser       for (auto *BB : R->blocks()) {
335182f2af35STobias Grosser         InstCount += std::distance(BB->begin(), BB->end());
335282f2af35STobias Grosser       }
335382f2af35STobias Grosser     }
335482f2af35STobias Grosser 
335500fd43b3SPhilip Pfaffe     isl_val *InstVal = isl_val_int_from_si(S->getIslCtx().get(), InstCount);
335682f2af35STobias Grosser     auto *InstExpr = isl_ast_expr_from_val(InstVal);
335782f2af35STobias Grosser     return isl_ast_expr_mul(InstExpr, Iterations);
335882f2af35STobias Grosser   }
335982f2af35STobias Grosser 
336082f2af35STobias Grosser   /// Approximate dynamic instructions executed in scop.
336182f2af35STobias Grosser   ///
336282f2af35STobias Grosser   /// @param S     The scop for which to approximate dynamic instructions.
336382f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
336482f2af35STobias Grosser   ///              expression.
336582f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
336682f2af35STobias Grosser   ///          in @p S.
336782f2af35STobias Grosser   __isl_give isl_ast_expr *
336882f2af35STobias Grosser   getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) {
336982f2af35STobias Grosser     isl_ast_expr *Instructions;
337082f2af35STobias Grosser 
337100fd43b3SPhilip Pfaffe     isl_val *Zero = isl_val_int_from_si(S.getIslCtx().get(), 0);
337282f2af35STobias Grosser     Instructions = isl_ast_expr_from_val(Zero);
337382f2af35STobias Grosser 
337482f2af35STobias Grosser     for (ScopStmt &Stmt : S) {
337582f2af35STobias Grosser       isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build);
337682f2af35STobias Grosser       Instructions = isl_ast_expr_add(Instructions, StmtInstructions);
337782f2af35STobias Grosser     }
337882f2af35STobias Grosser     return Instructions;
337982f2af35STobias Grosser   }
338082f2af35STobias Grosser 
338182f2af35STobias Grosser   /// Create a check that ensures sufficient compute in scop.
338282f2af35STobias Grosser   ///
338382f2af35STobias Grosser   /// @param S     The scop for which to ensure sufficient compute.
338482f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
338582f2af35STobias Grosser   ///              expression.
338682f2af35STobias Grosser   /// @returns An expression that evaluates to TRUE in case of sufficient
338782f2af35STobias Grosser   ///          compute and to FALSE, otherwise.
338882f2af35STobias Grosser   __isl_give isl_ast_expr *
338982f2af35STobias Grosser   createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) {
339082f2af35STobias Grosser     auto Iterations = getNumberOfIterations(S, Build);
339100fd43b3SPhilip Pfaffe     auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx().get(), MinCompute);
339282f2af35STobias Grosser     auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal);
339382f2af35STobias Grosser     return isl_ast_expr_ge(Iterations, MinComputeExpr);
339482f2af35STobias Grosser   }
339582f2af35STobias Grosser 
3396f291c8d5SSiddharth Bhat   /// Check if the basic block contains a function we cannot codegen for GPU
3397f291c8d5SSiddharth Bhat   /// kernels.
3398f291c8d5SSiddharth Bhat   ///
3399f291c8d5SSiddharth Bhat   /// If this basic block does something with a `Function` other than calling
3400f291c8d5SSiddharth Bhat   /// a function that we support in a kernel, return true.
34018fc6cdfbSTobias Grosser   bool containsInvalidKernelFunctionInBlock(const BasicBlock *BB,
34028fc6cdfbSTobias Grosser                                             bool AllowCUDALibDevice) {
3403f291c8d5SSiddharth Bhat     for (const Instruction &Inst : *BB) {
3404f291c8d5SSiddharth Bhat       const CallInst *Call = dyn_cast<CallInst>(&Inst);
34058fc6cdfbSTobias Grosser       if (Call && isValidFunctionInKernel(Call->getCalledFunction(),
340678027437SSiddharth Bhat                                           AllowCUDALibDevice))
3407f291c8d5SSiddharth Bhat         continue;
3408f291c8d5SSiddharth Bhat 
340978027437SSiddharth Bhat       for (Value *Op : Inst.operands())
341078027437SSiddharth Bhat         // Look for (<func-type>*) among operands of Inst
341178027437SSiddharth Bhat         if (auto PtrTy = dyn_cast<PointerType>(Op->getType())) {
341278027437SSiddharth Bhat           if (isa<FunctionType>(PtrTy->getElementType())) {
3413349506a9SNicola Zaghen             LLVM_DEBUG(dbgs()
3414349506a9SNicola Zaghen                        << Inst << " has illegal use of function in kernel.\n");
3415bccaea57SSiddharth Bhat             return true;
3416bccaea57SSiddharth Bhat           }
3417f291c8d5SSiddharth Bhat         }
341878027437SSiddharth Bhat     }
3419bccaea57SSiddharth Bhat     return false;
3420bccaea57SSiddharth Bhat   }
3421bccaea57SSiddharth Bhat 
3422f291c8d5SSiddharth Bhat   /// Return whether the Scop S uses functions in a way that we do not support.
34238fc6cdfbSTobias Grosser   bool containsInvalidKernelFunction(const Scop &S, bool AllowCUDALibDevice) {
3424bccaea57SSiddharth Bhat     for (auto &Stmt : S) {
3425bccaea57SSiddharth Bhat       if (Stmt.isBlockStmt()) {
34268fc6cdfbSTobias Grosser         if (containsInvalidKernelFunctionInBlock(Stmt.getBasicBlock(),
34278fc6cdfbSTobias Grosser                                                  AllowCUDALibDevice))
3428bccaea57SSiddharth Bhat           return true;
3429bccaea57SSiddharth Bhat       } else {
3430bccaea57SSiddharth Bhat         assert(Stmt.isRegionStmt() &&
3431bccaea57SSiddharth Bhat                "Stmt was neither block nor region statement");
3432bccaea57SSiddharth Bhat         for (const BasicBlock *BB : Stmt.getRegion()->blocks())
34338fc6cdfbSTobias Grosser           if (containsInvalidKernelFunctionInBlock(BB, AllowCUDALibDevice))
3434bccaea57SSiddharth Bhat             return true;
3435bccaea57SSiddharth Bhat       }
3436bccaea57SSiddharth Bhat     }
3437bccaea57SSiddharth Bhat     return false;
3438bccaea57SSiddharth Bhat   }
3439bccaea57SSiddharth Bhat 
344038fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
344138fc0aedSTobias Grosser   ///
344232837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
344332837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
344432837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
344538fc0aedSTobias Grosser     ScopAnnotator Annotator;
344638fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
344738fc0aedSTobias Grosser 
344838fc0aedSTobias Grosser     Region *R = &S->getRegion();
344938fc0aedSTobias Grosser 
345038fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
345138fc0aedSTobias Grosser 
345238fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
345338fc0aedSTobias Grosser 
345438fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
345538fc0aedSTobias Grosser 
345638fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
345738fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
345838fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
345938fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
346038fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
346138fc0aedSTobias Grosser     // code generating this scop.
346203346c27SSiddharth Bhat     BBPair StartExitBlocks;
346303346c27SSiddharth Bhat     BranchInst *CondBr = nullptr;
346403346c27SSiddharth Bhat     std::tie(StartExitBlocks, CondBr) =
34652d950f36SPhilip Pfaffe         executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI);
3466256070d8SAndreas Simbuerger     BasicBlock *StartBlock = std::get<0>(StartExitBlocks);
346738fc0aedSTobias Grosser 
346803346c27SSiddharth Bhat     assert(CondBr && "CondBr not initialized by executeScopConditionally");
346903346c27SSiddharth Bhat 
34702d950f36SPhilip Pfaffe     GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S,
347117f01968SSiddharth Bhat                                StartBlock, Prog, Runtime, Architecture);
3472acf80064SEli Friedman 
347338fc0aedSTobias Grosser     // TODO: Handle LICM
347438fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
347538fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
3476cb1aef8dSTobias Grosser 
347700fd43b3SPhilip Pfaffe     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx().get());
34782b852e2eSPhilip Pfaffe     isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build);
347982f2af35STobias Grosser     isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build);
348082f2af35STobias Grosser     Condition = isl_ast_expr_and(Condition, SufficientCompute);
3481cb1aef8dSTobias Grosser     isl_ast_build_free(Build);
3482cb1aef8dSTobias Grosser 
34839e3db2b7SSiddharth Bhat     // preload invariant loads. Note: This should happen before the RTC
34849e3db2b7SSiddharth Bhat     // because the RTC may depend on values that are invariant load hoisted.
348571dfb3ebSSiddharth Bhat     if (!NodeBuilder.preloadInvariantLoads()) {
34862fb847fbSTobias Grosser       // Patch the introduced branch condition to ensure that we always execute
34872fb847fbSTobias Grosser       // the original SCoP.
34882fb847fbSTobias Grosser       auto *FalseI1 = Builder.getFalse();
34892fb847fbSTobias Grosser       auto *SplitBBTerm = Builder.GetInsertBlock()->getTerminator();
34902fb847fbSTobias Grosser       SplitBBTerm->setOperand(0, FalseI1);
34912fb847fbSTobias Grosser 
3492349506a9SNicola Zaghen       LLVM_DEBUG(dbgs() << "preloading invariant loads failed in function: " +
34934ebeb356SSiddharth Bhat                                S->getFunction().getName() +
34944ebeb356SSiddharth Bhat                                " | Scop Region: " + S->getNameStr());
349571dfb3ebSSiddharth Bhat       // adjust the dominator tree accordingly.
349671dfb3ebSSiddharth Bhat       auto *ExitingBlock = StartBlock->getUniqueSuccessor();
349771dfb3ebSSiddharth Bhat       assert(ExitingBlock);
349871dfb3ebSSiddharth Bhat       auto *MergeBlock = ExitingBlock->getUniqueSuccessor();
349971dfb3ebSSiddharth Bhat       assert(MergeBlock);
350071dfb3ebSSiddharth Bhat       polly::markBlockUnreachable(*StartBlock, Builder);
350171dfb3ebSSiddharth Bhat       polly::markBlockUnreachable(*ExitingBlock, Builder);
350271dfb3ebSSiddharth Bhat       auto *ExitingBB = S->getExitingBlock();
350371dfb3ebSSiddharth Bhat       assert(ExitingBB);
35049e3db2b7SSiddharth Bhat 
350571dfb3ebSSiddharth Bhat       DT->changeImmediateDominator(MergeBlock, ExitingBB);
350671dfb3ebSSiddharth Bhat       DT->eraseNode(ExitingBlock);
350771dfb3ebSSiddharth Bhat       isl_ast_expr_free(Condition);
350871dfb3ebSSiddharth Bhat       isl_ast_node_free(Root);
350971dfb3ebSSiddharth Bhat     } else {
351071dfb3ebSSiddharth Bhat 
35117b9f5ca2SSiddharth Bhat       if (polly::PerfMonitoring) {
35127b9f5ca2SSiddharth Bhat         PerfMonitor P(*S, EnteringBB->getParent()->getParent());
35137b9f5ca2SSiddharth Bhat         P.initialize();
35147b9f5ca2SSiddharth Bhat         P.insertRegionStart(SplitBlock->getTerminator());
35157b9f5ca2SSiddharth Bhat 
35167b9f5ca2SSiddharth Bhat         // TODO: actually think if this is the correct exiting block to place
35177b9f5ca2SSiddharth Bhat         // the `end` performance marker. Invariant load hoisting changes
35187b9f5ca2SSiddharth Bhat         // the CFG in a way that I do not precisely understand, so I
35197b9f5ca2SSiddharth Bhat         // (Siddharth<[email protected]>) should come back to this and
35207b9f5ca2SSiddharth Bhat         // think about which exiting block to use.
35217b9f5ca2SSiddharth Bhat         auto *ExitingBlock = StartBlock->getUniqueSuccessor();
35227b9f5ca2SSiddharth Bhat         assert(ExitingBlock);
35237b9f5ca2SSiddharth Bhat         BasicBlock *MergeBlock = ExitingBlock->getUniqueSuccessor();
35247b9f5ca2SSiddharth Bhat         P.insertRegionEnd(MergeBlock->getTerminator());
35257b9f5ca2SSiddharth Bhat       }
35267b9f5ca2SSiddharth Bhat 
352771dfb3ebSSiddharth Bhat       NodeBuilder.addParameters(S->getContext().release());
3528cb1aef8dSTobias Grosser       Value *RTC = NodeBuilder.createRTC(Condition);
3529cb1aef8dSTobias Grosser       Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
3530cb1aef8dSTobias Grosser 
353138fc0aedSTobias Grosser       Builder.SetInsertPoint(&*StartBlock->begin());
3532fa7b0802STobias Grosser 
353338fc0aedSTobias Grosser       NodeBuilder.create(Root);
353471dfb3ebSSiddharth Bhat     }
35355857b701STobias Grosser 
3536bc653f20STobias Grosser     /// In case a sequential kernel has more surrounding loops as any parallel
3537bc653f20STobias Grosser     /// kernel, the SCoP is probably mostly sequential. Hence, there is no
3538de244eb4STobias Grosser     /// point in running it on a GPU.
3539bc653f20STobias Grosser     if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel)
354003346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
3541bc653f20STobias Grosser 
35425857b701STobias Grosser     if (!NodeBuilder.BuildSuccessful)
354303346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
354438fc0aedSTobias Grosser   }
354538fc0aedSTobias Grosser 
3546e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
3547e938517eSTobias Grosser     S = &CurrentScop;
354838fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
354938fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
355038fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
35517b5a4dfdSTobias Grosser     DL = &S->getRegion().getEntry()->getModule()->getDataLayout();
355238fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
3553e938517eSTobias Grosser 
3554349506a9SNicola Zaghen     LLVM_DEBUG(dbgs() << "PPCGCodeGen running on : " << getUniqueScopName(S)
3555656e6295SSiddharth Bhat                       << " | loop depth: " << S->getMaxLoopDepth() << "\n");
3556656e6295SSiddharth Bhat 
3557f291c8d5SSiddharth Bhat     // We currently do not support functions other than intrinsics inside
3558f291c8d5SSiddharth Bhat     // kernels, as code generation will need to offload function calls to the
3559f291c8d5SSiddharth Bhat     // kernel. This may lead to a kernel trying to call a function on the host.
3560bccaea57SSiddharth Bhat     // This also allows us to prevent codegen from trying to take the
3561bccaea57SSiddharth Bhat     // address of an intrinsic function to send to the kernel.
35628fc6cdfbSTobias Grosser     if (containsInvalidKernelFunction(CurrentScop,
35638fc6cdfbSTobias Grosser                                       Architecture == GPUArch::NVPTX64)) {
3564349506a9SNicola Zaghen       LLVM_DEBUG(
3565638316daSSiddharth Bhat           dbgs() << getUniqueScopName(S)
3566638316daSSiddharth Bhat                  << " contains function which cannot be materialised in a GPU "
3567f291c8d5SSiddharth Bhat                     "kernel. Bailing out.\n";);
3568bccaea57SSiddharth Bhat       return false;
3569f291c8d5SSiddharth Bhat     }
3570bccaea57SSiddharth Bhat 
3571e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
3572e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
3573f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
357438fc0aedSTobias Grosser 
357502ca346eSSingapuram Sanjay Srivallabh     if (PPCGGen->tree) {
357632837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
357702ca346eSSingapuram Sanjay Srivallabh       CurrentScop.markAsToBeSkipped();
3578638316daSSiddharth Bhat     } else {
3579349506a9SNicola Zaghen       LLVM_DEBUG(dbgs() << getUniqueScopName(S)
3580638316daSSiddharth Bhat                         << " has empty PPCGGen->tree. Bailing out.\n");
358102ca346eSSingapuram Sanjay Srivallabh     }
358238fc0aedSTobias Grosser 
3583b307ed4dSTobias Grosser     freeOptions(PPCGScop);
3584f384594dSTobias Grosser     freePPCGGen(PPCGGen);
3585e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
3586e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
3587e938517eSTobias Grosser 
3588e938517eSTobias Grosser     return true;
3589e938517eSTobias Grosser   }
35909dfe4e7cSTobias Grosser 
35919dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
35929dfe4e7cSTobias Grosser 
35939dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
3594a4f447c2SMichael Kruse     ScopPass::getAnalysisUsage(AU);
3595a4f447c2SMichael Kruse 
35969dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
35979dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
35989dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
35995cc87e3aSPhilip Pfaffe     AU.addRequired<ScopDetectionWrapperPass>();
36009dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
36019dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
36029dfe4e7cSTobias Grosser 
36039dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
36049dfe4e7cSTobias Grosser     //        region tree.
36059dfe4e7cSTobias Grosser   }
36069dfe4e7cSTobias Grosser };
360724222c73STobias Grosser } // namespace
36089dfe4e7cSTobias Grosser 
36099dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
36109dfe4e7cSTobias Grosser 
361117f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) {
361217f01968SSiddharth Bhat   PPCGCodeGeneration *generator = new PPCGCodeGeneration();
361317f01968SSiddharth Bhat   generator->Runtime = Runtime;
361417f01968SSiddharth Bhat   generator->Architecture = Arch;
361517f01968SSiddharth Bhat   return generator;
361617f01968SSiddharth Bhat }
36179dfe4e7cSTobias Grosser 
36189dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
36199dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
36209dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
36219dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
36229dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
36239dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
36249dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
36255cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
36269dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
36279dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
3628