19dfe4e7cSTobias Grosser //===------ PPCGCodeGeneration.cpp - Polly Accelerator Code Generation. ---===//
29dfe4e7cSTobias Grosser //
39dfe4e7cSTobias Grosser //                     The LLVM Compiler Infrastructure
49dfe4e7cSTobias Grosser //
59dfe4e7cSTobias Grosser // This file is distributed under the University of Illinois Open Source
69dfe4e7cSTobias Grosser // License. See LICENSE.TXT for details.
79dfe4e7cSTobias Grosser //
89dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===//
99dfe4e7cSTobias Grosser //
109dfe4e7cSTobias Grosser // Take a scop created by ScopInfo and map it to GPU code using the ppcg
119dfe4e7cSTobias Grosser // GPU mapping strategy.
129dfe4e7cSTobias Grosser //
139dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===//
149dfe4e7cSTobias Grosser 
1517f01968SSiddharth Bhat #include "polly/CodeGen/PPCGCodeGeneration.h"
16cb1aef8dSTobias Grosser #include "polly/CodeGen/IslAst.h"
179dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h"
1838fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h"
199dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h"
209dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h"
21f384594dSTobias Grosser #include "polly/Options.h"
22629109b6STobias Grosser #include "polly/ScopDetection.h"
239dfe4e7cSTobias Grosser #include "polly/ScopInfo.h"
24edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h"
2574dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h"
269dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h"
279dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h"
289dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h"
299dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
3074dc3cb4STobias Grosser #include "llvm/Analysis/TargetLibraryInfo.h"
3174dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h"
3274dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h"
33e1a98343STobias Grosser #include "llvm/IR/Verifier.h"
348fc6cdfbSTobias Grosser #include "llvm/IRReader/IRReader.h"
358fc6cdfbSTobias Grosser #include "llvm/Linker/Linker.h"
3674dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h"
3774dc3cb4STobias Grosser #include "llvm/Support/TargetSelect.h"
3874dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h"
399a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h"
40750160e2STobias Grosser #include "llvm/Transforms/Utils/BasicBlockUtils.h"
419dfe4e7cSTobias Grosser 
42f384594dSTobias Grosser #include "isl/union_map.h"
43f384594dSTobias Grosser 
44e938517eSTobias Grosser extern "C" {
45a56f8f8eSTobias Grosser #include "ppcg/cuda.h"
46a56f8f8eSTobias Grosser #include "ppcg/gpu.h"
47a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h"
48a56f8f8eSTobias Grosser #include "ppcg/ppcg.h"
49a56f8f8eSTobias Grosser #include "ppcg/schedule.h"
50e938517eSTobias Grosser }
51e938517eSTobias Grosser 
529dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h"
539dfe4e7cSTobias Grosser 
549dfe4e7cSTobias Grosser using namespace polly;
559dfe4e7cSTobias Grosser using namespace llvm;
569dfe4e7cSTobias Grosser 
579dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg"
589dfe4e7cSTobias Grosser 
59f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
60f384594dSTobias Grosser                                   cl::desc("Dump the computed GPU Schedule"),
61681bd568STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
62f384594dSTobias Grosser                                   cl::cat(PollyCategory));
6369b46751STobias Grosser 
6469b46751STobias Grosser static cl::opt<bool>
6569b46751STobias Grosser     DumpCode("polly-acc-dump-code",
6669b46751STobias Grosser              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
6769b46751STobias Grosser              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
6869b46751STobias Grosser 
6932837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
7032837fe3STobias Grosser                                   cl::desc("Dump the kernel LLVM-IR"),
7132837fe3STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
7232837fe3STobias Grosser                                   cl::cat(PollyCategory));
7332837fe3STobias Grosser 
7474dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
7574dc3cb4STobias Grosser                                    cl::desc("Dump the kernel assembly code"),
7674dc3cb4STobias Grosser                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
7774dc3cb4STobias Grosser                                    cl::cat(PollyCategory));
7874dc3cb4STobias Grosser 
7974dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath",
8074dc3cb4STobias Grosser                               cl::desc("Allow unsafe math optimizations"),
8174dc3cb4STobias Grosser                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
8274dc3cb4STobias Grosser                               cl::cat(PollyCategory));
83b513b491STobias Grosser static cl::opt<bool> SharedMemory("polly-acc-use-shared",
84b513b491STobias Grosser                                   cl::desc("Use shared memory"), cl::Hidden,
85b513b491STobias Grosser                                   cl::init(false), cl::ZeroOrMore,
86b513b491STobias Grosser                                   cl::cat(PollyCategory));
87130ca30fSTobias Grosser static cl::opt<bool> PrivateMemory("polly-acc-use-private",
88130ca30fSTobias Grosser                                    cl::desc("Use private memory"), cl::Hidden,
89130ca30fSTobias Grosser                                    cl::init(false), cl::ZeroOrMore,
90130ca30fSTobias Grosser                                    cl::cat(PollyCategory));
9174dc3cb4STobias Grosser 
92abed4969SSiddharth Bhat static cl::opt<bool> ManagedMemory("polly-acc-codegen-managed-memory",
93abed4969SSiddharth Bhat                                    cl::desc("Generate Host kernel code assuming"
94abed4969SSiddharth Bhat                                             " that all memory has been"
95abed4969SSiddharth Bhat                                             " declared as managed memory"),
96abed4969SSiddharth Bhat                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
97abed4969SSiddharth Bhat                                    cl::cat(PollyCategory));
98abed4969SSiddharth Bhat 
9965d7f72fSSiddharth Bhat static cl::opt<bool>
10065d7f72fSSiddharth Bhat     FailOnVerifyModuleFailure("polly-acc-fail-on-verify-module-failure",
10165d7f72fSSiddharth Bhat                               cl::desc("Fail and generate a backtrace if"
10265d7f72fSSiddharth Bhat                                        " verifyModule fails on the GPU "
10365d7f72fSSiddharth Bhat                                        " kernel module."),
10465d7f72fSSiddharth Bhat                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
10565d7f72fSSiddharth Bhat                               cl::cat(PollyCategory));
10665d7f72fSSiddharth Bhat 
1078fc6cdfbSTobias Grosser static cl::opt<std::string> CUDALibDevice(
1088fc6cdfbSTobias Grosser     "polly-acc-libdevice", cl::desc("Path to CUDA libdevice"), cl::Hidden,
1098fc6cdfbSTobias Grosser     cl::init("/usr/local/cuda/nvvm/libdevice/libdevice.compute_20.10.ll"),
1108fc6cdfbSTobias Grosser     cl::ZeroOrMore, cl::cat(PollyCategory));
1118fc6cdfbSTobias Grosser 
11274dc3cb4STobias Grosser static cl::opt<std::string>
11374dc3cb4STobias Grosser     CudaVersion("polly-acc-cuda-version",
11474dc3cb4STobias Grosser                 cl::desc("The CUDA version to compile for"), cl::Hidden,
11574dc3cb4STobias Grosser                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
11674dc3cb4STobias Grosser 
11782f2af35STobias Grosser static cl::opt<int>
11882f2af35STobias Grosser     MinCompute("polly-acc-mincompute",
11982f2af35STobias Grosser                cl::desc("Minimal number of compute statements to run on GPU."),
12082f2af35STobias Grosser                cl::Hidden, cl::init(10 * 512 * 512));
12182f2af35STobias Grosser 
122a82f2d26SSiddharth Bhat /// Used to store information PPCG wants for kills. This information is
123a82f2d26SSiddharth Bhat /// used by live range reordering.
124a82f2d26SSiddharth Bhat ///
125a82f2d26SSiddharth Bhat /// @see computeLiveRangeReordering
126a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGScop
127a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGProg
128a82f2d26SSiddharth Bhat struct MustKillsInfo {
129a82f2d26SSiddharth Bhat   /// Collection of all kill statements that will be sequenced at the end of
130a82f2d26SSiddharth Bhat   /// PPCGScop->schedule.
131a82f2d26SSiddharth Bhat   ///
132a82f2d26SSiddharth Bhat   /// The nodes in `KillsSchedule` will be merged using `isl_schedule_set`
133a82f2d26SSiddharth Bhat   /// which merges schedules in *arbitrary* order.
134a82f2d26SSiddharth Bhat   /// (we don't care about the order of the kills anyway).
135a82f2d26SSiddharth Bhat   isl::schedule KillsSchedule;
136a82f2d26SSiddharth Bhat   /// Map from kill statement instances to scalars that need to be
137a82f2d26SSiddharth Bhat   /// killed.
138a82f2d26SSiddharth Bhat   ///
139edfef5aeSSiddharth Bhat   /// We currently derive kill information for:
140edfef5aeSSiddharth Bhat   ///  1. phi nodes. PHI nodes are not alive outside the scop and can
141edfef5aeSSiddharth Bhat   ///     consequently all be killed.
142edfef5aeSSiddharth Bhat   ///  2. Scalar arrays that are not used outside the Scop. This is
143edfef5aeSSiddharth Bhat   ///     checked by `isScalarUsesContainedInScop`.
144edfef5aeSSiddharth Bhat   /// [params] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] }
145a82f2d26SSiddharth Bhat   isl::union_map TaggedMustKills;
146a82f2d26SSiddharth Bhat 
1479e3db2b7SSiddharth Bhat   /// Tagged must kills stripped of the tags.
1489e3db2b7SSiddharth Bhat   /// [params] -> { Stmt_phantom[]  -> scalar_to_kill[] }
1499e3db2b7SSiddharth Bhat   isl::union_map MustKills;
1509e3db2b7SSiddharth Bhat 
1519e3db2b7SSiddharth Bhat   MustKillsInfo() : KillsSchedule(nullptr) {}
152a82f2d26SSiddharth Bhat };
153a82f2d26SSiddharth Bhat 
154761e5b93SSiddharth Bhat /// Check if SAI's uses are entirely contained within Scop S.
155761e5b93SSiddharth Bhat /// If a scalar is used only with a Scop, we are free to kill it, as no data
156761e5b93SSiddharth Bhat /// can flow in/out of the value any more.
157761e5b93SSiddharth Bhat /// @see computeMustKillsInfo
158761e5b93SSiddharth Bhat static bool isScalarUsesContainedInScop(const Scop &S,
159761e5b93SSiddharth Bhat                                         const ScopArrayInfo *SAI) {
160761e5b93SSiddharth Bhat   assert(SAI->isValueKind() && "this function only deals with scalars."
161761e5b93SSiddharth Bhat                                " Dealing with arrays required alias analysis");
162761e5b93SSiddharth Bhat 
163761e5b93SSiddharth Bhat   const Region &R = S.getRegion();
164761e5b93SSiddharth Bhat   for (User *U : SAI->getBasePtr()->users()) {
165761e5b93SSiddharth Bhat     Instruction *I = dyn_cast<Instruction>(U);
166761e5b93SSiddharth Bhat     assert(I && "invalid user of scop array info");
167761e5b93SSiddharth Bhat     if (!R.contains(I))
168761e5b93SSiddharth Bhat       return false;
169761e5b93SSiddharth Bhat   }
170761e5b93SSiddharth Bhat   return true;
171761e5b93SSiddharth Bhat }
172761e5b93SSiddharth Bhat 
173a82f2d26SSiddharth Bhat /// Compute must-kills needed to enable live range reordering with PPCG.
174a82f2d26SSiddharth Bhat ///
175a82f2d26SSiddharth Bhat /// @params S The Scop to compute live range reordering information
176a82f2d26SSiddharth Bhat /// @returns live range reordering information that can be used to setup
177a82f2d26SSiddharth Bhat /// PPCG.
178a82f2d26SSiddharth Bhat static MustKillsInfo computeMustKillsInfo(const Scop &S) {
179a82f2d26SSiddharth Bhat   const isl::space ParamSpace(isl::manage(S.getParamSpace()));
180a82f2d26SSiddharth Bhat   MustKillsInfo Info;
181a82f2d26SSiddharth Bhat 
182761e5b93SSiddharth Bhat   // 1. Collect all ScopArrayInfo that satisfy *any* of the criteria:
183761e5b93SSiddharth Bhat   //      1.1 phi nodes in scop.
184761e5b93SSiddharth Bhat   //      1.2 scalars that are only used within the scop
185a82f2d26SSiddharth Bhat   SmallVector<isl::id, 4> KillMemIds;
186a82f2d26SSiddharth Bhat   for (ScopArrayInfo *SAI : S.arrays()) {
187761e5b93SSiddharth Bhat     if (SAI->isPHIKind() ||
188761e5b93SSiddharth Bhat         (SAI->isValueKind() && isScalarUsesContainedInScop(S, SAI)))
18977eef90fSTobias Grosser       KillMemIds.push_back(isl::manage(SAI->getBasePtrId().release()));
190a82f2d26SSiddharth Bhat   }
191a82f2d26SSiddharth Bhat 
192a82f2d26SSiddharth Bhat   Info.TaggedMustKills = isl::union_map::empty(isl::space(ParamSpace));
1939e3db2b7SSiddharth Bhat   Info.MustKills = isl::union_map::empty(isl::space(ParamSpace));
194a82f2d26SSiddharth Bhat 
195a82f2d26SSiddharth Bhat   // Initialising KillsSchedule to `isl_set_empty` creates an empty node in the
196a82f2d26SSiddharth Bhat   // schedule:
197a82f2d26SSiddharth Bhat   //     - filter: "[control] -> { }"
198a82f2d26SSiddharth Bhat   // So, we choose to not create this to keep the output a little nicer,
199a82f2d26SSiddharth Bhat   // at the cost of some code complexity.
200a82f2d26SSiddharth Bhat   Info.KillsSchedule = nullptr;
201a82f2d26SSiddharth Bhat 
202edfef5aeSSiddharth Bhat   for (isl::id &ToKillId : KillMemIds) {
203a82f2d26SSiddharth Bhat     isl::id KillStmtId = isl::id::alloc(
204edfef5aeSSiddharth Bhat         S.getIslCtx(),
205edfef5aeSSiddharth Bhat         std::string("SKill_phantom_").append(ToKillId.get_name()), nullptr);
206a82f2d26SSiddharth Bhat 
207a82f2d26SSiddharth Bhat     // NOTE: construction of tagged_must_kill:
208a82f2d26SSiddharth Bhat     // 2. We need to construct a map:
209edfef5aeSSiddharth Bhat     //     [param] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] }
210a82f2d26SSiddharth Bhat     // To construct this, we use `isl_map_domain_product` on 2 maps`:
211edfef5aeSSiddharth Bhat     // 2a. StmtToScalar:
212edfef5aeSSiddharth Bhat     //         [param] -> { Stmt_phantom[] -> scalar_to_kill[] }
213edfef5aeSSiddharth Bhat     // 2b. PhantomRefToScalar:
214edfef5aeSSiddharth Bhat     //         [param] -> { ref_phantom[] -> scalar_to_kill[] }
215a82f2d26SSiddharth Bhat     //
216a82f2d26SSiddharth Bhat     // Combining these with `isl_map_domain_product` gives us
217a82f2d26SSiddharth Bhat     // TaggedMustKill:
218edfef5aeSSiddharth Bhat     //     [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] }
219a82f2d26SSiddharth Bhat 
220edfef5aeSSiddharth Bhat     // 2a. [param] -> { Stmt[] -> scalar_to_kill[] }
221edfef5aeSSiddharth Bhat     isl::map StmtToScalar = isl::map::universe(isl::space(ParamSpace));
222edfef5aeSSiddharth Bhat     StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::in, isl::id(KillStmtId));
223edfef5aeSSiddharth Bhat     StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::out, isl::id(ToKillId));
224a82f2d26SSiddharth Bhat 
225a82f2d26SSiddharth Bhat     isl::id PhantomRefId = isl::id::alloc(
226edfef5aeSSiddharth Bhat         S.getIslCtx(), std::string("ref_phantom") + ToKillId.get_name(),
227edfef5aeSSiddharth Bhat         nullptr);
228a82f2d26SSiddharth Bhat 
229edfef5aeSSiddharth Bhat     // 2b. [param] -> { phantom_ref[] -> scalar_to_kill[] }
230edfef5aeSSiddharth Bhat     isl::map PhantomRefToScalar = isl::map::universe(isl::space(ParamSpace));
231edfef5aeSSiddharth Bhat     PhantomRefToScalar =
232edfef5aeSSiddharth Bhat         PhantomRefToScalar.set_tuple_id(isl::dim::in, PhantomRefId);
233edfef5aeSSiddharth Bhat     PhantomRefToScalar =
234edfef5aeSSiddharth Bhat         PhantomRefToScalar.set_tuple_id(isl::dim::out, ToKillId);
235a82f2d26SSiddharth Bhat 
236edfef5aeSSiddharth Bhat     // 2. [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] }
237edfef5aeSSiddharth Bhat     isl::map TaggedMustKill = StmtToScalar.domain_product(PhantomRefToScalar);
238a82f2d26SSiddharth Bhat     Info.TaggedMustKills = Info.TaggedMustKills.unite(TaggedMustKill);
239a82f2d26SSiddharth Bhat 
2409e3db2b7SSiddharth Bhat     // 2. [param] -> { Stmt[] -> scalar_to_kill[] }
2419e3db2b7SSiddharth Bhat     Info.MustKills = Info.TaggedMustKills.domain_factor_domain();
2429e3db2b7SSiddharth Bhat 
243a82f2d26SSiddharth Bhat     // 3. Create the kill schedule of the form:
244a82f2d26SSiddharth Bhat     //     "[param] -> { Stmt_phantom[] }"
245a82f2d26SSiddharth Bhat     // Then add this to Info.KillsSchedule.
246a82f2d26SSiddharth Bhat     isl::space KillStmtSpace = ParamSpace;
247a82f2d26SSiddharth Bhat     KillStmtSpace = KillStmtSpace.set_tuple_id(isl::dim::set, KillStmtId);
248a82f2d26SSiddharth Bhat     isl::union_set KillStmtDomain = isl::set::universe(KillStmtSpace);
249a82f2d26SSiddharth Bhat 
250a82f2d26SSiddharth Bhat     isl::schedule KillSchedule = isl::schedule::from_domain(KillStmtDomain);
251a82f2d26SSiddharth Bhat     if (Info.KillsSchedule)
252a82f2d26SSiddharth Bhat       Info.KillsSchedule = Info.KillsSchedule.set(KillSchedule);
253a82f2d26SSiddharth Bhat     else
254a82f2d26SSiddharth Bhat       Info.KillsSchedule = KillSchedule;
255a82f2d26SSiddharth Bhat   }
256a82f2d26SSiddharth Bhat 
257a82f2d26SSiddharth Bhat   return Info;
258a82f2d26SSiddharth Bhat }
259a82f2d26SSiddharth Bhat 
26060c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
26160c60025STobias Grosser ///
26260c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
26360c60025STobias Grosser /// of the scheduled ScopStmts.
26460c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
26535de9009SSiddharth Bhat     void *StmtT, __isl_take isl_ast_build *Build_C,
26660c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
26760c60025STobias Grosser                                        isl_id *Id, void *User),
26860c60025STobias Grosser     void *UserIndex,
26960c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
270edb885cbSTobias Grosser     void *UserExpr) {
27160c60025STobias Grosser 
272edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
27360c60025STobias Grosser 
27435de9009SSiddharth Bhat   if (!Stmt || !Build_C)
275edb885cbSTobias Grosser     return NULL;
276edb885cbSTobias Grosser 
27735de9009SSiddharth Bhat   isl::ast_build Build = isl::manage(isl_ast_build_copy(Build_C));
27835de9009SSiddharth Bhat   isl::ctx Ctx = Build.get_ctx();
27935de9009SSiddharth Bhat   isl::id_to_ast_expr RefToExpr = isl::id_to_ast_expr::alloc(Ctx, 0);
280edb885cbSTobias Grosser 
281edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
28235de9009SSiddharth Bhat     isl::map AddrFunc = Acc->getAddressFunction();
28335de9009SSiddharth Bhat     AddrFunc = AddrFunc.intersect_domain(isl::manage(Stmt->getDomain()));
28435de9009SSiddharth Bhat 
28535de9009SSiddharth Bhat     isl::id RefId = Acc->getId();
28635de9009SSiddharth Bhat     isl::pw_multi_aff PMA = isl::pw_multi_aff::from_map(AddrFunc);
28735de9009SSiddharth Bhat 
28835de9009SSiddharth Bhat     isl::multi_pw_aff MPA = isl::multi_pw_aff(PMA);
28935de9009SSiddharth Bhat     MPA = MPA.coalesce();
29035de9009SSiddharth Bhat     MPA = isl::manage(FunctionIndex(MPA.release(), RefId.get(), UserIndex));
29135de9009SSiddharth Bhat 
29235de9009SSiddharth Bhat     isl::ast_expr Access = Build.access_from(MPA);
29335de9009SSiddharth Bhat     Access = isl::manage(FunctionExpr(Access.release(), RefId.get(), UserExpr));
29435de9009SSiddharth Bhat     RefToExpr = RefToExpr.set(RefId, Access);
295edb885cbSTobias Grosser   }
296edb885cbSTobias Grosser 
29735de9009SSiddharth Bhat   return RefToExpr.release();
29860c60025STobias Grosser }
299f384594dSTobias Grosser 
300a90be207SSiddharth Bhat /// Given a LLVM Type, compute its size in bytes,
301a90be207SSiddharth Bhat static int computeSizeInBytes(const Type *T) {
302a90be207SSiddharth Bhat   int bytes = T->getPrimitiveSizeInBits() / 8;
303a90be207SSiddharth Bhat   if (bytes == 0)
304a90be207SSiddharth Bhat     bytes = T->getScalarSizeInBits() / 8;
305a90be207SSiddharth Bhat   return bytes;
306a90be207SSiddharth Bhat }
307a90be207SSiddharth Bhat 
30838fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
30938fc0aedSTobias Grosser ///
31038fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
311a6d48f59SMichael Kruse /// generates code for general-purpose AST nodes, with special functionality
31238fc0aedSTobias Grosser /// for generating GPU specific user nodes.
31338fc0aedSTobias Grosser ///
31438fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
31538fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
31638fc0aedSTobias Grosser public:
3172d950f36SPhilip Pfaffe   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator,
31838fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
319acf80064SEli Friedman                  DominatorTree &DT, Scop &S, BasicBlock *StartBlock,
32017f01968SSiddharth Bhat                  gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch)
3212d950f36SPhilip Pfaffe       : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock),
32217f01968SSiddharth Bhat         Prog(Prog), Runtime(Runtime), Arch(Arch) {
323edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
324edb885cbSTobias Grosser   }
32538fc0aedSTobias Grosser 
326fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
327fa7b0802STobias Grosser   void initializeAfterRTH();
328fa7b0802STobias Grosser 
329fa7b0802STobias Grosser   /// Finalize the generated scop.
330fa7b0802STobias Grosser   virtual void finalize();
331fa7b0802STobias Grosser 
3325857b701STobias Grosser   /// Track if the full build process was successful.
3335857b701STobias Grosser   ///
3345857b701STobias Grosser   /// This value is set to false, if throughout the build process an error
3355857b701STobias Grosser   /// occurred which prevents us from generating valid GPU code.
3365857b701STobias Grosser   bool BuildSuccessful = true;
3375857b701STobias Grosser 
338bc653f20STobias Grosser   /// The maximal number of loops surrounding a sequential kernel.
339bc653f20STobias Grosser   unsigned DeepestSequential = 0;
340bc653f20STobias Grosser 
341bc653f20STobias Grosser   /// The maximal number of loops surrounding a parallel kernel.
342bc653f20STobias Grosser   unsigned DeepestParallel = 0;
343bc653f20STobias Grosser 
34479f13b9aSSingapuram Sanjay Srivallabh   /// Return the name to set for the ptx_kernel.
34579f13b9aSSingapuram Sanjay Srivallabh   std::string getKernelFuncName(int Kernel_id);
34679f13b9aSSingapuram Sanjay Srivallabh 
34738fc0aedSTobias Grosser private:
34874dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
34974dc3cb4STobias Grosser   ///
35074dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
35174dc3cb4STobias Grosser   /// more.
35274dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
35374dc3cb4STobias Grosser 
35413c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
35513c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
3567287aeddSTobias Grosser 
357fa7b0802STobias Grosser   /// The current GPU context.
358fa7b0802STobias Grosser   Value *GPUContext;
359fa7b0802STobias Grosser 
360b513b491STobias Grosser   /// The set of isl_ids allocated in the kernel
361b513b491STobias Grosser   std::vector<isl_id *> KernelIds;
362b513b491STobias Grosser 
36332837fe3STobias Grosser   /// A module containing GPU code.
36432837fe3STobias Grosser   ///
36532837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
36632837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
36732837fe3STobias Grosser 
36832837fe3STobias Grosser   /// The GPU program we generate code for.
36932837fe3STobias Grosser   gpu_prog *Prog;
37032837fe3STobias Grosser 
37117f01968SSiddharth Bhat   /// The GPU Runtime implementation to use (OpenCL or CUDA).
37217f01968SSiddharth Bhat   GPURuntime Runtime;
37317f01968SSiddharth Bhat 
37417f01968SSiddharth Bhat   /// The GPU Architecture to target.
37517f01968SSiddharth Bhat   GPUArch Arch;
37617f01968SSiddharth Bhat 
377472f9654STobias Grosser   /// Class to free isl_ids.
378472f9654STobias Grosser   class IslIdDeleter {
379472f9654STobias Grosser   public:
380472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
381472f9654STobias Grosser   };
382472f9654STobias Grosser 
383472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
384472f9654STobias Grosser   ///
385472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
386472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
387472f9654STobias Grosser 
388edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
389edb885cbSTobias Grosser 
39038fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
39138fc0aedSTobias Grosser   ///
39238fc0aedSTobias Grosser   /// These AST nodes can be of type:
39338fc0aedSTobias Grosser   ///
39438fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
39538fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
39613c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
3975260c041STobias Grosser   ///   - In-kernel synchronization
3985260c041STobias Grosser   ///   - In-kernel memory copy statement
39938fc0aedSTobias Grosser   ///
4001fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
4011fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
40232837fe3STobias Grosser 
40313c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
40413c78e4dSTobias Grosser 
40513c78e4dSTobias Grosser   /// Create code for a data transfer statement
40613c78e4dSTobias Grosser   ///
40713c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
40813c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
40913c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
41013c78e4dSTobias Grosser                           enum DataDirection Direction);
41113c78e4dSTobias Grosser 
412edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
413edb885cbSTobias Grosser   ///
414edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
415edb885cbSTobias Grosser   ///
416f291c8d5SSiddharth Bhat   /// @returns A pair, whose first element contains the set of values
417f291c8d5SSiddharth Bhat   ///          referenced by the kernel, and whose second element contains the
418f291c8d5SSiddharth Bhat   ///          set of functions referenced by the kernel. All functions in the
419f291c8d5SSiddharth Bhat   ///          second set satisfy isValidFunctionInKernel.
420f291c8d5SSiddharth Bhat   std::pair<SetVector<Value *>, SetVector<Function *>>
421f291c8d5SSiddharth Bhat   getReferencesInKernel(ppcg_kernel *Kernel);
422edb885cbSTobias Grosser 
42379a947c2STobias Grosser   /// Compute the sizes of the execution grid for a given kernel.
42479a947c2STobias Grosser   ///
42579a947c2STobias Grosser   /// @param Kernel The kernel to compute grid sizes for.
42679a947c2STobias Grosser   ///
42779a947c2STobias Grosser   /// @returns A tuple with grid sizes for X and Y dimension
42879a947c2STobias Grosser   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
42979a947c2STobias Grosser 
430abed4969SSiddharth Bhat   /// Creates a array that can be sent to the kernel on the device using a
431abed4969SSiddharth Bhat   /// host pointer. This is required for managed memory, when we directly send
432abed4969SSiddharth Bhat   /// host pointers to the device.
433abed4969SSiddharth Bhat   /// \note
434abed4969SSiddharth Bhat   /// This is to be used only with managed memory
435abed4969SSiddharth Bhat   Value *getOrCreateManagedDeviceArray(gpu_array_info *Array,
436abed4969SSiddharth Bhat                                        ScopArrayInfo *ArrayInfo);
437abed4969SSiddharth Bhat 
43879a947c2STobias Grosser   /// Compute the sizes of the thread blocks for a given kernel.
43979a947c2STobias Grosser   ///
44079a947c2STobias Grosser   /// @param Kernel The kernel to compute thread block sizes for.
44179a947c2STobias Grosser   ///
44279a947c2STobias Grosser   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
44379a947c2STobias Grosser   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
44479a947c2STobias Grosser 
445a90be207SSiddharth Bhat   /// Store a specific kernel launch parameter in the array of kernel launch
446a90be207SSiddharth Bhat   /// parameters.
447a90be207SSiddharth Bhat   ///
448a90be207SSiddharth Bhat   /// @param Parameters The list of parameters in which to store.
449a90be207SSiddharth Bhat   /// @param Param      The kernel launch parameter to store.
450a90be207SSiddharth Bhat   /// @param Index      The index in the parameter list, at which to store the
451a90be207SSiddharth Bhat   ///                   parameter.
452a90be207SSiddharth Bhat   void insertStoreParameter(Instruction *Parameters, Instruction *Param,
453a90be207SSiddharth Bhat                             int Index);
454a90be207SSiddharth Bhat 
45579a947c2STobias Grosser   /// Create kernel launch parameters.
45679a947c2STobias Grosser   ///
45779a947c2STobias Grosser   /// @param Kernel        The kernel to create parameters for.
45879a947c2STobias Grosser   /// @param F             The kernel function that has been created.
45957693272STobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
46079a947c2STobias Grosser   ///
46179a947c2STobias Grosser   /// @returns A stack allocated array with pointers to the parameter
46279a947c2STobias Grosser   ///          values that are passed to the kernel.
46357693272STobias Grosser   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
46457693272STobias Grosser                                 SetVector<Value *> SubtreeValues);
46579a947c2STobias Grosser 
466b513b491STobias Grosser   /// Create declarations for kernel variable.
467b513b491STobias Grosser   ///
468b513b491STobias Grosser   /// This includes shared memory declarations.
469b513b491STobias Grosser   ///
470b513b491STobias Grosser   /// @param Kernel        The kernel definition to create variables for.
471b513b491STobias Grosser   /// @param FN            The function into which to generate the variables.
472b513b491STobias Grosser   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
473b513b491STobias Grosser 
474c1c6a2a6STobias Grosser   /// Add CUDA annotations to module.
475c1c6a2a6STobias Grosser   ///
476c1c6a2a6STobias Grosser   /// Add a set of CUDA annotations that declares the maximal block dimensions
477c1c6a2a6STobias Grosser   /// that will be used to execute the CUDA kernel. This allows the NVIDIA
478c1c6a2a6STobias Grosser   /// PTX compiler to bound the number of allocated registers to ensure the
479c1c6a2a6STobias Grosser   /// resulting kernel is known to run with up to as many block dimensions
480c1c6a2a6STobias Grosser   /// as specified here.
481c1c6a2a6STobias Grosser   ///
482c1c6a2a6STobias Grosser   /// @param M         The module to add the annotations to.
483c1c6a2a6STobias Grosser   /// @param BlockDimX The size of block dimension X.
484c1c6a2a6STobias Grosser   /// @param BlockDimY The size of block dimension Y.
485c1c6a2a6STobias Grosser   /// @param BlockDimZ The size of block dimension Z.
486c1c6a2a6STobias Grosser   void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY,
487c1c6a2a6STobias Grosser                           Value *BlockDimZ);
488c1c6a2a6STobias Grosser 
48932837fe3STobias Grosser   /// Create GPU kernel.
49032837fe3STobias Grosser   ///
49132837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
49232837fe3STobias Grosser   ///
49332837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
49432837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
49532837fe3STobias Grosser 
49613c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
49713c78e4dSTobias Grosser   ///
49813c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
49913c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
50013c78e4dSTobias Grosser 
501aaabbbf8STobias Grosser   /// Generate code to compute the minimal offset at which an array is accessed.
502aaabbbf8STobias Grosser   ///
503aaabbbf8STobias Grosser   /// The offset of an array is the minimal array location accessed in a scop.
504aaabbbf8STobias Grosser   ///
505aaabbbf8STobias Grosser   /// Example:
506aaabbbf8STobias Grosser   ///
507aaabbbf8STobias Grosser   ///   for (long i = 0; i < 100; i++)
508aaabbbf8STobias Grosser   ///     A[i + 42] += ...
509aaabbbf8STobias Grosser   ///
510aaabbbf8STobias Grosser   ///   getArrayOffset(A) results in 42.
511aaabbbf8STobias Grosser   ///
512aaabbbf8STobias Grosser   /// @param Array The array for which to compute the offset.
513aaabbbf8STobias Grosser   /// @returns An llvm::Value that contains the offset of the array.
514aaabbbf8STobias Grosser   Value *getArrayOffset(gpu_array_info *Array);
515aaabbbf8STobias Grosser 
51600bb5a99STobias Grosser   /// Prepare the kernel arguments for kernel code generation
51700bb5a99STobias Grosser   ///
51800bb5a99STobias Grosser   /// @param Kernel The kernel to generate code for.
51900bb5a99STobias Grosser   /// @param FN     The function created for the kernel.
52000bb5a99STobias Grosser   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
52100bb5a99STobias Grosser 
52232837fe3STobias Grosser   /// Create kernel function.
52332837fe3STobias Grosser   ///
52432837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
52532837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
52632837fe3STobias Grosser   /// start block of this newly created function.
52732837fe3STobias Grosser   ///
52832837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
529edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
530f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by this
531f291c8d5SSiddharth Bhat   ///                         kernel.
532edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
533f291c8d5SSiddharth Bhat                             SetVector<Value *> &SubtreeValues,
534f291c8d5SSiddharth Bhat                             SetVector<Function *> &SubtreeFunctions);
53532837fe3STobias Grosser 
53632837fe3STobias Grosser   /// Create the declaration of a kernel function.
53732837fe3STobias Grosser   ///
53832837fe3STobias Grosser   /// The kernel function takes as arguments:
53932837fe3STobias Grosser   ///
54032837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
541f6044bd0STobias Grosser   ///   - Host iterators
542c84a1995STobias Grosser   ///   - Parameters
54332837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
54432837fe3STobias Grosser   ///
54532837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
546edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
547edb885cbSTobias Grosser   ///
54832837fe3STobias Grosser   /// @returns The newly declared function.
549edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
550edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
55132837fe3STobias Grosser 
552472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
553472f9654STobias Grosser   ///
554472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
555472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
556472f9654STobias Grosser 
5572f3073b5SPhilipp Schaad   /// Insert function calls to retrieve the SPIR group/local ids.
5582f3073b5SPhilipp Schaad   ///
5592f3073b5SPhilipp Schaad   /// @param The kernel to generate the function calls for.
5602f3073b5SPhilipp Schaad   void insertKernelCallsSPIR(ppcg_kernel *Kernel);
5612f3073b5SPhilipp Schaad 
562f291c8d5SSiddharth Bhat   /// Setup the creation of functions referenced by the GPU kernel.
563f291c8d5SSiddharth Bhat   ///
564f291c8d5SSiddharth Bhat   /// 1. Create new function declarations in GPUModule which are the same as
565f291c8d5SSiddharth Bhat   /// SubtreeFunctions.
566f291c8d5SSiddharth Bhat   ///
567f291c8d5SSiddharth Bhat   /// 2. Populate IslNodeBuilder::ValueMap with mappings from
568f291c8d5SSiddharth Bhat   /// old functions (that come from the original module) to new functions
569f291c8d5SSiddharth Bhat   /// (that are created within GPUModule). That way, we generate references
570f291c8d5SSiddharth Bhat   /// to the correct function (in GPUModule) in BlockGenerator.
571f291c8d5SSiddharth Bhat   ///
572f291c8d5SSiddharth Bhat   /// @see IslNodeBuilder::ValueMap
573f291c8d5SSiddharth Bhat   /// @see BlockGenerator::GlobalMap
574f291c8d5SSiddharth Bhat   /// @see BlockGenerator::getNewValue
575f291c8d5SSiddharth Bhat   /// @see GPUNodeBuilder::getReferencesInKernel.
576f291c8d5SSiddharth Bhat   ///
577f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by
578f291c8d5SSiddharth Bhat   ///                         this kernel.
579f291c8d5SSiddharth Bhat   void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions);
580f291c8d5SSiddharth Bhat 
581b513b491STobias Grosser   /// Create a global-to-shared or shared-to-global copy statement.
582b513b491STobias Grosser   ///
583b513b491STobias Grosser   /// @param CopyStmt The copy statement to generate code for
584b513b491STobias Grosser   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
585b513b491STobias Grosser 
586edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
587edb885cbSTobias Grosser   ///
588edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
589edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
590edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
591edb885cbSTobias Grosser 
5925260c041STobias Grosser   /// Create an in-kernel synchronization call.
5935260c041STobias Grosser   void createKernelSync();
5945260c041STobias Grosser 
59574dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
59674dc3cb4STobias Grosser   ///
59774dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
59874dc3cb4STobias Grosser   std::string createKernelASM();
59974dc3cb4STobias Grosser 
60074dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
60174dc3cb4STobias Grosser   ///
60274dc3cb4STobias Grosser   /// @param F The function to remove references to.
60374dc3cb4STobias Grosser   void clearDominators(Function *F);
60474dc3cb4STobias Grosser 
60574dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
60674dc3cb4STobias Grosser   ///
60774dc3cb4STobias Grosser   /// @param F The function to remove references to.
60874dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
60974dc3cb4STobias Grosser 
61074dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
61174dc3cb4STobias Grosser   ///
61274dc3cb4STobias Grosser   /// @param F The function to remove references to.
61374dc3cb4STobias Grosser   void clearLoops(Function *F);
61474dc3cb4STobias Grosser 
6158fc6cdfbSTobias Grosser   /// Check if the scop requires to be linked with CUDA's libdevice.
6168fc6cdfbSTobias Grosser   bool requiresCUDALibDevice();
6178fc6cdfbSTobias Grosser 
6188fc6cdfbSTobias Grosser   /// Link with the NVIDIA libdevice library (if needed and available).
6198fc6cdfbSTobias Grosser   void addCUDALibDevice();
6208fc6cdfbSTobias Grosser 
62132837fe3STobias Grosser   /// Finalize the generation of the kernel function.
62232837fe3STobias Grosser   ///
62332837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
62432837fe3STobias Grosser   /// dump its IR to stderr.
62557793596STobias Grosser   ///
62657793596STobias Grosser   /// @returns The Assembly string of the kernel.
62757793596STobias Grosser   std::string finalizeKernelFunction();
628fa7b0802STobias Grosser 
62951dfc275STobias Grosser   /// Finalize the generation of the kernel arguments.
63051dfc275STobias Grosser   ///
63151dfc275STobias Grosser   /// This function ensures that not-read-only scalars used in a kernel are
632a6d48f59SMichael Kruse   /// stored back to the global memory location they are backed with before
63351dfc275STobias Grosser   /// the kernel terminates.
63451dfc275STobias Grosser   ///
63551dfc275STobias Grosser   /// @params Kernel The kernel to finalize kernel arguments for.
63651dfc275STobias Grosser   void finalizeKernelArguments(ppcg_kernel *Kernel);
63751dfc275STobias Grosser 
6387287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
639fa7b0802STobias Grosser   void allocateDeviceArrays();
640fa7b0802STobias Grosser 
6417287aeddSTobias Grosser   /// Free all allocated device arrays.
6427287aeddSTobias Grosser   void freeDeviceArrays();
6437287aeddSTobias Grosser 
644fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
645fa7b0802STobias Grosser   ///
646fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
647fa7b0802STobias Grosser   Value *createCallInitContext();
648fa7b0802STobias Grosser 
64979a947c2STobias Grosser   /// Create a call to get the device pointer for a kernel allocation.
65079a947c2STobias Grosser   ///
65179a947c2STobias Grosser   /// @param Allocation The Polly GPU allocation
65279a947c2STobias Grosser   ///
65379a947c2STobias Grosser   /// @returns The device parameter corresponding to this allocation.
65479a947c2STobias Grosser   Value *createCallGetDevicePtr(Value *Allocation);
65579a947c2STobias Grosser 
656fa7b0802STobias Grosser   /// Create a call to free the GPU context.
657fa7b0802STobias Grosser   ///
658fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
659fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
660fa7b0802STobias Grosser 
6617287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
6627287aeddSTobias Grosser   ///
6637287aeddSTobias Grosser   /// @param Size The size of memory to allocate
6647287aeddSTobias Grosser   ///
6657287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
666fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
6677287aeddSTobias Grosser 
6687287aeddSTobias Grosser   /// Create a call to free a device array.
6697287aeddSTobias Grosser   ///
6707287aeddSTobias Grosser   /// @param Array The device array to free.
6717287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
67213c78e4dSTobias Grosser 
67313c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
67413c78e4dSTobias Grosser   ///
67513c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
67613c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
67713c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
67813c78e4dSTobias Grosser                                       Value *Size);
67913c78e4dSTobias Grosser 
68013c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
68113c78e4dSTobias Grosser   ///
68213c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
68313c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
68413c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
68513c78e4dSTobias Grosser                                       Value *Size);
68657793596STobias Grosser 
687abed4969SSiddharth Bhat   /// Create a call to synchronize Host & Device.
688abed4969SSiddharth Bhat   /// \note
689abed4969SSiddharth Bhat   /// This is to be used only with managed memory.
690abed4969SSiddharth Bhat   void createCallSynchronizeDevice();
691abed4969SSiddharth Bhat 
69257793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
69357793596STobias Grosser   ///
69457793596STobias Grosser   /// @param Buffer The string describing the kernel.
69557793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
69657793596STobias Grosser   ///
69757793596STobias Grosser   /// @returns A pointer to a kernel object
69857793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
69957793596STobias Grosser 
70057793596STobias Grosser   /// Create a call to free a GPU kernel.
70157793596STobias Grosser   ///
70257793596STobias Grosser   /// @param GPUKernel THe kernel to free.
70357793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
70479a947c2STobias Grosser 
70579a947c2STobias Grosser   /// Create a call to launch a GPU kernel.
70679a947c2STobias Grosser   ///
70779a947c2STobias Grosser   /// @param GPUKernel  The kernel to launch.
70879a947c2STobias Grosser   /// @param GridDimX   The size of the first grid dimension.
70979a947c2STobias Grosser   /// @param GridDimY   The size of the second grid dimension.
71079a947c2STobias Grosser   /// @param GridBlockX The size of the first block dimension.
71179a947c2STobias Grosser   /// @param GridBlockY The size of the second block dimension.
71279a947c2STobias Grosser   /// @param GridBlockZ The size of the third block dimension.
713a6d48f59SMichael Kruse   /// @param Parameters A pointer to an array that contains itself pointers to
71479a947c2STobias Grosser   ///                   the parameter values passed for each kernel argument.
71579a947c2STobias Grosser   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
71679a947c2STobias Grosser                               Value *GridDimY, Value *BlockDimX,
71779a947c2STobias Grosser                               Value *BlockDimY, Value *BlockDimZ,
71879a947c2STobias Grosser                               Value *Parameters);
7191fb9b64dSTobias Grosser };
7201fb9b64dSTobias Grosser 
72179f13b9aSSingapuram Sanjay Srivallabh std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) {
7221abd9ffaSSingapuram Sanjay Srivallabh   return "FUNC_" + S.getFunction().getName().str() + "_SCOP_" +
7231abd9ffaSSingapuram Sanjay Srivallabh          std::to_string(S.getID()) + "_KERNEL_" + std::to_string(Kernel_id);
72479f13b9aSSingapuram Sanjay Srivallabh }
72579f13b9aSSingapuram Sanjay Srivallabh 
726fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
727750160e2STobias Grosser   BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(),
728750160e2STobias Grosser                                  &*Builder.GetInsertPoint(), &DT, &LI);
729750160e2STobias Grosser   NewBB->setName("polly.acc.initialize");
730750160e2STobias Grosser   Builder.SetInsertPoint(&NewBB->front());
731750160e2STobias Grosser 
732fa7b0802STobias Grosser   GPUContext = createCallInitContext();
733abed4969SSiddharth Bhat 
734abed4969SSiddharth Bhat   if (!ManagedMemory)
735fa7b0802STobias Grosser     allocateDeviceArrays();
736fa7b0802STobias Grosser }
737fa7b0802STobias Grosser 
738fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
739abed4969SSiddharth Bhat   if (!ManagedMemory)
7407287aeddSTobias Grosser     freeDeviceArrays();
741abed4969SSiddharth Bhat 
742fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
743fa7b0802STobias Grosser   IslNodeBuilder::finalize();
744fa7b0802STobias Grosser }
745fa7b0802STobias Grosser 
746fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
747abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory will directly send host pointers "
748abed4969SSiddharth Bhat                            "to the kernel. There is no need for device arrays");
749fa7b0802STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
750fa7b0802STobias Grosser 
751fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
752fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
75313c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
7547287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
7557287aeddSTobias Grosser     DevArrayName.append(Array->name);
756fa7b0802STobias Grosser 
75713c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
758aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(Array);
759aaabbbf8STobias Grosser     if (Offset)
760aaabbbf8STobias Grosser       ArraySize = Builder.CreateSub(
761aaabbbf8STobias Grosser           ArraySize,
762aaabbbf8STobias Grosser           Builder.CreateMul(Offset,
763aaabbbf8STobias Grosser                             Builder.getInt64(ScopArray->getElemSizeInBytes())));
7647287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
7657287aeddSTobias Grosser     DevArray->setName(DevArrayName);
76613c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
767fa7b0802STobias Grosser   }
768fa7b0802STobias Grosser 
769fa7b0802STobias Grosser   isl_ast_build_free(Build);
770fa7b0802STobias Grosser }
771fa7b0802STobias Grosser 
772c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX,
773c1c6a2a6STobias Grosser                                         Value *BlockDimY, Value *BlockDimZ) {
774c1c6a2a6STobias Grosser   auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations");
775c1c6a2a6STobias Grosser 
776c1c6a2a6STobias Grosser   for (auto &F : *M) {
777c1c6a2a6STobias Grosser     if (F.getCallingConv() != CallingConv::PTX_Kernel)
778c1c6a2a6STobias Grosser       continue;
779c1c6a2a6STobias Grosser 
780c1c6a2a6STobias Grosser     Value *V[] = {BlockDimX, BlockDimY, BlockDimZ};
781c1c6a2a6STobias Grosser 
782c1c6a2a6STobias Grosser     Metadata *Elements[] = {
783c1c6a2a6STobias Grosser         ValueAsMetadata::get(&F),   MDString::get(M->getContext(), "maxntidx"),
784c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"),
785c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"),
786c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[2]),
787c1c6a2a6STobias Grosser     };
788c1c6a2a6STobias Grosser     MDNode *Node = MDNode::get(M->getContext(), Elements);
789c1c6a2a6STobias Grosser     AnnotationNode->addOperand(Node);
790c1c6a2a6STobias Grosser   }
791c1c6a2a6STobias Grosser }
792c1c6a2a6STobias Grosser 
7937287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
794abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not use device arrays");
79513c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
79613c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
7977287aeddSTobias Grosser }
7987287aeddSTobias Grosser 
79957793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
80057793596STobias Grosser   const char *Name = "polly_getKernel";
80157793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
80257793596STobias Grosser   Function *F = M->getFunction(Name);
80357793596STobias Grosser 
80457793596STobias Grosser   // If F is not available, declare it.
80557793596STobias Grosser   if (!F) {
80657793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
80757793596STobias Grosser     std::vector<Type *> Args;
80857793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
80957793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
81057793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
81157793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
81257793596STobias Grosser   }
81357793596STobias Grosser 
81457793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
81557793596STobias Grosser }
81657793596STobias Grosser 
81779a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
81879a947c2STobias Grosser   const char *Name = "polly_getDevicePtr";
81979a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
82079a947c2STobias Grosser   Function *F = M->getFunction(Name);
82179a947c2STobias Grosser 
82279a947c2STobias Grosser   // If F is not available, declare it.
82379a947c2STobias Grosser   if (!F) {
82479a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
82579a947c2STobias Grosser     std::vector<Type *> Args;
82679a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
82779a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
82879a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
82979a947c2STobias Grosser   }
83079a947c2STobias Grosser 
83179a947c2STobias Grosser   return Builder.CreateCall(F, {Allocation});
83279a947c2STobias Grosser }
83379a947c2STobias Grosser 
83479a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
83579a947c2STobias Grosser                                             Value *GridDimY, Value *BlockDimX,
83679a947c2STobias Grosser                                             Value *BlockDimY, Value *BlockDimZ,
83779a947c2STobias Grosser                                             Value *Parameters) {
83879a947c2STobias Grosser   const char *Name = "polly_launchKernel";
83979a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
84079a947c2STobias Grosser   Function *F = M->getFunction(Name);
84179a947c2STobias Grosser 
84279a947c2STobias Grosser   // If F is not available, declare it.
84379a947c2STobias Grosser   if (!F) {
84479a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
84579a947c2STobias Grosser     std::vector<Type *> Args;
84679a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
84779a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
84879a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
84979a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
85079a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
85179a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
85279a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
85379a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
85479a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
85579a947c2STobias Grosser   }
85679a947c2STobias Grosser 
857ff40087aSTobias Grosser   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
85879a947c2STobias Grosser                          BlockDimZ, Parameters});
85979a947c2STobias Grosser }
86079a947c2STobias Grosser 
86157793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
86257793596STobias Grosser   const char *Name = "polly_freeKernel";
86357793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
86457793596STobias Grosser   Function *F = M->getFunction(Name);
86557793596STobias Grosser 
86657793596STobias Grosser   // If F is not available, declare it.
86757793596STobias Grosser   if (!F) {
86857793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
86957793596STobias Grosser     std::vector<Type *> Args;
87057793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
87157793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
87257793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
87357793596STobias Grosser   }
87457793596STobias Grosser 
87557793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
87657793596STobias Grosser }
87757793596STobias Grosser 
8787287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
879abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not allocate or free memory "
880abed4969SSiddharth Bhat                            "for device");
8817287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
8827287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8837287aeddSTobias Grosser   Function *F = M->getFunction(Name);
8847287aeddSTobias Grosser 
8857287aeddSTobias Grosser   // If F is not available, declare it.
8867287aeddSTobias Grosser   if (!F) {
8877287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
8887287aeddSTobias Grosser     std::vector<Type *> Args;
8897287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
8907287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
8917287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
8927287aeddSTobias Grosser   }
8937287aeddSTobias Grosser 
8947287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
8957287aeddSTobias Grosser }
8967287aeddSTobias Grosser 
897fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
898abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not allocate or free memory "
899abed4969SSiddharth Bhat                            "for device");
900fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
901fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
902fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
903fa7b0802STobias Grosser 
904fa7b0802STobias Grosser   // If F is not available, declare it.
905fa7b0802STobias Grosser   if (!F) {
906fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
907fa7b0802STobias Grosser     std::vector<Type *> Args;
908fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
909fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
910fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
911fa7b0802STobias Grosser   }
912fa7b0802STobias Grosser 
913fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
914fa7b0802STobias Grosser }
915fa7b0802STobias Grosser 
91613c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
91713c78e4dSTobias Grosser                                                     Value *DeviceData,
91813c78e4dSTobias Grosser                                                     Value *Size) {
919abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not transfer memory between "
920abed4969SSiddharth Bhat                            "device and host");
92113c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
92213c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
92313c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
92413c78e4dSTobias Grosser 
92513c78e4dSTobias Grosser   // If F is not available, declare it.
92613c78e4dSTobias Grosser   if (!F) {
92713c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
92813c78e4dSTobias Grosser     std::vector<Type *> Args;
92913c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
93013c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
93113c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
93213c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
93313c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
93413c78e4dSTobias Grosser   }
93513c78e4dSTobias Grosser 
93613c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
93713c78e4dSTobias Grosser }
93813c78e4dSTobias Grosser 
93913c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
94013c78e4dSTobias Grosser                                                     Value *HostData,
94113c78e4dSTobias Grosser                                                     Value *Size) {
942abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not transfer memory between "
943abed4969SSiddharth Bhat                            "device and host");
94413c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
94513c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
94613c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
94713c78e4dSTobias Grosser 
94813c78e4dSTobias Grosser   // If F is not available, declare it.
94913c78e4dSTobias Grosser   if (!F) {
95013c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
95113c78e4dSTobias Grosser     std::vector<Type *> Args;
95213c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
95313c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
95413c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
95513c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
95613c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
95713c78e4dSTobias Grosser   }
95813c78e4dSTobias Grosser 
95913c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
96013c78e4dSTobias Grosser }
96113c78e4dSTobias Grosser 
962abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() {
963abed4969SSiddharth Bhat   assert(ManagedMemory && "explicit synchronization is only necessary for "
964abed4969SSiddharth Bhat                           "managed memory");
965abed4969SSiddharth Bhat   const char *Name = "polly_synchronizeDevice";
966abed4969SSiddharth Bhat   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
967abed4969SSiddharth Bhat   Function *F = M->getFunction(Name);
968abed4969SSiddharth Bhat 
969abed4969SSiddharth Bhat   // If F is not available, declare it.
970abed4969SSiddharth Bhat   if (!F) {
971abed4969SSiddharth Bhat     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
972abed4969SSiddharth Bhat     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
973abed4969SSiddharth Bhat     F = Function::Create(Ty, Linkage, Name, M);
974abed4969SSiddharth Bhat   }
975abed4969SSiddharth Bhat 
976abed4969SSiddharth Bhat   Builder.CreateCall(F);
977abed4969SSiddharth Bhat }
978abed4969SSiddharth Bhat 
979fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
98017f01968SSiddharth Bhat   const char *Name;
98117f01968SSiddharth Bhat 
98217f01968SSiddharth Bhat   switch (Runtime) {
98317f01968SSiddharth Bhat   case GPURuntime::CUDA:
98417f01968SSiddharth Bhat     Name = "polly_initContextCUDA";
98517f01968SSiddharth Bhat     break;
98617f01968SSiddharth Bhat   case GPURuntime::OpenCL:
98717f01968SSiddharth Bhat     Name = "polly_initContextCL";
98817f01968SSiddharth Bhat     break;
98917f01968SSiddharth Bhat   }
99017f01968SSiddharth Bhat 
991fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
992fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
993fa7b0802STobias Grosser 
994fa7b0802STobias Grosser   // If F is not available, declare it.
995fa7b0802STobias Grosser   if (!F) {
996fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
997fa7b0802STobias Grosser     std::vector<Type *> Args;
998fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
999fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
1000fa7b0802STobias Grosser   }
1001fa7b0802STobias Grosser 
1002fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
1003fa7b0802STobias Grosser }
1004fa7b0802STobias Grosser 
1005fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
1006fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
1007fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1008fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
1009fa7b0802STobias Grosser 
1010fa7b0802STobias Grosser   // If F is not available, declare it.
1011fa7b0802STobias Grosser   if (!F) {
1012fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1013fa7b0802STobias Grosser     std::vector<Type *> Args;
1014fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
1015fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
1016fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
1017fa7b0802STobias Grosser   }
1018fa7b0802STobias Grosser 
1019fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
1020fa7b0802STobias Grosser }
1021fa7b0802STobias Grosser 
10225260c041STobias Grosser /// Check if one string is a prefix of another.
10235260c041STobias Grosser ///
10245260c041STobias Grosser /// @param String The string in which to look for the prefix.
10255260c041STobias Grosser /// @param Prefix The prefix to look for.
10265260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
10275260c041STobias Grosser   return String.find(Prefix) == 0;
10285260c041STobias Grosser }
10295260c041STobias Grosser 
103013c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
1031f7face4bSSiddharth Bhat   isl::ast_build Build =
1032f7face4bSSiddharth Bhat       isl::ast_build::from_context(isl::manage(S.getContext()));
103313c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
103413c78e4dSTobias Grosser 
103513c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
1036f7face4bSSiddharth Bhat     isl::multi_pw_aff ArrayBound =
1037f7face4bSSiddharth Bhat         isl::manage(isl_multi_pw_aff_copy(Array->bound));
1038f7face4bSSiddharth Bhat 
1039f7face4bSSiddharth Bhat     isl::pw_aff OffsetDimZero = ArrayBound.get_pw_aff(0);
1040f7face4bSSiddharth Bhat     isl::ast_expr Res = Build.expr_from(OffsetDimZero);
104113c78e4dSTobias Grosser 
104213c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
1043f7face4bSSiddharth Bhat       isl::pw_aff Bound_I = ArrayBound.get_pw_aff(i);
1044f7face4bSSiddharth Bhat       isl::ast_expr Expr = Build.expr_from(Bound_I);
1045f7face4bSSiddharth Bhat       Res = Res.mul(Expr);
104613c78e4dSTobias Grosser     }
104713c78e4dSTobias Grosser 
1048f7face4bSSiddharth Bhat     Value *NumElements = ExprBuilder.create(Res.release());
1049b79f4d39STobias Grosser     if (NumElements->getType() != ArraySize->getType())
1050b79f4d39STobias Grosser       NumElements = Builder.CreateSExt(NumElements, ArraySize->getType());
105113c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
105213c78e4dSTobias Grosser   }
105313c78e4dSTobias Grosser   return ArraySize;
105413c78e4dSTobias Grosser }
105513c78e4dSTobias Grosser 
1056aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) {
1057aaabbbf8STobias Grosser   if (gpu_array_is_scalar(Array))
1058aaabbbf8STobias Grosser     return nullptr;
1059aaabbbf8STobias Grosser 
1060ccbf4b50SSiddharth Bhat   isl::ast_build Build =
1061ccbf4b50SSiddharth Bhat       isl::ast_build::from_context(isl::manage(S.getContext()));
1062aaabbbf8STobias Grosser 
1063ccbf4b50SSiddharth Bhat   isl::set Min = isl::manage(isl_set_copy(Array->extent)).lexmin();
1064aaabbbf8STobias Grosser 
1065ccbf4b50SSiddharth Bhat   isl::set ZeroSet = isl::set::universe(Min.get_space());
1066aaabbbf8STobias Grosser 
1067ccbf4b50SSiddharth Bhat   for (long i = 0; i < Min.dim(isl::dim::set); i++)
1068ccbf4b50SSiddharth Bhat     ZeroSet = ZeroSet.fix_si(isl::dim::set, i, 0);
1069aaabbbf8STobias Grosser 
1070ccbf4b50SSiddharth Bhat   if (Min.is_subset(ZeroSet)) {
1071aaabbbf8STobias Grosser     return nullptr;
1072aaabbbf8STobias Grosser   }
1073aaabbbf8STobias Grosser 
1074ccbf4b50SSiddharth Bhat   isl::ast_expr Result = isl::ast_expr::from_val(isl::val(Min.get_ctx(), 0));
1075aaabbbf8STobias Grosser 
1076ccbf4b50SSiddharth Bhat   for (long i = 0; i < Min.dim(isl::dim::set); i++) {
1077aaabbbf8STobias Grosser     if (i > 0) {
1078ccbf4b50SSiddharth Bhat       isl::pw_aff Bound_I =
1079ccbf4b50SSiddharth Bhat           isl::manage(isl_multi_pw_aff_get_pw_aff(Array->bound, i - 1));
1080ccbf4b50SSiddharth Bhat       isl::ast_expr BExpr = Build.expr_from(Bound_I);
1081ccbf4b50SSiddharth Bhat       Result = Result.mul(BExpr);
1082aaabbbf8STobias Grosser     }
1083ccbf4b50SSiddharth Bhat     isl::pw_aff DimMin = Min.dim_min(i);
1084ccbf4b50SSiddharth Bhat     isl::ast_expr MExpr = Build.expr_from(DimMin);
1085ccbf4b50SSiddharth Bhat     Result = Result.add(MExpr);
1086aaabbbf8STobias Grosser   }
1087aaabbbf8STobias Grosser 
1088ccbf4b50SSiddharth Bhat   return ExprBuilder.create(Result.release());
1089aaabbbf8STobias Grosser }
1090aaabbbf8STobias Grosser 
1091abed4969SSiddharth Bhat Value *GPUNodeBuilder::getOrCreateManagedDeviceArray(gpu_array_info *Array,
1092abed4969SSiddharth Bhat                                                      ScopArrayInfo *ArrayInfo) {
1093abed4969SSiddharth Bhat 
1094abed4969SSiddharth Bhat   assert(ManagedMemory && "Only used when you wish to get a host "
1095abed4969SSiddharth Bhat                           "pointer for sending data to the kernel, "
1096abed4969SSiddharth Bhat                           "with managed memory");
1097abed4969SSiddharth Bhat   std::map<ScopArrayInfo *, Value *>::iterator it;
1098abed4969SSiddharth Bhat   if ((it = DeviceAllocations.find(ArrayInfo)) != DeviceAllocations.end()) {
1099abed4969SSiddharth Bhat     return it->second;
1100abed4969SSiddharth Bhat   } else {
1101abed4969SSiddharth Bhat     Value *HostPtr;
1102abed4969SSiddharth Bhat 
1103abed4969SSiddharth Bhat     if (gpu_array_is_scalar(Array))
1104abed4969SSiddharth Bhat       HostPtr = BlockGen.getOrCreateAlloca(ArrayInfo);
1105abed4969SSiddharth Bhat     else
1106abed4969SSiddharth Bhat       HostPtr = ArrayInfo->getBasePtr();
1107abed4969SSiddharth Bhat 
1108abed4969SSiddharth Bhat     Value *Offset = getArrayOffset(Array);
1109abed4969SSiddharth Bhat     if (Offset) {
1110abed4969SSiddharth Bhat       HostPtr = Builder.CreatePointerCast(
1111abed4969SSiddharth Bhat           HostPtr, ArrayInfo->getElementType()->getPointerTo());
1112abed4969SSiddharth Bhat       HostPtr = Builder.CreateGEP(HostPtr, Offset);
1113abed4969SSiddharth Bhat     }
1114abed4969SSiddharth Bhat 
1115abed4969SSiddharth Bhat     HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
1116abed4969SSiddharth Bhat     DeviceAllocations[ArrayInfo] = HostPtr;
1117abed4969SSiddharth Bhat     return HostPtr;
1118abed4969SSiddharth Bhat   }
1119abed4969SSiddharth Bhat }
1120abed4969SSiddharth Bhat 
112113c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
112213c78e4dSTobias Grosser                                         enum DataDirection Direction) {
1123abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory needs no data transfers");
112413c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
112513c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
112613c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
112713c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
112813c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
112913c78e4dSTobias Grosser 
113013c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
1131aaabbbf8STobias Grosser   Value *Offset = getArrayOffset(Array);
113213c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
113313c78e4dSTobias Grosser 
1134b06ff457STobias Grosser   Value *HostPtr;
1135b06ff457STobias Grosser 
1136b06ff457STobias Grosser   if (gpu_array_is_scalar(Array))
1137b06ff457STobias Grosser     HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
1138b06ff457STobias Grosser   else
1139b06ff457STobias Grosser     HostPtr = ScopArray->getBasePtr();
114013c78e4dSTobias Grosser 
1141aaabbbf8STobias Grosser   if (Offset) {
1142aaabbbf8STobias Grosser     HostPtr = Builder.CreatePointerCast(
1143aaabbbf8STobias Grosser         HostPtr, ScopArray->getElementType()->getPointerTo());
1144aaabbbf8STobias Grosser     HostPtr = Builder.CreateGEP(HostPtr, Offset);
1145aaabbbf8STobias Grosser   }
1146aaabbbf8STobias Grosser 
114713c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
114813c78e4dSTobias Grosser 
1149aaabbbf8STobias Grosser   if (Offset) {
1150aaabbbf8STobias Grosser     Size = Builder.CreateSub(
1151ff40087aSTobias Grosser         Size, Builder.CreateMul(
1152ff40087aSTobias Grosser                   Offset, Builder.getInt64(ScopArray->getElemSizeInBytes())));
1153aaabbbf8STobias Grosser   }
1154aaabbbf8STobias Grosser 
115513c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
115613c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
115713c78e4dSTobias Grosser   else
115813c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
115913c78e4dSTobias Grosser 
116013c78e4dSTobias Grosser   isl_id_free(Id);
116113c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
116213c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
116313c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
116413c78e4dSTobias Grosser }
116513c78e4dSTobias Grosser 
11661fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
116732837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
116832837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
116932837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
117032837fe3STobias Grosser   isl_id_free(Id);
117132837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
117232837fe3STobias Grosser 
117332837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
117432837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
117532837fe3STobias Grosser     createKernel(UserStmt);
117632837fe3STobias Grosser     isl_ast_expr_free(Expr);
117732837fe3STobias Grosser     return;
117832837fe3STobias Grosser   }
11799e3db2b7SSiddharth Bhat   if (!strcmp(Str, "init_device")) {
11809e3db2b7SSiddharth Bhat     initializeAfterRTH();
11819e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
11829e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
11839e3db2b7SSiddharth Bhat     return;
11849e3db2b7SSiddharth Bhat   }
11859e3db2b7SSiddharth Bhat   if (!strcmp(Str, "clear_device")) {
11869e3db2b7SSiddharth Bhat     finalize();
11879e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
11889e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
11899e3db2b7SSiddharth Bhat     return;
11909e3db2b7SSiddharth Bhat   }
119113c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
1192abed4969SSiddharth Bhat     if (!ManagedMemory)
119313c78e4dSTobias Grosser       createDataTransfer(UserStmt, HOST_TO_DEVICE);
1194abed4969SSiddharth Bhat     else
1195abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1196abed4969SSiddharth Bhat 
119732837fe3STobias Grosser     isl_ast_expr_free(Expr);
119813c78e4dSTobias Grosser     return;
119913c78e4dSTobias Grosser   }
120013c78e4dSTobias Grosser 
120113c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
1202abed4969SSiddharth Bhat     if (!ManagedMemory) {
120313c78e4dSTobias Grosser       createDataTransfer(UserStmt, DEVICE_TO_HOST);
1204abed4969SSiddharth Bhat     } else {
1205abed4969SSiddharth Bhat       createCallSynchronizeDevice();
1206abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1207abed4969SSiddharth Bhat     }
120813c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
120938fc0aedSTobias Grosser     return;
121038fc0aedSTobias Grosser   }
121138fc0aedSTobias Grosser 
12125260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
12135260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
12145260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
12155260c041STobias Grosser   isl_id_free(Anno);
12165260c041STobias Grosser 
12175260c041STobias Grosser   switch (KernelStmt->type) {
12185260c041STobias Grosser   case ppcg_kernel_domain:
1219edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
12205260c041STobias Grosser     isl_ast_node_free(UserStmt);
12215260c041STobias Grosser     return;
12225260c041STobias Grosser   case ppcg_kernel_copy:
1223b513b491STobias Grosser     createKernelCopy(KernelStmt);
12245260c041STobias Grosser     isl_ast_expr_free(Expr);
12255260c041STobias Grosser     isl_ast_node_free(UserStmt);
12265260c041STobias Grosser     return;
12275260c041STobias Grosser   case ppcg_kernel_sync:
12285260c041STobias Grosser     createKernelSync();
12295260c041STobias Grosser     isl_ast_expr_free(Expr);
12305260c041STobias Grosser     isl_ast_node_free(UserStmt);
12315260c041STobias Grosser     return;
12325260c041STobias Grosser   }
12335260c041STobias Grosser 
12345260c041STobias Grosser   isl_ast_expr_free(Expr);
12355260c041STobias Grosser   isl_ast_node_free(UserStmt);
12365260c041STobias Grosser   return;
12375260c041STobias Grosser }
1238b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
1239b513b491STobias Grosser   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
1240b513b491STobias Grosser   LocalIndex = isl_ast_expr_address_of(LocalIndex);
1241b513b491STobias Grosser   Value *LocalAddr = ExprBuilder.create(LocalIndex);
1242b513b491STobias Grosser   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
1243b513b491STobias Grosser   Index = isl_ast_expr_address_of(Index);
1244b513b491STobias Grosser   Value *GlobalAddr = ExprBuilder.create(Index);
1245b513b491STobias Grosser 
1246b513b491STobias Grosser   if (KernelStmt->u.c.read) {
1247b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read");
1248b513b491STobias Grosser     Builder.CreateStore(Load, LocalAddr);
1249b513b491STobias Grosser   } else {
1250b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write");
1251b513b491STobias Grosser     Builder.CreateStore(Load, GlobalAddr);
1252b513b491STobias Grosser   }
1253b513b491STobias Grosser }
12545260c041STobias Grosser 
1255edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
1256edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
1257edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1258edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
1259edb885cbSTobias Grosser 
1260edb885cbSTobias Grosser   LoopToScevMapT LTS;
1261edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
1262edb885cbSTobias Grosser 
1263edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
1264edb885cbSTobias Grosser 
1265edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
1266edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
1267edb885cbSTobias Grosser   else
1268a82c4b5dSTobias Grosser     RegionGen.copyStmt(*Stmt, LTS, Indexes);
1269edb885cbSTobias Grosser }
1270edb885cbSTobias Grosser 
12715260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
12725260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12732f3073b5SPhilipp Schaad   const char *SpirName = "__gen_ocl_barrier_global";
127417f01968SSiddharth Bhat 
127517f01968SSiddharth Bhat   Function *Sync;
127617f01968SSiddharth Bhat 
127717f01968SSiddharth Bhat   switch (Arch) {
12782f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
12792f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
12802f3073b5SPhilipp Schaad     Sync = M->getFunction(SpirName);
12812f3073b5SPhilipp Schaad 
12822f3073b5SPhilipp Schaad     // If Sync is not available, declare it.
12832f3073b5SPhilipp Schaad     if (!Sync) {
12842f3073b5SPhilipp Schaad       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
12852f3073b5SPhilipp Schaad       std::vector<Type *> Args;
12862f3073b5SPhilipp Schaad       FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
12872f3073b5SPhilipp Schaad       Sync = Function::Create(Ty, Linkage, SpirName, M);
12882f3073b5SPhilipp Schaad       Sync->setCallingConv(CallingConv::SPIR_FUNC);
12892f3073b5SPhilipp Schaad     }
12902f3073b5SPhilipp Schaad     break;
129117f01968SSiddharth Bhat   case GPUArch::NVPTX64:
129217f01968SSiddharth Bhat     Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
129317f01968SSiddharth Bhat     break;
129417f01968SSiddharth Bhat   }
129517f01968SSiddharth Bhat 
12965260c041STobias Grosser   Builder.CreateCall(Sync, {});
12975260c041STobias Grosser }
12985260c041STobias Grosser 
1299edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
1300edb885cbSTobias Grosser ///
1301edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
1302edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
1303edb885cbSTobias Grosser ///
1304edb885cbSTobias Grosser /// @param Node The node to collect references for.
1305edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
1306edb885cbSTobias Grosser ///
1307edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
1308edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
1309edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
1310edb885cbSTobias Grosser     return isl_bool_true;
1311edb885cbSTobias Grosser 
1312edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
1313edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
1314edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
1315edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
1316edb885cbSTobias Grosser   isl_id_free(Id);
1317edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
1318edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
1319edb885cbSTobias Grosser 
1320edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
1321edb885cbSTobias Grosser     return isl_bool_true;
1322edb885cbSTobias Grosser 
1323edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
1324edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
1325edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1326edb885cbSTobias Grosser   isl_id_free(Id);
1327edb885cbSTobias Grosser 
132800bb5a99STobias Grosser   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
1329edb885cbSTobias Grosser 
1330edb885cbSTobias Grosser   return isl_bool_true;
1331edb885cbSTobias Grosser }
1332edb885cbSTobias Grosser 
13338fc6cdfbSTobias Grosser /// A list of functions that are available in NVIDIA's libdevice.
13348fc6cdfbSTobias Grosser const std::set<std::string> CUDALibDeviceFunctions = {
13358fc6cdfbSTobias Grosser     "exp",  "expf",  "expl",     "cos",       "cosf",
13368fc6cdfbSTobias Grosser     "sqrt", "sqrtf", "copysign", "copysignf", "copysignl"};
13378fc6cdfbSTobias Grosser 
13388fc6cdfbSTobias Grosser /// Return the corresponding CUDA libdevice function name for @p F.
13398fc6cdfbSTobias Grosser ///
13408fc6cdfbSTobias Grosser /// Return "" if we are not compiling for CUDA.
13418fc6cdfbSTobias Grosser std::string getCUDALibDeviceFuntion(Function *F) {
13428fc6cdfbSTobias Grosser   if (CUDALibDeviceFunctions.count(F->getName()))
13438fc6cdfbSTobias Grosser     return std::string("__nv_") + std::string(F->getName());
13448fc6cdfbSTobias Grosser 
13458fc6cdfbSTobias Grosser   return "";
13468fc6cdfbSTobias Grosser }
13478fc6cdfbSTobias Grosser 
1348f291c8d5SSiddharth Bhat /// Check if F is a function that we can code-generate in a GPU kernel.
13498fc6cdfbSTobias Grosser static bool isValidFunctionInKernel(llvm::Function *F, bool AllowLibDevice) {
1350f291c8d5SSiddharth Bhat   assert(F && "F is an invalid pointer");
1351f291c8d5SSiddharth Bhat   // We string compare against the name of the function to allow
135254491db6STobias Grosser   // all variants of the intrinsic "llvm.sqrt.*", "llvm.fabs", and
135354491db6STobias Grosser   // "llvm.copysign".
135454491db6STobias Grosser   const StringRef Name = F->getName();
13558fc6cdfbSTobias Grosser 
13568fc6cdfbSTobias Grosser   if (AllowLibDevice && getCUDALibDeviceFuntion(F).length() > 0)
13578fc6cdfbSTobias Grosser     return true;
13588fc6cdfbSTobias Grosser 
135954491db6STobias Grosser   return F->isIntrinsic() &&
136054491db6STobias Grosser          (Name.startswith("llvm.sqrt") || Name.startswith("llvm.fabs") ||
136154491db6STobias Grosser           Name.startswith("llvm.copysign"));
1362f291c8d5SSiddharth Bhat }
1363f291c8d5SSiddharth Bhat 
1364f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value.
1365f291c8d5SSiddharth Bhat ///
1366f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along
1367f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and
1368f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not
1369f291c8d5SSiddharth Bhat /// `Function`s.
1370f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); }
1371f291c8d5SSiddharth Bhat 
1372f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`.
1373f291c8d5SSiddharth Bhat static SetVector<Function *>
13748fc6cdfbSTobias Grosser getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues,
13758fc6cdfbSTobias Grosser                                  bool AllowCUDALibDevice) {
1376f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1377f291c8d5SSiddharth Bhat   for (Value *It : RawSubtreeValues) {
1378f291c8d5SSiddharth Bhat     Function *F = dyn_cast<Function>(It);
1379f291c8d5SSiddharth Bhat     if (F) {
13808fc6cdfbSTobias Grosser       assert(isValidFunctionInKernel(F, AllowCUDALibDevice) &&
13818fc6cdfbSTobias Grosser              "Code should have bailed out by "
1382f291c8d5SSiddharth Bhat              "this point if an invalid function "
1383f291c8d5SSiddharth Bhat              "were present in a kernel.");
1384f291c8d5SSiddharth Bhat       SubtreeFunctions.insert(F);
1385f291c8d5SSiddharth Bhat     }
1386f291c8d5SSiddharth Bhat   }
1387f291c8d5SSiddharth Bhat   return SubtreeFunctions;
1388f291c8d5SSiddharth Bhat }
1389f291c8d5SSiddharth Bhat 
1390f291c8d5SSiddharth Bhat std::pair<SetVector<Value *>, SetVector<Function *>>
1391f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
1392edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
1393edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
1394edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1395edb885cbSTobias Grosser   SubtreeReferences References = {
1396edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
1397edb885cbSTobias Grosser 
1398edb885cbSTobias Grosser   for (const auto &I : IDToValue)
1399edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
1400edb885cbSTobias Grosser 
1401edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
1402edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
1403edb885cbSTobias Grosser 
1404edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
1405edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
1406edb885cbSTobias Grosser 
1407edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
1408d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
1409edb885cbSTobias Grosser 
1410edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
1411edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1412edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
1413edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1414edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1415edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1416edb885cbSTobias Grosser     isl_id_free(Id);
1417edb885cbSTobias Grosser   }
1418edb885cbSTobias Grosser   isl_space_free(Space);
1419edb885cbSTobias Grosser 
1420edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
1421edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1422edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1423edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1424edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1425edb885cbSTobias Grosser     isl_id_free(Id);
1426edb885cbSTobias Grosser   }
1427edb885cbSTobias Grosser 
1428f291c8d5SSiddharth Bhat   // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions
1429f291c8d5SSiddharth Bhat   // SubtreeValues. This is important, because we should not lose any
1430f291c8d5SSiddharth Bhat   // SubtreeValues in the process of constructing the
1431f291c8d5SSiddharth Bhat   // "ValidSubtree{Values, Functions} sets. Nor should the set
1432f291c8d5SSiddharth Bhat   // ValidSubtree{Values, Functions} have any common element.
1433f291c8d5SSiddharth Bhat   auto ValidSubtreeValuesIt =
1434f291c8d5SSiddharth Bhat       make_filter_range(SubtreeValues, isValidSubtreeValue);
1435f291c8d5SSiddharth Bhat   SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(),
1436f291c8d5SSiddharth Bhat                                         ValidSubtreeValuesIt.end());
14378fc6cdfbSTobias Grosser 
14388fc6cdfbSTobias Grosser   bool AllowCUDALibDevice = Arch == GPUArch::NVPTX64;
14398fc6cdfbSTobias Grosser 
1440f291c8d5SSiddharth Bhat   SetVector<Function *> ValidSubtreeFunctions(
14418fc6cdfbSTobias Grosser       getFunctionsFromRawSubtreeValues(SubtreeValues, AllowCUDALibDevice));
1442f291c8d5SSiddharth Bhat 
1443a1b2086aSSiddharth Bhat   // @see IslNodeBuilder::getReferencesInSubtree
1444a1b2086aSSiddharth Bhat   SetVector<Value *> ReplacedValues;
1445a1b2086aSSiddharth Bhat   for (Value *V : ValidSubtreeValues) {
1446a1b2086aSSiddharth Bhat     auto It = ValueMap.find(V);
1447a1b2086aSSiddharth Bhat     if (It == ValueMap.end())
1448a1b2086aSSiddharth Bhat       ReplacedValues.insert(V);
1449a1b2086aSSiddharth Bhat     else
1450a1b2086aSSiddharth Bhat       ReplacedValues.insert(It->second);
1451a1b2086aSSiddharth Bhat   }
1452a1b2086aSSiddharth Bhat   return std::make_pair(ReplacedValues, ValidSubtreeFunctions);
1453edb885cbSTobias Grosser }
1454edb885cbSTobias Grosser 
145574dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
145674dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
145774dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
145874dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
145974dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
146074dc3cb4STobias Grosser 
146174dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
146274dc3cb4STobias Grosser     DT.eraseNode(BB);
146374dc3cb4STobias Grosser }
146474dc3cb4STobias Grosser 
146574dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
146674dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
146774dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
146874dc3cb4STobias Grosser     if (L)
146974dc3cb4STobias Grosser       SE.forgetLoop(L);
147074dc3cb4STobias Grosser   }
147174dc3cb4STobias Grosser }
147274dc3cb4STobias Grosser 
147374dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
147474dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
147574dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
147674dc3cb4STobias Grosser     if (L)
147774dc3cb4STobias Grosser       SE.forgetLoop(L);
147874dc3cb4STobias Grosser     LI.removeBlock(&BB);
147974dc3cb4STobias Grosser   }
148074dc3cb4STobias Grosser }
148174dc3cb4STobias Grosser 
148279a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
148379a947c2STobias Grosser   std::vector<Value *> Sizes;
1484*4d5820d1SSiddharth Bhat   isl::ast_build Context =
1485*4d5820d1SSiddharth Bhat       isl::ast_build::from_context(isl::manage(S.getContext()));
148679a947c2STobias Grosser 
1487*4d5820d1SSiddharth Bhat   isl::multi_pw_aff GridSizePwAffs =
1488*4d5820d1SSiddharth Bhat       isl::manage(isl_multi_pw_aff_copy(Kernel->grid_size));
148979a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
1490*4d5820d1SSiddharth Bhat     isl::pw_aff Size = GridSizePwAffs.get_pw_aff(i);
1491*4d5820d1SSiddharth Bhat     isl::ast_expr GridSize = Context.expr_from(Size);
1492*4d5820d1SSiddharth Bhat     Value *Res = ExprBuilder.create(GridSize.release());
149379a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
149479a947c2STobias Grosser     Sizes.push_back(Res);
149579a947c2STobias Grosser   }
149679a947c2STobias Grosser 
149779a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
149879a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
149979a947c2STobias Grosser 
150079a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
150179a947c2STobias Grosser }
150279a947c2STobias Grosser 
150379a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
150479a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
150579a947c2STobias Grosser   std::vector<Value *> Sizes;
150679a947c2STobias Grosser 
150779a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
150879a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
150979a947c2STobias Grosser     Sizes.push_back(Res);
151079a947c2STobias Grosser   }
151179a947c2STobias Grosser 
151279a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
151379a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
151479a947c2STobias Grosser 
151579a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
151679a947c2STobias Grosser }
151779a947c2STobias Grosser 
1518a90be207SSiddharth Bhat void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters,
1519a90be207SSiddharth Bhat                                           Instruction *Param, int Index) {
1520a90be207SSiddharth Bhat   Value *Slot = Builder.CreateGEP(
1521a90be207SSiddharth Bhat       Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1522a90be207SSiddharth Bhat   Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1523a90be207SSiddharth Bhat   Builder.CreateStore(ParamTyped, Slot);
1524a90be207SSiddharth Bhat }
1525a90be207SSiddharth Bhat 
152657693272STobias Grosser Value *
152757693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
152857693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
1529a90be207SSiddharth Bhat   const int NumArgs = F->arg_size();
1530a90be207SSiddharth Bhat   std::vector<int> ArgSizes(NumArgs);
1531a90be207SSiddharth Bhat 
1532a90be207SSiddharth Bhat   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs);
153379a947c2STobias Grosser 
153479a947c2STobias Grosser   BasicBlock *EntryBlock =
153579a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
153667726b32STobias Grosser   auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace();
153779a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
153867726b32STobias Grosser   Instruction *Parameters = new AllocaInst(
153967726b32STobias Grosser       ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator());
154079a947c2STobias Grosser 
154179a947c2STobias Grosser   int Index = 0;
154279a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
154379a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
154479a947c2STobias Grosser       continue;
154579a947c2STobias Grosser 
154679a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1547206e9e3bSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
154879a947c2STobias Grosser 
1549a90be207SSiddharth Bhat     ArgSizes[Index] = SAI->getElemSizeInBytes();
1550a90be207SSiddharth Bhat 
1551abed4969SSiddharth Bhat     Value *DevArray = nullptr;
1552abed4969SSiddharth Bhat     if (ManagedMemory) {
1553abed4969SSiddharth Bhat       DevArray = getOrCreateManagedDeviceArray(
1554abed4969SSiddharth Bhat           &Prog->array[i], const_cast<ScopArrayInfo *>(SAI));
1555abed4969SSiddharth Bhat     } else {
1556abed4969SSiddharth Bhat       DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
155779a947c2STobias Grosser       DevArray = createCallGetDevicePtr(DevArray);
1558abed4969SSiddharth Bhat     }
1559abed4969SSiddharth Bhat     assert(DevArray != nullptr && "Array to be offloaded to device not "
1560abed4969SSiddharth Bhat                                   "initialized");
1561aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(&Prog->array[i]);
1562aaabbbf8STobias Grosser 
1563aaabbbf8STobias Grosser     if (Offset) {
1564aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(
1565aaabbbf8STobias Grosser           DevArray, SAI->getElementType()->getPointerTo());
1566aaabbbf8STobias Grosser       DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset));
1567aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1568aaabbbf8STobias Grosser     }
1569fe74a7a1STobias Grosser     Value *Slot = Builder.CreateGEP(
1570fe74a7a1STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1571aaabbbf8STobias Grosser 
1572fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1573abed4969SSiddharth Bhat       Value *ValPtr = nullptr;
1574abed4969SSiddharth Bhat       if (ManagedMemory)
1575abed4969SSiddharth Bhat         ValPtr = DevArray;
1576abed4969SSiddharth Bhat       else
1577abed4969SSiddharth Bhat         ValPtr = BlockGen.getOrCreateAlloca(SAI);
1578abed4969SSiddharth Bhat 
1579abed4969SSiddharth Bhat       assert(ValPtr != nullptr && "ValPtr that should point to a valid object"
1580abed4969SSiddharth Bhat                                   " to be stored into Parameters");
1581fe74a7a1STobias Grosser       Value *ValPtrCast =
1582fe74a7a1STobias Grosser           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1583fe74a7a1STobias Grosser       Builder.CreateStore(ValPtrCast, Slot);
1584fe74a7a1STobias Grosser     } else {
158567726b32STobias Grosser       Instruction *Param =
158667726b32STobias Grosser           new AllocaInst(Builder.getInt8PtrTy(), AddressSpace,
158767726b32STobias Grosser                          Launch + "_param_" + std::to_string(Index),
158879a947c2STobias Grosser                          EntryBlock->getTerminator());
158979a947c2STobias Grosser       Builder.CreateStore(DevArray, Param);
159079a947c2STobias Grosser       Value *ParamTyped =
159179a947c2STobias Grosser           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
159279a947c2STobias Grosser       Builder.CreateStore(ParamTyped, Slot);
1593fe74a7a1STobias Grosser     }
159479a947c2STobias Grosser     Index++;
159579a947c2STobias Grosser   }
159679a947c2STobias Grosser 
1597a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1598a490147cSTobias Grosser 
1599a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1600a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1601a490147cSTobias Grosser     Value *Val = IDToValue[Id];
1602a490147cSTobias Grosser     isl_id_free(Id);
1603a90be207SSiddharth Bhat 
1604a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1605a90be207SSiddharth Bhat 
160667726b32STobias Grosser     Instruction *Param =
160767726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
160867726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1609a490147cSTobias Grosser                        EntryBlock->getTerminator());
1610a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
1611a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1612a490147cSTobias Grosser     Index++;
1613a490147cSTobias Grosser   }
1614a490147cSTobias Grosser 
1615d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1616d8b94bcaSTobias Grosser 
1617d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
1618d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1619d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
1620a1b2086aSSiddharth Bhat     if (ValueMap.count(Val))
1621a1b2086aSSiddharth Bhat       Val = ValueMap[Val];
1622d8b94bcaSTobias Grosser     isl_id_free(Id);
1623a90be207SSiddharth Bhat 
1624a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1625a90be207SSiddharth Bhat 
162667726b32STobias Grosser     Instruction *Param =
162767726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
162867726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1629d8b94bcaSTobias Grosser                        EntryBlock->getTerminator());
1630d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
1631a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1632d8b94bcaSTobias Grosser     Index++;
1633d8b94bcaSTobias Grosser   }
1634d8b94bcaSTobias Grosser 
163557693272STobias Grosser   for (auto Val : SubtreeValues) {
1636a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1637a90be207SSiddharth Bhat 
163867726b32STobias Grosser     Instruction *Param =
163967726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
164067726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
164157693272STobias Grosser                        EntryBlock->getTerminator());
164257693272STobias Grosser     Builder.CreateStore(Val, Param);
1643a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1644a90be207SSiddharth Bhat     Index++;
1645a90be207SSiddharth Bhat   }
1646a90be207SSiddharth Bhat 
1647a90be207SSiddharth Bhat   for (int i = 0; i < NumArgs; i++) {
1648a90be207SSiddharth Bhat     Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]);
1649a90be207SSiddharth Bhat     Instruction *Param =
1650a90be207SSiddharth Bhat         new AllocaInst(Builder.getInt32Ty(), AddressSpace,
1651a90be207SSiddharth Bhat                        Launch + "_param_size_" + std::to_string(i),
1652a90be207SSiddharth Bhat                        EntryBlock->getTerminator());
1653a90be207SSiddharth Bhat     Builder.CreateStore(Val, Param);
1654a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
165557693272STobias Grosser     Index++;
165657693272STobias Grosser   }
165757693272STobias Grosser 
165879a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
165979a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
166079a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
166179a947c2STobias Grosser }
166279a947c2STobias Grosser 
1663f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions(
1664f291c8d5SSiddharth Bhat     SetVector<Function *> SubtreeFunctions) {
1665f291c8d5SSiddharth Bhat   for (auto Fn : SubtreeFunctions) {
1666f291c8d5SSiddharth Bhat     const std::string ClonedFnName = Fn->getName();
1667f291c8d5SSiddharth Bhat     Function *Clone = GPUModule->getFunction(ClonedFnName);
1668f291c8d5SSiddharth Bhat     if (!Clone)
1669f291c8d5SSiddharth Bhat       Clone =
1670f291c8d5SSiddharth Bhat           Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage,
1671f291c8d5SSiddharth Bhat                            ClonedFnName, GPUModule.get());
1672f291c8d5SSiddharth Bhat     assert(Clone && "Expected cloned function to be initialized.");
1673f291c8d5SSiddharth Bhat     assert(ValueMap.find(Fn) == ValueMap.end() &&
1674f291c8d5SSiddharth Bhat            "Fn already present in ValueMap");
1675f291c8d5SSiddharth Bhat     ValueMap[Fn] = Clone;
1676f291c8d5SSiddharth Bhat   }
1677f291c8d5SSiddharth Bhat }
167832837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
167932837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
168032837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
168132837fe3STobias Grosser   isl_id_free(Id);
168232837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
168332837fe3STobias Grosser 
1684bc653f20STobias Grosser   if (Kernel->n_grid > 1)
1685bc653f20STobias Grosser     DeepestParallel =
1686bc653f20STobias Grosser         std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set));
1687bc653f20STobias Grosser   else
1688bc653f20STobias Grosser     DeepestSequential =
1689bc653f20STobias Grosser         std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set));
1690bc653f20STobias Grosser 
1691c1c6a2a6STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1692c1c6a2a6STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1693c1c6a2a6STobias Grosser 
1694f291c8d5SSiddharth Bhat   SetVector<Value *> SubtreeValues;
1695f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1696f291c8d5SSiddharth Bhat   std::tie(SubtreeValues, SubtreeFunctions) = getReferencesInKernel(Kernel);
1697edb885cbSTobias Grosser 
169832837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
169932837fe3STobias Grosser 
170032837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1701472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1702edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
1703587f1f57STobias Grosser   BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap;
1704b06ff457STobias Grosser   ScalarMap.clear();
170532837fe3STobias Grosser 
1706edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1707edb885cbSTobias Grosser 
1708edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
1709edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
1710edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
1711edb885cbSTobias Grosser   for (const Loop *L : Loops) {
1712edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1713edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1714edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1715edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1716edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1717edb885cbSTobias Grosser     SubtreeValues.insert(V);
1718edb885cbSTobias Grosser   }
1719edb885cbSTobias Grosser 
1720f291c8d5SSiddharth Bhat   createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions);
1721f291c8d5SSiddharth Bhat   setupKernelSubtreeFunctions(SubtreeFunctions);
172232837fe3STobias Grosser 
172359ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
172459ab0705STobias Grosser 
172551dfc275STobias Grosser   finalizeKernelArguments(Kernel);
172674dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
17272f3073b5SPhilipp Schaad   if (Arch == GPUArch::NVPTX64)
1728c1c6a2a6STobias Grosser     addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
172974dc3cb4STobias Grosser   clearDominators(F);
173074dc3cb4STobias Grosser   clearScalarEvolution(F);
173174dc3cb4STobias Grosser   clearLoops(F);
173274dc3cb4STobias Grosser 
1733472f9654STobias Grosser   IDToValue = HostIDs;
173432837fe3STobias Grosser 
1735b06ff457STobias Grosser   ValueMap = std::move(HostValueMap);
1736b06ff457STobias Grosser   ScalarMap = std::move(HostScalarMap);
1737edb885cbSTobias Grosser   EscapeMap.clear();
1738edb885cbSTobias Grosser   IDToSAI.clear();
173974dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
174074dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
17414d5a9172STobias Grosser     S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array);
174274dc3cb4STobias Grosser   LocalArrays.clear();
1743edb885cbSTobias Grosser 
174451dfc275STobias Grosser   std::string ASMString = finalizeKernelFunction();
174551dfc275STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
174657693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
174779a947c2STobias Grosser 
174879f13b9aSSingapuram Sanjay Srivallabh   std::string Name = getKernelFuncName(Kernel->id);
174957793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
175057793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
175157793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
175279a947c2STobias Grosser 
175379a947c2STobias Grosser   Value *GridDimX, *GridDimY;
175479a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
175579a947c2STobias Grosser 
175679a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
175779a947c2STobias Grosser                          BlockDimZ, Parameters);
175857793596STobias Grosser   createCallFreeKernel(GPUKernel);
1759b513b491STobias Grosser 
1760b513b491STobias Grosser   for (auto Id : KernelIds)
1761b513b491STobias Grosser     isl_id_free(Id);
1762b513b491STobias Grosser 
1763b513b491STobias Grosser   KernelIds.clear();
176432837fe3STobias Grosser }
176532837fe3STobias Grosser 
176632837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
176732837fe3STobias Grosser ///
176832837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
176932837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
1770d277fedaSSiddharth Bhat   std::string Ret = "";
177132837fe3STobias Grosser 
1772d277fedaSSiddharth Bhat   if (!is64Bit) {
1773d277fedaSSiddharth Bhat     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
177430caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1775d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1776d277fedaSSiddharth Bhat   } else {
1777d277fedaSSiddharth Bhat     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
177830caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1779d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1780d277fedaSSiddharth Bhat   }
178132837fe3STobias Grosser 
178232837fe3STobias Grosser   return Ret;
178332837fe3STobias Grosser }
178432837fe3STobias Grosser 
17852f3073b5SPhilipp Schaad /// Compute the DataLayout string for a SPIR kernel.
17862f3073b5SPhilipp Schaad ///
17872f3073b5SPhilipp Schaad /// @param is64Bit Are we looking for a 64 bit architecture?
17882f3073b5SPhilipp Schaad static std::string computeSPIRDataLayout(bool is64Bit) {
17892f3073b5SPhilipp Schaad   std::string Ret = "";
17902f3073b5SPhilipp Schaad 
17912f3073b5SPhilipp Schaad   if (!is64Bit) {
17922f3073b5SPhilipp Schaad     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
179330caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
17942f3073b5SPhilipp Schaad            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
17952f3073b5SPhilipp Schaad            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
17962f3073b5SPhilipp Schaad   } else {
17972f3073b5SPhilipp Schaad     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
179830caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
17992f3073b5SPhilipp Schaad            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
18002f3073b5SPhilipp Schaad            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
18012f3073b5SPhilipp Schaad   }
18022f3073b5SPhilipp Schaad 
18032f3073b5SPhilipp Schaad   return Ret;
18042f3073b5SPhilipp Schaad }
18052f3073b5SPhilipp Schaad 
1806edb885cbSTobias Grosser Function *
1807edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1808edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
180932837fe3STobias Grosser   std::vector<Type *> Args;
181079f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
181132837fe3STobias Grosser 
18122f3073b5SPhilipp Schaad   std::vector<Metadata *> MemoryType;
18132f3073b5SPhilipp Schaad 
181432837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
181532837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
181632837fe3STobias Grosser       continue;
181732837fe3STobias Grosser 
1818fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1819fe74a7a1STobias Grosser       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1820206e9e3bSTobias Grosser       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
1821fe74a7a1STobias Grosser       Args.push_back(SAI->getElementType());
18222f3073b5SPhilipp Schaad       MemoryType.push_back(
18232f3073b5SPhilipp Schaad           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1824fe74a7a1STobias Grosser     } else {
1825d277fedaSSiddharth Bhat       static const int UseGlobalMemory = 1;
1826d277fedaSSiddharth Bhat       Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory));
18272f3073b5SPhilipp Schaad       MemoryType.push_back(
18282f3073b5SPhilipp Schaad           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 1)));
182932837fe3STobias Grosser     }
1830fe74a7a1STobias Grosser   }
183132837fe3STobias Grosser 
1832f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1833f6044bd0STobias Grosser 
18342f3073b5SPhilipp Schaad   for (long i = 0; i < NumHostIters; i++) {
1835f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
18362f3073b5SPhilipp Schaad     MemoryType.push_back(
18372f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
18382f3073b5SPhilipp Schaad   }
1839f6044bd0STobias Grosser 
1840c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1841c84a1995STobias Grosser 
1842cf66ef26STobias Grosser   for (long i = 0; i < NumVars; i++) {
1843cf66ef26STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1844cf66ef26STobias Grosser     Value *Val = IDToValue[Id];
1845cf66ef26STobias Grosser     isl_id_free(Id);
1846cf66ef26STobias Grosser     Args.push_back(Val->getType());
18472f3073b5SPhilipp Schaad     MemoryType.push_back(
18482f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1849cf66ef26STobias Grosser   }
1850c84a1995STobias Grosser 
18512f3073b5SPhilipp Schaad   for (auto *V : SubtreeValues) {
1852edb885cbSTobias Grosser     Args.push_back(V->getType());
18532f3073b5SPhilipp Schaad     MemoryType.push_back(
18542f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
18552f3073b5SPhilipp Schaad   }
1856edb885cbSTobias Grosser 
185732837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
185832837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
185932837fe3STobias Grosser                               GPUModule.get());
186017f01968SSiddharth Bhat 
18612f3073b5SPhilipp Schaad   std::vector<Metadata *> EmptyStrings;
18622f3073b5SPhilipp Schaad 
18632f3073b5SPhilipp Schaad   for (unsigned int i = 0; i < MemoryType.size(); i++) {
18642f3073b5SPhilipp Schaad     EmptyStrings.push_back(MDString::get(FN->getContext(), ""));
18652f3073b5SPhilipp Schaad   }
18662f3073b5SPhilipp Schaad 
18672f3073b5SPhilipp Schaad   if (Arch == GPUArch::SPIR32 || Arch == GPUArch::SPIR64) {
18682f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_addr_space",
18692f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), MemoryType));
18702f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_name",
18712f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18722f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_access_qual",
18732f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18742f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_type",
18752f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18762f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_type_qual",
18772f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18782f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_base_type",
18792f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18802f3073b5SPhilipp Schaad   }
18812f3073b5SPhilipp Schaad 
188217f01968SSiddharth Bhat   switch (Arch) {
188317f01968SSiddharth Bhat   case GPUArch::NVPTX64:
188432837fe3STobias Grosser     FN->setCallingConv(CallingConv::PTX_Kernel);
188517f01968SSiddharth Bhat     break;
18862f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
18872f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
18882f3073b5SPhilipp Schaad     FN->setCallingConv(CallingConv::SPIR_KERNEL);
18892f3073b5SPhilipp Schaad     break;
189017f01968SSiddharth Bhat   }
189132837fe3STobias Grosser 
189232837fe3STobias Grosser   auto Arg = FN->arg_begin();
189332837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
189432837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
189532837fe3STobias Grosser       continue;
189632837fe3STobias Grosser 
1897edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
1898edb885cbSTobias Grosser 
1899edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1900206e9e3bSTobias Grosser     const ScopArrayInfo *SAI =
1901206e9e3bSTobias Grosser         ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id)));
1902edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
1903edb885cbSTobias Grosser     Value *Val = &*Arg;
1904edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1905edb885cbSTobias Grosser     isl_ast_build *Build =
1906edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
1907f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1908edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1909edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
19109e3db2b7SSiddharth Bhat           Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j));
1911edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
1912edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
1913edb885cbSTobias Grosser     }
1914edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
19154d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array);
191674dc3cb4STobias Grosser     LocalArrays.push_back(Val);
1917edb885cbSTobias Grosser 
1918edb885cbSTobias Grosser     isl_ast_build_free(Build);
1919b513b491STobias Grosser     KernelIds.push_back(Id);
1920edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
192132837fe3STobias Grosser     Arg++;
192232837fe3STobias Grosser   }
192332837fe3STobias Grosser 
1924f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1925f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1926f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
1927f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
1928f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1929f6044bd0STobias Grosser     Arg++;
1930f6044bd0STobias Grosser   }
1931f6044bd0STobias Grosser 
1932c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
1933c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1934c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
193512453403STobias Grosser     Value *Val = IDToValue[Id];
193612453403STobias Grosser     ValueMap[Val] = &*Arg;
1937c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
1938c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1939c84a1995STobias Grosser     Arg++;
1940c84a1995STobias Grosser   }
1941c84a1995STobias Grosser 
1942edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
1943edb885cbSTobias Grosser     Arg->setName(V->getName());
1944edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
1945edb885cbSTobias Grosser     Arg++;
1946edb885cbSTobias Grosser   }
1947edb885cbSTobias Grosser 
194832837fe3STobias Grosser   return FN;
194932837fe3STobias Grosser }
195032837fe3STobias Grosser 
1951472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
195217f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsBID[2];
195317f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsTID[3];
1954472f9654STobias Grosser 
195517f01968SSiddharth Bhat   switch (Arch) {
19562f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
19572f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
19582f3073b5SPhilipp Schaad     llvm_unreachable("Cannot generate NVVM intrinsics for SPIR");
195917f01968SSiddharth Bhat   case GPUArch::NVPTX64:
196017f01968SSiddharth Bhat     IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x;
196117f01968SSiddharth Bhat     IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y;
196217f01968SSiddharth Bhat 
196317f01968SSiddharth Bhat     IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x;
196417f01968SSiddharth Bhat     IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y;
196517f01968SSiddharth Bhat     IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z;
196617f01968SSiddharth Bhat     break;
196717f01968SSiddharth Bhat   }
1968472f9654STobias Grosser 
1969472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1970472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
1971472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1972472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1973472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1974472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1975472f9654STobias Grosser     IDToValue[Id] = Val;
1976472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1977472f9654STobias Grosser   };
1978472f9654STobias Grosser 
1979472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
1980472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1981472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
1982472f9654STobias Grosser   }
1983472f9654STobias Grosser 
1984472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
1985472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1986472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
1987472f9654STobias Grosser   }
1988472f9654STobias Grosser }
1989472f9654STobias Grosser 
19902f3073b5SPhilipp Schaad void GPUNodeBuilder::insertKernelCallsSPIR(ppcg_kernel *Kernel) {
19912f3073b5SPhilipp Schaad   const char *GroupName[3] = {"__gen_ocl_get_group_id0",
19922f3073b5SPhilipp Schaad                               "__gen_ocl_get_group_id1",
19932f3073b5SPhilipp Schaad                               "__gen_ocl_get_group_id2"};
19942f3073b5SPhilipp Schaad 
19952f3073b5SPhilipp Schaad   const char *LocalName[3] = {"__gen_ocl_get_local_id0",
19962f3073b5SPhilipp Schaad                               "__gen_ocl_get_local_id1",
19972f3073b5SPhilipp Schaad                               "__gen_ocl_get_local_id2"};
19982f3073b5SPhilipp Schaad 
19992f3073b5SPhilipp Schaad   auto createFunc = [this](const char *Name, __isl_take isl_id *Id) mutable {
20002f3073b5SPhilipp Schaad     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
20012f3073b5SPhilipp Schaad     Function *FN = M->getFunction(Name);
20022f3073b5SPhilipp Schaad 
20032f3073b5SPhilipp Schaad     // If FN is not available, declare it.
20042f3073b5SPhilipp Schaad     if (!FN) {
20052f3073b5SPhilipp Schaad       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
20062f3073b5SPhilipp Schaad       std::vector<Type *> Args;
20072f3073b5SPhilipp Schaad       FunctionType *Ty = FunctionType::get(Builder.getInt32Ty(), Args, false);
20082f3073b5SPhilipp Schaad       FN = Function::Create(Ty, Linkage, Name, M);
20092f3073b5SPhilipp Schaad       FN->setCallingConv(CallingConv::SPIR_FUNC);
20102f3073b5SPhilipp Schaad     }
20112f3073b5SPhilipp Schaad 
20122f3073b5SPhilipp Schaad     Value *Val = Builder.CreateCall(FN, {});
20132f3073b5SPhilipp Schaad     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
20142f3073b5SPhilipp Schaad     IDToValue[Id] = Val;
20152f3073b5SPhilipp Schaad     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
20162f3073b5SPhilipp Schaad   };
20172f3073b5SPhilipp Schaad 
20182f3073b5SPhilipp Schaad   for (int i = 0; i < Kernel->n_grid; ++i)
20192f3073b5SPhilipp Schaad     createFunc(GroupName[i], isl_id_list_get_id(Kernel->block_ids, i));
20202f3073b5SPhilipp Schaad 
20212f3073b5SPhilipp Schaad   for (int i = 0; i < Kernel->n_block; ++i)
20222f3073b5SPhilipp Schaad     createFunc(LocalName[i], isl_id_list_get_id(Kernel->thread_ids, i));
20232f3073b5SPhilipp Schaad }
20242f3073b5SPhilipp Schaad 
202500bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
202600bb5a99STobias Grosser   auto Arg = FN->arg_begin();
202700bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
202800bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
202900bb5a99STobias Grosser       continue;
203000bb5a99STobias Grosser 
203100bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2032206e9e3bSTobias Grosser     const ScopArrayInfo *SAI =
2033206e9e3bSTobias Grosser         ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id)));
203400bb5a99STobias Grosser     isl_id_free(Id);
203500bb5a99STobias Grosser 
203600bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
203700bb5a99STobias Grosser       Arg++;
203800bb5a99STobias Grosser       continue;
203900bb5a99STobias Grosser     }
204000bb5a99STobias Grosser 
2041fe74a7a1STobias Grosser     Value *Val = &*Arg;
2042fe74a7a1STobias Grosser 
2043fe74a7a1STobias Grosser     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
204400bb5a99STobias Grosser       Type *TypePtr = SAI->getElementType()->getPointerTo();
2045fe74a7a1STobias Grosser       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
2046fe74a7a1STobias Grosser       Val = Builder.CreateLoad(TypedArgPtr);
2047fe74a7a1STobias Grosser     }
2048fe74a7a1STobias Grosser 
2049fe74a7a1STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
205000bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
205100bb5a99STobias Grosser 
205200bb5a99STobias Grosser     Arg++;
205300bb5a99STobias Grosser   }
205400bb5a99STobias Grosser }
205500bb5a99STobias Grosser 
205651dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) {
205751dfc275STobias Grosser   auto *FN = Builder.GetInsertBlock()->getParent();
205851dfc275STobias Grosser   auto Arg = FN->arg_begin();
205951dfc275STobias Grosser 
206051dfc275STobias Grosser   bool StoredScalar = false;
206151dfc275STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
206251dfc275STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
206351dfc275STobias Grosser       continue;
206451dfc275STobias Grosser 
206551dfc275STobias 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)));
206851dfc275STobias Grosser     isl_id_free(Id);
206951dfc275STobias Grosser 
207051dfc275STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
207151dfc275STobias Grosser       Arg++;
207251dfc275STobias Grosser       continue;
207351dfc275STobias Grosser     }
207451dfc275STobias Grosser 
207551dfc275STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
207651dfc275STobias Grosser       Arg++;
207751dfc275STobias Grosser       continue;
207851dfc275STobias Grosser     }
207951dfc275STobias Grosser 
208051dfc275STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
208151dfc275STobias Grosser     Value *ArgPtr = &*Arg;
208251dfc275STobias Grosser     Type *TypePtr = SAI->getElementType()->getPointerTo();
208351dfc275STobias Grosser     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
208451dfc275STobias Grosser     Value *Val = Builder.CreateLoad(Alloca);
208551dfc275STobias Grosser     Builder.CreateStore(Val, TypedArgPtr);
208651dfc275STobias Grosser     StoredScalar = true;
208751dfc275STobias Grosser 
208851dfc275STobias Grosser     Arg++;
208951dfc275STobias Grosser   }
209051dfc275STobias Grosser 
209151dfc275STobias Grosser   if (StoredScalar)
209251dfc275STobias Grosser     /// In case more than one thread contains scalar stores, the generated
209351dfc275STobias Grosser     /// code might be incorrect, if we only store at the end of the kernel.
209451dfc275STobias Grosser     /// To support this case we need to store these scalars back at each
209551dfc275STobias Grosser     /// memory store or at least before each kernel barrier.
209651dfc275STobias Grosser     if (Kernel->n_block != 0 || Kernel->n_grid != 0)
209751dfc275STobias Grosser       BuildSuccessful = 0;
209851dfc275STobias Grosser }
209951dfc275STobias Grosser 
2100b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
2101b513b491STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
2102b513b491STobias Grosser 
2103b513b491STobias Grosser   for (int i = 0; i < Kernel->n_var; ++i) {
2104b513b491STobias Grosser     struct ppcg_kernel_var &Var = Kernel->var[i];
2105b513b491STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
2106206e9e3bSTobias Grosser     Type *EleTy = ScopArrayInfo::getFromId(isl::manage(Id))->getElementType();
2107b513b491STobias Grosser 
2108f919d8b3STobias Grosser     Type *ArrayTy = EleTy;
2109b513b491STobias Grosser     SmallVector<const SCEV *, 4> Sizes;
2110b513b491STobias Grosser 
2111f5aff704SRoman Gareev     Sizes.push_back(nullptr);
2112928d7573STobias Grosser     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
2113b513b491STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2114f919d8b3STobias Grosser       long Bound = isl_val_get_num_si(Val);
2115b513b491STobias Grosser       isl_val_free(Val);
2116b513b491STobias Grosser       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
2117928d7573STobias Grosser     }
2118928d7573STobias Grosser 
2119928d7573STobias Grosser     for (int j = Var.array->n_index - 1; j >= 0; --j) {
2120928d7573STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2121928d7573STobias Grosser       long Bound = isl_val_get_num_si(Val);
2122928d7573STobias Grosser       isl_val_free(Val);
2123b513b491STobias Grosser       ArrayTy = ArrayType::get(ArrayTy, Bound);
2124b513b491STobias Grosser     }
2125b513b491STobias Grosser 
2126130ca30fSTobias Grosser     const ScopArrayInfo *SAI;
2127130ca30fSTobias Grosser     Value *Allocation;
2128130ca30fSTobias Grosser     if (Var.type == ppcg_access_shared) {
2129130ca30fSTobias Grosser       auto GlobalVar = new GlobalVariable(
2130130ca30fSTobias Grosser           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
2131130ca30fSTobias Grosser           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
2132130ca30fSTobias Grosser       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
2133f919d8b3STobias Grosser       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
2134f919d8b3STobias Grosser 
2135130ca30fSTobias Grosser       Allocation = GlobalVar;
2136130ca30fSTobias Grosser     } else if (Var.type == ppcg_access_private) {
2137130ca30fSTobias Grosser       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
2138130ca30fSTobias Grosser     } else {
2139130ca30fSTobias Grosser       llvm_unreachable("unknown variable type");
2140130ca30fSTobias Grosser     }
21414d5a9172STobias Grosser     SAI =
21424d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array);
2143b513b491STobias Grosser     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
2144130ca30fSTobias Grosser     IDToValue[Id] = Allocation;
2145130ca30fSTobias Grosser     LocalArrays.push_back(Allocation);
2146b513b491STobias Grosser     KernelIds.push_back(Id);
2147b513b491STobias Grosser     IDToSAI[Id] = SAI;
2148b513b491STobias Grosser   }
2149b513b491STobias Grosser }
2150b513b491STobias Grosser 
2151f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction(
2152f291c8d5SSiddharth Bhat     ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues,
2153f291c8d5SSiddharth Bhat     SetVector<Function *> &SubtreeFunctions) {
215479f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
215532837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
215617f01968SSiddharth Bhat 
215717f01968SSiddharth Bhat   switch (Arch) {
215817f01968SSiddharth Bhat   case GPUArch::NVPTX64:
215917f01968SSiddharth Bhat     if (Runtime == GPURuntime::CUDA)
216032837fe3STobias Grosser       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
216117f01968SSiddharth Bhat     else if (Runtime == GPURuntime::OpenCL)
216217f01968SSiddharth Bhat       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl"));
216332837fe3STobias Grosser     GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
216417f01968SSiddharth Bhat     break;
21652f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
21662f3073b5SPhilipp Schaad     GPUModule->setTargetTriple(Triple::normalize("spir-unknown-unknown"));
21672f3073b5SPhilipp Schaad     GPUModule->setDataLayout(computeSPIRDataLayout(false /* is64Bit */));
21682f3073b5SPhilipp Schaad     break;
21692f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
21702f3073b5SPhilipp Schaad     GPUModule->setTargetTriple(Triple::normalize("spir64-unknown-unknown"));
21712f3073b5SPhilipp Schaad     GPUModule->setDataLayout(computeSPIRDataLayout(true /* is64Bit */));
21722f3073b5SPhilipp Schaad     break;
217317f01968SSiddharth Bhat   }
217432837fe3STobias Grosser 
2175edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
217632837fe3STobias Grosser 
217759ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
217832837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
217932837fe3STobias Grosser 
218059ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
218159ab0705STobias Grosser 
218232837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
218332837fe3STobias Grosser   Builder.CreateRetVoid();
218432837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
2185472f9654STobias Grosser 
2186629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
2187629109b6STobias Grosser 
218800bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
2189b513b491STobias Grosser   createKernelVariables(Kernel, FN);
21902f3073b5SPhilipp Schaad 
21912f3073b5SPhilipp Schaad   switch (Arch) {
21922f3073b5SPhilipp Schaad   case GPUArch::NVPTX64:
2193472f9654STobias Grosser     insertKernelIntrinsics(Kernel);
21942f3073b5SPhilipp Schaad     break;
21952f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
21962f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
21972f3073b5SPhilipp Schaad     insertKernelCallsSPIR(Kernel);
21982f3073b5SPhilipp Schaad     break;
21992f3073b5SPhilipp Schaad   }
220032837fe3STobias Grosser }
220132837fe3STobias Grosser 
220274dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
220317f01968SSiddharth Bhat   llvm::Triple GPUTriple;
220417f01968SSiddharth Bhat 
220517f01968SSiddharth Bhat   switch (Arch) {
220617f01968SSiddharth Bhat   case GPUArch::NVPTX64:
220717f01968SSiddharth Bhat     switch (Runtime) {
220817f01968SSiddharth Bhat     case GPURuntime::CUDA:
220917f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda"));
221017f01968SSiddharth Bhat       break;
221117f01968SSiddharth Bhat     case GPURuntime::OpenCL:
221217f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl"));
221317f01968SSiddharth Bhat       break;
221417f01968SSiddharth Bhat     }
221517f01968SSiddharth Bhat     break;
22162f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
22172f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
22182f3073b5SPhilipp Schaad     std::string SPIRAssembly;
22192f3073b5SPhilipp Schaad     raw_string_ostream IROstream(SPIRAssembly);
22202f3073b5SPhilipp Schaad     IROstream << *GPUModule;
22212f3073b5SPhilipp Schaad     IROstream.flush();
22222f3073b5SPhilipp Schaad     return SPIRAssembly;
222317f01968SSiddharth Bhat   }
222417f01968SSiddharth Bhat 
222574dc3cb4STobias Grosser   std::string ErrMsg;
222674dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
222774dc3cb4STobias Grosser 
222874dc3cb4STobias Grosser   if (!GPUTarget) {
222974dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
223074dc3cb4STobias Grosser     return "";
223174dc3cb4STobias Grosser   }
223274dc3cb4STobias Grosser 
223374dc3cb4STobias Grosser   TargetOptions Options;
223474dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
223517f01968SSiddharth Bhat 
223617f01968SSiddharth Bhat   std::string subtarget;
223717f01968SSiddharth Bhat 
223817f01968SSiddharth Bhat   switch (Arch) {
223917f01968SSiddharth Bhat   case GPUArch::NVPTX64:
224017f01968SSiddharth Bhat     subtarget = CudaVersion;
224117f01968SSiddharth Bhat     break;
22422f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
22432f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
22442f3073b5SPhilipp Schaad     llvm_unreachable("No subtarget for SPIR architecture");
224517f01968SSiddharth Bhat   }
224617f01968SSiddharth Bhat 
224717f01968SSiddharth Bhat   std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine(
224817f01968SSiddharth Bhat       GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>()));
224974dc3cb4STobias Grosser 
225074dc3cb4STobias Grosser   SmallString<0> ASMString;
225174dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
225274dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
225374dc3cb4STobias Grosser 
225474dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
225574dc3cb4STobias Grosser 
225674dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
225774dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
225874dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
225974dc3cb4STobias Grosser     return "";
226074dc3cb4STobias Grosser   }
226174dc3cb4STobias Grosser 
226274dc3cb4STobias Grosser   PM.run(*GPUModule);
226374dc3cb4STobias Grosser 
226474dc3cb4STobias Grosser   return ASMStream.str();
226574dc3cb4STobias Grosser }
226674dc3cb4STobias Grosser 
22678fc6cdfbSTobias Grosser bool GPUNodeBuilder::requiresCUDALibDevice() {
22688fc6cdfbSTobias Grosser   for (Function &F : GPUModule->functions()) {
22698fc6cdfbSTobias Grosser     if (!F.isDeclaration())
22708fc6cdfbSTobias Grosser       continue;
22718fc6cdfbSTobias Grosser 
22728fc6cdfbSTobias Grosser     std::string CUDALibDeviceFunc = getCUDALibDeviceFuntion(&F);
22738fc6cdfbSTobias Grosser     if (CUDALibDeviceFunc.length() != 0) {
22748fc6cdfbSTobias Grosser       F.setName(CUDALibDeviceFunc);
22758fc6cdfbSTobias Grosser       return true;
22768fc6cdfbSTobias Grosser     }
22778fc6cdfbSTobias Grosser   }
22788fc6cdfbSTobias Grosser 
22798fc6cdfbSTobias Grosser   return false;
22808fc6cdfbSTobias Grosser }
22818fc6cdfbSTobias Grosser 
22828fc6cdfbSTobias Grosser void GPUNodeBuilder::addCUDALibDevice() {
22838fc6cdfbSTobias Grosser   if (Arch != GPUArch::NVPTX64)
22848fc6cdfbSTobias Grosser     return;
22858fc6cdfbSTobias Grosser 
22868fc6cdfbSTobias Grosser   if (requiresCUDALibDevice()) {
22878fc6cdfbSTobias Grosser     SMDiagnostic Error;
22888fc6cdfbSTobias Grosser 
22898fc6cdfbSTobias Grosser     errs() << CUDALibDevice << "\n";
22908fc6cdfbSTobias Grosser     auto LibDeviceModule =
22918fc6cdfbSTobias Grosser         parseIRFile(CUDALibDevice, Error, GPUModule->getContext());
22928fc6cdfbSTobias Grosser 
22938fc6cdfbSTobias Grosser     if (!LibDeviceModule) {
22948fc6cdfbSTobias Grosser       BuildSuccessful = false;
22958fc6cdfbSTobias Grosser       report_fatal_error("Could not find or load libdevice. Skipping GPU "
22968fc6cdfbSTobias Grosser                          "kernel generation. Please set -polly-acc-libdevice "
22978fc6cdfbSTobias Grosser                          "accordingly.\n");
22988fc6cdfbSTobias Grosser       return;
22998fc6cdfbSTobias Grosser     }
23008fc6cdfbSTobias Grosser 
23018fc6cdfbSTobias Grosser     Linker L(*GPUModule);
23028fc6cdfbSTobias Grosser 
23038fc6cdfbSTobias Grosser     // Set an nvptx64 target triple to avoid linker warnings. The original
23048fc6cdfbSTobias Grosser     // triple of the libdevice files are nvptx-unknown-unknown.
23058fc6cdfbSTobias Grosser     LibDeviceModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
23068fc6cdfbSTobias Grosser     L.linkInModule(std::move(LibDeviceModule), Linker::LinkOnlyNeeded);
23078fc6cdfbSTobias Grosser   }
23088fc6cdfbSTobias Grosser }
23098fc6cdfbSTobias Grosser 
231057793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
231165d7f72fSSiddharth Bhat 
23125857b701STobias Grosser   if (verifyModule(*GPUModule)) {
231365d7f72fSSiddharth Bhat     DEBUG(dbgs() << "verifyModule failed on module:\n";
231465d7f72fSSiddharth Bhat           GPUModule->print(dbgs(), nullptr); dbgs() << "\n";);
2315a0fb8b23SSiddharth Bhat     DEBUG(dbgs() << "verifyModule Error:\n";
2316a0fb8b23SSiddharth Bhat           verifyModule(*GPUModule, &dbgs()););
231765d7f72fSSiddharth Bhat 
231865d7f72fSSiddharth Bhat     if (FailOnVerifyModuleFailure)
231965d7f72fSSiddharth Bhat       llvm_unreachable("VerifyModule failed.");
232065d7f72fSSiddharth Bhat 
23215857b701STobias Grosser     BuildSuccessful = false;
23225857b701STobias Grosser     return "";
23235857b701STobias Grosser   }
232432837fe3STobias Grosser 
23258fc6cdfbSTobias Grosser   addCUDALibDevice();
23268fc6cdfbSTobias Grosser 
232732837fe3STobias Grosser   if (DumpKernelIR)
232832837fe3STobias Grosser     outs() << *GPUModule << "\n";
232932837fe3STobias Grosser 
23302f3073b5SPhilipp Schaad   if (Arch != GPUArch::SPIR32 && Arch != GPUArch::SPIR64) {
23319a18d559STobias Grosser     // Optimize module.
23329a18d559STobias Grosser     llvm::legacy::PassManager OptPasses;
23339a18d559STobias Grosser     PassManagerBuilder PassBuilder;
23349a18d559STobias Grosser     PassBuilder.OptLevel = 3;
23359a18d559STobias Grosser     PassBuilder.SizeLevel = 0;
23369a18d559STobias Grosser     PassBuilder.populateModulePassManager(OptPasses);
23379a18d559STobias Grosser     OptPasses.run(*GPUModule);
23382f3073b5SPhilipp Schaad   }
23399a18d559STobias Grosser 
234074dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
234174dc3cb4STobias Grosser 
234274dc3cb4STobias Grosser   if (DumpKernelASM)
234374dc3cb4STobias Grosser     outs() << Assembly << "\n";
234474dc3cb4STobias Grosser 
234532837fe3STobias Grosser   GPUModule.release();
2346472f9654STobias Grosser   KernelIDs.clear();
234757793596STobias Grosser 
234857793596STobias Grosser   return Assembly;
234932837fe3STobias Grosser }
235032837fe3STobias Grosser 
23519dfe4e7cSTobias Grosser namespace {
23529dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
23539dfe4e7cSTobias Grosser public:
23549dfe4e7cSTobias Grosser   static char ID;
23559dfe4e7cSTobias Grosser 
235617f01968SSiddharth Bhat   GPURuntime Runtime = GPURuntime::CUDA;
235717f01968SSiddharth Bhat 
235817f01968SSiddharth Bhat   GPUArch Architecture = GPUArch::NVPTX64;
235917f01968SSiddharth Bhat 
2360e938517eSTobias Grosser   /// The scop that is currently processed.
2361e938517eSTobias Grosser   Scop *S;
2362e938517eSTobias Grosser 
236338fc0aedSTobias Grosser   LoopInfo *LI;
236438fc0aedSTobias Grosser   DominatorTree *DT;
236538fc0aedSTobias Grosser   ScalarEvolution *SE;
236638fc0aedSTobias Grosser   const DataLayout *DL;
236738fc0aedSTobias Grosser   RegionInfo *RI;
236838fc0aedSTobias Grosser 
23699dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
23709dfe4e7cSTobias Grosser 
2371e938517eSTobias Grosser   /// Construct compilation options for PPCG.
2372e938517eSTobias Grosser   ///
2373e938517eSTobias Grosser   /// @returns The compilation options.
2374e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
2375e938517eSTobias Grosser     auto DebugOptions =
2376e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
2377e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
2378e938517eSTobias Grosser 
2379e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
2380e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
2381e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
2382e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
23838950ceadSTobias Grosser     DebugOptions->verbose = false;
2384e938517eSTobias Grosser 
2385e938517eSTobias Grosser     Options->debug = DebugOptions;
2386e938517eSTobias Grosser 
23879e3db2b7SSiddharth Bhat     Options->group_chains = false;
2388e938517eSTobias Grosser     Options->reschedule = true;
2389e938517eSTobias Grosser     Options->scale_tile_loops = false;
2390e938517eSTobias Grosser     Options->wrap = false;
2391e938517eSTobias Grosser 
2392e938517eSTobias Grosser     Options->non_negative_parameters = false;
2393e938517eSTobias Grosser     Options->ctx = nullptr;
2394e938517eSTobias Grosser     Options->sizes = nullptr;
2395e938517eSTobias Grosser 
23969e3db2b7SSiddharth Bhat     Options->tile = true;
23974eaedde5STobias Grosser     Options->tile_size = 32;
23984eaedde5STobias Grosser 
23999e3db2b7SSiddharth Bhat     Options->isolate_full_tiles = false;
24009e3db2b7SSiddharth Bhat 
2401130ca30fSTobias Grosser     Options->use_private_memory = PrivateMemory;
2402b513b491STobias Grosser     Options->use_shared_memory = SharedMemory;
2403b513b491STobias Grosser     Options->max_shared_memory = 48 * 1024;
2404e938517eSTobias Grosser 
2405e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
2406e938517eSTobias Grosser     Options->openmp = false;
2407e938517eSTobias Grosser     Options->linearize_device_arrays = true;
24089e3db2b7SSiddharth Bhat     Options->allow_gnu_extensions = false;
2409e938517eSTobias Grosser 
24109e3db2b7SSiddharth Bhat     Options->unroll_copy_shared = false;
24119e3db2b7SSiddharth Bhat     Options->unroll_gpu_tile = false;
24129e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
24139e3db2b7SSiddharth Bhat 
24149e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
24159e3db2b7SSiddharth Bhat     Options->hybrid = false;
2416e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
2417e938517eSTobias Grosser     Options->opencl_use_gpu = false;
2418e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
2419e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
2420e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
2421e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
2422e938517eSTobias Grosser 
2423e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
2424e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
2425e938517eSTobias Grosser 
2426e938517eSTobias Grosser     return Options;
2427e938517eSTobias Grosser   }
2428e938517eSTobias Grosser 
2429f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
2430f384594dSTobias Grosser   ///
2431f384594dSTobias Grosser   /// Instead of a normal access of the form:
2432f384594dSTobias Grosser   ///
2433f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
2434f384594dSTobias Grosser   ///
2435f384594dSTobias Grosser   /// a tagged access has the form
2436f384594dSTobias Grosser   ///
2437f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
2438f384594dSTobias Grosser   ///
2439f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
2440f384594dSTobias Grosser   /// triggered the access.
2441f384594dSTobias Grosser   ///
2442f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
2443f384594dSTobias Grosser   ///
2444f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
2445f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
2446f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
2447f384594dSTobias Grosser 
2448f384594dSTobias Grosser     for (auto &Stmt : *S)
2449f384594dSTobias Grosser       for (auto &Acc : Stmt)
2450f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
24511515f6b9STobias Grosser           isl_map *Relation = Acc->getAccessRelation().release();
2452f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
2453f384594dSTobias Grosser 
2454f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
2455f384594dSTobias Grosser           Space = isl_space_range(Space);
2456f384594dSTobias Grosser           Space = isl_space_from_range(Space);
2457fe46c3ffSTobias Grosser           Space =
2458fe46c3ffSTobias Grosser               isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
2459f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
2460f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
2461f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
2462f384594dSTobias Grosser         }
2463f384594dSTobias Grosser 
2464f384594dSTobias Grosser     return Accesses;
2465f384594dSTobias Grosser   }
2466f384594dSTobias Grosser 
2467f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
2468f384594dSTobias Grosser   ///
2469f384594dSTobias Grosser   /// @see getTaggedAccesses
2470f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
2471f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
2472f384594dSTobias Grosser   }
2473f384594dSTobias Grosser 
2474f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
2475f384594dSTobias Grosser   ///
2476f384594dSTobias Grosser   /// @see getTaggedAccesses
2477f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
2478f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
2479f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
2480f384594dSTobias Grosser   }
2481f384594dSTobias Grosser 
2482f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
2483f384594dSTobias Grosser   ///
2484f384594dSTobias Grosser   /// @see getTaggedAccesses
2485f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
2486f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
2487f384594dSTobias Grosser   }
2488f384594dSTobias Grosser 
2489aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
2490aef5196fSTobias Grosser   ///
2491aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
2492aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
2493aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
2494aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
2495aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
2496aef5196fSTobias Grosser   /// the data format that ppcg expects.
2497aef5196fSTobias Grosser   ///
2498aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
2499aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
2500aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
2501bd81a7eeSTobias Grosser         S->getIslCtx(),
2502bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
2503aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
2504aef5196fSTobias Grosser 
250525271b91STobias Grosser     for (const SCEV *P : S->parameters()) {
250625271b91STobias Grosser       isl_id *Id = S->getIdForParam(P);
2507aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2508aef5196fSTobias Grosser     }
2509aef5196fSTobias Grosser 
2510aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
251177eef90fSTobias Grosser       auto Id = Array->getBasePtrId().release();
2512aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2513aef5196fSTobias Grosser     }
2514aef5196fSTobias Grosser 
2515aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
2516aef5196fSTobias Grosser 
2517aef5196fSTobias Grosser     return Names;
2518aef5196fSTobias Grosser   }
2519aef5196fSTobias Grosser 
2520e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
2521e938517eSTobias Grosser   ///
2522f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
2523f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
2524f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
2525f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
2526e938517eSTobias Grosser   ///
2527e938517eSTobias Grosser   /// @returns A new ppcg scop.
2528e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
25299e3db2b7SSiddharth Bhat     MustKillsInfo KillsInfo = computeMustKillsInfo(*S);
25309e3db2b7SSiddharth Bhat 
2531e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
2532e938517eSTobias Grosser 
2533e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
2534a82f2d26SSiddharth Bhat     // enable live range reordering
2535a82f2d26SSiddharth Bhat     PPCGScop->options->live_range_reordering = 1;
2536e938517eSTobias Grosser 
2537e938517eSTobias Grosser     PPCGScop->start = 0;
2538e938517eSTobias Grosser     PPCGScop->end = 0;
2539e938517eSTobias Grosser 
2540f384594dSTobias Grosser     PPCGScop->context = S->getContext();
2541f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
25429e3db2b7SSiddharth Bhat     // TODO: investigate this further. PPCG calls collect_call_domains.
25439e3db2b7SSiddharth Bhat     PPCGScop->call = isl_union_set_from_set(S->getContext());
2544f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
2545f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
2546e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
2547f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
2548f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
2549f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
2550f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
2551e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
25529e3db2b7SSiddharth Bhat     PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.take();
25539e3db2b7SSiddharth Bhat     PPCGScop->must_kills = KillsInfo.MustKills.take();
25549e3db2b7SSiddharth Bhat 
2555e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
2556a82f2d26SSiddharth Bhat     PPCGScop->independence =
2557a82f2d26SSiddharth Bhat         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
2558e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
2559e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
2560e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
2561e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
2562e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
2563e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
2564e938517eSTobias Grosser 
2565f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
2566a82f2d26SSiddharth Bhat     // If we have something non-trivial to kill, add it to the schedule
2567a82f2d26SSiddharth Bhat     if (KillsInfo.KillsSchedule.get())
2568a82f2d26SSiddharth Bhat       PPCGScop->schedule = isl_schedule_sequence(
2569a82f2d26SSiddharth Bhat           PPCGScop->schedule, KillsInfo.KillsSchedule.take());
2570a82f2d26SSiddharth Bhat 
2571a82f2d26SSiddharth Bhat     PPCGScop->names = getNames();
2572e938517eSTobias Grosser     PPCGScop->pet = nullptr;
2573e938517eSTobias Grosser 
2574f384594dSTobias Grosser     compute_tagger(PPCGScop);
2575f384594dSTobias Grosser     compute_dependences(PPCGScop);
25769e3db2b7SSiddharth Bhat     eliminate_dead_code(PPCGScop);
2577f384594dSTobias Grosser 
2578e938517eSTobias Grosser     return PPCGScop;
2579e938517eSTobias Grosser   }
2580e938517eSTobias Grosser 
2581a6d48f59SMichael Kruse   /// Collect the array accesses in a statement.
258260f63b49STobias Grosser   ///
258360f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
258460f63b49STobias Grosser   ///
258560f63b49STobias Grosser   /// @returns A list of array accesses.
258660f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
258760f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
258860f63b49STobias Grosser 
258960f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
259060f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
259160f63b49STobias Grosser       Access->read = Acc->isRead();
259260f63b49STobias Grosser       Access->write = Acc->isWrite();
25931515f6b9STobias Grosser       Access->access = Acc->getAccessRelation().release();
259460f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
259560f63b49STobias Grosser       Space = isl_space_range(Space);
259660f63b49STobias Grosser       Space = isl_space_from_range(Space);
2597fe46c3ffSTobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
259860f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
259960f63b49STobias Grosser       Access->tagged_access =
26001515f6b9STobias Grosser           isl_map_domain_product(Acc->getAccessRelation().release(), Universe);
2601b513b491STobias Grosser       Access->exact_write = !Acc->isMayWrite();
2602fe46c3ffSTobias Grosser       Access->ref_id = Acc->getId().release();
260360f63b49STobias Grosser       Access->next = Accesses;
2604b513b491STobias Grosser       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
260560f63b49STobias Grosser       Accesses = Access;
260660f63b49STobias Grosser     }
260760f63b49STobias Grosser 
260860f63b49STobias Grosser     return Accesses;
260960f63b49STobias Grosser   }
261060f63b49STobias Grosser 
261169b46751STobias Grosser   /// Collect the list of GPU statements.
261269b46751STobias Grosser   ///
261369b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
261469b46751STobias Grosser   /// as well as a list with all memory accesses.
261569b46751STobias Grosser   ///
261669b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
261769b46751STobias Grosser   ///
261869b46751STobias Grosser   /// @returns A linked-list of statements.
261969b46751STobias Grosser   gpu_stmt *getStatements() {
262069b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
262169b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
262269b46751STobias Grosser 
262369b46751STobias Grosser     int i = 0;
262469b46751STobias Grosser     for (auto &Stmt : *S) {
262569b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
262669b46751STobias Grosser 
262769b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
262869b46751STobias Grosser 
262969b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
263069b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
263160f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
263269b46751STobias Grosser       i++;
263369b46751STobias Grosser     }
263469b46751STobias Grosser 
263569b46751STobias Grosser     return Stmts;
263669b46751STobias Grosser   }
263769b46751STobias Grosser 
263860f63b49STobias Grosser   /// Derive the extent of an array.
263960f63b49STobias Grosser   ///
2640d58acf86STobias Grosser   /// The extent of an array is the set of elements that are within the
2641d58acf86STobias Grosser   /// accessed array. For the inner dimensions, the extent constraints are
2642d58acf86STobias Grosser   /// 0 and the size of the corresponding array dimension. For the first
2643d58acf86STobias Grosser   /// (outermost) dimension, the extent constraints are the minimal and maximal
2644d58acf86STobias Grosser   /// subscript value for the first dimension.
264560f63b49STobias Grosser   ///
264660f63b49STobias Grosser   /// @param Array The array to derive the extent for.
264760f63b49STobias Grosser   ///
264860f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
264960f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
2650d58acf86STobias Grosser     unsigned NumDims = Array->getNumberOfDimensions();
265160f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
265260f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
2653d58acf86STobias Grosser     Accesses = isl_union_map_detect_equalities(Accesses);
265460f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
2655d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2656d58acf86STobias Grosser     AccessUSet = isl_union_set_detect_equalities(AccessUSet);
2657d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2658d58acf86STobias Grosser 
2659d58acf86STobias Grosser     if (isl_union_set_is_empty(AccessUSet)) {
2660d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
266177eef90fSTobias Grosser       return isl_set_empty(Array->getSpace().release());
2662d58acf86STobias Grosser     }
2663d58acf86STobias Grosser 
2664d58acf86STobias Grosser     if (Array->getNumberOfDimensions() == 0) {
2665d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
266677eef90fSTobias Grosser       return isl_set_universe(Array->getSpace().release());
2667d58acf86STobias Grosser     }
2668d58acf86STobias Grosser 
266960f63b49STobias Grosser     isl_set *AccessSet =
267077eef90fSTobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace().release());
267160f63b49STobias Grosser 
2672d58acf86STobias Grosser     isl_union_set_free(AccessUSet);
267377eef90fSTobias Grosser     isl_local_space *LS =
267477eef90fSTobias Grosser         isl_local_space_from_space(Array->getSpace().release());
2675d58acf86STobias Grosser 
2676d58acf86STobias Grosser     isl_pw_aff *Val =
2677d58acf86STobias Grosser         isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0));
2678d58acf86STobias Grosser 
2679d58acf86STobias Grosser     isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0);
2680d58acf86STobias Grosser     isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0);
2681d58acf86STobias Grosser     OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in,
2682d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
2683d58acf86STobias Grosser     OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in,
2684d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
268577eef90fSTobias Grosser     OuterMin = isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in,
268677eef90fSTobias Grosser                                        Array->getBasePtrId().release());
268777eef90fSTobias Grosser     OuterMax = isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in,
268877eef90fSTobias Grosser                                        Array->getBasePtrId().release());
2689d58acf86STobias Grosser 
269077eef90fSTobias Grosser     isl_set *Extent = isl_set_universe(Array->getSpace().release());
2691d58acf86STobias Grosser 
2692d58acf86STobias Grosser     Extent = isl_set_intersect(
2693d58acf86STobias Grosser         Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val)));
2694d58acf86STobias Grosser     Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val));
2695d58acf86STobias Grosser 
2696d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i)
2697d58acf86STobias Grosser       Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0);
2698d58acf86STobias Grosser 
2699b7f68b8cSSiddharth Bhat     for (unsigned i = 0; i < NumDims; ++i) {
2700d58acf86STobias Grosser       isl_pw_aff *PwAff =
270177eef90fSTobias Grosser           const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i).release());
2702b7f68b8cSSiddharth Bhat 
2703b7f68b8cSSiddharth Bhat       // isl_pw_aff can be NULL for zero dimension. Only in the case of a
2704b7f68b8cSSiddharth Bhat       // Fortran array will we have a legitimate dimension.
2705b7f68b8cSSiddharth Bhat       if (!PwAff) {
2706b7f68b8cSSiddharth Bhat         assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension");
2707b7f68b8cSSiddharth Bhat         continue;
2708b7f68b8cSSiddharth Bhat       }
2709b7f68b8cSSiddharth Bhat 
2710d58acf86STobias Grosser       isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain(
271177eef90fSTobias Grosser           isl_local_space_from_space(Array->getSpace().release()), isl_dim_set,
271277eef90fSTobias Grosser           i));
2713d58acf86STobias Grosser       PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in,
2714d58acf86STobias Grosser                                   isl_pw_aff_dim(Val, isl_dim_in));
2715d58acf86STobias Grosser       PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in,
2716d58acf86STobias Grosser                                       isl_pw_aff_get_tuple_id(Val, isl_dim_in));
2717d58acf86STobias Grosser       auto *Set = isl_pw_aff_gt_set(PwAff, Val);
2718d58acf86STobias Grosser       Extent = isl_set_intersect(Set, Extent);
2719d58acf86STobias Grosser     }
2720d58acf86STobias Grosser 
2721d58acf86STobias Grosser     return Extent;
272260f63b49STobias Grosser   }
272360f63b49STobias Grosser 
272460f63b49STobias Grosser   /// Derive the bounds of an array.
272560f63b49STobias Grosser   ///
272660f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
272760f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
272860f63b49STobias Grosser   /// ScopArrayInfo.
272960f63b49STobias Grosser   ///
273060f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
273160f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
273260f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
27339e3db2b7SSiddharth Bhat     isl_pw_aff_list *BoundsList =
27349e3db2b7SSiddharth Bhat         isl_pw_aff_list_alloc(S->getIslCtx(), PPCGArray.n_index);
27359e3db2b7SSiddharth Bhat     std::vector<isl::pw_aff> PwAffs;
27369e3db2b7SSiddharth Bhat 
27379e3db2b7SSiddharth Bhat     isl_space *AlignSpace = S->getParamSpace();
27389e3db2b7SSiddharth Bhat     AlignSpace = isl_space_add_dims(AlignSpace, isl_dim_set, 1);
27399e3db2b7SSiddharth Bhat 
274060f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
274102293ed7STobias Grosser       if (isl_set_is_empty(PPCGArray.extent)) {
274202293ed7STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
274302293ed7STobias Grosser         isl_local_space *LS = isl_local_space_from_space(
274402293ed7STobias Grosser             isl_space_params(isl_set_get_space(Dom)));
274502293ed7STobias Grosser         isl_set_free(Dom);
27469e3db2b7SSiddharth Bhat         isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS));
27479e3db2b7SSiddharth Bhat         Zero = isl_pw_aff_align_params(Zero, isl_space_copy(AlignSpace));
27489e3db2b7SSiddharth Bhat         PwAffs.push_back(isl::manage(isl_pw_aff_copy(Zero)));
27499e3db2b7SSiddharth Bhat         BoundsList = isl_pw_aff_list_insert(BoundsList, 0, Zero);
275002293ed7STobias Grosser       } else {
275160f63b49STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
275260f63b49STobias Grosser         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
275360f63b49STobias Grosser         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
275460f63b49STobias Grosser         isl_set_free(Dom);
275560f63b49STobias Grosser         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
275602293ed7STobias Grosser         isl_local_space *LS =
275702293ed7STobias Grosser             isl_local_space_from_space(isl_set_get_space(Dom));
275860f63b49STobias Grosser         isl_aff *One = isl_aff_zero_on_domain(LS);
275960f63b49STobias Grosser         One = isl_aff_add_constant_si(One, 1);
276060f63b49STobias Grosser         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
276160f63b49STobias Grosser         Bound = isl_pw_aff_gist(Bound, S->getContext());
27629e3db2b7SSiddharth Bhat         Bound = isl_pw_aff_align_params(Bound, isl_space_copy(AlignSpace));
27639e3db2b7SSiddharth Bhat         PwAffs.push_back(isl::manage(isl_pw_aff_copy(Bound)));
27649e3db2b7SSiddharth Bhat         BoundsList = isl_pw_aff_list_insert(BoundsList, 0, Bound);
276560f63b49STobias Grosser       }
276602293ed7STobias Grosser     }
276760f63b49STobias Grosser 
276860f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
276977eef90fSTobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i).release();
277060f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
277160f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
277260f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
27739e3db2b7SSiddharth Bhat       Bound = isl_pw_aff_align_params(Bound, isl_space_copy(AlignSpace));
27749e3db2b7SSiddharth Bhat       PwAffs.push_back(isl::manage(isl_pw_aff_copy(Bound)));
27759e3db2b7SSiddharth Bhat       BoundsList = isl_pw_aff_list_insert(BoundsList, i, Bound);
277660f63b49STobias Grosser     }
27779e3db2b7SSiddharth Bhat 
27789e3db2b7SSiddharth Bhat     isl_space_free(AlignSpace);
27799e3db2b7SSiddharth Bhat     isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent);
27809e3db2b7SSiddharth Bhat 
27819e3db2b7SSiddharth Bhat     assert(BoundsSpace && "Unable to access space of array.");
27829e3db2b7SSiddharth Bhat     assert(BoundsList && "Unable to access list of bounds.");
27839e3db2b7SSiddharth Bhat 
27849e3db2b7SSiddharth Bhat     PPCGArray.bound =
27859e3db2b7SSiddharth Bhat         isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList);
27869e3db2b7SSiddharth Bhat     assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly.");
278760f63b49STobias Grosser   }
278860f63b49STobias Grosser 
278960f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
279060f63b49STobias Grosser   ///
279160f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
279243f178bbSSiddharth Bhat   void createArrays(gpu_prog *PPCGProg,
279343f178bbSSiddharth Bhat                     const SmallVector<ScopArrayInfo *, 4> &ValidSAIs) {
279460f63b49STobias Grosser     int i = 0;
279543f178bbSSiddharth Bhat     for (auto &Array : ValidSAIs) {
279660f63b49STobias Grosser       std::string TypeName;
279760f63b49STobias Grosser       raw_string_ostream OS(TypeName);
279860f63b49STobias Grosser 
279960f63b49STobias Grosser       OS << *Array->getElementType();
280060f63b49STobias Grosser       TypeName = OS.str();
280160f63b49STobias Grosser 
280260f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
280360f63b49STobias Grosser 
280477eef90fSTobias Grosser       PPCGArray.space = Array->getSpace().release();
280560f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
280660f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
280760f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
280860f63b49STobias Grosser       PPCGArray.extent = nullptr;
280960f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
281060f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
281160f63b49STobias Grosser       PPCGArray.n_ref = 0;
281260f63b49STobias Grosser       PPCGArray.refs = nullptr;
281360f63b49STobias Grosser       PPCGArray.accessed = true;
2814fe74a7a1STobias Grosser       PPCGArray.read_only_scalar =
2815fe74a7a1STobias Grosser           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
281660f63b49STobias Grosser       PPCGArray.has_compound_element = false;
281760f63b49STobias Grosser       PPCGArray.local = false;
281860f63b49STobias Grosser       PPCGArray.declare_local = false;
281960f63b49STobias Grosser       PPCGArray.global = false;
282060f63b49STobias Grosser       PPCGArray.linearize = false;
282160f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
282213c78e4dSTobias Grosser       PPCGArray.user = Array;
282360f63b49STobias Grosser 
28249e3db2b7SSiddharth Bhat       PPCGArray.bound = nullptr;
282560f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
28262d010dafSTobias Grosser       i++;
2827b9fc860aSTobias Grosser 
2828b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
282960f63b49STobias Grosser     }
283060f63b49STobias Grosser   }
283160f63b49STobias Grosser 
283260f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
283360f63b49STobias Grosser   ///
283460f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
283560f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
283660f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
283760f63b49STobias Grosser 
2838d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
283977eef90fSTobias Grosser       isl_space *Space = Array->getSpace().release();
284060f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
284160f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
284260f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
284360f63b49STobias Grosser     }
284460f63b49STobias Grosser 
284560f63b49STobias Grosser     return Maps;
284660f63b49STobias Grosser   }
284760f63b49STobias Grosser 
2848e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
2849e938517eSTobias Grosser   ///
2850a6d48f59SMichael Kruse   /// @returns A new gpu program description.
2851e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
2852e938517eSTobias Grosser 
2853e938517eSTobias Grosser     if (!PPCGScop)
2854e938517eSTobias Grosser       return nullptr;
2855e938517eSTobias Grosser 
2856e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
2857e938517eSTobias Grosser 
2858e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
2859e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
2860aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
286160f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
286260f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
286360f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
286460f63b49STobias Grosser     PPCGProg->tagged_must_kill =
286560f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
286660f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
286760f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
28689e3db2b7SSiddharth Bhat     // TODO: verify that this assignment is correct.
2869e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
2870a82f2d26SSiddharth Bhat 
2871a82f2d26SSiddharth Bhat     // this needs to be set when live range reordering is enabled.
2872a82f2d26SSiddharth Bhat     // NOTE: I believe that is conservatively correct. I'm not sure
2873a82f2d26SSiddharth Bhat     //       what the semantics of this is.
2874a82f2d26SSiddharth Bhat     // Quoting PPCG/gpu.h: "Order dependences on non-scalars."
2875a82f2d26SSiddharth Bhat     PPCGProg->array_order =
2876a82f2d26SSiddharth Bhat         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
287769b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
287869b46751STobias Grosser     PPCGProg->stmts = getStatements();
287943f178bbSSiddharth Bhat 
288043f178bbSSiddharth Bhat     // Only consider arrays that have a non-empty extent.
288143f178bbSSiddharth Bhat     // Otherwise, this will cause us to consider the following kinds of
288243f178bbSSiddharth Bhat     // empty arrays:
288343f178bbSSiddharth Bhat     //     1. Invariant loads that are represented by SAI objects.
288443f178bbSSiddharth Bhat     //     2. Arrays with statically known zero size.
288543f178bbSSiddharth Bhat     auto ValidSAIsRange =
288643f178bbSSiddharth Bhat         make_filter_range(S->arrays(), [this](ScopArrayInfo *SAI) -> bool {
288743f178bbSSiddharth Bhat           return !isl::manage(getExtent(SAI)).is_empty();
288843f178bbSSiddharth Bhat         });
288943f178bbSSiddharth Bhat     SmallVector<ScopArrayInfo *, 4> ValidSAIs(ValidSAIsRange.begin(),
289043f178bbSSiddharth Bhat                                               ValidSAIsRange.end());
289143f178bbSSiddharth Bhat 
289243f178bbSSiddharth Bhat     PPCGProg->n_array =
289343f178bbSSiddharth Bhat         ValidSAIs.size(); // std::distance(S->array_begin(), S->array_end());
289460f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
289560f63b49STobias Grosser                                        PPCGProg->n_array);
289660f63b49STobias Grosser 
289743f178bbSSiddharth Bhat     createArrays(PPCGProg, ValidSAIs);
2898e938517eSTobias Grosser 
2899d58acf86STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
2900e938517eSTobias Grosser     return PPCGProg;
2901e938517eSTobias Grosser   }
2902e938517eSTobias Grosser 
290369b46751STobias Grosser   struct PrintGPUUserData {
290469b46751STobias Grosser     struct cuda_info *CudaInfo;
290569b46751STobias Grosser     struct gpu_prog *PPCGProg;
290669b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
290769b46751STobias Grosser   };
290869b46751STobias Grosser 
290969b46751STobias Grosser   /// Print a user statement node in the host code.
291069b46751STobias Grosser   ///
291169b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
291269b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
291369b46751STobias Grosser   /// host ast.
291469b46751STobias Grosser   ///
291569b46751STobias Grosser   /// @param P The printer to print to
291669b46751STobias Grosser   /// @param Options The printing options to use
291769b46751STobias Grosser   /// @param Node The node to print
291869b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
291969b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
292069b46751STobias Grosser   ///
292169b46751STobias Grosser   /// @returns A printer to which the output has been printed.
292269b46751STobias Grosser   static __isl_give isl_printer *
292369b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
292469b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
292569b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
292669b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
292769b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
292869b46751STobias Grosser 
292969b46751STobias Grosser     if (Id) {
293020251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
293120251734STobias Grosser 
293220251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
293320251734STobias Grosser       // otherwise try to call pet functionality that is not available in
293420251734STobias Grosser       // Polly.
293520251734STobias Grosser       if (IsUser) {
293620251734STobias Grosser         P = isl_printer_start_line(P);
293720251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
293820251734STobias Grosser         P = isl_printer_end_line(P);
293920251734STobias Grosser         isl_id_free(Id);
294020251734STobias Grosser         isl_ast_print_options_free(Options);
294120251734STobias Grosser         return P;
294220251734STobias Grosser       }
294320251734STobias Grosser 
294469b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
294569b46751STobias Grosser       isl_id_free(Id);
294669b46751STobias Grosser       Data->Kernels.push_back(Kernel);
294769b46751STobias Grosser     }
294869b46751STobias Grosser 
294969b46751STobias Grosser     return print_host_user(P, Options, Node, User);
295069b46751STobias Grosser   }
295169b46751STobias Grosser 
295269b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
295369b46751STobias Grosser   ///
295469b46751STobias Grosser   /// @param Kernel The kernel to print
295569b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
295669b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
295769b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
295869b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
295969b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
296069b46751STobias Grosser     char *String = isl_printer_get_str(P);
296169b46751STobias Grosser     printf("%s\n", String);
296269b46751STobias Grosser     free(String);
296369b46751STobias Grosser     isl_printer_free(P);
296469b46751STobias Grosser   }
296569b46751STobias Grosser 
296669b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
296769b46751STobias Grosser   ///
296869b46751STobias Grosser   /// @param Tree An AST describing GPU code
296969b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
297069b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
297169b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
297269b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
297369b46751STobias Grosser 
297469b46751STobias Grosser     PrintGPUUserData Data;
297569b46751STobias Grosser     Data.PPCGProg = PPCGProg;
297669b46751STobias Grosser 
297769b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
297869b46751STobias Grosser     Options =
297969b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
298069b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
298169b46751STobias Grosser     char *String = isl_printer_get_str(P);
298269b46751STobias Grosser     printf("# host\n");
298369b46751STobias Grosser     printf("%s\n", String);
298469b46751STobias Grosser     free(String);
298569b46751STobias Grosser     isl_printer_free(P);
298669b46751STobias Grosser 
298769b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
298869b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
298969b46751STobias Grosser       printKernel(Kernel);
299069b46751STobias Grosser     }
299169b46751STobias Grosser   }
299269b46751STobias Grosser 
2993f384594dSTobias Grosser   // Generate a GPU program using PPCG.
2994f384594dSTobias Grosser   //
2995f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
2996f384594dSTobias Grosser   //
2997f384594dSTobias Grosser   //  1) Compute new schedule for the program.
2998f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
2999f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
3000f384594dSTobias Grosser   //
3001f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
3002f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
3003f384594dSTobias Grosser   // strategy directly from this pass.
3004f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
3005f384594dSTobias Grosser 
3006f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
3007f384594dSTobias Grosser 
3008f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
3009f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
3010f384594dSTobias Grosser     PPCGGen->print = nullptr;
3011f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
301260c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
3013f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
3014f384594dSTobias Grosser     PPCGGen->tree = nullptr;
3015f384594dSTobias Grosser     PPCGGen->types.n = 0;
3016f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
3017f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
3018f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
3019f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
3020f384594dSTobias Grosser 
3021f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
3022f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
3023f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
30242341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
3025f384594dSTobias Grosser 
3026f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
3027f384594dSTobias Grosser 
3028aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
3029aef5196fSTobias Grosser 
303069b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
3031aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
303269b46751STobias Grosser     } else {
3033aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
303469b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
303569b46751STobias Grosser     }
3036aef5196fSTobias Grosser 
3037f384594dSTobias Grosser     if (DumpSchedule) {
3038f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
3039f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
3040f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
3041f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
3042f384594dSTobias Grosser       if (Schedule)
3043f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
3044f384594dSTobias Grosser       else
3045f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
3046f384594dSTobias Grosser 
3047f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
3048f384594dSTobias Grosser       isl_printer_free(P);
3049f384594dSTobias Grosser     }
3050f384594dSTobias Grosser 
305169b46751STobias Grosser     if (DumpCode) {
305269b46751STobias Grosser       printf("Code\n");
305369b46751STobias Grosser       printf("====\n");
305469b46751STobias Grosser       if (PPCGGen->tree)
305569b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
305669b46751STobias Grosser       else
305769b46751STobias Grosser         printf("No code generated\n");
305869b46751STobias Grosser     }
305969b46751STobias Grosser 
3060f384594dSTobias Grosser     isl_schedule_free(Schedule);
3061f384594dSTobias Grosser 
3062f384594dSTobias Grosser     return PPCGGen;
3063f384594dSTobias Grosser   }
3064f384594dSTobias Grosser 
3065f384594dSTobias Grosser   /// Free gpu_gen structure.
3066f384594dSTobias Grosser   ///
3067f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
3068f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
3069f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
3070f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
3071f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
3072f384594dSTobias Grosser     free(PPCGGen);
3073f384594dSTobias Grosser   }
3074f384594dSTobias Grosser 
3075b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
3076b307ed4dSTobias Grosser   ///
3077b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
3078b307ed4dSTobias Grosser   /// ourselves.
3079b307ed4dSTobias Grosser   ///
3080b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
3081b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
3082b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
3083b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
3084b307ed4dSTobias Grosser     free(PPCGScop->options);
3085b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
3086b307ed4dSTobias Grosser   }
3087b307ed4dSTobias Grosser 
308882f2af35STobias Grosser   /// Approximate the number of points in the set.
308982f2af35STobias Grosser   ///
309082f2af35STobias Grosser   /// This function returns an ast expression that overapproximates the number
309182f2af35STobias Grosser   /// of points in an isl set through the rectangular hull surrounding this set.
309282f2af35STobias Grosser   ///
309382f2af35STobias Grosser   /// @param Set   The set to count.
309482f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
309582f2af35STobias Grosser   ///              expression.
309682f2af35STobias Grosser   ///
309782f2af35STobias Grosser   /// @returns An approximation of the number of points in the set.
309882f2af35STobias Grosser   __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set,
309982f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
310082f2af35STobias Grosser 
310182f2af35STobias Grosser     isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1);
310282f2af35STobias Grosser     auto *Expr = isl_ast_expr_from_val(isl_val_copy(One));
310382f2af35STobias Grosser 
310482f2af35STobias Grosser     isl_space *Space = isl_set_get_space(Set);
310582f2af35STobias Grosser     Space = isl_space_params(Space);
310682f2af35STobias Grosser     auto *Univ = isl_set_universe(Space);
310782f2af35STobias Grosser     isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One);
310882f2af35STobias Grosser 
310982f2af35STobias Grosser     for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) {
311082f2af35STobias Grosser       isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i);
311182f2af35STobias Grosser       isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i);
311282f2af35STobias Grosser       isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min);
311382f2af35STobias Grosser       DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff));
311482f2af35STobias Grosser       auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize);
311582f2af35STobias Grosser       Expr = isl_ast_expr_mul(Expr, DimSizeExpr);
311682f2af35STobias Grosser     }
311782f2af35STobias Grosser 
311882f2af35STobias Grosser     isl_set_free(Set);
311982f2af35STobias Grosser     isl_pw_aff_free(OneAff);
312082f2af35STobias Grosser 
312182f2af35STobias Grosser     return Expr;
312282f2af35STobias Grosser   }
312382f2af35STobias Grosser 
312482f2af35STobias Grosser   /// Approximate a number of dynamic instructions executed by a given
312582f2af35STobias Grosser   /// statement.
312682f2af35STobias Grosser   ///
312782f2af35STobias Grosser   /// @param Stmt  The statement for which to compute the number of dynamic
312882f2af35STobias Grosser   ///              instructions.
312982f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
313082f2af35STobias Grosser   ///              expression.
313182f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
313282f2af35STobias Grosser   ///          by @p Stmt.
313382f2af35STobias Grosser   __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt,
313482f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
313582f2af35STobias Grosser     auto Iterations = approxPointsInSet(Stmt.getDomain(), Build);
313682f2af35STobias Grosser 
313782f2af35STobias Grosser     long InstCount = 0;
313882f2af35STobias Grosser 
313982f2af35STobias Grosser     if (Stmt.isBlockStmt()) {
314082f2af35STobias Grosser       auto *BB = Stmt.getBasicBlock();
314182f2af35STobias Grosser       InstCount = std::distance(BB->begin(), BB->end());
314282f2af35STobias Grosser     } else {
314382f2af35STobias Grosser       auto *R = Stmt.getRegion();
314482f2af35STobias Grosser 
314582f2af35STobias Grosser       for (auto *BB : R->blocks()) {
314682f2af35STobias Grosser         InstCount += std::distance(BB->begin(), BB->end());
314782f2af35STobias Grosser       }
314882f2af35STobias Grosser     }
314982f2af35STobias Grosser 
315082f2af35STobias Grosser     isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount);
315182f2af35STobias Grosser     auto *InstExpr = isl_ast_expr_from_val(InstVal);
315282f2af35STobias Grosser     return isl_ast_expr_mul(InstExpr, Iterations);
315382f2af35STobias Grosser   }
315482f2af35STobias Grosser 
315582f2af35STobias Grosser   /// Approximate dynamic instructions executed in scop.
315682f2af35STobias Grosser   ///
315782f2af35STobias Grosser   /// @param S     The scop for which to approximate dynamic instructions.
315882f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
315982f2af35STobias Grosser   ///              expression.
316082f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
316182f2af35STobias Grosser   ///          in @p S.
316282f2af35STobias Grosser   __isl_give isl_ast_expr *
316382f2af35STobias Grosser   getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) {
316482f2af35STobias Grosser     isl_ast_expr *Instructions;
316582f2af35STobias Grosser 
316682f2af35STobias Grosser     isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0);
316782f2af35STobias Grosser     Instructions = isl_ast_expr_from_val(Zero);
316882f2af35STobias Grosser 
316982f2af35STobias Grosser     for (ScopStmt &Stmt : S) {
317082f2af35STobias Grosser       isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build);
317182f2af35STobias Grosser       Instructions = isl_ast_expr_add(Instructions, StmtInstructions);
317282f2af35STobias Grosser     }
317382f2af35STobias Grosser     return Instructions;
317482f2af35STobias Grosser   }
317582f2af35STobias Grosser 
317682f2af35STobias Grosser   /// Create a check that ensures sufficient compute in scop.
317782f2af35STobias Grosser   ///
317882f2af35STobias Grosser   /// @param S     The scop for which to ensure sufficient compute.
317982f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
318082f2af35STobias Grosser   ///              expression.
318182f2af35STobias Grosser   /// @returns An expression that evaluates to TRUE in case of sufficient
318282f2af35STobias Grosser   ///          compute and to FALSE, otherwise.
318382f2af35STobias Grosser   __isl_give isl_ast_expr *
318482f2af35STobias Grosser   createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) {
318582f2af35STobias Grosser     auto Iterations = getNumberOfIterations(S, Build);
318682f2af35STobias Grosser     auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute);
318782f2af35STobias Grosser     auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal);
318882f2af35STobias Grosser     return isl_ast_expr_ge(Iterations, MinComputeExpr);
318982f2af35STobias Grosser   }
319082f2af35STobias Grosser 
3191f291c8d5SSiddharth Bhat   /// Check if the basic block contains a function we cannot codegen for GPU
3192f291c8d5SSiddharth Bhat   /// kernels.
3193f291c8d5SSiddharth Bhat   ///
3194f291c8d5SSiddharth Bhat   /// If this basic block does something with a `Function` other than calling
3195f291c8d5SSiddharth Bhat   /// a function that we support in a kernel, return true.
31968fc6cdfbSTobias Grosser   bool containsInvalidKernelFunctionInBlock(const BasicBlock *BB,
31978fc6cdfbSTobias Grosser                                             bool AllowCUDALibDevice) {
3198f291c8d5SSiddharth Bhat     for (const Instruction &Inst : *BB) {
3199f291c8d5SSiddharth Bhat       const CallInst *Call = dyn_cast<CallInst>(&Inst);
32008fc6cdfbSTobias Grosser       if (Call && isValidFunctionInKernel(Call->getCalledFunction(),
32018fc6cdfbSTobias Grosser                                           AllowCUDALibDevice)) {
3202f291c8d5SSiddharth Bhat         continue;
3203f291c8d5SSiddharth Bhat       }
3204f291c8d5SSiddharth Bhat 
3205bccaea57SSiddharth Bhat       for (Value *SrcVal : Inst.operands()) {
3206bccaea57SSiddharth Bhat         PointerType *p = dyn_cast<PointerType>(SrcVal->getType());
3207bccaea57SSiddharth Bhat         if (!p)
3208bccaea57SSiddharth Bhat           continue;
3209bccaea57SSiddharth Bhat         if (isa<FunctionType>(p->getElementType()))
3210bccaea57SSiddharth Bhat           return true;
3211bccaea57SSiddharth Bhat       }
3212f291c8d5SSiddharth Bhat     }
3213bccaea57SSiddharth Bhat     return false;
3214bccaea57SSiddharth Bhat   }
3215bccaea57SSiddharth Bhat 
3216f291c8d5SSiddharth Bhat   /// Return whether the Scop S uses functions in a way that we do not support.
32178fc6cdfbSTobias Grosser   bool containsInvalidKernelFunction(const Scop &S, bool AllowCUDALibDevice) {
3218bccaea57SSiddharth Bhat     for (auto &Stmt : S) {
3219bccaea57SSiddharth Bhat       if (Stmt.isBlockStmt()) {
32208fc6cdfbSTobias Grosser         if (containsInvalidKernelFunctionInBlock(Stmt.getBasicBlock(),
32218fc6cdfbSTobias Grosser                                                  AllowCUDALibDevice))
3222bccaea57SSiddharth Bhat           return true;
3223bccaea57SSiddharth Bhat       } else {
3224bccaea57SSiddharth Bhat         assert(Stmt.isRegionStmt() &&
3225bccaea57SSiddharth Bhat                "Stmt was neither block nor region statement");
3226bccaea57SSiddharth Bhat         for (const BasicBlock *BB : Stmt.getRegion()->blocks())
32278fc6cdfbSTobias Grosser           if (containsInvalidKernelFunctionInBlock(BB, AllowCUDALibDevice))
3228bccaea57SSiddharth Bhat             return true;
3229bccaea57SSiddharth Bhat       }
3230bccaea57SSiddharth Bhat     }
3231bccaea57SSiddharth Bhat     return false;
3232bccaea57SSiddharth Bhat   }
3233bccaea57SSiddharth Bhat 
323438fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
323538fc0aedSTobias Grosser   ///
323632837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
323732837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
323832837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
323938fc0aedSTobias Grosser     ScopAnnotator Annotator;
324038fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
324138fc0aedSTobias Grosser 
324238fc0aedSTobias Grosser     Region *R = &S->getRegion();
324338fc0aedSTobias Grosser 
324438fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
324538fc0aedSTobias Grosser 
324638fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
324738fc0aedSTobias Grosser 
324838fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
324938fc0aedSTobias Grosser 
325038fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
325138fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
325238fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
325338fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
325438fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
325538fc0aedSTobias Grosser     // code generating this scop.
325603346c27SSiddharth Bhat     BBPair StartExitBlocks;
325703346c27SSiddharth Bhat     BranchInst *CondBr = nullptr;
325803346c27SSiddharth Bhat     std::tie(StartExitBlocks, CondBr) =
32592d950f36SPhilip Pfaffe         executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI);
3260256070d8SAndreas Simbuerger     BasicBlock *StartBlock = std::get<0>(StartExitBlocks);
326138fc0aedSTobias Grosser 
326203346c27SSiddharth Bhat     assert(CondBr && "CondBr not initialized by executeScopConditionally");
326303346c27SSiddharth Bhat 
32642d950f36SPhilip Pfaffe     GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S,
326517f01968SSiddharth Bhat                                StartBlock, Prog, Runtime, Architecture);
3266acf80064SEli Friedman 
326738fc0aedSTobias Grosser     // TODO: Handle LICM
326838fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
326938fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
327038fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
3271cb1aef8dSTobias Grosser 
3272cb1aef8dSTobias Grosser     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx());
32732b852e2eSPhilip Pfaffe     isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build);
327482f2af35STobias Grosser     isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build);
327582f2af35STobias Grosser     Condition = isl_ast_expr_and(Condition, SufficientCompute);
3276cb1aef8dSTobias Grosser     isl_ast_build_free(Build);
3277cb1aef8dSTobias Grosser 
32789e3db2b7SSiddharth Bhat     // preload invariant loads. Note: This should happen before the RTC
32799e3db2b7SSiddharth Bhat     // because the RTC may depend on values that are invariant load hoisted.
32804ebeb356SSiddharth Bhat     if (!NodeBuilder.preloadInvariantLoads())
32814ebeb356SSiddharth Bhat       report_fatal_error("preloading invariant loads failed in function: " +
32824ebeb356SSiddharth Bhat                          S->getFunction().getName() +
32834ebeb356SSiddharth Bhat                          " | Scop Region: " + S->getNameStr());
32849e3db2b7SSiddharth Bhat 
3285cb1aef8dSTobias Grosser     Value *RTC = NodeBuilder.createRTC(Condition);
3286cb1aef8dSTobias Grosser     Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
3287cb1aef8dSTobias Grosser 
328838fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
3289fa7b0802STobias Grosser 
329038fc0aedSTobias Grosser     NodeBuilder.create(Root);
32915857b701STobias Grosser 
3292bc653f20STobias Grosser     /// In case a sequential kernel has more surrounding loops as any parallel
3293bc653f20STobias Grosser     /// kernel, the SCoP is probably mostly sequential. Hence, there is no
3294de244eb4STobias Grosser     /// point in running it on a GPU.
3295bc653f20STobias Grosser     if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel)
329603346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
3297bc653f20STobias Grosser 
32985857b701STobias Grosser     if (!NodeBuilder.BuildSuccessful)
329903346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
330038fc0aedSTobias Grosser   }
330138fc0aedSTobias Grosser 
3302e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
3303e938517eSTobias Grosser     S = &CurrentScop;
330438fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
330538fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
330638fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
33077b5a4dfdSTobias Grosser     DL = &S->getRegion().getEntry()->getModule()->getDataLayout();
330838fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
3309e938517eSTobias Grosser 
3310f291c8d5SSiddharth Bhat     // We currently do not support functions other than intrinsics inside
3311f291c8d5SSiddharth Bhat     // kernels, as code generation will need to offload function calls to the
3312f291c8d5SSiddharth Bhat     // kernel. This may lead to a kernel trying to call a function on the host.
3313bccaea57SSiddharth Bhat     // This also allows us to prevent codegen from trying to take the
3314bccaea57SSiddharth Bhat     // address of an intrinsic function to send to the kernel.
33158fc6cdfbSTobias Grosser     if (containsInvalidKernelFunction(CurrentScop,
33168fc6cdfbSTobias Grosser                                       Architecture == GPUArch::NVPTX64)) {
3317f291c8d5SSiddharth Bhat       DEBUG(
3318f291c8d5SSiddharth Bhat           dbgs()
3319f291c8d5SSiddharth Bhat               << "Scop contains function which cannot be materialised in a GPU "
3320f291c8d5SSiddharth Bhat                  "kernel. Bailing out.\n";);
3321bccaea57SSiddharth Bhat       return false;
3322f291c8d5SSiddharth Bhat     }
3323bccaea57SSiddharth Bhat 
3324e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
3325e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
3326f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
332738fc0aedSTobias Grosser 
332802ca346eSSingapuram Sanjay Srivallabh     if (PPCGGen->tree) {
332932837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
333002ca346eSSingapuram Sanjay Srivallabh       CurrentScop.markAsToBeSkipped();
333102ca346eSSingapuram Sanjay Srivallabh     }
333238fc0aedSTobias Grosser 
3333b307ed4dSTobias Grosser     freeOptions(PPCGScop);
3334f384594dSTobias Grosser     freePPCGGen(PPCGGen);
3335e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
3336e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
3337e938517eSTobias Grosser 
3338e938517eSTobias Grosser     return true;
3339e938517eSTobias Grosser   }
33409dfe4e7cSTobias Grosser 
33419dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
33429dfe4e7cSTobias Grosser 
33439dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
33449dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
33459dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
33469dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
33475cc87e3aSPhilip Pfaffe     AU.addRequired<ScopDetectionWrapperPass>();
33489dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
33499dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
33509dfe4e7cSTobias Grosser 
33519dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
33529dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
33539dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
33549dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
33559dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
33565cc87e3aSPhilip Pfaffe     AU.addPreserved<ScopDetectionWrapperPass>();
33579dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
33589dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
33599dfe4e7cSTobias Grosser 
33609dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
33619dfe4e7cSTobias Grosser     //        region tree.
33629dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
33639dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
33649dfe4e7cSTobias Grosser   }
33659dfe4e7cSTobias Grosser };
336624222c73STobias Grosser } // namespace
33679dfe4e7cSTobias Grosser 
33689dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
33699dfe4e7cSTobias Grosser 
337017f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) {
337117f01968SSiddharth Bhat   PPCGCodeGeneration *generator = new PPCGCodeGeneration();
337217f01968SSiddharth Bhat   generator->Runtime = Runtime;
337317f01968SSiddharth Bhat   generator->Architecture = Arch;
337417f01968SSiddharth Bhat   return generator;
337517f01968SSiddharth Bhat }
33769dfe4e7cSTobias Grosser 
33779dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
33789dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
33799dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
33809dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
33819dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
33829dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
33839dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
33845cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
33859dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
33869dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
3387