19dfe4e7cSTobias Grosser //===------ PPCGCodeGeneration.cpp - Polly Accelerator Code Generation. ---===//
29dfe4e7cSTobias Grosser //
39dfe4e7cSTobias Grosser //                     The LLVM Compiler Infrastructure
49dfe4e7cSTobias Grosser //
59dfe4e7cSTobias Grosser // This file is distributed under the University of Illinois Open Source
69dfe4e7cSTobias Grosser // License. See LICENSE.TXT for details.
79dfe4e7cSTobias Grosser //
89dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===//
99dfe4e7cSTobias Grosser //
109dfe4e7cSTobias Grosser // Take a scop created by ScopInfo and map it to GPU code using the ppcg
119dfe4e7cSTobias Grosser // GPU mapping strategy.
129dfe4e7cSTobias Grosser //
139dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===//
149dfe4e7cSTobias Grosser 
1517f01968SSiddharth Bhat #include "polly/CodeGen/PPCGCodeGeneration.h"
16*71dfb3ebSSiddharth Bhat #include "polly/CodeGen/CodeGeneration.h"
17cb1aef8dSTobias Grosser #include "polly/CodeGen/IslAst.h"
189dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.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"
279dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h"
289dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h"
299dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h"
309dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
3174dc3cb4STobias Grosser #include "llvm/Analysis/TargetLibraryInfo.h"
3274dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h"
3374dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h"
34e1a98343STobias Grosser #include "llvm/IR/Verifier.h"
358fc6cdfbSTobias Grosser #include "llvm/IRReader/IRReader.h"
368fc6cdfbSTobias Grosser #include "llvm/Linker/Linker.h"
3774dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h"
3874dc3cb4STobias Grosser #include "llvm/Support/TargetSelect.h"
3974dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h"
409a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h"
41750160e2STobias Grosser #include "llvm/Transforms/Utils/BasicBlockUtils.h"
429dfe4e7cSTobias Grosser 
43f384594dSTobias Grosser #include "isl/union_map.h"
44f384594dSTobias Grosser 
45e938517eSTobias Grosser extern "C" {
46a56f8f8eSTobias Grosser #include "ppcg/cuda.h"
47a56f8f8eSTobias Grosser #include "ppcg/gpu.h"
48a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h"
49a56f8f8eSTobias Grosser #include "ppcg/ppcg.h"
50a56f8f8eSTobias Grosser #include "ppcg/schedule.h"
51e938517eSTobias Grosser }
52e938517eSTobias Grosser 
539dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h"
549dfe4e7cSTobias Grosser 
559dfe4e7cSTobias Grosser using namespace polly;
569dfe4e7cSTobias Grosser using namespace llvm;
579dfe4e7cSTobias Grosser 
589dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg"
599dfe4e7cSTobias Grosser 
60f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
61f384594dSTobias Grosser                                   cl::desc("Dump the computed GPU Schedule"),
62681bd568STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
63f384594dSTobias Grosser                                   cl::cat(PollyCategory));
6469b46751STobias Grosser 
6569b46751STobias Grosser static cl::opt<bool>
6669b46751STobias Grosser     DumpCode("polly-acc-dump-code",
6769b46751STobias Grosser              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
6869b46751STobias Grosser              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
6969b46751STobias Grosser 
7032837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
7132837fe3STobias Grosser                                   cl::desc("Dump the kernel LLVM-IR"),
7232837fe3STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
7332837fe3STobias Grosser                                   cl::cat(PollyCategory));
7432837fe3STobias Grosser 
7574dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
7674dc3cb4STobias Grosser                                    cl::desc("Dump the kernel assembly code"),
7774dc3cb4STobias Grosser                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
7874dc3cb4STobias Grosser                                    cl::cat(PollyCategory));
7974dc3cb4STobias Grosser 
8074dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath",
8174dc3cb4STobias Grosser                               cl::desc("Allow unsafe math optimizations"),
8274dc3cb4STobias Grosser                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
8374dc3cb4STobias Grosser                               cl::cat(PollyCategory));
84b513b491STobias Grosser static cl::opt<bool> SharedMemory("polly-acc-use-shared",
85b513b491STobias Grosser                                   cl::desc("Use shared memory"), cl::Hidden,
86b513b491STobias Grosser                                   cl::init(false), cl::ZeroOrMore,
87b513b491STobias Grosser                                   cl::cat(PollyCategory));
88130ca30fSTobias Grosser static cl::opt<bool> PrivateMemory("polly-acc-use-private",
89130ca30fSTobias Grosser                                    cl::desc("Use private memory"), cl::Hidden,
90130ca30fSTobias Grosser                                    cl::init(false), cl::ZeroOrMore,
91130ca30fSTobias Grosser                                    cl::cat(PollyCategory));
9274dc3cb4STobias Grosser 
93abed4969SSiddharth Bhat static cl::opt<bool> ManagedMemory("polly-acc-codegen-managed-memory",
94abed4969SSiddharth Bhat                                    cl::desc("Generate Host kernel code assuming"
95abed4969SSiddharth Bhat                                             " that all memory has been"
96abed4969SSiddharth Bhat                                             " declared as managed memory"),
97abed4969SSiddharth Bhat                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
98abed4969SSiddharth Bhat                                    cl::cat(PollyCategory));
99abed4969SSiddharth Bhat 
10065d7f72fSSiddharth Bhat static cl::opt<bool>
10165d7f72fSSiddharth Bhat     FailOnVerifyModuleFailure("polly-acc-fail-on-verify-module-failure",
10265d7f72fSSiddharth Bhat                               cl::desc("Fail and generate a backtrace if"
10365d7f72fSSiddharth Bhat                                        " verifyModule fails on the GPU "
10465d7f72fSSiddharth Bhat                                        " kernel module."),
10565d7f72fSSiddharth Bhat                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
10665d7f72fSSiddharth Bhat                               cl::cat(PollyCategory));
10765d7f72fSSiddharth Bhat 
1088fc6cdfbSTobias Grosser static cl::opt<std::string> CUDALibDevice(
1098fc6cdfbSTobias Grosser     "polly-acc-libdevice", cl::desc("Path to CUDA libdevice"), cl::Hidden,
1108fc6cdfbSTobias Grosser     cl::init("/usr/local/cuda/nvvm/libdevice/libdevice.compute_20.10.ll"),
1118fc6cdfbSTobias Grosser     cl::ZeroOrMore, cl::cat(PollyCategory));
1128fc6cdfbSTobias Grosser 
11374dc3cb4STobias Grosser static cl::opt<std::string>
11474dc3cb4STobias Grosser     CudaVersion("polly-acc-cuda-version",
11574dc3cb4STobias Grosser                 cl::desc("The CUDA version to compile for"), cl::Hidden,
11674dc3cb4STobias Grosser                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
11774dc3cb4STobias Grosser 
11882f2af35STobias Grosser static cl::opt<int>
11982f2af35STobias Grosser     MinCompute("polly-acc-mincompute",
12082f2af35STobias Grosser                cl::desc("Minimal number of compute statements to run on GPU."),
12182f2af35STobias Grosser                cl::Hidden, cl::init(10 * 512 * 512));
12282f2af35STobias Grosser 
123638316daSSiddharth Bhat /// Return  a unique name for a Scop, which is the scop region with the
124638316daSSiddharth Bhat /// function name.
125638316daSSiddharth Bhat std::string getUniqueScopName(const Scop *S) {
126638316daSSiddharth Bhat   return "Scop Region: " + S->getNameStr() +
127638316daSSiddharth Bhat          " | Function: " + std::string(S->getFunction().getName());
128638316daSSiddharth Bhat }
129638316daSSiddharth Bhat 
130a82f2d26SSiddharth Bhat /// Used to store information PPCG wants for kills. This information is
131a82f2d26SSiddharth Bhat /// used by live range reordering.
132a82f2d26SSiddharth Bhat ///
133a82f2d26SSiddharth Bhat /// @see computeLiveRangeReordering
134a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGScop
135a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGProg
136a82f2d26SSiddharth Bhat struct MustKillsInfo {
137a82f2d26SSiddharth Bhat   /// Collection of all kill statements that will be sequenced at the end of
138a82f2d26SSiddharth Bhat   /// PPCGScop->schedule.
139a82f2d26SSiddharth Bhat   ///
140a82f2d26SSiddharth Bhat   /// The nodes in `KillsSchedule` will be merged using `isl_schedule_set`
141a82f2d26SSiddharth Bhat   /// which merges schedules in *arbitrary* order.
142a82f2d26SSiddharth Bhat   /// (we don't care about the order of the kills anyway).
143a82f2d26SSiddharth Bhat   isl::schedule KillsSchedule;
144a82f2d26SSiddharth Bhat   /// Map from kill statement instances to scalars that need to be
145a82f2d26SSiddharth Bhat   /// killed.
146a82f2d26SSiddharth Bhat   ///
147edfef5aeSSiddharth Bhat   /// We currently derive kill information for:
148edfef5aeSSiddharth Bhat   ///  1. phi nodes. PHI nodes are not alive outside the scop and can
149edfef5aeSSiddharth Bhat   ///     consequently all be killed.
150edfef5aeSSiddharth Bhat   ///  2. Scalar arrays that are not used outside the Scop. This is
151edfef5aeSSiddharth Bhat   ///     checked by `isScalarUsesContainedInScop`.
152edfef5aeSSiddharth Bhat   /// [params] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] }
153a82f2d26SSiddharth Bhat   isl::union_map TaggedMustKills;
154a82f2d26SSiddharth Bhat 
1559e3db2b7SSiddharth Bhat   /// Tagged must kills stripped of the tags.
1569e3db2b7SSiddharth Bhat   /// [params] -> { Stmt_phantom[]  -> scalar_to_kill[] }
1579e3db2b7SSiddharth Bhat   isl::union_map MustKills;
1589e3db2b7SSiddharth Bhat 
1599e3db2b7SSiddharth Bhat   MustKillsInfo() : KillsSchedule(nullptr) {}
160a82f2d26SSiddharth Bhat };
161a82f2d26SSiddharth Bhat 
162761e5b93SSiddharth Bhat /// Check if SAI's uses are entirely contained within Scop S.
163761e5b93SSiddharth Bhat /// If a scalar is used only with a Scop, we are free to kill it, as no data
164761e5b93SSiddharth Bhat /// can flow in/out of the value any more.
165761e5b93SSiddharth Bhat /// @see computeMustKillsInfo
166761e5b93SSiddharth Bhat static bool isScalarUsesContainedInScop(const Scop &S,
167761e5b93SSiddharth Bhat                                         const ScopArrayInfo *SAI) {
168761e5b93SSiddharth Bhat   assert(SAI->isValueKind() && "this function only deals with scalars."
169761e5b93SSiddharth Bhat                                " Dealing with arrays required alias analysis");
170761e5b93SSiddharth Bhat 
171761e5b93SSiddharth Bhat   const Region &R = S.getRegion();
172761e5b93SSiddharth Bhat   for (User *U : SAI->getBasePtr()->users()) {
173761e5b93SSiddharth Bhat     Instruction *I = dyn_cast<Instruction>(U);
174761e5b93SSiddharth Bhat     assert(I && "invalid user of scop array info");
175761e5b93SSiddharth Bhat     if (!R.contains(I))
176761e5b93SSiddharth Bhat       return false;
177761e5b93SSiddharth Bhat   }
178761e5b93SSiddharth Bhat   return true;
179761e5b93SSiddharth Bhat }
180761e5b93SSiddharth Bhat 
181a82f2d26SSiddharth Bhat /// Compute must-kills needed to enable live range reordering with PPCG.
182a82f2d26SSiddharth Bhat ///
183a82f2d26SSiddharth Bhat /// @params S The Scop to compute live range reordering information
184a82f2d26SSiddharth Bhat /// @returns live range reordering information that can be used to setup
185a82f2d26SSiddharth Bhat /// PPCG.
186a82f2d26SSiddharth Bhat static MustKillsInfo computeMustKillsInfo(const Scop &S) {
187b65ccc43STobias Grosser   const isl::space ParamSpace = S.getParamSpace();
188a82f2d26SSiddharth Bhat   MustKillsInfo Info;
189a82f2d26SSiddharth Bhat 
190761e5b93SSiddharth Bhat   // 1. Collect all ScopArrayInfo that satisfy *any* of the criteria:
191761e5b93SSiddharth Bhat   //      1.1 phi nodes in scop.
192761e5b93SSiddharth Bhat   //      1.2 scalars that are only used within the scop
193a82f2d26SSiddharth Bhat   SmallVector<isl::id, 4> KillMemIds;
194a82f2d26SSiddharth Bhat   for (ScopArrayInfo *SAI : S.arrays()) {
195761e5b93SSiddharth Bhat     if (SAI->isPHIKind() ||
196761e5b93SSiddharth Bhat         (SAI->isValueKind() && isScalarUsesContainedInScop(S, SAI)))
19777eef90fSTobias Grosser       KillMemIds.push_back(isl::manage(SAI->getBasePtrId().release()));
198a82f2d26SSiddharth Bhat   }
199a82f2d26SSiddharth Bhat 
200d70ea7feSTobias Grosser   Info.TaggedMustKills = isl::union_map::empty(ParamSpace);
201d70ea7feSTobias Grosser   Info.MustKills = isl::union_map::empty(ParamSpace);
202a82f2d26SSiddharth Bhat 
203a82f2d26SSiddharth Bhat   // Initialising KillsSchedule to `isl_set_empty` creates an empty node in the
204a82f2d26SSiddharth Bhat   // schedule:
205a82f2d26SSiddharth Bhat   //     - filter: "[control] -> { }"
206a82f2d26SSiddharth Bhat   // So, we choose to not create this to keep the output a little nicer,
207a82f2d26SSiddharth Bhat   // at the cost of some code complexity.
208a82f2d26SSiddharth Bhat   Info.KillsSchedule = nullptr;
209a82f2d26SSiddharth Bhat 
210edfef5aeSSiddharth Bhat   for (isl::id &ToKillId : KillMemIds) {
211a82f2d26SSiddharth Bhat     isl::id KillStmtId = isl::id::alloc(
212edfef5aeSSiddharth Bhat         S.getIslCtx(),
213edfef5aeSSiddharth Bhat         std::string("SKill_phantom_").append(ToKillId.get_name()), nullptr);
214a82f2d26SSiddharth Bhat 
215a82f2d26SSiddharth Bhat     // NOTE: construction of tagged_must_kill:
216a82f2d26SSiddharth Bhat     // 2. We need to construct a map:
217edfef5aeSSiddharth Bhat     //     [param] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] }
218a82f2d26SSiddharth Bhat     // To construct this, we use `isl_map_domain_product` on 2 maps`:
219edfef5aeSSiddharth Bhat     // 2a. StmtToScalar:
220edfef5aeSSiddharth Bhat     //         [param] -> { Stmt_phantom[] -> scalar_to_kill[] }
221edfef5aeSSiddharth Bhat     // 2b. PhantomRefToScalar:
222edfef5aeSSiddharth Bhat     //         [param] -> { ref_phantom[] -> scalar_to_kill[] }
223a82f2d26SSiddharth Bhat     //
224a82f2d26SSiddharth Bhat     // Combining these with `isl_map_domain_product` gives us
225a82f2d26SSiddharth Bhat     // TaggedMustKill:
226edfef5aeSSiddharth Bhat     //     [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] }
227a82f2d26SSiddharth Bhat 
228edfef5aeSSiddharth Bhat     // 2a. [param] -> { Stmt[] -> scalar_to_kill[] }
229d70ea7feSTobias Grosser     isl::map StmtToScalar = isl::map::universe(ParamSpace);
230edfef5aeSSiddharth Bhat     StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::in, isl::id(KillStmtId));
231edfef5aeSSiddharth Bhat     StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::out, isl::id(ToKillId));
232a82f2d26SSiddharth Bhat 
233a82f2d26SSiddharth Bhat     isl::id PhantomRefId = isl::id::alloc(
234edfef5aeSSiddharth Bhat         S.getIslCtx(), std::string("ref_phantom") + ToKillId.get_name(),
235edfef5aeSSiddharth Bhat         nullptr);
236a82f2d26SSiddharth Bhat 
237edfef5aeSSiddharth Bhat     // 2b. [param] -> { phantom_ref[] -> scalar_to_kill[] }
238d70ea7feSTobias Grosser     isl::map PhantomRefToScalar = isl::map::universe(ParamSpace);
239edfef5aeSSiddharth Bhat     PhantomRefToScalar =
240edfef5aeSSiddharth Bhat         PhantomRefToScalar.set_tuple_id(isl::dim::in, PhantomRefId);
241edfef5aeSSiddharth Bhat     PhantomRefToScalar =
242edfef5aeSSiddharth Bhat         PhantomRefToScalar.set_tuple_id(isl::dim::out, ToKillId);
243a82f2d26SSiddharth Bhat 
244edfef5aeSSiddharth Bhat     // 2. [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] }
245edfef5aeSSiddharth Bhat     isl::map TaggedMustKill = StmtToScalar.domain_product(PhantomRefToScalar);
246a82f2d26SSiddharth Bhat     Info.TaggedMustKills = Info.TaggedMustKills.unite(TaggedMustKill);
247a82f2d26SSiddharth Bhat 
2489e3db2b7SSiddharth Bhat     // 2. [param] -> { Stmt[] -> scalar_to_kill[] }
2499e3db2b7SSiddharth Bhat     Info.MustKills = Info.TaggedMustKills.domain_factor_domain();
2509e3db2b7SSiddharth Bhat 
251a82f2d26SSiddharth Bhat     // 3. Create the kill schedule of the form:
252a82f2d26SSiddharth Bhat     //     "[param] -> { Stmt_phantom[] }"
253a82f2d26SSiddharth Bhat     // Then add this to Info.KillsSchedule.
254a82f2d26SSiddharth Bhat     isl::space KillStmtSpace = ParamSpace;
255a82f2d26SSiddharth Bhat     KillStmtSpace = KillStmtSpace.set_tuple_id(isl::dim::set, KillStmtId);
256a82f2d26SSiddharth Bhat     isl::union_set KillStmtDomain = isl::set::universe(KillStmtSpace);
257a82f2d26SSiddharth Bhat 
258a82f2d26SSiddharth Bhat     isl::schedule KillSchedule = isl::schedule::from_domain(KillStmtDomain);
259a82f2d26SSiddharth Bhat     if (Info.KillsSchedule)
260a82f2d26SSiddharth Bhat       Info.KillsSchedule = Info.KillsSchedule.set(KillSchedule);
261a82f2d26SSiddharth Bhat     else
262a82f2d26SSiddharth Bhat       Info.KillsSchedule = KillSchedule;
263a82f2d26SSiddharth Bhat   }
264a82f2d26SSiddharth Bhat 
265a82f2d26SSiddharth Bhat   return Info;
266a82f2d26SSiddharth Bhat }
267a82f2d26SSiddharth Bhat 
26860c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
26960c60025STobias Grosser ///
27060c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
27160c60025STobias Grosser /// of the scheduled ScopStmts.
27260c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
27335de9009SSiddharth Bhat     void *StmtT, __isl_take isl_ast_build *Build_C,
27460c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
27560c60025STobias Grosser                                        isl_id *Id, void *User),
27660c60025STobias Grosser     void *UserIndex,
27760c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
278edb885cbSTobias Grosser     void *UserExpr) {
27960c60025STobias Grosser 
280edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
28160c60025STobias Grosser 
28235de9009SSiddharth Bhat   if (!Stmt || !Build_C)
283edb885cbSTobias Grosser     return NULL;
284edb885cbSTobias Grosser 
28535de9009SSiddharth Bhat   isl::ast_build Build = isl::manage(isl_ast_build_copy(Build_C));
28635de9009SSiddharth Bhat   isl::ctx Ctx = Build.get_ctx();
28735de9009SSiddharth Bhat   isl::id_to_ast_expr RefToExpr = isl::id_to_ast_expr::alloc(Ctx, 0);
288edb885cbSTobias Grosser 
289edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
29035de9009SSiddharth Bhat     isl::map AddrFunc = Acc->getAddressFunction();
291dcf8d696STobias Grosser     AddrFunc = AddrFunc.intersect_domain(Stmt->getDomain());
29235de9009SSiddharth Bhat 
29335de9009SSiddharth Bhat     isl::id RefId = Acc->getId();
29435de9009SSiddharth Bhat     isl::pw_multi_aff PMA = isl::pw_multi_aff::from_map(AddrFunc);
29535de9009SSiddharth Bhat 
29635de9009SSiddharth Bhat     isl::multi_pw_aff MPA = isl::multi_pw_aff(PMA);
29735de9009SSiddharth Bhat     MPA = MPA.coalesce();
29835de9009SSiddharth Bhat     MPA = isl::manage(FunctionIndex(MPA.release(), RefId.get(), UserIndex));
29935de9009SSiddharth Bhat 
30035de9009SSiddharth Bhat     isl::ast_expr Access = Build.access_from(MPA);
30135de9009SSiddharth Bhat     Access = isl::manage(FunctionExpr(Access.release(), RefId.get(), UserExpr));
30235de9009SSiddharth Bhat     RefToExpr = RefToExpr.set(RefId, Access);
303edb885cbSTobias Grosser   }
304edb885cbSTobias Grosser 
30535de9009SSiddharth Bhat   return RefToExpr.release();
30660c60025STobias Grosser }
307f384594dSTobias Grosser 
308a90be207SSiddharth Bhat /// Given a LLVM Type, compute its size in bytes,
309a90be207SSiddharth Bhat static int computeSizeInBytes(const Type *T) {
310a90be207SSiddharth Bhat   int bytes = T->getPrimitiveSizeInBits() / 8;
311a90be207SSiddharth Bhat   if (bytes == 0)
312a90be207SSiddharth Bhat     bytes = T->getScalarSizeInBits() / 8;
313a90be207SSiddharth Bhat   return bytes;
314a90be207SSiddharth Bhat }
315a90be207SSiddharth Bhat 
31638fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
31738fc0aedSTobias Grosser ///
31838fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
319a6d48f59SMichael Kruse /// generates code for general-purpose AST nodes, with special functionality
32038fc0aedSTobias Grosser /// for generating GPU specific user nodes.
32138fc0aedSTobias Grosser ///
32238fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
32338fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
32438fc0aedSTobias Grosser public:
3252d950f36SPhilip Pfaffe   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator,
32638fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
327acf80064SEli Friedman                  DominatorTree &DT, Scop &S, BasicBlock *StartBlock,
32817f01968SSiddharth Bhat                  gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch)
3292d950f36SPhilip Pfaffe       : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock),
33017f01968SSiddharth Bhat         Prog(Prog), Runtime(Runtime), Arch(Arch) {
331edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
332edb885cbSTobias Grosser   }
33338fc0aedSTobias Grosser 
334fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
335fa7b0802STobias Grosser   void initializeAfterRTH();
336fa7b0802STobias Grosser 
337fa7b0802STobias Grosser   /// Finalize the generated scop.
338fa7b0802STobias Grosser   virtual void finalize();
339fa7b0802STobias Grosser 
3405857b701STobias Grosser   /// Track if the full build process was successful.
3415857b701STobias Grosser   ///
3425857b701STobias Grosser   /// This value is set to false, if throughout the build process an error
3435857b701STobias Grosser   /// occurred which prevents us from generating valid GPU code.
3445857b701STobias Grosser   bool BuildSuccessful = true;
3455857b701STobias Grosser 
346bc653f20STobias Grosser   /// The maximal number of loops surrounding a sequential kernel.
347bc653f20STobias Grosser   unsigned DeepestSequential = 0;
348bc653f20STobias Grosser 
349bc653f20STobias Grosser   /// The maximal number of loops surrounding a parallel kernel.
350bc653f20STobias Grosser   unsigned DeepestParallel = 0;
351bc653f20STobias Grosser 
35279f13b9aSSingapuram Sanjay Srivallabh   /// Return the name to set for the ptx_kernel.
35379f13b9aSSingapuram Sanjay Srivallabh   std::string getKernelFuncName(int Kernel_id);
35479f13b9aSSingapuram Sanjay Srivallabh 
35538fc0aedSTobias Grosser private:
35674dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
35774dc3cb4STobias Grosser   ///
35874dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
35974dc3cb4STobias Grosser   /// more.
36074dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
36174dc3cb4STobias Grosser 
36213c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
36313c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
3647287aeddSTobias Grosser 
365fa7b0802STobias Grosser   /// The current GPU context.
366fa7b0802STobias Grosser   Value *GPUContext;
367fa7b0802STobias Grosser 
368b513b491STobias Grosser   /// The set of isl_ids allocated in the kernel
369b513b491STobias Grosser   std::vector<isl_id *> KernelIds;
370b513b491STobias Grosser 
37132837fe3STobias Grosser   /// A module containing GPU code.
37232837fe3STobias Grosser   ///
37332837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
37432837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
37532837fe3STobias Grosser 
37632837fe3STobias Grosser   /// The GPU program we generate code for.
37732837fe3STobias Grosser   gpu_prog *Prog;
37832837fe3STobias Grosser 
37917f01968SSiddharth Bhat   /// The GPU Runtime implementation to use (OpenCL or CUDA).
38017f01968SSiddharth Bhat   GPURuntime Runtime;
38117f01968SSiddharth Bhat 
38217f01968SSiddharth Bhat   /// The GPU Architecture to target.
38317f01968SSiddharth Bhat   GPUArch Arch;
38417f01968SSiddharth Bhat 
385472f9654STobias Grosser   /// Class to free isl_ids.
386472f9654STobias Grosser   class IslIdDeleter {
387472f9654STobias Grosser   public:
388472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
389472f9654STobias Grosser   };
390472f9654STobias Grosser 
391472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
392472f9654STobias Grosser   ///
393472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
394472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
395472f9654STobias Grosser 
396edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
397edb885cbSTobias Grosser 
39838fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
39938fc0aedSTobias Grosser   ///
40038fc0aedSTobias Grosser   /// These AST nodes can be of type:
40138fc0aedSTobias Grosser   ///
40238fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
40338fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
40413c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
4055260c041STobias Grosser   ///   - In-kernel synchronization
4065260c041STobias Grosser   ///   - In-kernel memory copy statement
40738fc0aedSTobias Grosser   ///
4081fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
4091fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
41032837fe3STobias Grosser 
41113c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
41213c78e4dSTobias Grosser 
41313c78e4dSTobias Grosser   /// Create code for a data transfer statement
41413c78e4dSTobias Grosser   ///
41513c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
41613c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
41713c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
41813c78e4dSTobias Grosser                           enum DataDirection Direction);
41913c78e4dSTobias Grosser 
420edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
421edb885cbSTobias Grosser   ///
422edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
423edb885cbSTobias Grosser   ///
424e53c924bSSiddharth Bhat   /// @returns A tuple, whose:
425e53c924bSSiddharth Bhat   ///          - First element contains the set of values referenced by the
426e53c924bSSiddharth Bhat   ///            kernel
427e53c924bSSiddharth Bhat   ///          - Second element contains the set of functions referenced by the
428e53c924bSSiddharth Bhat   ///             kernel. All functions in the set satisfy
429e53c924bSSiddharth Bhat   ///             `isValidFunctionInKernel`.
430e53c924bSSiddharth Bhat   ///          - Third element contains loops that have induction variables
431e53c924bSSiddharth Bhat   ///            which are used in the kernel, *and* these loops are *neither*
432e53c924bSSiddharth Bhat   ///            in the scop, nor do they immediately surroung the Scop.
433e53c924bSSiddharth Bhat   ///            See [Code generation of induction variables of loops outside
434e53c924bSSiddharth Bhat   ///            Scops]
435e53c924bSSiddharth Bhat   std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>>
436f291c8d5SSiddharth Bhat   getReferencesInKernel(ppcg_kernel *Kernel);
437edb885cbSTobias Grosser 
43879a947c2STobias Grosser   /// Compute the sizes of the execution grid for a given kernel.
43979a947c2STobias Grosser   ///
44079a947c2STobias Grosser   /// @param Kernel The kernel to compute grid sizes for.
44179a947c2STobias Grosser   ///
44279a947c2STobias Grosser   /// @returns A tuple with grid sizes for X and Y dimension
44379a947c2STobias Grosser   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
44479a947c2STobias Grosser 
445b99c1171STobias Grosser   /// Get the managed array pointer for sending host pointers to the device.
446abed4969SSiddharth Bhat   /// \note
447abed4969SSiddharth Bhat   /// This is to be used only with managed memory
448b99c1171STobias Grosser   Value *getManagedDeviceArray(gpu_array_info *Array, ScopArrayInfo *ArrayInfo);
449abed4969SSiddharth Bhat 
45079a947c2STobias Grosser   /// Compute the sizes of the thread blocks for a given kernel.
45179a947c2STobias Grosser   ///
45279a947c2STobias Grosser   /// @param Kernel The kernel to compute thread block sizes for.
45379a947c2STobias Grosser   ///
45479a947c2STobias Grosser   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
45579a947c2STobias Grosser   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
45679a947c2STobias Grosser 
457a90be207SSiddharth Bhat   /// Store a specific kernel launch parameter in the array of kernel launch
458a90be207SSiddharth Bhat   /// parameters.
459a90be207SSiddharth Bhat   ///
460a90be207SSiddharth Bhat   /// @param Parameters The list of parameters in which to store.
461a90be207SSiddharth Bhat   /// @param Param      The kernel launch parameter to store.
462a90be207SSiddharth Bhat   /// @param Index      The index in the parameter list, at which to store the
463a90be207SSiddharth Bhat   ///                   parameter.
464a90be207SSiddharth Bhat   void insertStoreParameter(Instruction *Parameters, Instruction *Param,
465a90be207SSiddharth Bhat                             int Index);
466a90be207SSiddharth Bhat 
46779a947c2STobias Grosser   /// Create kernel launch parameters.
46879a947c2STobias Grosser   ///
46979a947c2STobias Grosser   /// @param Kernel        The kernel to create parameters for.
47079a947c2STobias Grosser   /// @param F             The kernel function that has been created.
47157693272STobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
47279a947c2STobias Grosser   ///
47379a947c2STobias Grosser   /// @returns A stack allocated array with pointers to the parameter
47479a947c2STobias Grosser   ///          values that are passed to the kernel.
47557693272STobias Grosser   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
47657693272STobias Grosser                                 SetVector<Value *> SubtreeValues);
47779a947c2STobias Grosser 
478b513b491STobias Grosser   /// Create declarations for kernel variable.
479b513b491STobias Grosser   ///
480b513b491STobias Grosser   /// This includes shared memory declarations.
481b513b491STobias Grosser   ///
482b513b491STobias Grosser   /// @param Kernel        The kernel definition to create variables for.
483b513b491STobias Grosser   /// @param FN            The function into which to generate the variables.
484b513b491STobias Grosser   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
485b513b491STobias Grosser 
486c1c6a2a6STobias Grosser   /// Add CUDA annotations to module.
487c1c6a2a6STobias Grosser   ///
488c1c6a2a6STobias Grosser   /// Add a set of CUDA annotations that declares the maximal block dimensions
489c1c6a2a6STobias Grosser   /// that will be used to execute the CUDA kernel. This allows the NVIDIA
490c1c6a2a6STobias Grosser   /// PTX compiler to bound the number of allocated registers to ensure the
491c1c6a2a6STobias Grosser   /// resulting kernel is known to run with up to as many block dimensions
492c1c6a2a6STobias Grosser   /// as specified here.
493c1c6a2a6STobias Grosser   ///
494c1c6a2a6STobias Grosser   /// @param M         The module to add the annotations to.
495c1c6a2a6STobias Grosser   /// @param BlockDimX The size of block dimension X.
496c1c6a2a6STobias Grosser   /// @param BlockDimY The size of block dimension Y.
497c1c6a2a6STobias Grosser   /// @param BlockDimZ The size of block dimension Z.
498c1c6a2a6STobias Grosser   void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY,
499c1c6a2a6STobias Grosser                           Value *BlockDimZ);
500c1c6a2a6STobias Grosser 
50132837fe3STobias Grosser   /// Create GPU kernel.
50232837fe3STobias Grosser   ///
50332837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
50432837fe3STobias Grosser   ///
50532837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
50632837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
50732837fe3STobias Grosser 
50813c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
50913c78e4dSTobias Grosser   ///
51013c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
51113c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
51213c78e4dSTobias Grosser 
513aaabbbf8STobias Grosser   /// Generate code to compute the minimal offset at which an array is accessed.
514aaabbbf8STobias Grosser   ///
515aaabbbf8STobias Grosser   /// The offset of an array is the minimal array location accessed in a scop.
516aaabbbf8STobias Grosser   ///
517aaabbbf8STobias Grosser   /// Example:
518aaabbbf8STobias Grosser   ///
519aaabbbf8STobias Grosser   ///   for (long i = 0; i < 100; i++)
520aaabbbf8STobias Grosser   ///     A[i + 42] += ...
521aaabbbf8STobias Grosser   ///
522aaabbbf8STobias Grosser   ///   getArrayOffset(A) results in 42.
523aaabbbf8STobias Grosser   ///
524aaabbbf8STobias Grosser   /// @param Array The array for which to compute the offset.
525aaabbbf8STobias Grosser   /// @returns An llvm::Value that contains the offset of the array.
526aaabbbf8STobias Grosser   Value *getArrayOffset(gpu_array_info *Array);
527aaabbbf8STobias Grosser 
52800bb5a99STobias Grosser   /// Prepare the kernel arguments for kernel code generation
52900bb5a99STobias Grosser   ///
53000bb5a99STobias Grosser   /// @param Kernel The kernel to generate code for.
53100bb5a99STobias Grosser   /// @param FN     The function created for the kernel.
53200bb5a99STobias Grosser   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
53300bb5a99STobias Grosser 
53432837fe3STobias Grosser   /// Create kernel function.
53532837fe3STobias Grosser   ///
53632837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
53732837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
53832837fe3STobias Grosser   /// start block of this newly created function.
53932837fe3STobias Grosser   ///
54032837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
541edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
542f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by this
543f291c8d5SSiddharth Bhat   ///                         kernel.
544edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
545f291c8d5SSiddharth Bhat                             SetVector<Value *> &SubtreeValues,
546f291c8d5SSiddharth Bhat                             SetVector<Function *> &SubtreeFunctions);
54732837fe3STobias Grosser 
54832837fe3STobias Grosser   /// Create the declaration of a kernel function.
54932837fe3STobias Grosser   ///
55032837fe3STobias Grosser   /// The kernel function takes as arguments:
55132837fe3STobias Grosser   ///
55232837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
553f6044bd0STobias Grosser   ///   - Host iterators
554c84a1995STobias Grosser   ///   - Parameters
55532837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
55632837fe3STobias Grosser   ///
55732837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
558edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
559edb885cbSTobias Grosser   ///
56032837fe3STobias Grosser   /// @returns The newly declared function.
561edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
562edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
56332837fe3STobias Grosser 
564472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
565472f9654STobias Grosser   ///
566472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
567472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
568472f9654STobias Grosser 
5692f3073b5SPhilipp Schaad   /// Insert function calls to retrieve the SPIR group/local ids.
5702f3073b5SPhilipp Schaad   ///
5712f3073b5SPhilipp Schaad   /// @param The kernel to generate the function calls for.
5722f3073b5SPhilipp Schaad   void insertKernelCallsSPIR(ppcg_kernel *Kernel);
5732f3073b5SPhilipp Schaad 
574f291c8d5SSiddharth Bhat   /// Setup the creation of functions referenced by the GPU kernel.
575f291c8d5SSiddharth Bhat   ///
576f291c8d5SSiddharth Bhat   /// 1. Create new function declarations in GPUModule which are the same as
577f291c8d5SSiddharth Bhat   /// SubtreeFunctions.
578f291c8d5SSiddharth Bhat   ///
579f291c8d5SSiddharth Bhat   /// 2. Populate IslNodeBuilder::ValueMap with mappings from
580f291c8d5SSiddharth Bhat   /// old functions (that come from the original module) to new functions
581f291c8d5SSiddharth Bhat   /// (that are created within GPUModule). That way, we generate references
582f291c8d5SSiddharth Bhat   /// to the correct function (in GPUModule) in BlockGenerator.
583f291c8d5SSiddharth Bhat   ///
584f291c8d5SSiddharth Bhat   /// @see IslNodeBuilder::ValueMap
585f291c8d5SSiddharth Bhat   /// @see BlockGenerator::GlobalMap
586f291c8d5SSiddharth Bhat   /// @see BlockGenerator::getNewValue
587f291c8d5SSiddharth Bhat   /// @see GPUNodeBuilder::getReferencesInKernel.
588f291c8d5SSiddharth Bhat   ///
589f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by
590f291c8d5SSiddharth Bhat   ///                         this kernel.
591f291c8d5SSiddharth Bhat   void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions);
592f291c8d5SSiddharth Bhat 
593b513b491STobias Grosser   /// Create a global-to-shared or shared-to-global copy statement.
594b513b491STobias Grosser   ///
595b513b491STobias Grosser   /// @param CopyStmt The copy statement to generate code for
596b513b491STobias Grosser   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
597b513b491STobias Grosser 
598edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
599edb885cbSTobias Grosser   ///
600edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
601edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
602edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
603edb885cbSTobias Grosser 
6045260c041STobias Grosser   /// Create an in-kernel synchronization call.
6055260c041STobias Grosser   void createKernelSync();
6065260c041STobias Grosser 
60774dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
60874dc3cb4STobias Grosser   ///
60974dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
61074dc3cb4STobias Grosser   std::string createKernelASM();
61174dc3cb4STobias Grosser 
61274dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
61374dc3cb4STobias Grosser   ///
61474dc3cb4STobias Grosser   /// @param F The function to remove references to.
61574dc3cb4STobias Grosser   void clearDominators(Function *F);
61674dc3cb4STobias Grosser 
61774dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
61874dc3cb4STobias Grosser   ///
61974dc3cb4STobias Grosser   /// @param F The function to remove references to.
62074dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
62174dc3cb4STobias Grosser 
62274dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
62374dc3cb4STobias Grosser   ///
62474dc3cb4STobias Grosser   /// @param F The function to remove references to.
62574dc3cb4STobias Grosser   void clearLoops(Function *F);
62674dc3cb4STobias Grosser 
6278fc6cdfbSTobias Grosser   /// Check if the scop requires to be linked with CUDA's libdevice.
6288fc6cdfbSTobias Grosser   bool requiresCUDALibDevice();
6298fc6cdfbSTobias Grosser 
6308fc6cdfbSTobias Grosser   /// Link with the NVIDIA libdevice library (if needed and available).
6318fc6cdfbSTobias Grosser   void addCUDALibDevice();
6328fc6cdfbSTobias Grosser 
63332837fe3STobias Grosser   /// Finalize the generation of the kernel function.
63432837fe3STobias Grosser   ///
63532837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
63632837fe3STobias Grosser   /// dump its IR to stderr.
63757793596STobias Grosser   ///
63857793596STobias Grosser   /// @returns The Assembly string of the kernel.
63957793596STobias Grosser   std::string finalizeKernelFunction();
640fa7b0802STobias Grosser 
64151dfc275STobias Grosser   /// Finalize the generation of the kernel arguments.
64251dfc275STobias Grosser   ///
64351dfc275STobias Grosser   /// This function ensures that not-read-only scalars used in a kernel are
644a6d48f59SMichael Kruse   /// stored back to the global memory location they are backed with before
64551dfc275STobias Grosser   /// the kernel terminates.
64651dfc275STobias Grosser   ///
64751dfc275STobias Grosser   /// @params Kernel The kernel to finalize kernel arguments for.
64851dfc275STobias Grosser   void finalizeKernelArguments(ppcg_kernel *Kernel);
64951dfc275STobias Grosser 
6507287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
651fa7b0802STobias Grosser   void allocateDeviceArrays();
652fa7b0802STobias Grosser 
653b99c1171STobias Grosser   /// Create code to prepare the managed device pointers.
654b99c1171STobias Grosser   void prepareManagedDeviceArrays();
655b99c1171STobias Grosser 
6567287aeddSTobias Grosser   /// Free all allocated device arrays.
6577287aeddSTobias Grosser   void freeDeviceArrays();
6587287aeddSTobias Grosser 
659fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
660fa7b0802STobias Grosser   ///
661fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
662fa7b0802STobias Grosser   Value *createCallInitContext();
663fa7b0802STobias Grosser 
66479a947c2STobias Grosser   /// Create a call to get the device pointer for a kernel allocation.
66579a947c2STobias Grosser   ///
66679a947c2STobias Grosser   /// @param Allocation The Polly GPU allocation
66779a947c2STobias Grosser   ///
66879a947c2STobias Grosser   /// @returns The device parameter corresponding to this allocation.
66979a947c2STobias Grosser   Value *createCallGetDevicePtr(Value *Allocation);
67079a947c2STobias Grosser 
671fa7b0802STobias Grosser   /// Create a call to free the GPU context.
672fa7b0802STobias Grosser   ///
673fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
674fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
675fa7b0802STobias Grosser 
6767287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
6777287aeddSTobias Grosser   ///
6787287aeddSTobias Grosser   /// @param Size The size of memory to allocate
6797287aeddSTobias Grosser   ///
6807287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
681fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
6827287aeddSTobias Grosser 
6837287aeddSTobias Grosser   /// Create a call to free a device array.
6847287aeddSTobias Grosser   ///
6857287aeddSTobias Grosser   /// @param Array The device array to free.
6867287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
68713c78e4dSTobias Grosser 
68813c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
68913c78e4dSTobias Grosser   ///
69013c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
69113c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
69213c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
69313c78e4dSTobias Grosser                                       Value *Size);
69413c78e4dSTobias Grosser 
69513c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
69613c78e4dSTobias Grosser   ///
69713c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
69813c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
69913c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
70013c78e4dSTobias Grosser                                       Value *Size);
70157793596STobias Grosser 
702abed4969SSiddharth Bhat   /// Create a call to synchronize Host & Device.
703abed4969SSiddharth Bhat   /// \note
704abed4969SSiddharth Bhat   /// This is to be used only with managed memory.
705abed4969SSiddharth Bhat   void createCallSynchronizeDevice();
706abed4969SSiddharth Bhat 
70757793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
70857793596STobias Grosser   ///
70957793596STobias Grosser   /// @param Buffer The string describing the kernel.
71057793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
71157793596STobias Grosser   ///
71257793596STobias Grosser   /// @returns A pointer to a kernel object
71357793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
71457793596STobias Grosser 
71557793596STobias Grosser   /// Create a call to free a GPU kernel.
71657793596STobias Grosser   ///
71757793596STobias Grosser   /// @param GPUKernel THe kernel to free.
71857793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
71979a947c2STobias Grosser 
72079a947c2STobias Grosser   /// Create a call to launch a GPU kernel.
72179a947c2STobias Grosser   ///
72279a947c2STobias Grosser   /// @param GPUKernel  The kernel to launch.
72379a947c2STobias Grosser   /// @param GridDimX   The size of the first grid dimension.
72479a947c2STobias Grosser   /// @param GridDimY   The size of the second grid dimension.
72579a947c2STobias Grosser   /// @param GridBlockX The size of the first block dimension.
72679a947c2STobias Grosser   /// @param GridBlockY The size of the second block dimension.
72779a947c2STobias Grosser   /// @param GridBlockZ The size of the third block dimension.
728a6d48f59SMichael Kruse   /// @param Parameters A pointer to an array that contains itself pointers to
72979a947c2STobias Grosser   ///                   the parameter values passed for each kernel argument.
73079a947c2STobias Grosser   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
73179a947c2STobias Grosser                               Value *GridDimY, Value *BlockDimX,
73279a947c2STobias Grosser                               Value *BlockDimY, Value *BlockDimZ,
73379a947c2STobias Grosser                               Value *Parameters);
7341fb9b64dSTobias Grosser };
7351fb9b64dSTobias Grosser 
73679f13b9aSSingapuram Sanjay Srivallabh std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) {
7371abd9ffaSSingapuram Sanjay Srivallabh   return "FUNC_" + S.getFunction().getName().str() + "_SCOP_" +
7381abd9ffaSSingapuram Sanjay Srivallabh          std::to_string(S.getID()) + "_KERNEL_" + std::to_string(Kernel_id);
73979f13b9aSSingapuram Sanjay Srivallabh }
74079f13b9aSSingapuram Sanjay Srivallabh 
741fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
742750160e2STobias Grosser   BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(),
743750160e2STobias Grosser                                  &*Builder.GetInsertPoint(), &DT, &LI);
744750160e2STobias Grosser   NewBB->setName("polly.acc.initialize");
745750160e2STobias Grosser   Builder.SetInsertPoint(&NewBB->front());
746750160e2STobias Grosser 
747fa7b0802STobias Grosser   GPUContext = createCallInitContext();
748abed4969SSiddharth Bhat 
749abed4969SSiddharth Bhat   if (!ManagedMemory)
750fa7b0802STobias Grosser     allocateDeviceArrays();
751b99c1171STobias Grosser   else
752b99c1171STobias Grosser     prepareManagedDeviceArrays();
753fa7b0802STobias Grosser }
754fa7b0802STobias Grosser 
755fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
756abed4969SSiddharth Bhat   if (!ManagedMemory)
7577287aeddSTobias Grosser     freeDeviceArrays();
758abed4969SSiddharth Bhat 
759fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
760fa7b0802STobias Grosser   IslNodeBuilder::finalize();
761fa7b0802STobias Grosser }
762fa7b0802STobias Grosser 
763fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
764abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory will directly send host pointers "
765abed4969SSiddharth Bhat                            "to the kernel. There is no need for device arrays");
7668ea1fc19STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext().release());
767fa7b0802STobias Grosser 
768fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
769fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
77013c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
7717287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
7727287aeddSTobias Grosser     DevArrayName.append(Array->name);
773fa7b0802STobias Grosser 
77413c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
775aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(Array);
776aaabbbf8STobias Grosser     if (Offset)
777aaabbbf8STobias Grosser       ArraySize = Builder.CreateSub(
778aaabbbf8STobias Grosser           ArraySize,
779aaabbbf8STobias Grosser           Builder.CreateMul(Offset,
780aaabbbf8STobias Grosser                             Builder.getInt64(ScopArray->getElemSizeInBytes())));
7817287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
7827287aeddSTobias Grosser     DevArray->setName(DevArrayName);
78313c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
784fa7b0802STobias Grosser   }
785fa7b0802STobias Grosser 
786fa7b0802STobias Grosser   isl_ast_build_free(Build);
787fa7b0802STobias Grosser }
788fa7b0802STobias Grosser 
789b99c1171STobias Grosser void GPUNodeBuilder::prepareManagedDeviceArrays() {
790b99c1171STobias Grosser   assert(ManagedMemory &&
791b99c1171STobias Grosser          "Device array most only be prepared in managed-memory mode");
792b99c1171STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
793b99c1171STobias Grosser     gpu_array_info *Array = &Prog->array[i];
794b99c1171STobias Grosser     ScopArrayInfo *ScopArray = (ScopArrayInfo *)Array->user;
795b99c1171STobias Grosser     Value *HostPtr;
796b99c1171STobias Grosser 
797b99c1171STobias Grosser     if (gpu_array_is_scalar(Array))
798b99c1171STobias Grosser       HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
799b99c1171STobias Grosser     else
800b99c1171STobias Grosser       HostPtr = ScopArray->getBasePtr();
801b99c1171STobias Grosser     HostPtr = getLatestValue(HostPtr);
802b99c1171STobias Grosser 
803b99c1171STobias Grosser     Value *Offset = getArrayOffset(Array);
804b99c1171STobias Grosser     if (Offset) {
805b99c1171STobias Grosser       HostPtr = Builder.CreatePointerCast(
806b99c1171STobias Grosser           HostPtr, ScopArray->getElementType()->getPointerTo());
807b99c1171STobias Grosser       HostPtr = Builder.CreateGEP(HostPtr, Offset);
808b99c1171STobias Grosser     }
809b99c1171STobias Grosser 
810b99c1171STobias Grosser     HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
811b99c1171STobias Grosser     DeviceAllocations[ScopArray] = HostPtr;
812b99c1171STobias Grosser   }
813b99c1171STobias Grosser }
814b99c1171STobias Grosser 
815c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX,
816c1c6a2a6STobias Grosser                                         Value *BlockDimY, Value *BlockDimZ) {
817c1c6a2a6STobias Grosser   auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations");
818c1c6a2a6STobias Grosser 
819c1c6a2a6STobias Grosser   for (auto &F : *M) {
820c1c6a2a6STobias Grosser     if (F.getCallingConv() != CallingConv::PTX_Kernel)
821c1c6a2a6STobias Grosser       continue;
822c1c6a2a6STobias Grosser 
823c1c6a2a6STobias Grosser     Value *V[] = {BlockDimX, BlockDimY, BlockDimZ};
824c1c6a2a6STobias Grosser 
825c1c6a2a6STobias Grosser     Metadata *Elements[] = {
826c1c6a2a6STobias Grosser         ValueAsMetadata::get(&F),   MDString::get(M->getContext(), "maxntidx"),
827c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"),
828c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"),
829c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[2]),
830c1c6a2a6STobias Grosser     };
831c1c6a2a6STobias Grosser     MDNode *Node = MDNode::get(M->getContext(), Elements);
832c1c6a2a6STobias Grosser     AnnotationNode->addOperand(Node);
833c1c6a2a6STobias Grosser   }
834c1c6a2a6STobias Grosser }
835c1c6a2a6STobias Grosser 
8367287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
837abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not use device arrays");
83813c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
83913c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
8407287aeddSTobias Grosser }
8417287aeddSTobias Grosser 
84257793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
84357793596STobias Grosser   const char *Name = "polly_getKernel";
84457793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
84557793596STobias Grosser   Function *F = M->getFunction(Name);
84657793596STobias Grosser 
84757793596STobias Grosser   // If F is not available, declare it.
84857793596STobias Grosser   if (!F) {
84957793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
85057793596STobias Grosser     std::vector<Type *> Args;
85157793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
85257793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
85357793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
85457793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
85557793596STobias Grosser   }
85657793596STobias Grosser 
85757793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
85857793596STobias Grosser }
85957793596STobias Grosser 
86079a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
86179a947c2STobias Grosser   const char *Name = "polly_getDevicePtr";
86279a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
86379a947c2STobias Grosser   Function *F = M->getFunction(Name);
86479a947c2STobias Grosser 
86579a947c2STobias Grosser   // If F is not available, declare it.
86679a947c2STobias Grosser   if (!F) {
86779a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
86879a947c2STobias Grosser     std::vector<Type *> Args;
86979a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
87079a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
87179a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
87279a947c2STobias Grosser   }
87379a947c2STobias Grosser 
87479a947c2STobias Grosser   return Builder.CreateCall(F, {Allocation});
87579a947c2STobias Grosser }
87679a947c2STobias Grosser 
87779a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
87879a947c2STobias Grosser                                             Value *GridDimY, Value *BlockDimX,
87979a947c2STobias Grosser                                             Value *BlockDimY, Value *BlockDimZ,
88079a947c2STobias Grosser                                             Value *Parameters) {
88179a947c2STobias Grosser   const char *Name = "polly_launchKernel";
88279a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
88379a947c2STobias Grosser   Function *F = M->getFunction(Name);
88479a947c2STobias Grosser 
88579a947c2STobias Grosser   // If F is not available, declare it.
88679a947c2STobias Grosser   if (!F) {
88779a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
88879a947c2STobias Grosser     std::vector<Type *> Args;
88979a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
89079a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
89179a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
89279a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
89379a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
89479a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
89579a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
89679a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
89779a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
89879a947c2STobias Grosser   }
89979a947c2STobias Grosser 
900ff40087aSTobias Grosser   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
90179a947c2STobias Grosser                          BlockDimZ, Parameters});
90279a947c2STobias Grosser }
90379a947c2STobias Grosser 
90457793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
90557793596STobias Grosser   const char *Name = "polly_freeKernel";
90657793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
90757793596STobias Grosser   Function *F = M->getFunction(Name);
90857793596STobias Grosser 
90957793596STobias Grosser   // If F is not available, declare it.
91057793596STobias Grosser   if (!F) {
91157793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
91257793596STobias Grosser     std::vector<Type *> Args;
91357793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
91457793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
91557793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
91657793596STobias Grosser   }
91757793596STobias Grosser 
91857793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
91957793596STobias Grosser }
92057793596STobias Grosser 
9217287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
922abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not allocate or free memory "
923abed4969SSiddharth Bhat                            "for device");
9247287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
9257287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9267287aeddSTobias Grosser   Function *F = M->getFunction(Name);
9277287aeddSTobias Grosser 
9287287aeddSTobias Grosser   // If F is not available, declare it.
9297287aeddSTobias Grosser   if (!F) {
9307287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
9317287aeddSTobias Grosser     std::vector<Type *> Args;
9327287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
9337287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
9347287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
9357287aeddSTobias Grosser   }
9367287aeddSTobias Grosser 
9377287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
9387287aeddSTobias Grosser }
9397287aeddSTobias Grosser 
940fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
941abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not allocate or free memory "
942abed4969SSiddharth Bhat                            "for device");
943fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
944fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
945fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
946fa7b0802STobias Grosser 
947fa7b0802STobias Grosser   // If F is not available, declare it.
948fa7b0802STobias Grosser   if (!F) {
949fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
950fa7b0802STobias Grosser     std::vector<Type *> Args;
951fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
952fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
953fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
954fa7b0802STobias Grosser   }
955fa7b0802STobias Grosser 
956fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
957fa7b0802STobias Grosser }
958fa7b0802STobias Grosser 
95913c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
96013c78e4dSTobias Grosser                                                     Value *DeviceData,
96113c78e4dSTobias Grosser                                                     Value *Size) {
962abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not transfer memory between "
963abed4969SSiddharth Bhat                            "device and host");
96413c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
96513c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
96613c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
96713c78e4dSTobias Grosser 
96813c78e4dSTobias Grosser   // If F is not available, declare it.
96913c78e4dSTobias Grosser   if (!F) {
97013c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
97113c78e4dSTobias Grosser     std::vector<Type *> Args;
97213c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
97313c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
97413c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
97513c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
97613c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
97713c78e4dSTobias Grosser   }
97813c78e4dSTobias Grosser 
97913c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
98013c78e4dSTobias Grosser }
98113c78e4dSTobias Grosser 
98213c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
98313c78e4dSTobias Grosser                                                     Value *HostData,
98413c78e4dSTobias Grosser                                                     Value *Size) {
985abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not transfer memory between "
986abed4969SSiddharth Bhat                            "device and host");
98713c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
98813c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
98913c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
99013c78e4dSTobias Grosser 
99113c78e4dSTobias Grosser   // If F is not available, declare it.
99213c78e4dSTobias Grosser   if (!F) {
99313c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
99413c78e4dSTobias Grosser     std::vector<Type *> Args;
99513c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
99613c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
99713c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
99813c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
99913c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
100013c78e4dSTobias Grosser   }
100113c78e4dSTobias Grosser 
100213c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
100313c78e4dSTobias Grosser }
100413c78e4dSTobias Grosser 
1005abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() {
1006abed4969SSiddharth Bhat   assert(ManagedMemory && "explicit synchronization is only necessary for "
1007abed4969SSiddharth Bhat                           "managed memory");
1008abed4969SSiddharth Bhat   const char *Name = "polly_synchronizeDevice";
1009abed4969SSiddharth Bhat   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1010abed4969SSiddharth Bhat   Function *F = M->getFunction(Name);
1011abed4969SSiddharth Bhat 
1012abed4969SSiddharth Bhat   // If F is not available, declare it.
1013abed4969SSiddharth Bhat   if (!F) {
1014abed4969SSiddharth Bhat     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1015abed4969SSiddharth Bhat     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
1016abed4969SSiddharth Bhat     F = Function::Create(Ty, Linkage, Name, M);
1017abed4969SSiddharth Bhat   }
1018abed4969SSiddharth Bhat 
1019abed4969SSiddharth Bhat   Builder.CreateCall(F);
1020abed4969SSiddharth Bhat }
1021abed4969SSiddharth Bhat 
1022fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
102317f01968SSiddharth Bhat   const char *Name;
102417f01968SSiddharth Bhat 
102517f01968SSiddharth Bhat   switch (Runtime) {
102617f01968SSiddharth Bhat   case GPURuntime::CUDA:
102717f01968SSiddharth Bhat     Name = "polly_initContextCUDA";
102817f01968SSiddharth Bhat     break;
102917f01968SSiddharth Bhat   case GPURuntime::OpenCL:
103017f01968SSiddharth Bhat     Name = "polly_initContextCL";
103117f01968SSiddharth Bhat     break;
103217f01968SSiddharth Bhat   }
103317f01968SSiddharth Bhat 
1034fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1035fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
1036fa7b0802STobias Grosser 
1037fa7b0802STobias Grosser   // If F is not available, declare it.
1038fa7b0802STobias Grosser   if (!F) {
1039fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1040fa7b0802STobias Grosser     std::vector<Type *> Args;
1041fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
1042fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
1043fa7b0802STobias Grosser   }
1044fa7b0802STobias Grosser 
1045fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
1046fa7b0802STobias Grosser }
1047fa7b0802STobias Grosser 
1048fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
1049fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
1050fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1051fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
1052fa7b0802STobias Grosser 
1053fa7b0802STobias Grosser   // If F is not available, declare it.
1054fa7b0802STobias Grosser   if (!F) {
1055fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1056fa7b0802STobias Grosser     std::vector<Type *> Args;
1057fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
1058fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
1059fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
1060fa7b0802STobias Grosser   }
1061fa7b0802STobias Grosser 
1062fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
1063fa7b0802STobias Grosser }
1064fa7b0802STobias Grosser 
10655260c041STobias Grosser /// Check if one string is a prefix of another.
10665260c041STobias Grosser ///
10675260c041STobias Grosser /// @param String The string in which to look for the prefix.
10685260c041STobias Grosser /// @param Prefix The prefix to look for.
10695260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
10705260c041STobias Grosser   return String.find(Prefix) == 0;
10715260c041STobias Grosser }
10725260c041STobias Grosser 
107313c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
1074b65ccc43STobias Grosser   isl::ast_build Build = isl::ast_build::from_context(S.getContext());
107513c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
107613c78e4dSTobias Grosser 
107713c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
1078f7face4bSSiddharth Bhat     isl::multi_pw_aff ArrayBound =
1079f7face4bSSiddharth Bhat         isl::manage(isl_multi_pw_aff_copy(Array->bound));
1080f7face4bSSiddharth Bhat 
1081f7face4bSSiddharth Bhat     isl::pw_aff OffsetDimZero = ArrayBound.get_pw_aff(0);
1082f7face4bSSiddharth Bhat     isl::ast_expr Res = Build.expr_from(OffsetDimZero);
108313c78e4dSTobias Grosser 
108413c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
1085f7face4bSSiddharth Bhat       isl::pw_aff Bound_I = ArrayBound.get_pw_aff(i);
1086f7face4bSSiddharth Bhat       isl::ast_expr Expr = Build.expr_from(Bound_I);
1087f7face4bSSiddharth Bhat       Res = Res.mul(Expr);
108813c78e4dSTobias Grosser     }
108913c78e4dSTobias Grosser 
1090f7face4bSSiddharth Bhat     Value *NumElements = ExprBuilder.create(Res.release());
1091b79f4d39STobias Grosser     if (NumElements->getType() != ArraySize->getType())
1092b79f4d39STobias Grosser       NumElements = Builder.CreateSExt(NumElements, ArraySize->getType());
109313c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
109413c78e4dSTobias Grosser   }
109513c78e4dSTobias Grosser   return ArraySize;
109613c78e4dSTobias Grosser }
109713c78e4dSTobias Grosser 
1098aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) {
1099aaabbbf8STobias Grosser   if (gpu_array_is_scalar(Array))
1100aaabbbf8STobias Grosser     return nullptr;
1101aaabbbf8STobias Grosser 
1102b65ccc43STobias Grosser   isl::ast_build Build = isl::ast_build::from_context(S.getContext());
1103aaabbbf8STobias Grosser 
1104ccbf4b50SSiddharth Bhat   isl::set Min = isl::manage(isl_set_copy(Array->extent)).lexmin();
1105aaabbbf8STobias Grosser 
1106ccbf4b50SSiddharth Bhat   isl::set ZeroSet = isl::set::universe(Min.get_space());
1107aaabbbf8STobias Grosser 
1108ccbf4b50SSiddharth Bhat   for (long i = 0; i < Min.dim(isl::dim::set); i++)
1109ccbf4b50SSiddharth Bhat     ZeroSet = ZeroSet.fix_si(isl::dim::set, i, 0);
1110aaabbbf8STobias Grosser 
1111ccbf4b50SSiddharth Bhat   if (Min.is_subset(ZeroSet)) {
1112aaabbbf8STobias Grosser     return nullptr;
1113aaabbbf8STobias Grosser   }
1114aaabbbf8STobias Grosser 
1115ccbf4b50SSiddharth Bhat   isl::ast_expr Result = isl::ast_expr::from_val(isl::val(Min.get_ctx(), 0));
1116aaabbbf8STobias Grosser 
1117ccbf4b50SSiddharth Bhat   for (long i = 0; i < Min.dim(isl::dim::set); i++) {
1118aaabbbf8STobias Grosser     if (i > 0) {
1119ccbf4b50SSiddharth Bhat       isl::pw_aff Bound_I =
1120ccbf4b50SSiddharth Bhat           isl::manage(isl_multi_pw_aff_get_pw_aff(Array->bound, i - 1));
1121ccbf4b50SSiddharth Bhat       isl::ast_expr BExpr = Build.expr_from(Bound_I);
1122ccbf4b50SSiddharth Bhat       Result = Result.mul(BExpr);
1123aaabbbf8STobias Grosser     }
1124ccbf4b50SSiddharth Bhat     isl::pw_aff DimMin = Min.dim_min(i);
1125ccbf4b50SSiddharth Bhat     isl::ast_expr MExpr = Build.expr_from(DimMin);
1126ccbf4b50SSiddharth Bhat     Result = Result.add(MExpr);
1127aaabbbf8STobias Grosser   }
1128aaabbbf8STobias Grosser 
1129ccbf4b50SSiddharth Bhat   return ExprBuilder.create(Result.release());
1130aaabbbf8STobias Grosser }
1131aaabbbf8STobias Grosser 
1132b99c1171STobias Grosser Value *GPUNodeBuilder::getManagedDeviceArray(gpu_array_info *Array,
1133abed4969SSiddharth Bhat                                              ScopArrayInfo *ArrayInfo) {
1134abed4969SSiddharth Bhat   assert(ManagedMemory && "Only used when you wish to get a host "
1135abed4969SSiddharth Bhat                           "pointer for sending data to the kernel, "
1136abed4969SSiddharth Bhat                           "with managed memory");
1137abed4969SSiddharth Bhat   std::map<ScopArrayInfo *, Value *>::iterator it;
1138b99c1171STobias Grosser   it = DeviceAllocations.find(ArrayInfo);
1139b99c1171STobias Grosser   assert(it != DeviceAllocations.end() &&
1140b99c1171STobias Grosser          "Device array expected to be available");
1141abed4969SSiddharth Bhat   return it->second;
1142abed4969SSiddharth Bhat }
1143abed4969SSiddharth Bhat 
114413c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
114513c78e4dSTobias Grosser                                         enum DataDirection Direction) {
1146abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory needs no data transfers");
114713c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
114813c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
114913c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
115013c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
115113c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
115213c78e4dSTobias Grosser 
115313c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
1154aaabbbf8STobias Grosser   Value *Offset = getArrayOffset(Array);
115513c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
115613c78e4dSTobias Grosser 
1157b06ff457STobias Grosser   Value *HostPtr;
1158b06ff457STobias Grosser 
1159b06ff457STobias Grosser   if (gpu_array_is_scalar(Array))
1160b06ff457STobias Grosser     HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
1161b06ff457STobias Grosser   else
1162b06ff457STobias Grosser     HostPtr = ScopArray->getBasePtr();
1163edf9581eSSiddharth Bhat   HostPtr = getLatestValue(HostPtr);
116413c78e4dSTobias Grosser 
1165aaabbbf8STobias Grosser   if (Offset) {
1166aaabbbf8STobias Grosser     HostPtr = Builder.CreatePointerCast(
1167aaabbbf8STobias Grosser         HostPtr, ScopArray->getElementType()->getPointerTo());
1168aaabbbf8STobias Grosser     HostPtr = Builder.CreateGEP(HostPtr, Offset);
1169aaabbbf8STobias Grosser   }
1170aaabbbf8STobias Grosser 
117113c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
117213c78e4dSTobias Grosser 
1173aaabbbf8STobias Grosser   if (Offset) {
1174aaabbbf8STobias Grosser     Size = Builder.CreateSub(
1175ff40087aSTobias Grosser         Size, Builder.CreateMul(
1176ff40087aSTobias Grosser                   Offset, Builder.getInt64(ScopArray->getElemSizeInBytes())));
1177aaabbbf8STobias Grosser   }
1178aaabbbf8STobias Grosser 
117913c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
118013c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
118113c78e4dSTobias Grosser   else
118213c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
118313c78e4dSTobias Grosser 
118413c78e4dSTobias Grosser   isl_id_free(Id);
118513c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
118613c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
118713c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
118813c78e4dSTobias Grosser }
118913c78e4dSTobias Grosser 
11901fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
119132837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
119232837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
119332837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
119432837fe3STobias Grosser   isl_id_free(Id);
119532837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
119632837fe3STobias Grosser 
119732837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
119832837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
119932837fe3STobias Grosser     createKernel(UserStmt);
120032837fe3STobias Grosser     isl_ast_expr_free(Expr);
120132837fe3STobias Grosser     return;
120232837fe3STobias Grosser   }
12039e3db2b7SSiddharth Bhat   if (!strcmp(Str, "init_device")) {
12049e3db2b7SSiddharth Bhat     initializeAfterRTH();
12059e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
12069e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
12079e3db2b7SSiddharth Bhat     return;
12089e3db2b7SSiddharth Bhat   }
12099e3db2b7SSiddharth Bhat   if (!strcmp(Str, "clear_device")) {
12109e3db2b7SSiddharth Bhat     finalize();
12119e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
12129e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
12139e3db2b7SSiddharth Bhat     return;
12149e3db2b7SSiddharth Bhat   }
121513c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
1216abed4969SSiddharth Bhat     if (!ManagedMemory)
121713c78e4dSTobias Grosser       createDataTransfer(UserStmt, HOST_TO_DEVICE);
1218abed4969SSiddharth Bhat     else
1219abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1220abed4969SSiddharth Bhat 
122132837fe3STobias Grosser     isl_ast_expr_free(Expr);
122213c78e4dSTobias Grosser     return;
122313c78e4dSTobias Grosser   }
122413c78e4dSTobias Grosser 
122513c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
1226abed4969SSiddharth Bhat     if (!ManagedMemory) {
122713c78e4dSTobias Grosser       createDataTransfer(UserStmt, DEVICE_TO_HOST);
1228abed4969SSiddharth Bhat     } else {
1229abed4969SSiddharth Bhat       createCallSynchronizeDevice();
1230abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1231abed4969SSiddharth Bhat     }
123213c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
123338fc0aedSTobias Grosser     return;
123438fc0aedSTobias Grosser   }
123538fc0aedSTobias Grosser 
12365260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
12375260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
12385260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
12395260c041STobias Grosser   isl_id_free(Anno);
12405260c041STobias Grosser 
12415260c041STobias Grosser   switch (KernelStmt->type) {
12425260c041STobias Grosser   case ppcg_kernel_domain:
1243edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
12445260c041STobias Grosser     isl_ast_node_free(UserStmt);
12455260c041STobias Grosser     return;
12465260c041STobias Grosser   case ppcg_kernel_copy:
1247b513b491STobias Grosser     createKernelCopy(KernelStmt);
12485260c041STobias Grosser     isl_ast_expr_free(Expr);
12495260c041STobias Grosser     isl_ast_node_free(UserStmt);
12505260c041STobias Grosser     return;
12515260c041STobias Grosser   case ppcg_kernel_sync:
12525260c041STobias Grosser     createKernelSync();
12535260c041STobias Grosser     isl_ast_expr_free(Expr);
12545260c041STobias Grosser     isl_ast_node_free(UserStmt);
12555260c041STobias Grosser     return;
12565260c041STobias Grosser   }
12575260c041STobias Grosser 
12585260c041STobias Grosser   isl_ast_expr_free(Expr);
12595260c041STobias Grosser   isl_ast_node_free(UserStmt);
12605260c041STobias Grosser   return;
12615260c041STobias Grosser }
1262b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
1263b513b491STobias Grosser   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
1264b513b491STobias Grosser   LocalIndex = isl_ast_expr_address_of(LocalIndex);
1265b513b491STobias Grosser   Value *LocalAddr = ExprBuilder.create(LocalIndex);
1266b513b491STobias Grosser   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
1267b513b491STobias Grosser   Index = isl_ast_expr_address_of(Index);
1268b513b491STobias Grosser   Value *GlobalAddr = ExprBuilder.create(Index);
1269b513b491STobias Grosser 
1270b513b491STobias Grosser   if (KernelStmt->u.c.read) {
1271b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read");
1272b513b491STobias Grosser     Builder.CreateStore(Load, LocalAddr);
1273b513b491STobias Grosser   } else {
1274b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write");
1275b513b491STobias Grosser     Builder.CreateStore(Load, GlobalAddr);
1276b513b491STobias Grosser   }
1277b513b491STobias Grosser }
12785260c041STobias Grosser 
1279edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
1280edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
1281edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1282edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
1283edb885cbSTobias Grosser 
1284edb885cbSTobias Grosser   LoopToScevMapT LTS;
1285edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
1286edb885cbSTobias Grosser 
1287edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
1288edb885cbSTobias Grosser 
1289edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
1290edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
1291edb885cbSTobias Grosser   else
1292a82c4b5dSTobias Grosser     RegionGen.copyStmt(*Stmt, LTS, Indexes);
1293edb885cbSTobias Grosser }
1294edb885cbSTobias Grosser 
12955260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
12965260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12972f3073b5SPhilipp Schaad   const char *SpirName = "__gen_ocl_barrier_global";
129817f01968SSiddharth Bhat 
129917f01968SSiddharth Bhat   Function *Sync;
130017f01968SSiddharth Bhat 
130117f01968SSiddharth Bhat   switch (Arch) {
13022f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
13032f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
13042f3073b5SPhilipp Schaad     Sync = M->getFunction(SpirName);
13052f3073b5SPhilipp Schaad 
13062f3073b5SPhilipp Schaad     // If Sync is not available, declare it.
13072f3073b5SPhilipp Schaad     if (!Sync) {
13082f3073b5SPhilipp Schaad       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
13092f3073b5SPhilipp Schaad       std::vector<Type *> Args;
13102f3073b5SPhilipp Schaad       FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
13112f3073b5SPhilipp Schaad       Sync = Function::Create(Ty, Linkage, SpirName, M);
13122f3073b5SPhilipp Schaad       Sync->setCallingConv(CallingConv::SPIR_FUNC);
13132f3073b5SPhilipp Schaad     }
13142f3073b5SPhilipp Schaad     break;
131517f01968SSiddharth Bhat   case GPUArch::NVPTX64:
131617f01968SSiddharth Bhat     Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
131717f01968SSiddharth Bhat     break;
131817f01968SSiddharth Bhat   }
131917f01968SSiddharth Bhat 
13205260c041STobias Grosser   Builder.CreateCall(Sync, {});
13215260c041STobias Grosser }
13225260c041STobias Grosser 
1323edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
1324edb885cbSTobias Grosser ///
1325edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
1326edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
1327edb885cbSTobias Grosser ///
1328edb885cbSTobias Grosser /// @param Node The node to collect references for.
1329edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
1330edb885cbSTobias Grosser ///
1331edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
1332edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
1333edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
1334edb885cbSTobias Grosser     return isl_bool_true;
1335edb885cbSTobias Grosser 
1336edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
1337edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
1338edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
1339edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
1340edb885cbSTobias Grosser   isl_id_free(Id);
1341edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
1342edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
1343edb885cbSTobias Grosser 
1344edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
1345edb885cbSTobias Grosser     return isl_bool_true;
1346edb885cbSTobias Grosser 
1347edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
1348edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
1349edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1350edb885cbSTobias Grosser   isl_id_free(Id);
1351edb885cbSTobias Grosser 
135200bb5a99STobias Grosser   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
1353edb885cbSTobias Grosser 
1354edb885cbSTobias Grosser   return isl_bool_true;
1355edb885cbSTobias Grosser }
1356edb885cbSTobias Grosser 
13578fc6cdfbSTobias Grosser /// A list of functions that are available in NVIDIA's libdevice.
13588fc6cdfbSTobias Grosser const std::set<std::string> CUDALibDeviceFunctions = {
13598fc6cdfbSTobias Grosser     "exp",  "expf",  "expl",     "cos",       "cosf",
13608fc6cdfbSTobias Grosser     "sqrt", "sqrtf", "copysign", "copysignf", "copysignl"};
13618fc6cdfbSTobias Grosser 
13628fc6cdfbSTobias Grosser /// Return the corresponding CUDA libdevice function name for @p F.
13638fc6cdfbSTobias Grosser ///
13648fc6cdfbSTobias Grosser /// Return "" if we are not compiling for CUDA.
13658fc6cdfbSTobias Grosser std::string getCUDALibDeviceFuntion(Function *F) {
13668fc6cdfbSTobias Grosser   if (CUDALibDeviceFunctions.count(F->getName()))
13678fc6cdfbSTobias Grosser     return std::string("__nv_") + std::string(F->getName());
13688fc6cdfbSTobias Grosser 
13698fc6cdfbSTobias Grosser   return "";
13708fc6cdfbSTobias Grosser }
13718fc6cdfbSTobias Grosser 
1372f291c8d5SSiddharth Bhat /// Check if F is a function that we can code-generate in a GPU kernel.
13738fc6cdfbSTobias Grosser static bool isValidFunctionInKernel(llvm::Function *F, bool AllowLibDevice) {
1374f291c8d5SSiddharth Bhat   assert(F && "F is an invalid pointer");
1375f291c8d5SSiddharth Bhat   // We string compare against the name of the function to allow
137654491db6STobias Grosser   // all variants of the intrinsic "llvm.sqrt.*", "llvm.fabs", and
137754491db6STobias Grosser   // "llvm.copysign".
137854491db6STobias Grosser   const StringRef Name = F->getName();
13798fc6cdfbSTobias Grosser 
13808fc6cdfbSTobias Grosser   if (AllowLibDevice && getCUDALibDeviceFuntion(F).length() > 0)
13818fc6cdfbSTobias Grosser     return true;
13828fc6cdfbSTobias Grosser 
138354491db6STobias Grosser   return F->isIntrinsic() &&
138454491db6STobias Grosser          (Name.startswith("llvm.sqrt") || Name.startswith("llvm.fabs") ||
138554491db6STobias Grosser           Name.startswith("llvm.copysign"));
1386f291c8d5SSiddharth Bhat }
1387f291c8d5SSiddharth Bhat 
1388f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value.
1389f291c8d5SSiddharth Bhat ///
1390f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along
1391f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and
1392f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not
1393f291c8d5SSiddharth Bhat /// `Function`s.
1394f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); }
1395f291c8d5SSiddharth Bhat 
1396f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`.
1397f291c8d5SSiddharth Bhat static SetVector<Function *>
13988fc6cdfbSTobias Grosser getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues,
13998fc6cdfbSTobias Grosser                                  bool AllowCUDALibDevice) {
1400f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1401f291c8d5SSiddharth Bhat   for (Value *It : RawSubtreeValues) {
1402f291c8d5SSiddharth Bhat     Function *F = dyn_cast<Function>(It);
1403f291c8d5SSiddharth Bhat     if (F) {
14048fc6cdfbSTobias Grosser       assert(isValidFunctionInKernel(F, AllowCUDALibDevice) &&
14058fc6cdfbSTobias Grosser              "Code should have bailed out by "
1406f291c8d5SSiddharth Bhat              "this point if an invalid function "
1407f291c8d5SSiddharth Bhat              "were present in a kernel.");
1408f291c8d5SSiddharth Bhat       SubtreeFunctions.insert(F);
1409f291c8d5SSiddharth Bhat     }
1410f291c8d5SSiddharth Bhat   }
1411f291c8d5SSiddharth Bhat   return SubtreeFunctions;
1412f291c8d5SSiddharth Bhat }
1413f291c8d5SSiddharth Bhat 
1414e53c924bSSiddharth Bhat std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>>
1415f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
1416edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
1417edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
1418edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1419edb885cbSTobias Grosser   SubtreeReferences References = {
1420edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
1421edb885cbSTobias Grosser 
1422edb885cbSTobias Grosser   for (const auto &I : IDToValue)
1423edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
1424edb885cbSTobias Grosser 
1425e53c924bSSiddharth Bhat   // NOTE: this is populated in IslNodeBuilder::addParameters
1426e53c924bSSiddharth Bhat   // See [Code generation of induction variables of loops outside Scops].
1427e53c924bSSiddharth Bhat   for (const auto &I : OutsideLoopIterations)
1428e53c924bSSiddharth Bhat     SubtreeValues.insert(cast<SCEVUnknown>(I.second)->getValue());
1429e53c924bSSiddharth Bhat 
1430edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
1431edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
1432edb885cbSTobias Grosser 
1433e53c924bSSiddharth Bhat   for (const SCEV *Expr : SCEVs) {
1434edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
1435e53c924bSSiddharth Bhat     findLoops(Expr, Loops);
1436e53c924bSSiddharth Bhat   }
1437e53c924bSSiddharth Bhat 
1438e53c924bSSiddharth Bhat   Loops.remove_if([this](const Loop *L) {
1439e53c924bSSiddharth Bhat     return S.contains(L) || L->contains(S.getEntry());
1440e53c924bSSiddharth Bhat   });
1441edb885cbSTobias Grosser 
1442edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
1443d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
1444edb885cbSTobias Grosser 
1445b65ccc43STobias Grosser   isl_space *Space = S.getParamSpace().release();
1446edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1447edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
1448edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1449edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1450edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1451edb885cbSTobias Grosser     isl_id_free(Id);
1452edb885cbSTobias Grosser   }
1453edb885cbSTobias Grosser   isl_space_free(Space);
1454edb885cbSTobias Grosser 
1455edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
1456edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1457edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1458edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1459edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1460edb885cbSTobias Grosser     isl_id_free(Id);
1461edb885cbSTobias Grosser   }
1462edb885cbSTobias Grosser 
1463f291c8d5SSiddharth Bhat   // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions
1464f291c8d5SSiddharth Bhat   // SubtreeValues. This is important, because we should not lose any
1465f291c8d5SSiddharth Bhat   // SubtreeValues in the process of constructing the
1466f291c8d5SSiddharth Bhat   // "ValidSubtree{Values, Functions} sets. Nor should the set
1467f291c8d5SSiddharth Bhat   // ValidSubtree{Values, Functions} have any common element.
1468f291c8d5SSiddharth Bhat   auto ValidSubtreeValuesIt =
1469f291c8d5SSiddharth Bhat       make_filter_range(SubtreeValues, isValidSubtreeValue);
1470f291c8d5SSiddharth Bhat   SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(),
1471f291c8d5SSiddharth Bhat                                         ValidSubtreeValuesIt.end());
14728fc6cdfbSTobias Grosser 
14738fc6cdfbSTobias Grosser   bool AllowCUDALibDevice = Arch == GPUArch::NVPTX64;
14748fc6cdfbSTobias Grosser 
1475f291c8d5SSiddharth Bhat   SetVector<Function *> ValidSubtreeFunctions(
14768fc6cdfbSTobias Grosser       getFunctionsFromRawSubtreeValues(SubtreeValues, AllowCUDALibDevice));
1477f291c8d5SSiddharth Bhat 
1478a1b2086aSSiddharth Bhat   // @see IslNodeBuilder::getReferencesInSubtree
1479a1b2086aSSiddharth Bhat   SetVector<Value *> ReplacedValues;
1480a1b2086aSSiddharth Bhat   for (Value *V : ValidSubtreeValues) {
1481a1b2086aSSiddharth Bhat     auto It = ValueMap.find(V);
1482a1b2086aSSiddharth Bhat     if (It == ValueMap.end())
1483a1b2086aSSiddharth Bhat       ReplacedValues.insert(V);
1484a1b2086aSSiddharth Bhat     else
1485a1b2086aSSiddharth Bhat       ReplacedValues.insert(It->second);
1486a1b2086aSSiddharth Bhat   }
1487e53c924bSSiddharth Bhat   return std::make_tuple(ReplacedValues, ValidSubtreeFunctions, Loops);
1488edb885cbSTobias Grosser }
1489edb885cbSTobias Grosser 
149074dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
149174dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
149274dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
149374dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
149474dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
149574dc3cb4STobias Grosser 
149674dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
149774dc3cb4STobias Grosser     DT.eraseNode(BB);
149874dc3cb4STobias Grosser }
149974dc3cb4STobias Grosser 
150074dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
150174dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
150274dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
150374dc3cb4STobias Grosser     if (L)
150474dc3cb4STobias Grosser       SE.forgetLoop(L);
150574dc3cb4STobias Grosser   }
150674dc3cb4STobias Grosser }
150774dc3cb4STobias Grosser 
150874dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
150974dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
151074dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
151174dc3cb4STobias Grosser     if (L)
151274dc3cb4STobias Grosser       SE.forgetLoop(L);
151374dc3cb4STobias Grosser     LI.removeBlock(&BB);
151474dc3cb4STobias Grosser   }
151574dc3cb4STobias Grosser }
151674dc3cb4STobias Grosser 
151779a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
151879a947c2STobias Grosser   std::vector<Value *> Sizes;
15198ea1fc19STobias Grosser   isl::ast_build Context = isl::ast_build::from_context(S.getContext());
152079a947c2STobias Grosser 
15214d5820d1SSiddharth Bhat   isl::multi_pw_aff GridSizePwAffs =
15224d5820d1SSiddharth Bhat       isl::manage(isl_multi_pw_aff_copy(Kernel->grid_size));
152379a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
15244d5820d1SSiddharth Bhat     isl::pw_aff Size = GridSizePwAffs.get_pw_aff(i);
15254d5820d1SSiddharth Bhat     isl::ast_expr GridSize = Context.expr_from(Size);
15264d5820d1SSiddharth Bhat     Value *Res = ExprBuilder.create(GridSize.release());
152779a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
152879a947c2STobias Grosser     Sizes.push_back(Res);
152979a947c2STobias Grosser   }
153079a947c2STobias Grosser 
153179a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
153279a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
153379a947c2STobias Grosser 
153479a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
153579a947c2STobias Grosser }
153679a947c2STobias Grosser 
153779a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
153879a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
153979a947c2STobias Grosser   std::vector<Value *> Sizes;
154079a947c2STobias Grosser 
154179a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
154279a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
154379a947c2STobias Grosser     Sizes.push_back(Res);
154479a947c2STobias Grosser   }
154579a947c2STobias Grosser 
154679a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
154779a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
154879a947c2STobias Grosser 
154979a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
155079a947c2STobias Grosser }
155179a947c2STobias Grosser 
1552a90be207SSiddharth Bhat void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters,
1553a90be207SSiddharth Bhat                                           Instruction *Param, int Index) {
1554a90be207SSiddharth Bhat   Value *Slot = Builder.CreateGEP(
1555a90be207SSiddharth Bhat       Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1556a90be207SSiddharth Bhat   Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1557a90be207SSiddharth Bhat   Builder.CreateStore(ParamTyped, Slot);
1558a90be207SSiddharth Bhat }
1559a90be207SSiddharth Bhat 
156057693272STobias Grosser Value *
156157693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
156257693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
1563a90be207SSiddharth Bhat   const int NumArgs = F->arg_size();
1564a90be207SSiddharth Bhat   std::vector<int> ArgSizes(NumArgs);
1565a90be207SSiddharth Bhat 
1566a90be207SSiddharth Bhat   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs);
156779a947c2STobias Grosser 
156879a947c2STobias Grosser   BasicBlock *EntryBlock =
156979a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
157067726b32STobias Grosser   auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace();
157179a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
157267726b32STobias Grosser   Instruction *Parameters = new AllocaInst(
157367726b32STobias Grosser       ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator());
157479a947c2STobias Grosser 
157579a947c2STobias Grosser   int Index = 0;
157679a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
157779a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
157879a947c2STobias Grosser       continue;
157979a947c2STobias Grosser 
158079a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1581206e9e3bSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
158279a947c2STobias Grosser 
1583a90be207SSiddharth Bhat     ArgSizes[Index] = SAI->getElemSizeInBytes();
1584a90be207SSiddharth Bhat 
1585abed4969SSiddharth Bhat     Value *DevArray = nullptr;
1586abed4969SSiddharth Bhat     if (ManagedMemory) {
1587b99c1171STobias Grosser       DevArray = getManagedDeviceArray(&Prog->array[i],
1588b99c1171STobias Grosser                                        const_cast<ScopArrayInfo *>(SAI));
1589abed4969SSiddharth Bhat     } else {
1590abed4969SSiddharth Bhat       DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
159179a947c2STobias Grosser       DevArray = createCallGetDevicePtr(DevArray);
1592abed4969SSiddharth Bhat     }
1593abed4969SSiddharth Bhat     assert(DevArray != nullptr && "Array to be offloaded to device not "
1594abed4969SSiddharth Bhat                                   "initialized");
1595aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(&Prog->array[i]);
1596aaabbbf8STobias Grosser 
1597aaabbbf8STobias Grosser     if (Offset) {
1598aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(
1599aaabbbf8STobias Grosser           DevArray, SAI->getElementType()->getPointerTo());
1600aaabbbf8STobias Grosser       DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset));
1601aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1602aaabbbf8STobias Grosser     }
1603fe74a7a1STobias Grosser     Value *Slot = Builder.CreateGEP(
1604fe74a7a1STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1605aaabbbf8STobias Grosser 
1606fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1607abed4969SSiddharth Bhat       Value *ValPtr = nullptr;
1608abed4969SSiddharth Bhat       if (ManagedMemory)
1609abed4969SSiddharth Bhat         ValPtr = DevArray;
1610abed4969SSiddharth Bhat       else
1611abed4969SSiddharth Bhat         ValPtr = BlockGen.getOrCreateAlloca(SAI);
1612abed4969SSiddharth Bhat 
1613abed4969SSiddharth Bhat       assert(ValPtr != nullptr && "ValPtr that should point to a valid object"
1614abed4969SSiddharth Bhat                                   " to be stored into Parameters");
1615fe74a7a1STobias Grosser       Value *ValPtrCast =
1616fe74a7a1STobias Grosser           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1617fe74a7a1STobias Grosser       Builder.CreateStore(ValPtrCast, Slot);
1618fe74a7a1STobias Grosser     } else {
161967726b32STobias Grosser       Instruction *Param =
162067726b32STobias Grosser           new AllocaInst(Builder.getInt8PtrTy(), AddressSpace,
162167726b32STobias Grosser                          Launch + "_param_" + std::to_string(Index),
162279a947c2STobias Grosser                          EntryBlock->getTerminator());
162379a947c2STobias Grosser       Builder.CreateStore(DevArray, Param);
162479a947c2STobias Grosser       Value *ParamTyped =
162579a947c2STobias Grosser           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
162679a947c2STobias Grosser       Builder.CreateStore(ParamTyped, Slot);
1627fe74a7a1STobias Grosser     }
162879a947c2STobias Grosser     Index++;
162979a947c2STobias Grosser   }
163079a947c2STobias Grosser 
1631a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1632a490147cSTobias Grosser 
1633a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1634a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1635a490147cSTobias Grosser     Value *Val = IDToValue[Id];
1636a490147cSTobias Grosser     isl_id_free(Id);
1637a90be207SSiddharth Bhat 
1638a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1639a90be207SSiddharth Bhat 
164067726b32STobias Grosser     Instruction *Param =
164167726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
164267726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1643a490147cSTobias Grosser                        EntryBlock->getTerminator());
1644a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
1645a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1646a490147cSTobias Grosser     Index++;
1647a490147cSTobias Grosser   }
1648a490147cSTobias Grosser 
1649d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1650d8b94bcaSTobias Grosser 
1651d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
1652d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1653d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
1654a1b2086aSSiddharth Bhat     if (ValueMap.count(Val))
1655a1b2086aSSiddharth Bhat       Val = ValueMap[Val];
1656d8b94bcaSTobias Grosser     isl_id_free(Id);
1657a90be207SSiddharth Bhat 
1658a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1659a90be207SSiddharth Bhat 
166067726b32STobias Grosser     Instruction *Param =
166167726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
166267726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1663d8b94bcaSTobias Grosser                        EntryBlock->getTerminator());
1664d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
1665a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1666d8b94bcaSTobias Grosser     Index++;
1667d8b94bcaSTobias Grosser   }
1668d8b94bcaSTobias Grosser 
166957693272STobias Grosser   for (auto Val : SubtreeValues) {
1670a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1671a90be207SSiddharth Bhat 
167267726b32STobias Grosser     Instruction *Param =
167367726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
167467726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
167557693272STobias Grosser                        EntryBlock->getTerminator());
167657693272STobias Grosser     Builder.CreateStore(Val, Param);
1677a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1678a90be207SSiddharth Bhat     Index++;
1679a90be207SSiddharth Bhat   }
1680a90be207SSiddharth Bhat 
1681a90be207SSiddharth Bhat   for (int i = 0; i < NumArgs; i++) {
1682a90be207SSiddharth Bhat     Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]);
1683a90be207SSiddharth Bhat     Instruction *Param =
1684a90be207SSiddharth Bhat         new AllocaInst(Builder.getInt32Ty(), AddressSpace,
1685a90be207SSiddharth Bhat                        Launch + "_param_size_" + std::to_string(i),
1686a90be207SSiddharth Bhat                        EntryBlock->getTerminator());
1687a90be207SSiddharth Bhat     Builder.CreateStore(Val, Param);
1688a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
168957693272STobias Grosser     Index++;
169057693272STobias Grosser   }
169157693272STobias Grosser 
169279a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
169379a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
169479a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
169579a947c2STobias Grosser }
169679a947c2STobias Grosser 
1697f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions(
1698f291c8d5SSiddharth Bhat     SetVector<Function *> SubtreeFunctions) {
1699f291c8d5SSiddharth Bhat   for (auto Fn : SubtreeFunctions) {
1700f291c8d5SSiddharth Bhat     const std::string ClonedFnName = Fn->getName();
1701f291c8d5SSiddharth Bhat     Function *Clone = GPUModule->getFunction(ClonedFnName);
1702f291c8d5SSiddharth Bhat     if (!Clone)
1703f291c8d5SSiddharth Bhat       Clone =
1704f291c8d5SSiddharth Bhat           Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage,
1705f291c8d5SSiddharth Bhat                            ClonedFnName, GPUModule.get());
1706f291c8d5SSiddharth Bhat     assert(Clone && "Expected cloned function to be initialized.");
1707f291c8d5SSiddharth Bhat     assert(ValueMap.find(Fn) == ValueMap.end() &&
1708f291c8d5SSiddharth Bhat            "Fn already present in ValueMap");
1709f291c8d5SSiddharth Bhat     ValueMap[Fn] = Clone;
1710f291c8d5SSiddharth Bhat   }
1711f291c8d5SSiddharth Bhat }
171232837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
171332837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
171432837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
171532837fe3STobias Grosser   isl_id_free(Id);
171632837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
171732837fe3STobias Grosser 
1718bc653f20STobias Grosser   if (Kernel->n_grid > 1)
1719bc653f20STobias Grosser     DeepestParallel =
1720bc653f20STobias Grosser         std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set));
1721bc653f20STobias Grosser   else
1722bc653f20STobias Grosser     DeepestSequential =
1723bc653f20STobias Grosser         std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set));
1724bc653f20STobias Grosser 
1725c1c6a2a6STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1726c1c6a2a6STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1727c1c6a2a6STobias Grosser 
1728f291c8d5SSiddharth Bhat   SetVector<Value *> SubtreeValues;
1729f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1730e53c924bSSiddharth Bhat   SetVector<const Loop *> Loops;
1731e53c924bSSiddharth Bhat   std::tie(SubtreeValues, SubtreeFunctions, Loops) =
1732e53c924bSSiddharth Bhat       getReferencesInKernel(Kernel);
1733edb885cbSTobias Grosser 
173432837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
173532837fe3STobias Grosser 
173632837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1737472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1738edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
1739587f1f57STobias Grosser   BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap;
1740b06ff457STobias Grosser   ScalarMap.clear();
174132837fe3STobias Grosser 
1742edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
1743edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
1744edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
1745edb885cbSTobias Grosser   for (const Loop *L : Loops) {
1746edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1747edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1748edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1749edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1750edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1751edb885cbSTobias Grosser     SubtreeValues.insert(V);
1752edb885cbSTobias Grosser   }
1753edb885cbSTobias Grosser 
1754f291c8d5SSiddharth Bhat   createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions);
1755f291c8d5SSiddharth Bhat   setupKernelSubtreeFunctions(SubtreeFunctions);
175632837fe3STobias Grosser 
175759ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
175859ab0705STobias Grosser 
175951dfc275STobias Grosser   finalizeKernelArguments(Kernel);
176074dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
17612f3073b5SPhilipp Schaad   if (Arch == GPUArch::NVPTX64)
1762c1c6a2a6STobias Grosser     addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
176374dc3cb4STobias Grosser   clearDominators(F);
176474dc3cb4STobias Grosser   clearScalarEvolution(F);
176574dc3cb4STobias Grosser   clearLoops(F);
176674dc3cb4STobias Grosser 
1767472f9654STobias Grosser   IDToValue = HostIDs;
176832837fe3STobias Grosser 
1769b06ff457STobias Grosser   ValueMap = std::move(HostValueMap);
1770b06ff457STobias Grosser   ScalarMap = std::move(HostScalarMap);
1771edb885cbSTobias Grosser   EscapeMap.clear();
1772edb885cbSTobias Grosser   IDToSAI.clear();
177374dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
177474dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
17754d5a9172STobias Grosser     S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array);
177674dc3cb4STobias Grosser   LocalArrays.clear();
1777edb885cbSTobias Grosser 
177851dfc275STobias Grosser   std::string ASMString = finalizeKernelFunction();
177951dfc275STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
178057693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
178179a947c2STobias Grosser 
178279f13b9aSSingapuram Sanjay Srivallabh   std::string Name = getKernelFuncName(Kernel->id);
178357793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
178457793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
178557793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
178679a947c2STobias Grosser 
178779a947c2STobias Grosser   Value *GridDimX, *GridDimY;
178879a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
178979a947c2STobias Grosser 
179079a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
179179a947c2STobias Grosser                          BlockDimZ, Parameters);
179257793596STobias Grosser   createCallFreeKernel(GPUKernel);
1793b513b491STobias Grosser 
1794b513b491STobias Grosser   for (auto Id : KernelIds)
1795b513b491STobias Grosser     isl_id_free(Id);
1796b513b491STobias Grosser 
1797b513b491STobias Grosser   KernelIds.clear();
179832837fe3STobias Grosser }
179932837fe3STobias Grosser 
180032837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
180132837fe3STobias Grosser ///
180232837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
180332837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
1804d277fedaSSiddharth Bhat   std::string Ret = "";
180532837fe3STobias Grosser 
1806d277fedaSSiddharth Bhat   if (!is64Bit) {
1807d277fedaSSiddharth Bhat     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
180830caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1809d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1810d277fedaSSiddharth Bhat   } else {
1811d277fedaSSiddharth Bhat     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
181230caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1813d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1814d277fedaSSiddharth Bhat   }
181532837fe3STobias Grosser 
181632837fe3STobias Grosser   return Ret;
181732837fe3STobias Grosser }
181832837fe3STobias Grosser 
18192f3073b5SPhilipp Schaad /// Compute the DataLayout string for a SPIR kernel.
18202f3073b5SPhilipp Schaad ///
18212f3073b5SPhilipp Schaad /// @param is64Bit Are we looking for a 64 bit architecture?
18222f3073b5SPhilipp Schaad static std::string computeSPIRDataLayout(bool is64Bit) {
18232f3073b5SPhilipp Schaad   std::string Ret = "";
18242f3073b5SPhilipp Schaad 
18252f3073b5SPhilipp Schaad   if (!is64Bit) {
18262f3073b5SPhilipp Schaad     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
182730caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
18282f3073b5SPhilipp Schaad            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
18292f3073b5SPhilipp Schaad            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
18302f3073b5SPhilipp Schaad   } else {
18312f3073b5SPhilipp Schaad     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
183230caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
18332f3073b5SPhilipp Schaad            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
18342f3073b5SPhilipp Schaad            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
18352f3073b5SPhilipp Schaad   }
18362f3073b5SPhilipp Schaad 
18372f3073b5SPhilipp Schaad   return Ret;
18382f3073b5SPhilipp Schaad }
18392f3073b5SPhilipp Schaad 
1840edb885cbSTobias Grosser Function *
1841edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1842edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
184332837fe3STobias Grosser   std::vector<Type *> Args;
184479f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
184532837fe3STobias Grosser 
18462f3073b5SPhilipp Schaad   std::vector<Metadata *> MemoryType;
18472f3073b5SPhilipp Schaad 
184832837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
184932837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
185032837fe3STobias Grosser       continue;
185132837fe3STobias Grosser 
1852fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1853fe74a7a1STobias Grosser       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1854206e9e3bSTobias Grosser       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
1855fe74a7a1STobias Grosser       Args.push_back(SAI->getElementType());
18562f3073b5SPhilipp Schaad       MemoryType.push_back(
18572f3073b5SPhilipp Schaad           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1858fe74a7a1STobias Grosser     } else {
1859d277fedaSSiddharth Bhat       static const int UseGlobalMemory = 1;
1860d277fedaSSiddharth Bhat       Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory));
18612f3073b5SPhilipp Schaad       MemoryType.push_back(
18622f3073b5SPhilipp Schaad           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 1)));
186332837fe3STobias Grosser     }
1864fe74a7a1STobias Grosser   }
186532837fe3STobias Grosser 
1866f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1867f6044bd0STobias Grosser 
18682f3073b5SPhilipp Schaad   for (long i = 0; i < NumHostIters; i++) {
1869f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
18702f3073b5SPhilipp Schaad     MemoryType.push_back(
18712f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
18722f3073b5SPhilipp Schaad   }
1873f6044bd0STobias Grosser 
1874c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1875c84a1995STobias Grosser 
1876cf66ef26STobias Grosser   for (long i = 0; i < NumVars; i++) {
1877cf66ef26STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1878cf66ef26STobias Grosser     Value *Val = IDToValue[Id];
1879cf66ef26STobias Grosser     isl_id_free(Id);
1880cf66ef26STobias Grosser     Args.push_back(Val->getType());
18812f3073b5SPhilipp Schaad     MemoryType.push_back(
18822f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1883cf66ef26STobias Grosser   }
1884c84a1995STobias Grosser 
18852f3073b5SPhilipp Schaad   for (auto *V : SubtreeValues) {
1886edb885cbSTobias Grosser     Args.push_back(V->getType());
18872f3073b5SPhilipp Schaad     MemoryType.push_back(
18882f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
18892f3073b5SPhilipp Schaad   }
1890edb885cbSTobias Grosser 
189132837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
189232837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
189332837fe3STobias Grosser                               GPUModule.get());
189417f01968SSiddharth Bhat 
18952f3073b5SPhilipp Schaad   std::vector<Metadata *> EmptyStrings;
18962f3073b5SPhilipp Schaad 
18972f3073b5SPhilipp Schaad   for (unsigned int i = 0; i < MemoryType.size(); i++) {
18982f3073b5SPhilipp Schaad     EmptyStrings.push_back(MDString::get(FN->getContext(), ""));
18992f3073b5SPhilipp Schaad   }
19002f3073b5SPhilipp Schaad 
19012f3073b5SPhilipp Schaad   if (Arch == GPUArch::SPIR32 || Arch == GPUArch::SPIR64) {
19022f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_addr_space",
19032f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), MemoryType));
19042f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_name",
19052f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
19062f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_access_qual",
19072f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
19082f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_type",
19092f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
19102f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_type_qual",
19112f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
19122f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_base_type",
19132f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
19142f3073b5SPhilipp Schaad   }
19152f3073b5SPhilipp Schaad 
191617f01968SSiddharth Bhat   switch (Arch) {
191717f01968SSiddharth Bhat   case GPUArch::NVPTX64:
191832837fe3STobias Grosser     FN->setCallingConv(CallingConv::PTX_Kernel);
191917f01968SSiddharth Bhat     break;
19202f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
19212f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
19222f3073b5SPhilipp Schaad     FN->setCallingConv(CallingConv::SPIR_KERNEL);
19232f3073b5SPhilipp Schaad     break;
192417f01968SSiddharth Bhat   }
192532837fe3STobias Grosser 
192632837fe3STobias Grosser   auto Arg = FN->arg_begin();
192732837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
192832837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
192932837fe3STobias Grosser       continue;
193032837fe3STobias Grosser 
1931edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
1932edb885cbSTobias Grosser 
1933edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1934206e9e3bSTobias Grosser     const ScopArrayInfo *SAI =
1935206e9e3bSTobias Grosser         ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id)));
1936edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
1937edb885cbSTobias Grosser     Value *Val = &*Arg;
1938edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1939edb885cbSTobias Grosser     isl_ast_build *Build =
1940edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
1941f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1942edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1943edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
19449e3db2b7SSiddharth Bhat           Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j));
1945edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
1946edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
1947edb885cbSTobias Grosser     }
1948edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
19494d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array);
195074dc3cb4STobias Grosser     LocalArrays.push_back(Val);
1951edb885cbSTobias Grosser 
1952edb885cbSTobias Grosser     isl_ast_build_free(Build);
1953b513b491STobias Grosser     KernelIds.push_back(Id);
1954edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
195532837fe3STobias Grosser     Arg++;
195632837fe3STobias Grosser   }
195732837fe3STobias Grosser 
1958f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1959f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1960f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
1961f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
1962f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1963f6044bd0STobias Grosser     Arg++;
1964f6044bd0STobias Grosser   }
1965f6044bd0STobias Grosser 
1966c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
1967c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1968c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
196912453403STobias Grosser     Value *Val = IDToValue[Id];
197012453403STobias Grosser     ValueMap[Val] = &*Arg;
1971c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
1972c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1973c84a1995STobias Grosser     Arg++;
1974c84a1995STobias Grosser   }
1975c84a1995STobias Grosser 
1976edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
1977edb885cbSTobias Grosser     Arg->setName(V->getName());
1978edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
1979edb885cbSTobias Grosser     Arg++;
1980edb885cbSTobias Grosser   }
1981edb885cbSTobias Grosser 
198232837fe3STobias Grosser   return FN;
198332837fe3STobias Grosser }
198432837fe3STobias Grosser 
1985472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
198617f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsBID[2];
198717f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsTID[3];
1988472f9654STobias Grosser 
198917f01968SSiddharth Bhat   switch (Arch) {
19902f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
19912f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
19922f3073b5SPhilipp Schaad     llvm_unreachable("Cannot generate NVVM intrinsics for SPIR");
199317f01968SSiddharth Bhat   case GPUArch::NVPTX64:
199417f01968SSiddharth Bhat     IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x;
199517f01968SSiddharth Bhat     IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y;
199617f01968SSiddharth Bhat 
199717f01968SSiddharth Bhat     IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x;
199817f01968SSiddharth Bhat     IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y;
199917f01968SSiddharth Bhat     IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z;
200017f01968SSiddharth Bhat     break;
200117f01968SSiddharth Bhat   }
2002472f9654STobias Grosser 
2003472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
2004472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
2005472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
2006472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
2007472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
2008472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
2009472f9654STobias Grosser     IDToValue[Id] = Val;
2010472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
2011472f9654STobias Grosser   };
2012472f9654STobias Grosser 
2013472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
2014472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
2015472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
2016472f9654STobias Grosser   }
2017472f9654STobias Grosser 
2018472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
2019472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
2020472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
2021472f9654STobias Grosser   }
2022472f9654STobias Grosser }
2023472f9654STobias Grosser 
20242f3073b5SPhilipp Schaad void GPUNodeBuilder::insertKernelCallsSPIR(ppcg_kernel *Kernel) {
20252f3073b5SPhilipp Schaad   const char *GroupName[3] = {"__gen_ocl_get_group_id0",
20262f3073b5SPhilipp Schaad                               "__gen_ocl_get_group_id1",
20272f3073b5SPhilipp Schaad                               "__gen_ocl_get_group_id2"};
20282f3073b5SPhilipp Schaad 
20292f3073b5SPhilipp Schaad   const char *LocalName[3] = {"__gen_ocl_get_local_id0",
20302f3073b5SPhilipp Schaad                               "__gen_ocl_get_local_id1",
20312f3073b5SPhilipp Schaad                               "__gen_ocl_get_local_id2"};
20322f3073b5SPhilipp Schaad 
20332f3073b5SPhilipp Schaad   auto createFunc = [this](const char *Name, __isl_take isl_id *Id) mutable {
20342f3073b5SPhilipp Schaad     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
20352f3073b5SPhilipp Schaad     Function *FN = M->getFunction(Name);
20362f3073b5SPhilipp Schaad 
20372f3073b5SPhilipp Schaad     // If FN is not available, declare it.
20382f3073b5SPhilipp Schaad     if (!FN) {
20392f3073b5SPhilipp Schaad       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
20402f3073b5SPhilipp Schaad       std::vector<Type *> Args;
20412f3073b5SPhilipp Schaad       FunctionType *Ty = FunctionType::get(Builder.getInt32Ty(), Args, false);
20422f3073b5SPhilipp Schaad       FN = Function::Create(Ty, Linkage, Name, M);
20432f3073b5SPhilipp Schaad       FN->setCallingConv(CallingConv::SPIR_FUNC);
20442f3073b5SPhilipp Schaad     }
20452f3073b5SPhilipp Schaad 
20462f3073b5SPhilipp Schaad     Value *Val = Builder.CreateCall(FN, {});
20472f3073b5SPhilipp Schaad     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
20482f3073b5SPhilipp Schaad     IDToValue[Id] = Val;
20492f3073b5SPhilipp Schaad     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
20502f3073b5SPhilipp Schaad   };
20512f3073b5SPhilipp Schaad 
20522f3073b5SPhilipp Schaad   for (int i = 0; i < Kernel->n_grid; ++i)
20532f3073b5SPhilipp Schaad     createFunc(GroupName[i], isl_id_list_get_id(Kernel->block_ids, i));
20542f3073b5SPhilipp Schaad 
20552f3073b5SPhilipp Schaad   for (int i = 0; i < Kernel->n_block; ++i)
20562f3073b5SPhilipp Schaad     createFunc(LocalName[i], isl_id_list_get_id(Kernel->thread_ids, i));
20572f3073b5SPhilipp Schaad }
20582f3073b5SPhilipp Schaad 
205900bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
206000bb5a99STobias Grosser   auto Arg = FN->arg_begin();
206100bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
206200bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
206300bb5a99STobias Grosser       continue;
206400bb5a99STobias Grosser 
206500bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2066206e9e3bSTobias Grosser     const ScopArrayInfo *SAI =
2067206e9e3bSTobias Grosser         ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id)));
206800bb5a99STobias Grosser     isl_id_free(Id);
206900bb5a99STobias Grosser 
207000bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
207100bb5a99STobias Grosser       Arg++;
207200bb5a99STobias Grosser       continue;
207300bb5a99STobias Grosser     }
207400bb5a99STobias Grosser 
2075fe74a7a1STobias Grosser     Value *Val = &*Arg;
2076fe74a7a1STobias Grosser 
2077fe74a7a1STobias Grosser     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
207800bb5a99STobias Grosser       Type *TypePtr = SAI->getElementType()->getPointerTo();
2079fe74a7a1STobias Grosser       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
2080fe74a7a1STobias Grosser       Val = Builder.CreateLoad(TypedArgPtr);
2081fe74a7a1STobias Grosser     }
2082fe74a7a1STobias Grosser 
2083fe74a7a1STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
208400bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
208500bb5a99STobias Grosser 
208600bb5a99STobias Grosser     Arg++;
208700bb5a99STobias Grosser   }
208800bb5a99STobias Grosser }
208900bb5a99STobias Grosser 
209051dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) {
209151dfc275STobias Grosser   auto *FN = Builder.GetInsertBlock()->getParent();
209251dfc275STobias Grosser   auto Arg = FN->arg_begin();
209351dfc275STobias Grosser 
209451dfc275STobias Grosser   bool StoredScalar = false;
209551dfc275STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
209651dfc275STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
209751dfc275STobias Grosser       continue;
209851dfc275STobias Grosser 
209951dfc275STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2100206e9e3bSTobias Grosser     const ScopArrayInfo *SAI =
2101206e9e3bSTobias Grosser         ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id)));
210251dfc275STobias Grosser     isl_id_free(Id);
210351dfc275STobias Grosser 
210451dfc275STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
210551dfc275STobias Grosser       Arg++;
210651dfc275STobias Grosser       continue;
210751dfc275STobias Grosser     }
210851dfc275STobias Grosser 
210951dfc275STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
211051dfc275STobias Grosser       Arg++;
211151dfc275STobias Grosser       continue;
211251dfc275STobias Grosser     }
211351dfc275STobias Grosser 
211451dfc275STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
211551dfc275STobias Grosser     Value *ArgPtr = &*Arg;
211651dfc275STobias Grosser     Type *TypePtr = SAI->getElementType()->getPointerTo();
211751dfc275STobias Grosser     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
211851dfc275STobias Grosser     Value *Val = Builder.CreateLoad(Alloca);
211951dfc275STobias Grosser     Builder.CreateStore(Val, TypedArgPtr);
212051dfc275STobias Grosser     StoredScalar = true;
212151dfc275STobias Grosser 
212251dfc275STobias Grosser     Arg++;
212351dfc275STobias Grosser   }
212451dfc275STobias Grosser 
2125638316daSSiddharth Bhat   if (StoredScalar) {
212651dfc275STobias Grosser     /// In case more than one thread contains scalar stores, the generated
212751dfc275STobias Grosser     /// code might be incorrect, if we only store at the end of the kernel.
212851dfc275STobias Grosser     /// To support this case we need to store these scalars back at each
212951dfc275STobias Grosser     /// memory store or at least before each kernel barrier.
2130638316daSSiddharth Bhat     if (Kernel->n_block != 0 || Kernel->n_grid != 0) {
213151dfc275STobias Grosser       BuildSuccessful = 0;
2132638316daSSiddharth Bhat       DEBUG(
2133638316daSSiddharth Bhat           dbgs() << getUniqueScopName(&S)
2134638316daSSiddharth Bhat                  << " has a store to a scalar value that"
2135638316daSSiddharth Bhat                     " would be undefined to run in parallel. Bailing out.\n";);
2136638316daSSiddharth Bhat     }
2137638316daSSiddharth Bhat   }
213851dfc275STobias Grosser }
213951dfc275STobias Grosser 
2140b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
2141b513b491STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
2142b513b491STobias Grosser 
2143b513b491STobias Grosser   for (int i = 0; i < Kernel->n_var; ++i) {
2144b513b491STobias Grosser     struct ppcg_kernel_var &Var = Kernel->var[i];
2145b513b491STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
2146206e9e3bSTobias Grosser     Type *EleTy = ScopArrayInfo::getFromId(isl::manage(Id))->getElementType();
2147b513b491STobias Grosser 
2148f919d8b3STobias Grosser     Type *ArrayTy = EleTy;
2149b513b491STobias Grosser     SmallVector<const SCEV *, 4> Sizes;
2150b513b491STobias Grosser 
2151f5aff704SRoman Gareev     Sizes.push_back(nullptr);
2152928d7573STobias Grosser     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
2153b513b491STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2154f919d8b3STobias Grosser       long Bound = isl_val_get_num_si(Val);
2155b513b491STobias Grosser       isl_val_free(Val);
2156b513b491STobias Grosser       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
2157928d7573STobias Grosser     }
2158928d7573STobias Grosser 
2159928d7573STobias Grosser     for (int j = Var.array->n_index - 1; j >= 0; --j) {
2160928d7573STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2161928d7573STobias Grosser       long Bound = isl_val_get_num_si(Val);
2162928d7573STobias Grosser       isl_val_free(Val);
2163b513b491STobias Grosser       ArrayTy = ArrayType::get(ArrayTy, Bound);
2164b513b491STobias Grosser     }
2165b513b491STobias Grosser 
2166130ca30fSTobias Grosser     const ScopArrayInfo *SAI;
2167130ca30fSTobias Grosser     Value *Allocation;
2168130ca30fSTobias Grosser     if (Var.type == ppcg_access_shared) {
2169130ca30fSTobias Grosser       auto GlobalVar = new GlobalVariable(
2170130ca30fSTobias Grosser           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
2171130ca30fSTobias Grosser           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
2172130ca30fSTobias Grosser       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
2173f919d8b3STobias Grosser       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
2174f919d8b3STobias Grosser 
2175130ca30fSTobias Grosser       Allocation = GlobalVar;
2176130ca30fSTobias Grosser     } else if (Var.type == ppcg_access_private) {
2177130ca30fSTobias Grosser       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
2178130ca30fSTobias Grosser     } else {
2179130ca30fSTobias Grosser       llvm_unreachable("unknown variable type");
2180130ca30fSTobias Grosser     }
21814d5a9172STobias Grosser     SAI =
21824d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array);
2183b513b491STobias Grosser     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
2184130ca30fSTobias Grosser     IDToValue[Id] = Allocation;
2185130ca30fSTobias Grosser     LocalArrays.push_back(Allocation);
2186b513b491STobias Grosser     KernelIds.push_back(Id);
2187b513b491STobias Grosser     IDToSAI[Id] = SAI;
2188b513b491STobias Grosser   }
2189b513b491STobias Grosser }
2190b513b491STobias Grosser 
2191f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction(
2192f291c8d5SSiddharth Bhat     ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues,
2193f291c8d5SSiddharth Bhat     SetVector<Function *> &SubtreeFunctions) {
219479f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
219532837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
219617f01968SSiddharth Bhat 
219717f01968SSiddharth Bhat   switch (Arch) {
219817f01968SSiddharth Bhat   case GPUArch::NVPTX64:
219917f01968SSiddharth Bhat     if (Runtime == GPURuntime::CUDA)
220032837fe3STobias Grosser       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
220117f01968SSiddharth Bhat     else if (Runtime == GPURuntime::OpenCL)
220217f01968SSiddharth Bhat       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl"));
220332837fe3STobias Grosser     GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
220417f01968SSiddharth Bhat     break;
22052f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
22062f3073b5SPhilipp Schaad     GPUModule->setTargetTriple(Triple::normalize("spir-unknown-unknown"));
22072f3073b5SPhilipp Schaad     GPUModule->setDataLayout(computeSPIRDataLayout(false /* is64Bit */));
22082f3073b5SPhilipp Schaad     break;
22092f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
22102f3073b5SPhilipp Schaad     GPUModule->setTargetTriple(Triple::normalize("spir64-unknown-unknown"));
22112f3073b5SPhilipp Schaad     GPUModule->setDataLayout(computeSPIRDataLayout(true /* is64Bit */));
22122f3073b5SPhilipp Schaad     break;
221317f01968SSiddharth Bhat   }
221432837fe3STobias Grosser 
2215edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
221632837fe3STobias Grosser 
221759ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
221832837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
221932837fe3STobias Grosser 
222059ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
222159ab0705STobias Grosser 
222232837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
222332837fe3STobias Grosser   Builder.CreateRetVoid();
222432837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
2225472f9654STobias Grosser 
2226629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
2227629109b6STobias Grosser 
222800bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
2229b513b491STobias Grosser   createKernelVariables(Kernel, FN);
22302f3073b5SPhilipp Schaad 
22312f3073b5SPhilipp Schaad   switch (Arch) {
22322f3073b5SPhilipp Schaad   case GPUArch::NVPTX64:
2233472f9654STobias Grosser     insertKernelIntrinsics(Kernel);
22342f3073b5SPhilipp Schaad     break;
22352f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
22362f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
22372f3073b5SPhilipp Schaad     insertKernelCallsSPIR(Kernel);
22382f3073b5SPhilipp Schaad     break;
22392f3073b5SPhilipp Schaad   }
224032837fe3STobias Grosser }
224132837fe3STobias Grosser 
224274dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
224317f01968SSiddharth Bhat   llvm::Triple GPUTriple;
224417f01968SSiddharth Bhat 
224517f01968SSiddharth Bhat   switch (Arch) {
224617f01968SSiddharth Bhat   case GPUArch::NVPTX64:
224717f01968SSiddharth Bhat     switch (Runtime) {
224817f01968SSiddharth Bhat     case GPURuntime::CUDA:
224917f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda"));
225017f01968SSiddharth Bhat       break;
225117f01968SSiddharth Bhat     case GPURuntime::OpenCL:
225217f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl"));
225317f01968SSiddharth Bhat       break;
225417f01968SSiddharth Bhat     }
225517f01968SSiddharth Bhat     break;
22562f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
22572f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
22582f3073b5SPhilipp Schaad     std::string SPIRAssembly;
22592f3073b5SPhilipp Schaad     raw_string_ostream IROstream(SPIRAssembly);
22602f3073b5SPhilipp Schaad     IROstream << *GPUModule;
22612f3073b5SPhilipp Schaad     IROstream.flush();
22622f3073b5SPhilipp Schaad     return SPIRAssembly;
226317f01968SSiddharth Bhat   }
226417f01968SSiddharth Bhat 
226574dc3cb4STobias Grosser   std::string ErrMsg;
226674dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
226774dc3cb4STobias Grosser 
226874dc3cb4STobias Grosser   if (!GPUTarget) {
226974dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
227074dc3cb4STobias Grosser     return "";
227174dc3cb4STobias Grosser   }
227274dc3cb4STobias Grosser 
227374dc3cb4STobias Grosser   TargetOptions Options;
227474dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
227517f01968SSiddharth Bhat 
227617f01968SSiddharth Bhat   std::string subtarget;
227717f01968SSiddharth Bhat 
227817f01968SSiddharth Bhat   switch (Arch) {
227917f01968SSiddharth Bhat   case GPUArch::NVPTX64:
228017f01968SSiddharth Bhat     subtarget = CudaVersion;
228117f01968SSiddharth Bhat     break;
22822f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
22832f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
22842f3073b5SPhilipp Schaad     llvm_unreachable("No subtarget for SPIR architecture");
228517f01968SSiddharth Bhat   }
228617f01968SSiddharth Bhat 
228717f01968SSiddharth Bhat   std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine(
228817f01968SSiddharth Bhat       GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>()));
228974dc3cb4STobias Grosser 
229074dc3cb4STobias Grosser   SmallString<0> ASMString;
229174dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
229274dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
229374dc3cb4STobias Grosser 
229474dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
229574dc3cb4STobias Grosser 
229674dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
229774dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
229874dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
229974dc3cb4STobias Grosser     return "";
230074dc3cb4STobias Grosser   }
230174dc3cb4STobias Grosser 
230274dc3cb4STobias Grosser   PM.run(*GPUModule);
230374dc3cb4STobias Grosser 
230474dc3cb4STobias Grosser   return ASMStream.str();
230574dc3cb4STobias Grosser }
230674dc3cb4STobias Grosser 
23078fc6cdfbSTobias Grosser bool GPUNodeBuilder::requiresCUDALibDevice() {
23085b307cdbSTobias Grosser   bool RequiresLibDevice = false;
23098fc6cdfbSTobias Grosser   for (Function &F : GPUModule->functions()) {
23108fc6cdfbSTobias Grosser     if (!F.isDeclaration())
23118fc6cdfbSTobias Grosser       continue;
23128fc6cdfbSTobias Grosser 
23138fc6cdfbSTobias Grosser     std::string CUDALibDeviceFunc = getCUDALibDeviceFuntion(&F);
23148fc6cdfbSTobias Grosser     if (CUDALibDeviceFunc.length() != 0) {
23158fc6cdfbSTobias Grosser       F.setName(CUDALibDeviceFunc);
23165b307cdbSTobias Grosser       RequiresLibDevice = true;
23178fc6cdfbSTobias Grosser     }
23188fc6cdfbSTobias Grosser   }
23198fc6cdfbSTobias Grosser 
23205b307cdbSTobias Grosser   return RequiresLibDevice;
23218fc6cdfbSTobias Grosser }
23228fc6cdfbSTobias Grosser 
23238fc6cdfbSTobias Grosser void GPUNodeBuilder::addCUDALibDevice() {
23248fc6cdfbSTobias Grosser   if (Arch != GPUArch::NVPTX64)
23258fc6cdfbSTobias Grosser     return;
23268fc6cdfbSTobias Grosser 
23278fc6cdfbSTobias Grosser   if (requiresCUDALibDevice()) {
23288fc6cdfbSTobias Grosser     SMDiagnostic Error;
23298fc6cdfbSTobias Grosser 
23308fc6cdfbSTobias Grosser     errs() << CUDALibDevice << "\n";
23318fc6cdfbSTobias Grosser     auto LibDeviceModule =
23328fc6cdfbSTobias Grosser         parseIRFile(CUDALibDevice, Error, GPUModule->getContext());
23338fc6cdfbSTobias Grosser 
23348fc6cdfbSTobias Grosser     if (!LibDeviceModule) {
23358fc6cdfbSTobias Grosser       BuildSuccessful = false;
23368fc6cdfbSTobias Grosser       report_fatal_error("Could not find or load libdevice. Skipping GPU "
23378fc6cdfbSTobias Grosser                          "kernel generation. Please set -polly-acc-libdevice "
23388fc6cdfbSTobias Grosser                          "accordingly.\n");
23398fc6cdfbSTobias Grosser       return;
23408fc6cdfbSTobias Grosser     }
23418fc6cdfbSTobias Grosser 
23428fc6cdfbSTobias Grosser     Linker L(*GPUModule);
23438fc6cdfbSTobias Grosser 
23448fc6cdfbSTobias Grosser     // Set an nvptx64 target triple to avoid linker warnings. The original
23458fc6cdfbSTobias Grosser     // triple of the libdevice files are nvptx-unknown-unknown.
23468fc6cdfbSTobias Grosser     LibDeviceModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
23478fc6cdfbSTobias Grosser     L.linkInModule(std::move(LibDeviceModule), Linker::LinkOnlyNeeded);
23488fc6cdfbSTobias Grosser   }
23498fc6cdfbSTobias Grosser }
23508fc6cdfbSTobias Grosser 
235157793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
235265d7f72fSSiddharth Bhat 
23535857b701STobias Grosser   if (verifyModule(*GPUModule)) {
235465d7f72fSSiddharth Bhat     DEBUG(dbgs() << "verifyModule failed on module:\n";
235565d7f72fSSiddharth Bhat           GPUModule->print(dbgs(), nullptr); dbgs() << "\n";);
2356a0fb8b23SSiddharth Bhat     DEBUG(dbgs() << "verifyModule Error:\n";
2357a0fb8b23SSiddharth Bhat           verifyModule(*GPUModule, &dbgs()););
235865d7f72fSSiddharth Bhat 
235965d7f72fSSiddharth Bhat     if (FailOnVerifyModuleFailure)
236065d7f72fSSiddharth Bhat       llvm_unreachable("VerifyModule failed.");
236165d7f72fSSiddharth Bhat 
23625857b701STobias Grosser     BuildSuccessful = false;
23635857b701STobias Grosser     return "";
23645857b701STobias Grosser   }
236532837fe3STobias Grosser 
23668fc6cdfbSTobias Grosser   addCUDALibDevice();
23678fc6cdfbSTobias Grosser 
236832837fe3STobias Grosser   if (DumpKernelIR)
236932837fe3STobias Grosser     outs() << *GPUModule << "\n";
237032837fe3STobias Grosser 
23712f3073b5SPhilipp Schaad   if (Arch != GPUArch::SPIR32 && Arch != GPUArch::SPIR64) {
23729a18d559STobias Grosser     // Optimize module.
23739a18d559STobias Grosser     llvm::legacy::PassManager OptPasses;
23749a18d559STobias Grosser     PassManagerBuilder PassBuilder;
23759a18d559STobias Grosser     PassBuilder.OptLevel = 3;
23769a18d559STobias Grosser     PassBuilder.SizeLevel = 0;
23779a18d559STobias Grosser     PassBuilder.populateModulePassManager(OptPasses);
23789a18d559STobias Grosser     OptPasses.run(*GPUModule);
23792f3073b5SPhilipp Schaad   }
23809a18d559STobias Grosser 
238174dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
238274dc3cb4STobias Grosser 
238374dc3cb4STobias Grosser   if (DumpKernelASM)
238474dc3cb4STobias Grosser     outs() << Assembly << "\n";
238574dc3cb4STobias Grosser 
238632837fe3STobias Grosser   GPUModule.release();
2387472f9654STobias Grosser   KernelIDs.clear();
238857793596STobias Grosser 
238957793596STobias Grosser   return Assembly;
239032837fe3STobias Grosser }
2391eadf76d3SSiddharth Bhat /// Construct an `isl_pw_aff_list` from a vector of `isl_pw_aff`
2392eadf76d3SSiddharth Bhat /// @param PwAffs The list of piecewise affine functions to create an
2393eadf76d3SSiddharth Bhat ///               `isl_pw_aff_list` from. We expect an rvalue ref because
2394eadf76d3SSiddharth Bhat ///               all the isl_pw_aff are used up by this function.
2395eadf76d3SSiddharth Bhat ///
2396eadf76d3SSiddharth Bhat /// @returns  The `isl_pw_aff_list`.
2397eadf76d3SSiddharth Bhat __isl_give isl_pw_aff_list *
2398eadf76d3SSiddharth Bhat createPwAffList(isl_ctx *Context,
2399eadf76d3SSiddharth Bhat                 const std::vector<__isl_take isl_pw_aff *> &&PwAffs) {
2400eadf76d3SSiddharth Bhat   isl_pw_aff_list *List = isl_pw_aff_list_alloc(Context, PwAffs.size());
2401eadf76d3SSiddharth Bhat 
2402eadf76d3SSiddharth Bhat   for (unsigned i = 0; i < PwAffs.size(); i++) {
2403eadf76d3SSiddharth Bhat     List = isl_pw_aff_list_insert(List, i, PwAffs[i]);
2404eadf76d3SSiddharth Bhat   }
2405eadf76d3SSiddharth Bhat   return List;
2406eadf76d3SSiddharth Bhat }
2407eadf76d3SSiddharth Bhat 
2408eadf76d3SSiddharth Bhat /// Align all the `PwAffs` such that they have the same parameter dimensions.
2409eadf76d3SSiddharth Bhat ///
2410eadf76d3SSiddharth Bhat /// We loop over all `pw_aff` and align all of their spaces together to
2411eadf76d3SSiddharth Bhat /// create a common space for all the `pw_aff`. This common space is the
2412eadf76d3SSiddharth Bhat /// `AlignSpace`. We then align all the `pw_aff` to this space. We start
2413eadf76d3SSiddharth Bhat /// with the given `SeedSpace`.
2414eadf76d3SSiddharth Bhat /// @param PwAffs    The list of piecewise affine functions we want to align.
2415eadf76d3SSiddharth Bhat ///                  This is an rvalue reference because the entire vector is
2416eadf76d3SSiddharth Bhat ///                  used up by the end of the operation.
2417eadf76d3SSiddharth Bhat /// @param SeedSpace The space to start the alignment process with.
2418eadf76d3SSiddharth Bhat /// @returns         A std::pair, whose first element is the aligned space,
2419eadf76d3SSiddharth Bhat ///                  whose second element is the vector of aligned piecewise
2420eadf76d3SSiddharth Bhat ///                  affines.
2421eadf76d3SSiddharth Bhat static std::pair<__isl_give isl_space *, std::vector<__isl_give isl_pw_aff *>>
2422eadf76d3SSiddharth Bhat alignPwAffs(const std::vector<__isl_take isl_pw_aff *> &&PwAffs,
2423eadf76d3SSiddharth Bhat             __isl_take isl_space *SeedSpace) {
2424eadf76d3SSiddharth Bhat   assert(SeedSpace && "Invalid seed space given.");
2425eadf76d3SSiddharth Bhat 
2426eadf76d3SSiddharth Bhat   isl_space *AlignSpace = SeedSpace;
2427eadf76d3SSiddharth Bhat   for (isl_pw_aff *PwAff : PwAffs) {
2428eadf76d3SSiddharth Bhat     isl_space *PwAffSpace = isl_pw_aff_get_domain_space(PwAff);
2429eadf76d3SSiddharth Bhat     AlignSpace = isl_space_align_params(AlignSpace, PwAffSpace);
2430eadf76d3SSiddharth Bhat   }
2431eadf76d3SSiddharth Bhat   std::vector<isl_pw_aff *> AdjustedPwAffs;
2432eadf76d3SSiddharth Bhat 
2433eadf76d3SSiddharth Bhat   for (unsigned i = 0; i < PwAffs.size(); i++) {
2434eadf76d3SSiddharth Bhat     isl_pw_aff *Adjusted = PwAffs[i];
2435eadf76d3SSiddharth Bhat     assert(Adjusted && "Invalid pw_aff given.");
2436eadf76d3SSiddharth Bhat     Adjusted = isl_pw_aff_align_params(Adjusted, isl_space_copy(AlignSpace));
2437eadf76d3SSiddharth Bhat     AdjustedPwAffs.push_back(Adjusted);
2438eadf76d3SSiddharth Bhat   }
2439eadf76d3SSiddharth Bhat   return std::make_pair(AlignSpace, AdjustedPwAffs);
2440eadf76d3SSiddharth Bhat }
244132837fe3STobias Grosser 
24429dfe4e7cSTobias Grosser namespace {
24439dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
24449dfe4e7cSTobias Grosser public:
24459dfe4e7cSTobias Grosser   static char ID;
24469dfe4e7cSTobias Grosser 
244717f01968SSiddharth Bhat   GPURuntime Runtime = GPURuntime::CUDA;
244817f01968SSiddharth Bhat 
244917f01968SSiddharth Bhat   GPUArch Architecture = GPUArch::NVPTX64;
245017f01968SSiddharth Bhat 
2451e938517eSTobias Grosser   /// The scop that is currently processed.
2452e938517eSTobias Grosser   Scop *S;
2453e938517eSTobias Grosser 
245438fc0aedSTobias Grosser   LoopInfo *LI;
245538fc0aedSTobias Grosser   DominatorTree *DT;
245638fc0aedSTobias Grosser   ScalarEvolution *SE;
245738fc0aedSTobias Grosser   const DataLayout *DL;
245838fc0aedSTobias Grosser   RegionInfo *RI;
245938fc0aedSTobias Grosser 
24609dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
24619dfe4e7cSTobias Grosser 
2462e938517eSTobias Grosser   /// Construct compilation options for PPCG.
2463e938517eSTobias Grosser   ///
2464e938517eSTobias Grosser   /// @returns The compilation options.
2465e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
2466e938517eSTobias Grosser     auto DebugOptions =
2467e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
2468e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
2469e938517eSTobias Grosser 
2470e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
2471e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
2472e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
2473e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
24748950ceadSTobias Grosser     DebugOptions->verbose = false;
2475e938517eSTobias Grosser 
2476e938517eSTobias Grosser     Options->debug = DebugOptions;
2477e938517eSTobias Grosser 
24789e3db2b7SSiddharth Bhat     Options->group_chains = false;
2479e938517eSTobias Grosser     Options->reschedule = true;
2480e938517eSTobias Grosser     Options->scale_tile_loops = false;
2481e938517eSTobias Grosser     Options->wrap = false;
2482e938517eSTobias Grosser 
2483e938517eSTobias Grosser     Options->non_negative_parameters = false;
2484e938517eSTobias Grosser     Options->ctx = nullptr;
2485e938517eSTobias Grosser     Options->sizes = nullptr;
2486e938517eSTobias Grosser 
24879e3db2b7SSiddharth Bhat     Options->tile = true;
24884eaedde5STobias Grosser     Options->tile_size = 32;
24894eaedde5STobias Grosser 
24909e3db2b7SSiddharth Bhat     Options->isolate_full_tiles = false;
24919e3db2b7SSiddharth Bhat 
2492130ca30fSTobias Grosser     Options->use_private_memory = PrivateMemory;
2493b513b491STobias Grosser     Options->use_shared_memory = SharedMemory;
2494b513b491STobias Grosser     Options->max_shared_memory = 48 * 1024;
2495e938517eSTobias Grosser 
2496e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
2497e938517eSTobias Grosser     Options->openmp = false;
2498e938517eSTobias Grosser     Options->linearize_device_arrays = true;
24999e3db2b7SSiddharth Bhat     Options->allow_gnu_extensions = false;
2500e938517eSTobias Grosser 
25019e3db2b7SSiddharth Bhat     Options->unroll_copy_shared = false;
25029e3db2b7SSiddharth Bhat     Options->unroll_gpu_tile = false;
25039e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
25049e3db2b7SSiddharth Bhat 
25059e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
25069e3db2b7SSiddharth Bhat     Options->hybrid = false;
2507e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
2508e938517eSTobias Grosser     Options->opencl_use_gpu = false;
2509e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
2510e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
2511e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
2512e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
2513e938517eSTobias Grosser 
2514e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
2515e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
2516e938517eSTobias Grosser 
2517e938517eSTobias Grosser     return Options;
2518e938517eSTobias Grosser   }
2519e938517eSTobias Grosser 
2520f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
2521f384594dSTobias Grosser   ///
2522f384594dSTobias Grosser   /// Instead of a normal access of the form:
2523f384594dSTobias Grosser   ///
2524f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
2525f384594dSTobias Grosser   ///
2526f384594dSTobias Grosser   /// a tagged access has the form
2527f384594dSTobias Grosser   ///
2528f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
2529f384594dSTobias Grosser   ///
2530f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
2531f384594dSTobias Grosser   /// triggered the access.
2532f384594dSTobias Grosser   ///
2533f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
2534f384594dSTobias Grosser   ///
2535f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
2536f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
2537b65ccc43STobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace().release());
2538f384594dSTobias Grosser 
2539f384594dSTobias Grosser     for (auto &Stmt : *S)
2540f384594dSTobias Grosser       for (auto &Acc : Stmt)
2541f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
25421515f6b9STobias Grosser           isl_map *Relation = Acc->getAccessRelation().release();
2543dcf8d696STobias Grosser           Relation =
2544dcf8d696STobias Grosser               isl_map_intersect_domain(Relation, Stmt.getDomain().release());
2545f384594dSTobias Grosser 
2546f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
2547f384594dSTobias Grosser           Space = isl_space_range(Space);
2548f384594dSTobias Grosser           Space = isl_space_from_range(Space);
2549fe46c3ffSTobias Grosser           Space =
2550fe46c3ffSTobias Grosser               isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
2551f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
2552f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
2553f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
2554f384594dSTobias Grosser         }
2555f384594dSTobias Grosser 
2556f384594dSTobias Grosser     return Accesses;
2557f384594dSTobias Grosser   }
2558f384594dSTobias Grosser 
2559f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
2560f384594dSTobias Grosser   ///
2561f384594dSTobias Grosser   /// @see getTaggedAccesses
2562f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
2563f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
2564f384594dSTobias Grosser   }
2565f384594dSTobias Grosser 
2566f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
2567f384594dSTobias Grosser   ///
2568f384594dSTobias Grosser   /// @see getTaggedAccesses
2569f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
2570f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
2571f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
2572f384594dSTobias Grosser   }
2573f384594dSTobias Grosser 
2574f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
2575f384594dSTobias Grosser   ///
2576f384594dSTobias Grosser   /// @see getTaggedAccesses
2577f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
2578f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
2579f384594dSTobias Grosser   }
2580f384594dSTobias Grosser 
2581aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
2582aef5196fSTobias Grosser   ///
2583aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
2584aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
2585aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
2586aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
2587aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
2588aef5196fSTobias Grosser   /// the data format that ppcg expects.
2589aef5196fSTobias Grosser   ///
2590aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
2591aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
2592aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
2593bd81a7eeSTobias Grosser         S->getIslCtx(),
2594bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
2595aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
2596aef5196fSTobias Grosser 
259725271b91STobias Grosser     for (const SCEV *P : S->parameters()) {
25989a63570bSTobias Grosser       isl_id *Id = S->getIdForParam(P).release();
2599aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2600aef5196fSTobias Grosser     }
2601aef5196fSTobias Grosser 
2602aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
260377eef90fSTobias Grosser       auto Id = Array->getBasePtrId().release();
2604aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2605aef5196fSTobias Grosser     }
2606aef5196fSTobias Grosser 
2607aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
2608aef5196fSTobias Grosser 
2609aef5196fSTobias Grosser     return Names;
2610aef5196fSTobias Grosser   }
2611aef5196fSTobias Grosser 
2612e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
2613e938517eSTobias Grosser   ///
2614f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
2615f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
2616f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
2617f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
2618e938517eSTobias Grosser   ///
2619e938517eSTobias Grosser   /// @returns A new ppcg scop.
2620e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
26219e3db2b7SSiddharth Bhat     MustKillsInfo KillsInfo = computeMustKillsInfo(*S);
26229e3db2b7SSiddharth Bhat 
2623e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
2624e938517eSTobias Grosser 
2625e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
2626a82f2d26SSiddharth Bhat     // enable live range reordering
2627a82f2d26SSiddharth Bhat     PPCGScop->options->live_range_reordering = 1;
2628e938517eSTobias Grosser 
2629e938517eSTobias Grosser     PPCGScop->start = 0;
2630e938517eSTobias Grosser     PPCGScop->end = 0;
2631e938517eSTobias Grosser 
26328ea1fc19STobias Grosser     PPCGScop->context = S->getContext().release();
263331df6f31STobias Grosser     PPCGScop->domain = S->getDomains().release();
26349e3db2b7SSiddharth Bhat     // TODO: investigate this further. PPCG calls collect_call_domains.
26358ea1fc19STobias Grosser     PPCGScop->call = isl_union_set_from_set(S->getContext().release());
2636f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
26375ab39ff2STobias Grosser     PPCGScop->reads = S->getReads().release();
2638e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
2639f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
26405ab39ff2STobias Grosser     PPCGScop->may_writes = S->getWrites().release();
2641f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
26425ab39ff2STobias Grosser     PPCGScop->must_writes = S->getMustWrites().release();
2643e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
26449e3db2b7SSiddharth Bhat     PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.take();
26459e3db2b7SSiddharth Bhat     PPCGScop->must_kills = KillsInfo.MustKills.take();
26469e3db2b7SSiddharth Bhat 
2647e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
2648a82f2d26SSiddharth Bhat     PPCGScop->independence =
2649a82f2d26SSiddharth Bhat         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
2650e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
2651e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
2652e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
2653e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
2654e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
2655e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
2656e938517eSTobias Grosser 
265761bd3a48STobias Grosser     PPCGScop->schedule = S->getScheduleTree().release();
2658a82f2d26SSiddharth Bhat     // If we have something non-trivial to kill, add it to the schedule
2659a82f2d26SSiddharth Bhat     if (KillsInfo.KillsSchedule.get())
2660a82f2d26SSiddharth Bhat       PPCGScop->schedule = isl_schedule_sequence(
2661a82f2d26SSiddharth Bhat           PPCGScop->schedule, KillsInfo.KillsSchedule.take());
2662a82f2d26SSiddharth Bhat 
2663a82f2d26SSiddharth Bhat     PPCGScop->names = getNames();
2664e938517eSTobias Grosser     PPCGScop->pet = nullptr;
2665e938517eSTobias Grosser 
2666f384594dSTobias Grosser     compute_tagger(PPCGScop);
2667f384594dSTobias Grosser     compute_dependences(PPCGScop);
26689e3db2b7SSiddharth Bhat     eliminate_dead_code(PPCGScop);
2669f384594dSTobias Grosser 
2670e938517eSTobias Grosser     return PPCGScop;
2671e938517eSTobias Grosser   }
2672e938517eSTobias Grosser 
2673a6d48f59SMichael Kruse   /// Collect the array accesses in a statement.
267460f63b49STobias Grosser   ///
267560f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
267660f63b49STobias Grosser   ///
267760f63b49STobias Grosser   /// @returns A list of array accesses.
267860f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
267960f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
268060f63b49STobias Grosser 
268160f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
268260f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
268360f63b49STobias Grosser       Access->read = Acc->isRead();
268460f63b49STobias Grosser       Access->write = Acc->isWrite();
26851515f6b9STobias Grosser       Access->access = Acc->getAccessRelation().release();
268660f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
268760f63b49STobias Grosser       Space = isl_space_range(Space);
268860f63b49STobias Grosser       Space = isl_space_from_range(Space);
2689fe46c3ffSTobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
269060f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
269160f63b49STobias Grosser       Access->tagged_access =
26921515f6b9STobias Grosser           isl_map_domain_product(Acc->getAccessRelation().release(), Universe);
2693b513b491STobias Grosser       Access->exact_write = !Acc->isMayWrite();
2694fe46c3ffSTobias Grosser       Access->ref_id = Acc->getId().release();
269560f63b49STobias Grosser       Access->next = Accesses;
2696b513b491STobias Grosser       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
269760f63b49STobias Grosser       Accesses = Access;
269860f63b49STobias Grosser     }
269960f63b49STobias Grosser 
270060f63b49STobias Grosser     return Accesses;
270160f63b49STobias Grosser   }
270260f63b49STobias Grosser 
270369b46751STobias Grosser   /// Collect the list of GPU statements.
270469b46751STobias Grosser   ///
270569b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
270669b46751STobias Grosser   /// as well as a list with all memory accesses.
270769b46751STobias Grosser   ///
270869b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
270969b46751STobias Grosser   ///
271069b46751STobias Grosser   /// @returns A linked-list of statements.
271169b46751STobias Grosser   gpu_stmt *getStatements() {
271269b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
271369b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
271469b46751STobias Grosser 
271569b46751STobias Grosser     int i = 0;
271669b46751STobias Grosser     for (auto &Stmt : *S) {
271769b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
271869b46751STobias Grosser 
2719dcf8d696STobias Grosser       GPUStmt->id = Stmt.getDomainId().release();
272069b46751STobias Grosser 
272169b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
272269b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
272360f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
272469b46751STobias Grosser       i++;
272569b46751STobias Grosser     }
272669b46751STobias Grosser 
272769b46751STobias Grosser     return Stmts;
272869b46751STobias Grosser   }
272969b46751STobias Grosser 
273060f63b49STobias Grosser   /// Derive the extent of an array.
273160f63b49STobias Grosser   ///
2732d58acf86STobias Grosser   /// The extent of an array is the set of elements that are within the
2733d58acf86STobias Grosser   /// accessed array. For the inner dimensions, the extent constraints are
2734d58acf86STobias Grosser   /// 0 and the size of the corresponding array dimension. For the first
2735d58acf86STobias Grosser   /// (outermost) dimension, the extent constraints are the minimal and maximal
2736d58acf86STobias Grosser   /// subscript value for the first dimension.
273760f63b49STobias Grosser   ///
273860f63b49STobias Grosser   /// @param Array The array to derive the extent for.
273960f63b49STobias Grosser   ///
274060f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
274160f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
2742d58acf86STobias Grosser     unsigned NumDims = Array->getNumberOfDimensions();
27435ab39ff2STobias Grosser     isl_union_map *Accesses = S->getAccesses().release();
274431df6f31STobias Grosser     Accesses =
274531df6f31STobias Grosser         isl_union_map_intersect_domain(Accesses, S->getDomains().release());
2746d58acf86STobias Grosser     Accesses = isl_union_map_detect_equalities(Accesses);
274760f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
2748d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2749d58acf86STobias Grosser     AccessUSet = isl_union_set_detect_equalities(AccessUSet);
2750d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2751d58acf86STobias Grosser 
2752d58acf86STobias Grosser     if (isl_union_set_is_empty(AccessUSet)) {
2753d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
275477eef90fSTobias Grosser       return isl_set_empty(Array->getSpace().release());
2755d58acf86STobias Grosser     }
2756d58acf86STobias Grosser 
2757d58acf86STobias Grosser     if (Array->getNumberOfDimensions() == 0) {
2758d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
275977eef90fSTobias Grosser       return isl_set_universe(Array->getSpace().release());
2760d58acf86STobias Grosser     }
2761d58acf86STobias Grosser 
276260f63b49STobias Grosser     isl_set *AccessSet =
276377eef90fSTobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace().release());
276460f63b49STobias Grosser 
2765d58acf86STobias Grosser     isl_union_set_free(AccessUSet);
276677eef90fSTobias Grosser     isl_local_space *LS =
276777eef90fSTobias Grosser         isl_local_space_from_space(Array->getSpace().release());
2768d58acf86STobias Grosser 
2769d58acf86STobias Grosser     isl_pw_aff *Val =
2770d58acf86STobias Grosser         isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0));
2771d58acf86STobias Grosser 
2772d58acf86STobias Grosser     isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0);
2773d58acf86STobias Grosser     isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0);
2774d58acf86STobias Grosser     OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in,
2775d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
2776d58acf86STobias Grosser     OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in,
2777d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
277877eef90fSTobias Grosser     OuterMin = isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in,
277977eef90fSTobias Grosser                                        Array->getBasePtrId().release());
278077eef90fSTobias Grosser     OuterMax = isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in,
278177eef90fSTobias Grosser                                        Array->getBasePtrId().release());
2782d58acf86STobias Grosser 
278377eef90fSTobias Grosser     isl_set *Extent = isl_set_universe(Array->getSpace().release());
2784d58acf86STobias Grosser 
2785d58acf86STobias Grosser     Extent = isl_set_intersect(
2786d58acf86STobias Grosser         Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val)));
2787d58acf86STobias Grosser     Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val));
2788d58acf86STobias Grosser 
2789d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i)
2790d58acf86STobias Grosser       Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0);
2791d58acf86STobias Grosser 
2792b7f68b8cSSiddharth Bhat     for (unsigned i = 0; i < NumDims; ++i) {
2793d58acf86STobias Grosser       isl_pw_aff *PwAff =
279477eef90fSTobias Grosser           const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i).release());
2795b7f68b8cSSiddharth Bhat 
2796b7f68b8cSSiddharth Bhat       // isl_pw_aff can be NULL for zero dimension. Only in the case of a
2797b7f68b8cSSiddharth Bhat       // Fortran array will we have a legitimate dimension.
2798b7f68b8cSSiddharth Bhat       if (!PwAff) {
2799b7f68b8cSSiddharth Bhat         assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension");
2800b7f68b8cSSiddharth Bhat         continue;
2801b7f68b8cSSiddharth Bhat       }
2802b7f68b8cSSiddharth Bhat 
2803d58acf86STobias Grosser       isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain(
280477eef90fSTobias Grosser           isl_local_space_from_space(Array->getSpace().release()), isl_dim_set,
280577eef90fSTobias Grosser           i));
2806d58acf86STobias Grosser       PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in,
2807d58acf86STobias Grosser                                   isl_pw_aff_dim(Val, isl_dim_in));
2808d58acf86STobias Grosser       PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in,
2809d58acf86STobias Grosser                                       isl_pw_aff_get_tuple_id(Val, isl_dim_in));
2810d58acf86STobias Grosser       auto *Set = isl_pw_aff_gt_set(PwAff, Val);
2811d58acf86STobias Grosser       Extent = isl_set_intersect(Set, Extent);
2812d58acf86STobias Grosser     }
2813d58acf86STobias Grosser 
2814d58acf86STobias Grosser     return Extent;
281560f63b49STobias Grosser   }
281660f63b49STobias Grosser 
281760f63b49STobias Grosser   /// Derive the bounds of an array.
281860f63b49STobias Grosser   ///
281960f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
282060f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
282160f63b49STobias Grosser   /// ScopArrayInfo.
282260f63b49STobias Grosser   ///
282360f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
282460f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
282560f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
2826eadf76d3SSiddharth Bhat     std::vector<isl_pw_aff *> Bounds;
28279e3db2b7SSiddharth Bhat 
282860f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
282902293ed7STobias Grosser       if (isl_set_is_empty(PPCGArray.extent)) {
283002293ed7STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
283102293ed7STobias Grosser         isl_local_space *LS = isl_local_space_from_space(
283202293ed7STobias Grosser             isl_space_params(isl_set_get_space(Dom)));
283302293ed7STobias Grosser         isl_set_free(Dom);
28349e3db2b7SSiddharth Bhat         isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS));
2835eadf76d3SSiddharth Bhat         Bounds.push_back(Zero);
283602293ed7STobias Grosser       } else {
283760f63b49STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
283860f63b49STobias Grosser         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
283960f63b49STobias Grosser         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
284060f63b49STobias Grosser         isl_set_free(Dom);
284160f63b49STobias Grosser         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
284202293ed7STobias Grosser         isl_local_space *LS =
284302293ed7STobias Grosser             isl_local_space_from_space(isl_set_get_space(Dom));
284460f63b49STobias Grosser         isl_aff *One = isl_aff_zero_on_domain(LS);
284560f63b49STobias Grosser         One = isl_aff_add_constant_si(One, 1);
284660f63b49STobias Grosser         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
28478ea1fc19STobias Grosser         Bound = isl_pw_aff_gist(Bound, S->getContext().release());
2848eadf76d3SSiddharth Bhat         Bounds.push_back(Bound);
284960f63b49STobias Grosser       }
285002293ed7STobias Grosser     }
285160f63b49STobias Grosser 
285260f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
285377eef90fSTobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i).release();
285460f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
285560f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
285660f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
2857eadf76d3SSiddharth Bhat       Bounds.push_back(Bound);
285860f63b49STobias Grosser     }
28599e3db2b7SSiddharth Bhat 
2860eadf76d3SSiddharth Bhat     /// To construct a `isl_multi_pw_aff`, we need all the indivisual `pw_aff`
2861eadf76d3SSiddharth Bhat     /// to have the same parameter dimensions. So, we need to align them to an
2862eadf76d3SSiddharth Bhat     /// appropriate space.
2863eadf76d3SSiddharth Bhat     /// Scop::Context is _not_ an appropriate space, because when we have
2864eadf76d3SSiddharth Bhat     /// `-polly-ignore-parameter-bounds` enabled, the Scop::Context does not
2865eadf76d3SSiddharth Bhat     /// contain all parameter dimensions.
2866eadf76d3SSiddharth Bhat     /// So, use the helper `alignPwAffs` to align all the `isl_pw_aff` together.
2867b65ccc43STobias Grosser     isl_space *SeedAlignSpace = S->getParamSpace().release();
2868eadf76d3SSiddharth Bhat     SeedAlignSpace = isl_space_add_dims(SeedAlignSpace, isl_dim_set, 1);
2869eadf76d3SSiddharth Bhat 
2870eadf76d3SSiddharth Bhat     isl_space *AlignSpace = nullptr;
2871eadf76d3SSiddharth Bhat     std::vector<isl_pw_aff *> AlignedBounds;
2872eadf76d3SSiddharth Bhat     std::tie(AlignSpace, AlignedBounds) =
2873eadf76d3SSiddharth Bhat         alignPwAffs(std::move(Bounds), SeedAlignSpace);
2874eadf76d3SSiddharth Bhat 
2875eadf76d3SSiddharth Bhat     assert(AlignSpace && "alignPwAffs did not initialise AlignSpace");
2876eadf76d3SSiddharth Bhat 
2877eadf76d3SSiddharth Bhat     isl_pw_aff_list *BoundsList =
2878eadf76d3SSiddharth Bhat         createPwAffList(S->getIslCtx(), std::move(AlignedBounds));
2879eadf76d3SSiddharth Bhat 
28809e3db2b7SSiddharth Bhat     isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent);
2881eadf76d3SSiddharth Bhat     BoundsSpace = isl_space_align_params(BoundsSpace, AlignSpace);
28829e3db2b7SSiddharth Bhat 
28839e3db2b7SSiddharth Bhat     assert(BoundsSpace && "Unable to access space of array.");
28849e3db2b7SSiddharth Bhat     assert(BoundsList && "Unable to access list of bounds.");
28859e3db2b7SSiddharth Bhat 
28869e3db2b7SSiddharth Bhat     PPCGArray.bound =
28879e3db2b7SSiddharth Bhat         isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList);
28889e3db2b7SSiddharth Bhat     assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly.");
288960f63b49STobias Grosser   }
289060f63b49STobias Grosser 
289160f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
289260f63b49STobias Grosser   ///
289360f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
289443f178bbSSiddharth Bhat   void createArrays(gpu_prog *PPCGProg,
289543f178bbSSiddharth Bhat                     const SmallVector<ScopArrayInfo *, 4> &ValidSAIs) {
289660f63b49STobias Grosser     int i = 0;
289743f178bbSSiddharth Bhat     for (auto &Array : ValidSAIs) {
289860f63b49STobias Grosser       std::string TypeName;
289960f63b49STobias Grosser       raw_string_ostream OS(TypeName);
290060f63b49STobias Grosser 
290160f63b49STobias Grosser       OS << *Array->getElementType();
290260f63b49STobias Grosser       TypeName = OS.str();
290360f63b49STobias Grosser 
290460f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
290560f63b49STobias Grosser 
290677eef90fSTobias Grosser       PPCGArray.space = Array->getSpace().release();
290760f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
290860f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
290960f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
291060f63b49STobias Grosser       PPCGArray.extent = nullptr;
291160f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
291260f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
291360f63b49STobias Grosser       PPCGArray.n_ref = 0;
291460f63b49STobias Grosser       PPCGArray.refs = nullptr;
291560f63b49STobias Grosser       PPCGArray.accessed = true;
2916fe74a7a1STobias Grosser       PPCGArray.read_only_scalar =
2917fe74a7a1STobias Grosser           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
291860f63b49STobias Grosser       PPCGArray.has_compound_element = false;
291960f63b49STobias Grosser       PPCGArray.local = false;
292060f63b49STobias Grosser       PPCGArray.declare_local = false;
292160f63b49STobias Grosser       PPCGArray.global = false;
292260f63b49STobias Grosser       PPCGArray.linearize = false;
292360f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
292413c78e4dSTobias Grosser       PPCGArray.user = Array;
292560f63b49STobias Grosser 
29269e3db2b7SSiddharth Bhat       PPCGArray.bound = nullptr;
292760f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
29282d010dafSTobias Grosser       i++;
2929b9fc860aSTobias Grosser 
2930b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
293160f63b49STobias Grosser     }
293260f63b49STobias Grosser   }
293360f63b49STobias Grosser 
293460f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
293560f63b49STobias Grosser   ///
293660f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
293760f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
2938b65ccc43STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace().release());
293960f63b49STobias Grosser 
2940d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
294177eef90fSTobias Grosser       isl_space *Space = Array->getSpace().release();
294260f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
294360f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
294460f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
294560f63b49STobias Grosser     }
294660f63b49STobias Grosser 
294760f63b49STobias Grosser     return Maps;
294860f63b49STobias Grosser   }
294960f63b49STobias Grosser 
2950e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
2951e938517eSTobias Grosser   ///
2952a6d48f59SMichael Kruse   /// @returns A new gpu program description.
2953e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
2954e938517eSTobias Grosser 
2955e938517eSTobias Grosser     if (!PPCGScop)
2956e938517eSTobias Grosser       return nullptr;
2957e938517eSTobias Grosser 
2958e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
2959e938517eSTobias Grosser 
2960e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
2961e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
2962aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
296360f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
296460f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
296560f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
296660f63b49STobias Grosser     PPCGProg->tagged_must_kill =
296760f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
296860f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
296960f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
29709e3db2b7SSiddharth Bhat     // TODO: verify that this assignment is correct.
2971e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
2972a82f2d26SSiddharth Bhat 
2973a82f2d26SSiddharth Bhat     // this needs to be set when live range reordering is enabled.
2974a82f2d26SSiddharth Bhat     // NOTE: I believe that is conservatively correct. I'm not sure
2975a82f2d26SSiddharth Bhat     //       what the semantics of this is.
2976a82f2d26SSiddharth Bhat     // Quoting PPCG/gpu.h: "Order dependences on non-scalars."
2977a82f2d26SSiddharth Bhat     PPCGProg->array_order =
2978a82f2d26SSiddharth Bhat         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
297969b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
298069b46751STobias Grosser     PPCGProg->stmts = getStatements();
298143f178bbSSiddharth Bhat 
298243f178bbSSiddharth Bhat     // Only consider arrays that have a non-empty extent.
298343f178bbSSiddharth Bhat     // Otherwise, this will cause us to consider the following kinds of
298443f178bbSSiddharth Bhat     // empty arrays:
298543f178bbSSiddharth Bhat     //     1. Invariant loads that are represented by SAI objects.
298643f178bbSSiddharth Bhat     //     2. Arrays with statically known zero size.
298743f178bbSSiddharth Bhat     auto ValidSAIsRange =
298843f178bbSSiddharth Bhat         make_filter_range(S->arrays(), [this](ScopArrayInfo *SAI) -> bool {
298943f178bbSSiddharth Bhat           return !isl::manage(getExtent(SAI)).is_empty();
299043f178bbSSiddharth Bhat         });
299143f178bbSSiddharth Bhat     SmallVector<ScopArrayInfo *, 4> ValidSAIs(ValidSAIsRange.begin(),
299243f178bbSSiddharth Bhat                                               ValidSAIsRange.end());
299343f178bbSSiddharth Bhat 
299443f178bbSSiddharth Bhat     PPCGProg->n_array =
299543f178bbSSiddharth Bhat         ValidSAIs.size(); // std::distance(S->array_begin(), S->array_end());
299660f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
299760f63b49STobias Grosser                                        PPCGProg->n_array);
299860f63b49STobias Grosser 
299943f178bbSSiddharth Bhat     createArrays(PPCGProg, ValidSAIs);
3000e938517eSTobias Grosser 
3001d58acf86STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
3002e938517eSTobias Grosser     return PPCGProg;
3003e938517eSTobias Grosser   }
3004e938517eSTobias Grosser 
300569b46751STobias Grosser   struct PrintGPUUserData {
300669b46751STobias Grosser     struct cuda_info *CudaInfo;
300769b46751STobias Grosser     struct gpu_prog *PPCGProg;
300869b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
300969b46751STobias Grosser   };
301069b46751STobias Grosser 
301169b46751STobias Grosser   /// Print a user statement node in the host code.
301269b46751STobias Grosser   ///
301369b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
301469b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
301569b46751STobias Grosser   /// host ast.
301669b46751STobias Grosser   ///
301769b46751STobias Grosser   /// @param P The printer to print to
301869b46751STobias Grosser   /// @param Options The printing options to use
301969b46751STobias Grosser   /// @param Node The node to print
302069b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
302169b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
302269b46751STobias Grosser   ///
302369b46751STobias Grosser   /// @returns A printer to which the output has been printed.
302469b46751STobias Grosser   static __isl_give isl_printer *
302569b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
302669b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
302769b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
302869b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
302969b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
303069b46751STobias Grosser 
303169b46751STobias Grosser     if (Id) {
303220251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
303320251734STobias Grosser 
303420251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
303520251734STobias Grosser       // otherwise try to call pet functionality that is not available in
303620251734STobias Grosser       // Polly.
303720251734STobias Grosser       if (IsUser) {
303820251734STobias Grosser         P = isl_printer_start_line(P);
303920251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
304020251734STobias Grosser         P = isl_printer_end_line(P);
304120251734STobias Grosser         isl_id_free(Id);
304220251734STobias Grosser         isl_ast_print_options_free(Options);
304320251734STobias Grosser         return P;
304420251734STobias Grosser       }
304520251734STobias Grosser 
304669b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
304769b46751STobias Grosser       isl_id_free(Id);
304869b46751STobias Grosser       Data->Kernels.push_back(Kernel);
304969b46751STobias Grosser     }
305069b46751STobias Grosser 
305169b46751STobias Grosser     return print_host_user(P, Options, Node, User);
305269b46751STobias Grosser   }
305369b46751STobias Grosser 
305469b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
305569b46751STobias Grosser   ///
305669b46751STobias Grosser   /// @param Kernel The kernel to print
305769b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
305869b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
305969b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
306069b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
306169b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
306269b46751STobias Grosser     char *String = isl_printer_get_str(P);
306369b46751STobias Grosser     printf("%s\n", String);
306469b46751STobias Grosser     free(String);
306569b46751STobias Grosser     isl_printer_free(P);
306669b46751STobias Grosser   }
306769b46751STobias Grosser 
306869b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
306969b46751STobias Grosser   ///
307069b46751STobias Grosser   /// @param Tree An AST describing GPU code
307169b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
307269b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
307369b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
307469b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
307569b46751STobias Grosser 
307669b46751STobias Grosser     PrintGPUUserData Data;
307769b46751STobias Grosser     Data.PPCGProg = PPCGProg;
307869b46751STobias Grosser 
307969b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
308069b46751STobias Grosser     Options =
308169b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
308269b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
308369b46751STobias Grosser     char *String = isl_printer_get_str(P);
308469b46751STobias Grosser     printf("# host\n");
308569b46751STobias Grosser     printf("%s\n", String);
308669b46751STobias Grosser     free(String);
308769b46751STobias Grosser     isl_printer_free(P);
308869b46751STobias Grosser 
308969b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
309069b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
309169b46751STobias Grosser       printKernel(Kernel);
309269b46751STobias Grosser     }
309369b46751STobias Grosser   }
309469b46751STobias Grosser 
3095f384594dSTobias Grosser   // Generate a GPU program using PPCG.
3096f384594dSTobias Grosser   //
3097f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
3098f384594dSTobias Grosser   //
3099f384594dSTobias Grosser   //  1) Compute new schedule for the program.
3100f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
3101f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
3102f384594dSTobias Grosser   //
3103f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
3104f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
3105f384594dSTobias Grosser   // strategy directly from this pass.
3106f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
3107f384594dSTobias Grosser 
3108f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
3109f384594dSTobias Grosser 
3110f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
3111f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
3112f384594dSTobias Grosser     PPCGGen->print = nullptr;
3113f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
311460c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
3115f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
3116f384594dSTobias Grosser     PPCGGen->tree = nullptr;
3117f384594dSTobias Grosser     PPCGGen->types.n = 0;
3118f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
3119f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
3120f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
3121f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
3122f384594dSTobias Grosser 
3123f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
3124f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
3125f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
31262341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
3127f384594dSTobias Grosser 
3128f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
3129f384594dSTobias Grosser 
3130aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
3131aef5196fSTobias Grosser 
3132b5563c68STobias Grosser     Schedule =
3133b5563c68STobias Grosser         isl_schedule_align_params(Schedule, S->getFullParamSpace().release());
3134b5563c68STobias Grosser 
313569b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
3136aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
3137638316daSSiddharth Bhat       DEBUG(dbgs() << getUniqueScopName(S)
3138638316daSSiddharth Bhat                    << " does not have permutable bands. Bailing out\n";);
313969b46751STobias Grosser     } else {
3140aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
314169b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
314269b46751STobias Grosser     }
3143aef5196fSTobias Grosser 
3144f384594dSTobias Grosser     if (DumpSchedule) {
3145f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
3146f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
3147f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
3148f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
3149f384594dSTobias Grosser       if (Schedule)
3150f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
3151f384594dSTobias Grosser       else
3152f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
3153f384594dSTobias Grosser 
3154f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
3155f384594dSTobias Grosser       isl_printer_free(P);
3156f384594dSTobias Grosser     }
3157f384594dSTobias Grosser 
315869b46751STobias Grosser     if (DumpCode) {
315969b46751STobias Grosser       printf("Code\n");
316069b46751STobias Grosser       printf("====\n");
316169b46751STobias Grosser       if (PPCGGen->tree)
316269b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
316369b46751STobias Grosser       else
316469b46751STobias Grosser         printf("No code generated\n");
316569b46751STobias Grosser     }
316669b46751STobias Grosser 
3167f384594dSTobias Grosser     isl_schedule_free(Schedule);
3168f384594dSTobias Grosser 
3169f384594dSTobias Grosser     return PPCGGen;
3170f384594dSTobias Grosser   }
3171f384594dSTobias Grosser 
3172f384594dSTobias Grosser   /// Free gpu_gen structure.
3173f384594dSTobias Grosser   ///
3174f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
3175f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
3176f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
3177f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
3178f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
3179f384594dSTobias Grosser     free(PPCGGen);
3180f384594dSTobias Grosser   }
3181f384594dSTobias Grosser 
3182b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
3183b307ed4dSTobias Grosser   ///
3184b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
3185b307ed4dSTobias Grosser   /// ourselves.
3186b307ed4dSTobias Grosser   ///
3187b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
3188b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
3189b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
3190b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
3191b307ed4dSTobias Grosser     free(PPCGScop->options);
3192b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
3193b307ed4dSTobias Grosser   }
3194b307ed4dSTobias Grosser 
319582f2af35STobias Grosser   /// Approximate the number of points in the set.
319682f2af35STobias Grosser   ///
319782f2af35STobias Grosser   /// This function returns an ast expression that overapproximates the number
319882f2af35STobias Grosser   /// of points in an isl set through the rectangular hull surrounding this set.
319982f2af35STobias Grosser   ///
320082f2af35STobias Grosser   /// @param Set   The set to count.
320182f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
320282f2af35STobias Grosser   ///              expression.
320382f2af35STobias Grosser   ///
320482f2af35STobias Grosser   /// @returns An approximation of the number of points in the set.
320582f2af35STobias Grosser   __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set,
320682f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
320782f2af35STobias Grosser 
320882f2af35STobias Grosser     isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1);
320982f2af35STobias Grosser     auto *Expr = isl_ast_expr_from_val(isl_val_copy(One));
321082f2af35STobias Grosser 
321182f2af35STobias Grosser     isl_space *Space = isl_set_get_space(Set);
321282f2af35STobias Grosser     Space = isl_space_params(Space);
321382f2af35STobias Grosser     auto *Univ = isl_set_universe(Space);
321482f2af35STobias Grosser     isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One);
321582f2af35STobias Grosser 
321682f2af35STobias Grosser     for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) {
321782f2af35STobias Grosser       isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i);
321882f2af35STobias Grosser       isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i);
321982f2af35STobias Grosser       isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min);
322082f2af35STobias Grosser       DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff));
322182f2af35STobias Grosser       auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize);
322282f2af35STobias Grosser       Expr = isl_ast_expr_mul(Expr, DimSizeExpr);
322382f2af35STobias Grosser     }
322482f2af35STobias Grosser 
322582f2af35STobias Grosser     isl_set_free(Set);
322682f2af35STobias Grosser     isl_pw_aff_free(OneAff);
322782f2af35STobias Grosser 
322882f2af35STobias Grosser     return Expr;
322982f2af35STobias Grosser   }
323082f2af35STobias Grosser 
323182f2af35STobias Grosser   /// Approximate a number of dynamic instructions executed by a given
323282f2af35STobias Grosser   /// statement.
323382f2af35STobias Grosser   ///
323482f2af35STobias Grosser   /// @param Stmt  The statement for which to compute the number of dynamic
323582f2af35STobias Grosser   ///              instructions.
323682f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
323782f2af35STobias Grosser   ///              expression.
323882f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
323982f2af35STobias Grosser   ///          by @p Stmt.
324082f2af35STobias Grosser   __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt,
324182f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
3242dcf8d696STobias Grosser     auto Iterations = approxPointsInSet(Stmt.getDomain().release(), Build);
324382f2af35STobias Grosser 
324482f2af35STobias Grosser     long InstCount = 0;
324582f2af35STobias Grosser 
324682f2af35STobias Grosser     if (Stmt.isBlockStmt()) {
324782f2af35STobias Grosser       auto *BB = Stmt.getBasicBlock();
324882f2af35STobias Grosser       InstCount = std::distance(BB->begin(), BB->end());
324982f2af35STobias Grosser     } else {
325082f2af35STobias Grosser       auto *R = Stmt.getRegion();
325182f2af35STobias Grosser 
325282f2af35STobias Grosser       for (auto *BB : R->blocks()) {
325382f2af35STobias Grosser         InstCount += std::distance(BB->begin(), BB->end());
325482f2af35STobias Grosser       }
325582f2af35STobias Grosser     }
325682f2af35STobias Grosser 
325782f2af35STobias Grosser     isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount);
325882f2af35STobias Grosser     auto *InstExpr = isl_ast_expr_from_val(InstVal);
325982f2af35STobias Grosser     return isl_ast_expr_mul(InstExpr, Iterations);
326082f2af35STobias Grosser   }
326182f2af35STobias Grosser 
326282f2af35STobias Grosser   /// Approximate dynamic instructions executed in scop.
326382f2af35STobias Grosser   ///
326482f2af35STobias Grosser   /// @param S     The scop for which to approximate dynamic instructions.
326582f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
326682f2af35STobias Grosser   ///              expression.
326782f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
326882f2af35STobias Grosser   ///          in @p S.
326982f2af35STobias Grosser   __isl_give isl_ast_expr *
327082f2af35STobias Grosser   getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) {
327182f2af35STobias Grosser     isl_ast_expr *Instructions;
327282f2af35STobias Grosser 
327382f2af35STobias Grosser     isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0);
327482f2af35STobias Grosser     Instructions = isl_ast_expr_from_val(Zero);
327582f2af35STobias Grosser 
327682f2af35STobias Grosser     for (ScopStmt &Stmt : S) {
327782f2af35STobias Grosser       isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build);
327882f2af35STobias Grosser       Instructions = isl_ast_expr_add(Instructions, StmtInstructions);
327982f2af35STobias Grosser     }
328082f2af35STobias Grosser     return Instructions;
328182f2af35STobias Grosser   }
328282f2af35STobias Grosser 
328382f2af35STobias Grosser   /// Create a check that ensures sufficient compute in scop.
328482f2af35STobias Grosser   ///
328582f2af35STobias Grosser   /// @param S     The scop for which to ensure sufficient compute.
328682f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
328782f2af35STobias Grosser   ///              expression.
328882f2af35STobias Grosser   /// @returns An expression that evaluates to TRUE in case of sufficient
328982f2af35STobias Grosser   ///          compute and to FALSE, otherwise.
329082f2af35STobias Grosser   __isl_give isl_ast_expr *
329182f2af35STobias Grosser   createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) {
329282f2af35STobias Grosser     auto Iterations = getNumberOfIterations(S, Build);
329382f2af35STobias Grosser     auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute);
329482f2af35STobias Grosser     auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal);
329582f2af35STobias Grosser     return isl_ast_expr_ge(Iterations, MinComputeExpr);
329682f2af35STobias Grosser   }
329782f2af35STobias Grosser 
3298f291c8d5SSiddharth Bhat   /// Check if the basic block contains a function we cannot codegen for GPU
3299f291c8d5SSiddharth Bhat   /// kernels.
3300f291c8d5SSiddharth Bhat   ///
3301f291c8d5SSiddharth Bhat   /// If this basic block does something with a `Function` other than calling
3302f291c8d5SSiddharth Bhat   /// a function that we support in a kernel, return true.
33038fc6cdfbSTobias Grosser   bool containsInvalidKernelFunctionInBlock(const BasicBlock *BB,
33048fc6cdfbSTobias Grosser                                             bool AllowCUDALibDevice) {
3305f291c8d5SSiddharth Bhat     for (const Instruction &Inst : *BB) {
3306f291c8d5SSiddharth Bhat       const CallInst *Call = dyn_cast<CallInst>(&Inst);
33078fc6cdfbSTobias Grosser       if (Call && isValidFunctionInKernel(Call->getCalledFunction(),
33088fc6cdfbSTobias Grosser                                           AllowCUDALibDevice)) {
3309f291c8d5SSiddharth Bhat         continue;
3310f291c8d5SSiddharth Bhat       }
3311f291c8d5SSiddharth Bhat 
3312bccaea57SSiddharth Bhat       for (Value *SrcVal : Inst.operands()) {
3313bccaea57SSiddharth Bhat         PointerType *p = dyn_cast<PointerType>(SrcVal->getType());
3314bccaea57SSiddharth Bhat         if (!p)
3315bccaea57SSiddharth Bhat           continue;
3316bccaea57SSiddharth Bhat         if (isa<FunctionType>(p->getElementType()))
3317bccaea57SSiddharth Bhat           return true;
3318bccaea57SSiddharth Bhat       }
3319f291c8d5SSiddharth Bhat     }
3320bccaea57SSiddharth Bhat     return false;
3321bccaea57SSiddharth Bhat   }
3322bccaea57SSiddharth Bhat 
3323f291c8d5SSiddharth Bhat   /// Return whether the Scop S uses functions in a way that we do not support.
33248fc6cdfbSTobias Grosser   bool containsInvalidKernelFunction(const Scop &S, bool AllowCUDALibDevice) {
3325bccaea57SSiddharth Bhat     for (auto &Stmt : S) {
3326bccaea57SSiddharth Bhat       if (Stmt.isBlockStmt()) {
33278fc6cdfbSTobias Grosser         if (containsInvalidKernelFunctionInBlock(Stmt.getBasicBlock(),
33288fc6cdfbSTobias Grosser                                                  AllowCUDALibDevice))
3329bccaea57SSiddharth Bhat           return true;
3330bccaea57SSiddharth Bhat       } else {
3331bccaea57SSiddharth Bhat         assert(Stmt.isRegionStmt() &&
3332bccaea57SSiddharth Bhat                "Stmt was neither block nor region statement");
3333bccaea57SSiddharth Bhat         for (const BasicBlock *BB : Stmt.getRegion()->blocks())
33348fc6cdfbSTobias Grosser           if (containsInvalidKernelFunctionInBlock(BB, AllowCUDALibDevice))
3335bccaea57SSiddharth Bhat             return true;
3336bccaea57SSiddharth Bhat       }
3337bccaea57SSiddharth Bhat     }
3338bccaea57SSiddharth Bhat     return false;
3339bccaea57SSiddharth Bhat   }
3340bccaea57SSiddharth Bhat 
334138fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
334238fc0aedSTobias Grosser   ///
334332837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
334432837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
334532837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
334638fc0aedSTobias Grosser     ScopAnnotator Annotator;
334738fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
334838fc0aedSTobias Grosser 
334938fc0aedSTobias Grosser     Region *R = &S->getRegion();
335038fc0aedSTobias Grosser 
335138fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
335238fc0aedSTobias Grosser 
335338fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
335438fc0aedSTobias Grosser 
335538fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
335638fc0aedSTobias Grosser 
335738fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
335838fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
335938fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
336038fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
336138fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
336238fc0aedSTobias Grosser     // code generating this scop.
336303346c27SSiddharth Bhat     BBPair StartExitBlocks;
336403346c27SSiddharth Bhat     BranchInst *CondBr = nullptr;
336503346c27SSiddharth Bhat     std::tie(StartExitBlocks, CondBr) =
33662d950f36SPhilip Pfaffe         executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI);
3367256070d8SAndreas Simbuerger     BasicBlock *StartBlock = std::get<0>(StartExitBlocks);
336838fc0aedSTobias Grosser 
336903346c27SSiddharth Bhat     assert(CondBr && "CondBr not initialized by executeScopConditionally");
337003346c27SSiddharth Bhat 
33712d950f36SPhilip Pfaffe     GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S,
337217f01968SSiddharth Bhat                                StartBlock, Prog, Runtime, Architecture);
3373acf80064SEli Friedman 
337438fc0aedSTobias Grosser     // TODO: Handle LICM
337538fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
337638fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
3377cb1aef8dSTobias Grosser 
3378cb1aef8dSTobias Grosser     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx());
33792b852e2eSPhilip Pfaffe     isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build);
338082f2af35STobias Grosser     isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build);
338182f2af35STobias Grosser     Condition = isl_ast_expr_and(Condition, SufficientCompute);
3382cb1aef8dSTobias Grosser     isl_ast_build_free(Build);
3383cb1aef8dSTobias Grosser 
33849e3db2b7SSiddharth Bhat     // preload invariant loads. Note: This should happen before the RTC
33859e3db2b7SSiddharth Bhat     // because the RTC may depend on values that are invariant load hoisted.
3386*71dfb3ebSSiddharth Bhat     if (!NodeBuilder.preloadInvariantLoads()) {
3387*71dfb3ebSSiddharth Bhat       DEBUG(dbgs() << "preloading invariant loads failed in function: " +
33884ebeb356SSiddharth Bhat                           S->getFunction().getName() +
33894ebeb356SSiddharth Bhat                           " | Scop Region: " + S->getNameStr());
3390*71dfb3ebSSiddharth Bhat       // adjust the dominator tree accordingly.
3391*71dfb3ebSSiddharth Bhat       auto *ExitingBlock = StartBlock->getUniqueSuccessor();
3392*71dfb3ebSSiddharth Bhat       assert(ExitingBlock);
3393*71dfb3ebSSiddharth Bhat       auto *MergeBlock = ExitingBlock->getUniqueSuccessor();
3394*71dfb3ebSSiddharth Bhat       assert(MergeBlock);
3395*71dfb3ebSSiddharth Bhat       polly::markBlockUnreachable(*StartBlock, Builder);
3396*71dfb3ebSSiddharth Bhat       polly::markBlockUnreachable(*ExitingBlock, Builder);
3397*71dfb3ebSSiddharth Bhat       auto *ExitingBB = S->getExitingBlock();
3398*71dfb3ebSSiddharth Bhat       assert(ExitingBB);
33999e3db2b7SSiddharth Bhat 
3400*71dfb3ebSSiddharth Bhat       DT->changeImmediateDominator(MergeBlock, ExitingBB);
3401*71dfb3ebSSiddharth Bhat       DT->eraseNode(ExitingBlock);
3402*71dfb3ebSSiddharth Bhat       isl_ast_expr_free(Condition);
3403*71dfb3ebSSiddharth Bhat       isl_ast_node_free(Root);
3404*71dfb3ebSSiddharth Bhat     } else {
3405*71dfb3ebSSiddharth Bhat 
3406*71dfb3ebSSiddharth Bhat       NodeBuilder.addParameters(S->getContext().release());
3407cb1aef8dSTobias Grosser       Value *RTC = NodeBuilder.createRTC(Condition);
3408cb1aef8dSTobias Grosser       Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
3409cb1aef8dSTobias Grosser 
341038fc0aedSTobias Grosser       Builder.SetInsertPoint(&*StartBlock->begin());
3411fa7b0802STobias Grosser 
341238fc0aedSTobias Grosser       NodeBuilder.create(Root);
3413*71dfb3ebSSiddharth Bhat     }
34145857b701STobias Grosser 
3415bc653f20STobias Grosser     /// In case a sequential kernel has more surrounding loops as any parallel
3416bc653f20STobias Grosser     /// kernel, the SCoP is probably mostly sequential. Hence, there is no
3417de244eb4STobias Grosser     /// point in running it on a GPU.
3418bc653f20STobias Grosser     if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel)
341903346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
3420bc653f20STobias Grosser 
34215857b701STobias Grosser     if (!NodeBuilder.BuildSuccessful)
342203346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
342338fc0aedSTobias Grosser   }
342438fc0aedSTobias Grosser 
3425e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
3426e938517eSTobias Grosser     S = &CurrentScop;
342738fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
342838fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
342938fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
34307b5a4dfdSTobias Grosser     DL = &S->getRegion().getEntry()->getModule()->getDataLayout();
343138fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
3432e938517eSTobias Grosser 
3433f291c8d5SSiddharth Bhat     // We currently do not support functions other than intrinsics inside
3434f291c8d5SSiddharth Bhat     // kernels, as code generation will need to offload function calls to the
3435f291c8d5SSiddharth Bhat     // kernel. This may lead to a kernel trying to call a function on the host.
3436bccaea57SSiddharth Bhat     // This also allows us to prevent codegen from trying to take the
3437bccaea57SSiddharth Bhat     // address of an intrinsic function to send to the kernel.
34388fc6cdfbSTobias Grosser     if (containsInvalidKernelFunction(CurrentScop,
34398fc6cdfbSTobias Grosser                                       Architecture == GPUArch::NVPTX64)) {
3440f291c8d5SSiddharth Bhat       DEBUG(
3441638316daSSiddharth Bhat           dbgs() << getUniqueScopName(S)
3442638316daSSiddharth Bhat                  << " contains function which cannot be materialised in a GPU "
3443f291c8d5SSiddharth Bhat                     "kernel. Bailing out.\n";);
3444bccaea57SSiddharth Bhat       return false;
3445f291c8d5SSiddharth Bhat     }
3446bccaea57SSiddharth Bhat 
3447e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
3448e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
3449f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
345038fc0aedSTobias Grosser 
345102ca346eSSingapuram Sanjay Srivallabh     if (PPCGGen->tree) {
345232837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
345302ca346eSSingapuram Sanjay Srivallabh       CurrentScop.markAsToBeSkipped();
3454638316daSSiddharth Bhat     } else {
3455638316daSSiddharth Bhat       DEBUG(dbgs() << getUniqueScopName(S)
3456638316daSSiddharth Bhat                    << " has empty PPCGGen->tree. Bailing out.\n");
345702ca346eSSingapuram Sanjay Srivallabh     }
345838fc0aedSTobias Grosser 
3459b307ed4dSTobias Grosser     freeOptions(PPCGScop);
3460f384594dSTobias Grosser     freePPCGGen(PPCGGen);
3461e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
3462e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
3463e938517eSTobias Grosser 
3464e938517eSTobias Grosser     return true;
3465e938517eSTobias Grosser   }
34669dfe4e7cSTobias Grosser 
34679dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
34689dfe4e7cSTobias Grosser 
34699dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
34709dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
34719dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
34729dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
34735cc87e3aSPhilip Pfaffe     AU.addRequired<ScopDetectionWrapperPass>();
34749dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
34759dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
34769dfe4e7cSTobias Grosser 
34779dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
34789dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
34799dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
34809dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
34819dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
34825cc87e3aSPhilip Pfaffe     AU.addPreserved<ScopDetectionWrapperPass>();
34839dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
34849dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
34859dfe4e7cSTobias Grosser 
34869dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
34879dfe4e7cSTobias Grosser     //        region tree.
34889dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
34899dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
34909dfe4e7cSTobias Grosser   }
34919dfe4e7cSTobias Grosser };
349224222c73STobias Grosser } // namespace
34939dfe4e7cSTobias Grosser 
34949dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
34959dfe4e7cSTobias Grosser 
349617f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) {
349717f01968SSiddharth Bhat   PPCGCodeGeneration *generator = new PPCGCodeGeneration();
349817f01968SSiddharth Bhat   generator->Runtime = Runtime;
349917f01968SSiddharth Bhat   generator->Architecture = Arch;
350017f01968SSiddharth Bhat   return generator;
350117f01968SSiddharth Bhat }
35029dfe4e7cSTobias Grosser 
35039dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
35049dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
35059dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
35069dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
35079dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
35089dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
35099dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
35105cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
35119dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
35129dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
3513