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 
122*638316daSSiddharth Bhat /// Return  a unique name for a Scop, which is the scop region with the
123*638316daSSiddharth Bhat /// function name.
124*638316daSSiddharth Bhat std::string getUniqueScopName(const Scop *S) {
125*638316daSSiddharth Bhat   return "Scop Region: " + S->getNameStr() +
126*638316daSSiddharth Bhat          " | Function: " + std::string(S->getFunction().getName());
127*638316daSSiddharth Bhat }
128*638316daSSiddharth Bhat 
129a82f2d26SSiddharth Bhat /// Used to store information PPCG wants for kills. This information is
130a82f2d26SSiddharth Bhat /// used by live range reordering.
131a82f2d26SSiddharth Bhat ///
132a82f2d26SSiddharth Bhat /// @see computeLiveRangeReordering
133a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGScop
134a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGProg
135a82f2d26SSiddharth Bhat struct MustKillsInfo {
136a82f2d26SSiddharth Bhat   /// Collection of all kill statements that will be sequenced at the end of
137a82f2d26SSiddharth Bhat   /// PPCGScop->schedule.
138a82f2d26SSiddharth Bhat   ///
139a82f2d26SSiddharth Bhat   /// The nodes in `KillsSchedule` will be merged using `isl_schedule_set`
140a82f2d26SSiddharth Bhat   /// which merges schedules in *arbitrary* order.
141a82f2d26SSiddharth Bhat   /// (we don't care about the order of the kills anyway).
142a82f2d26SSiddharth Bhat   isl::schedule KillsSchedule;
143a82f2d26SSiddharth Bhat   /// Map from kill statement instances to scalars that need to be
144a82f2d26SSiddharth Bhat   /// killed.
145a82f2d26SSiddharth Bhat   ///
146edfef5aeSSiddharth Bhat   /// We currently derive kill information for:
147edfef5aeSSiddharth Bhat   ///  1. phi nodes. PHI nodes are not alive outside the scop and can
148edfef5aeSSiddharth Bhat   ///     consequently all be killed.
149edfef5aeSSiddharth Bhat   ///  2. Scalar arrays that are not used outside the Scop. This is
150edfef5aeSSiddharth Bhat   ///     checked by `isScalarUsesContainedInScop`.
151edfef5aeSSiddharth Bhat   /// [params] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] }
152a82f2d26SSiddharth Bhat   isl::union_map TaggedMustKills;
153a82f2d26SSiddharth Bhat 
1549e3db2b7SSiddharth Bhat   /// Tagged must kills stripped of the tags.
1559e3db2b7SSiddharth Bhat   /// [params] -> { Stmt_phantom[]  -> scalar_to_kill[] }
1569e3db2b7SSiddharth Bhat   isl::union_map MustKills;
1579e3db2b7SSiddharth Bhat 
1589e3db2b7SSiddharth Bhat   MustKillsInfo() : KillsSchedule(nullptr) {}
159a82f2d26SSiddharth Bhat };
160a82f2d26SSiddharth Bhat 
161761e5b93SSiddharth Bhat /// Check if SAI's uses are entirely contained within Scop S.
162761e5b93SSiddharth Bhat /// If a scalar is used only with a Scop, we are free to kill it, as no data
163761e5b93SSiddharth Bhat /// can flow in/out of the value any more.
164761e5b93SSiddharth Bhat /// @see computeMustKillsInfo
165761e5b93SSiddharth Bhat static bool isScalarUsesContainedInScop(const Scop &S,
166761e5b93SSiddharth Bhat                                         const ScopArrayInfo *SAI) {
167761e5b93SSiddharth Bhat   assert(SAI->isValueKind() && "this function only deals with scalars."
168761e5b93SSiddharth Bhat                                " Dealing with arrays required alias analysis");
169761e5b93SSiddharth Bhat 
170761e5b93SSiddharth Bhat   const Region &R = S.getRegion();
171761e5b93SSiddharth Bhat   for (User *U : SAI->getBasePtr()->users()) {
172761e5b93SSiddharth Bhat     Instruction *I = dyn_cast<Instruction>(U);
173761e5b93SSiddharth Bhat     assert(I && "invalid user of scop array info");
174761e5b93SSiddharth Bhat     if (!R.contains(I))
175761e5b93SSiddharth Bhat       return false;
176761e5b93SSiddharth Bhat   }
177761e5b93SSiddharth Bhat   return true;
178761e5b93SSiddharth Bhat }
179761e5b93SSiddharth Bhat 
180a82f2d26SSiddharth Bhat /// Compute must-kills needed to enable live range reordering with PPCG.
181a82f2d26SSiddharth Bhat ///
182a82f2d26SSiddharth Bhat /// @params S The Scop to compute live range reordering information
183a82f2d26SSiddharth Bhat /// @returns live range reordering information that can be used to setup
184a82f2d26SSiddharth Bhat /// PPCG.
185a82f2d26SSiddharth Bhat static MustKillsInfo computeMustKillsInfo(const Scop &S) {
186a82f2d26SSiddharth Bhat   const isl::space ParamSpace(isl::manage(S.getParamSpace()));
187a82f2d26SSiddharth Bhat   MustKillsInfo Info;
188a82f2d26SSiddharth Bhat 
189761e5b93SSiddharth Bhat   // 1. Collect all ScopArrayInfo that satisfy *any* of the criteria:
190761e5b93SSiddharth Bhat   //      1.1 phi nodes in scop.
191761e5b93SSiddharth Bhat   //      1.2 scalars that are only used within the scop
192a82f2d26SSiddharth Bhat   SmallVector<isl::id, 4> KillMemIds;
193a82f2d26SSiddharth Bhat   for (ScopArrayInfo *SAI : S.arrays()) {
194761e5b93SSiddharth Bhat     if (SAI->isPHIKind() ||
195761e5b93SSiddharth Bhat         (SAI->isValueKind() && isScalarUsesContainedInScop(S, SAI)))
19677eef90fSTobias Grosser       KillMemIds.push_back(isl::manage(SAI->getBasePtrId().release()));
197a82f2d26SSiddharth Bhat   }
198a82f2d26SSiddharth Bhat 
199a82f2d26SSiddharth Bhat   Info.TaggedMustKills = isl::union_map::empty(isl::space(ParamSpace));
2009e3db2b7SSiddharth Bhat   Info.MustKills = isl::union_map::empty(isl::space(ParamSpace));
201a82f2d26SSiddharth Bhat 
202a82f2d26SSiddharth Bhat   // Initialising KillsSchedule to `isl_set_empty` creates an empty node in the
203a82f2d26SSiddharth Bhat   // schedule:
204a82f2d26SSiddharth Bhat   //     - filter: "[control] -> { }"
205a82f2d26SSiddharth Bhat   // So, we choose to not create this to keep the output a little nicer,
206a82f2d26SSiddharth Bhat   // at the cost of some code complexity.
207a82f2d26SSiddharth Bhat   Info.KillsSchedule = nullptr;
208a82f2d26SSiddharth Bhat 
209edfef5aeSSiddharth Bhat   for (isl::id &ToKillId : KillMemIds) {
210a82f2d26SSiddharth Bhat     isl::id KillStmtId = isl::id::alloc(
211edfef5aeSSiddharth Bhat         S.getIslCtx(),
212edfef5aeSSiddharth Bhat         std::string("SKill_phantom_").append(ToKillId.get_name()), nullptr);
213a82f2d26SSiddharth Bhat 
214a82f2d26SSiddharth Bhat     // NOTE: construction of tagged_must_kill:
215a82f2d26SSiddharth Bhat     // 2. We need to construct a map:
216edfef5aeSSiddharth Bhat     //     [param] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] }
217a82f2d26SSiddharth Bhat     // To construct this, we use `isl_map_domain_product` on 2 maps`:
218edfef5aeSSiddharth Bhat     // 2a. StmtToScalar:
219edfef5aeSSiddharth Bhat     //         [param] -> { Stmt_phantom[] -> scalar_to_kill[] }
220edfef5aeSSiddharth Bhat     // 2b. PhantomRefToScalar:
221edfef5aeSSiddharth Bhat     //         [param] -> { ref_phantom[] -> scalar_to_kill[] }
222a82f2d26SSiddharth Bhat     //
223a82f2d26SSiddharth Bhat     // Combining these with `isl_map_domain_product` gives us
224a82f2d26SSiddharth Bhat     // TaggedMustKill:
225edfef5aeSSiddharth Bhat     //     [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] }
226a82f2d26SSiddharth Bhat 
227edfef5aeSSiddharth Bhat     // 2a. [param] -> { Stmt[] -> scalar_to_kill[] }
228edfef5aeSSiddharth Bhat     isl::map StmtToScalar = isl::map::universe(isl::space(ParamSpace));
229edfef5aeSSiddharth Bhat     StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::in, isl::id(KillStmtId));
230edfef5aeSSiddharth Bhat     StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::out, isl::id(ToKillId));
231a82f2d26SSiddharth Bhat 
232a82f2d26SSiddharth Bhat     isl::id PhantomRefId = isl::id::alloc(
233edfef5aeSSiddharth Bhat         S.getIslCtx(), std::string("ref_phantom") + ToKillId.get_name(),
234edfef5aeSSiddharth Bhat         nullptr);
235a82f2d26SSiddharth Bhat 
236edfef5aeSSiddharth Bhat     // 2b. [param] -> { phantom_ref[] -> scalar_to_kill[] }
237edfef5aeSSiddharth Bhat     isl::map PhantomRefToScalar = isl::map::universe(isl::space(ParamSpace));
238edfef5aeSSiddharth Bhat     PhantomRefToScalar =
239edfef5aeSSiddharth Bhat         PhantomRefToScalar.set_tuple_id(isl::dim::in, PhantomRefId);
240edfef5aeSSiddharth Bhat     PhantomRefToScalar =
241edfef5aeSSiddharth Bhat         PhantomRefToScalar.set_tuple_id(isl::dim::out, ToKillId);
242a82f2d26SSiddharth Bhat 
243edfef5aeSSiddharth Bhat     // 2. [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] }
244edfef5aeSSiddharth Bhat     isl::map TaggedMustKill = StmtToScalar.domain_product(PhantomRefToScalar);
245a82f2d26SSiddharth Bhat     Info.TaggedMustKills = Info.TaggedMustKills.unite(TaggedMustKill);
246a82f2d26SSiddharth Bhat 
2479e3db2b7SSiddharth Bhat     // 2. [param] -> { Stmt[] -> scalar_to_kill[] }
2489e3db2b7SSiddharth Bhat     Info.MustKills = Info.TaggedMustKills.domain_factor_domain();
2499e3db2b7SSiddharth Bhat 
250a82f2d26SSiddharth Bhat     // 3. Create the kill schedule of the form:
251a82f2d26SSiddharth Bhat     //     "[param] -> { Stmt_phantom[] }"
252a82f2d26SSiddharth Bhat     // Then add this to Info.KillsSchedule.
253a82f2d26SSiddharth Bhat     isl::space KillStmtSpace = ParamSpace;
254a82f2d26SSiddharth Bhat     KillStmtSpace = KillStmtSpace.set_tuple_id(isl::dim::set, KillStmtId);
255a82f2d26SSiddharth Bhat     isl::union_set KillStmtDomain = isl::set::universe(KillStmtSpace);
256a82f2d26SSiddharth Bhat 
257a82f2d26SSiddharth Bhat     isl::schedule KillSchedule = isl::schedule::from_domain(KillStmtDomain);
258a82f2d26SSiddharth Bhat     if (Info.KillsSchedule)
259a82f2d26SSiddharth Bhat       Info.KillsSchedule = Info.KillsSchedule.set(KillSchedule);
260a82f2d26SSiddharth Bhat     else
261a82f2d26SSiddharth Bhat       Info.KillsSchedule = KillSchedule;
262a82f2d26SSiddharth Bhat   }
263a82f2d26SSiddharth Bhat 
264a82f2d26SSiddharth Bhat   return Info;
265a82f2d26SSiddharth Bhat }
266a82f2d26SSiddharth Bhat 
26760c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
26860c60025STobias Grosser ///
26960c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
27060c60025STobias Grosser /// of the scheduled ScopStmts.
27160c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
27235de9009SSiddharth Bhat     void *StmtT, __isl_take isl_ast_build *Build_C,
27360c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
27460c60025STobias Grosser                                        isl_id *Id, void *User),
27560c60025STobias Grosser     void *UserIndex,
27660c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
277edb885cbSTobias Grosser     void *UserExpr) {
27860c60025STobias Grosser 
279edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
28060c60025STobias Grosser 
28135de9009SSiddharth Bhat   if (!Stmt || !Build_C)
282edb885cbSTobias Grosser     return NULL;
283edb885cbSTobias Grosser 
28435de9009SSiddharth Bhat   isl::ast_build Build = isl::manage(isl_ast_build_copy(Build_C));
28535de9009SSiddharth Bhat   isl::ctx Ctx = Build.get_ctx();
28635de9009SSiddharth Bhat   isl::id_to_ast_expr RefToExpr = isl::id_to_ast_expr::alloc(Ctx, 0);
287edb885cbSTobias Grosser 
288edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
28935de9009SSiddharth Bhat     isl::map AddrFunc = Acc->getAddressFunction();
29035de9009SSiddharth Bhat     AddrFunc = AddrFunc.intersect_domain(isl::manage(Stmt->getDomain()));
29135de9009SSiddharth Bhat 
29235de9009SSiddharth Bhat     isl::id RefId = Acc->getId();
29335de9009SSiddharth Bhat     isl::pw_multi_aff PMA = isl::pw_multi_aff::from_map(AddrFunc);
29435de9009SSiddharth Bhat 
29535de9009SSiddharth Bhat     isl::multi_pw_aff MPA = isl::multi_pw_aff(PMA);
29635de9009SSiddharth Bhat     MPA = MPA.coalesce();
29735de9009SSiddharth Bhat     MPA = isl::manage(FunctionIndex(MPA.release(), RefId.get(), UserIndex));
29835de9009SSiddharth Bhat 
29935de9009SSiddharth Bhat     isl::ast_expr Access = Build.access_from(MPA);
30035de9009SSiddharth Bhat     Access = isl::manage(FunctionExpr(Access.release(), RefId.get(), UserExpr));
30135de9009SSiddharth Bhat     RefToExpr = RefToExpr.set(RefId, Access);
302edb885cbSTobias Grosser   }
303edb885cbSTobias Grosser 
30435de9009SSiddharth Bhat   return RefToExpr.release();
30560c60025STobias Grosser }
306f384594dSTobias Grosser 
307a90be207SSiddharth Bhat /// Given a LLVM Type, compute its size in bytes,
308a90be207SSiddharth Bhat static int computeSizeInBytes(const Type *T) {
309a90be207SSiddharth Bhat   int bytes = T->getPrimitiveSizeInBits() / 8;
310a90be207SSiddharth Bhat   if (bytes == 0)
311a90be207SSiddharth Bhat     bytes = T->getScalarSizeInBits() / 8;
312a90be207SSiddharth Bhat   return bytes;
313a90be207SSiddharth Bhat }
314a90be207SSiddharth Bhat 
31538fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
31638fc0aedSTobias Grosser ///
31738fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
318a6d48f59SMichael Kruse /// generates code for general-purpose AST nodes, with special functionality
31938fc0aedSTobias Grosser /// for generating GPU specific user nodes.
32038fc0aedSTobias Grosser ///
32138fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
32238fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
32338fc0aedSTobias Grosser public:
3242d950f36SPhilip Pfaffe   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator,
32538fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
326acf80064SEli Friedman                  DominatorTree &DT, Scop &S, BasicBlock *StartBlock,
32717f01968SSiddharth Bhat                  gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch)
3282d950f36SPhilip Pfaffe       : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock),
32917f01968SSiddharth Bhat         Prog(Prog), Runtime(Runtime), Arch(Arch) {
330edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
331edb885cbSTobias Grosser   }
33238fc0aedSTobias Grosser 
333fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
334fa7b0802STobias Grosser   void initializeAfterRTH();
335fa7b0802STobias Grosser 
336fa7b0802STobias Grosser   /// Finalize the generated scop.
337fa7b0802STobias Grosser   virtual void finalize();
338fa7b0802STobias Grosser 
3395857b701STobias Grosser   /// Track if the full build process was successful.
3405857b701STobias Grosser   ///
3415857b701STobias Grosser   /// This value is set to false, if throughout the build process an error
3425857b701STobias Grosser   /// occurred which prevents us from generating valid GPU code.
3435857b701STobias Grosser   bool BuildSuccessful = true;
3445857b701STobias Grosser 
345bc653f20STobias Grosser   /// The maximal number of loops surrounding a sequential kernel.
346bc653f20STobias Grosser   unsigned DeepestSequential = 0;
347bc653f20STobias Grosser 
348bc653f20STobias Grosser   /// The maximal number of loops surrounding a parallel kernel.
349bc653f20STobias Grosser   unsigned DeepestParallel = 0;
350bc653f20STobias Grosser 
35179f13b9aSSingapuram Sanjay Srivallabh   /// Return the name to set for the ptx_kernel.
35279f13b9aSSingapuram Sanjay Srivallabh   std::string getKernelFuncName(int Kernel_id);
35379f13b9aSSingapuram Sanjay Srivallabh 
35438fc0aedSTobias Grosser private:
35574dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
35674dc3cb4STobias Grosser   ///
35774dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
35874dc3cb4STobias Grosser   /// more.
35974dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
36074dc3cb4STobias Grosser 
36113c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
36213c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
3637287aeddSTobias Grosser 
364fa7b0802STobias Grosser   /// The current GPU context.
365fa7b0802STobias Grosser   Value *GPUContext;
366fa7b0802STobias Grosser 
367b513b491STobias Grosser   /// The set of isl_ids allocated in the kernel
368b513b491STobias Grosser   std::vector<isl_id *> KernelIds;
369b513b491STobias Grosser 
37032837fe3STobias Grosser   /// A module containing GPU code.
37132837fe3STobias Grosser   ///
37232837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
37332837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
37432837fe3STobias Grosser 
37532837fe3STobias Grosser   /// The GPU program we generate code for.
37632837fe3STobias Grosser   gpu_prog *Prog;
37732837fe3STobias Grosser 
37817f01968SSiddharth Bhat   /// The GPU Runtime implementation to use (OpenCL or CUDA).
37917f01968SSiddharth Bhat   GPURuntime Runtime;
38017f01968SSiddharth Bhat 
38117f01968SSiddharth Bhat   /// The GPU Architecture to target.
38217f01968SSiddharth Bhat   GPUArch Arch;
38317f01968SSiddharth Bhat 
384472f9654STobias Grosser   /// Class to free isl_ids.
385472f9654STobias Grosser   class IslIdDeleter {
386472f9654STobias Grosser   public:
387472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
388472f9654STobias Grosser   };
389472f9654STobias Grosser 
390472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
391472f9654STobias Grosser   ///
392472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
393472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
394472f9654STobias Grosser 
395edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
396edb885cbSTobias Grosser 
39738fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
39838fc0aedSTobias Grosser   ///
39938fc0aedSTobias Grosser   /// These AST nodes can be of type:
40038fc0aedSTobias Grosser   ///
40138fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
40238fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
40313c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
4045260c041STobias Grosser   ///   - In-kernel synchronization
4055260c041STobias Grosser   ///   - In-kernel memory copy statement
40638fc0aedSTobias Grosser   ///
4071fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
4081fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
40932837fe3STobias Grosser 
41013c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
41113c78e4dSTobias Grosser 
41213c78e4dSTobias Grosser   /// Create code for a data transfer statement
41313c78e4dSTobias Grosser   ///
41413c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
41513c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
41613c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
41713c78e4dSTobias Grosser                           enum DataDirection Direction);
41813c78e4dSTobias Grosser 
419edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
420edb885cbSTobias Grosser   ///
421edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
422edb885cbSTobias Grosser   ///
423f291c8d5SSiddharth Bhat   /// @returns A pair, whose first element contains the set of values
424f291c8d5SSiddharth Bhat   ///          referenced by the kernel, and whose second element contains the
425f291c8d5SSiddharth Bhat   ///          set of functions referenced by the kernel. All functions in the
426f291c8d5SSiddharth Bhat   ///          second set satisfy isValidFunctionInKernel.
427f291c8d5SSiddharth Bhat   std::pair<SetVector<Value *>, SetVector<Function *>>
428f291c8d5SSiddharth Bhat   getReferencesInKernel(ppcg_kernel *Kernel);
429edb885cbSTobias Grosser 
43079a947c2STobias Grosser   /// Compute the sizes of the execution grid for a given kernel.
43179a947c2STobias Grosser   ///
43279a947c2STobias Grosser   /// @param Kernel The kernel to compute grid sizes for.
43379a947c2STobias Grosser   ///
43479a947c2STobias Grosser   /// @returns A tuple with grid sizes for X and Y dimension
43579a947c2STobias Grosser   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
43679a947c2STobias Grosser 
437abed4969SSiddharth Bhat   /// Creates a array that can be sent to the kernel on the device using a
438abed4969SSiddharth Bhat   /// host pointer. This is required for managed memory, when we directly send
439abed4969SSiddharth Bhat   /// host pointers to the device.
440abed4969SSiddharth Bhat   /// \note
441abed4969SSiddharth Bhat   /// This is to be used only with managed memory
442abed4969SSiddharth Bhat   Value *getOrCreateManagedDeviceArray(gpu_array_info *Array,
443abed4969SSiddharth Bhat                                        ScopArrayInfo *ArrayInfo);
444abed4969SSiddharth Bhat 
44579a947c2STobias Grosser   /// Compute the sizes of the thread blocks for a given kernel.
44679a947c2STobias Grosser   ///
44779a947c2STobias Grosser   /// @param Kernel The kernel to compute thread block sizes for.
44879a947c2STobias Grosser   ///
44979a947c2STobias Grosser   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
45079a947c2STobias Grosser   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
45179a947c2STobias Grosser 
452a90be207SSiddharth Bhat   /// Store a specific kernel launch parameter in the array of kernel launch
453a90be207SSiddharth Bhat   /// parameters.
454a90be207SSiddharth Bhat   ///
455a90be207SSiddharth Bhat   /// @param Parameters The list of parameters in which to store.
456a90be207SSiddharth Bhat   /// @param Param      The kernel launch parameter to store.
457a90be207SSiddharth Bhat   /// @param Index      The index in the parameter list, at which to store the
458a90be207SSiddharth Bhat   ///                   parameter.
459a90be207SSiddharth Bhat   void insertStoreParameter(Instruction *Parameters, Instruction *Param,
460a90be207SSiddharth Bhat                             int Index);
461a90be207SSiddharth Bhat 
46279a947c2STobias Grosser   /// Create kernel launch parameters.
46379a947c2STobias Grosser   ///
46479a947c2STobias Grosser   /// @param Kernel        The kernel to create parameters for.
46579a947c2STobias Grosser   /// @param F             The kernel function that has been created.
46657693272STobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
46779a947c2STobias Grosser   ///
46879a947c2STobias Grosser   /// @returns A stack allocated array with pointers to the parameter
46979a947c2STobias Grosser   ///          values that are passed to the kernel.
47057693272STobias Grosser   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
47157693272STobias Grosser                                 SetVector<Value *> SubtreeValues);
47279a947c2STobias Grosser 
473b513b491STobias Grosser   /// Create declarations for kernel variable.
474b513b491STobias Grosser   ///
475b513b491STobias Grosser   /// This includes shared memory declarations.
476b513b491STobias Grosser   ///
477b513b491STobias Grosser   /// @param Kernel        The kernel definition to create variables for.
478b513b491STobias Grosser   /// @param FN            The function into which to generate the variables.
479b513b491STobias Grosser   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
480b513b491STobias Grosser 
481c1c6a2a6STobias Grosser   /// Add CUDA annotations to module.
482c1c6a2a6STobias Grosser   ///
483c1c6a2a6STobias Grosser   /// Add a set of CUDA annotations that declares the maximal block dimensions
484c1c6a2a6STobias Grosser   /// that will be used to execute the CUDA kernel. This allows the NVIDIA
485c1c6a2a6STobias Grosser   /// PTX compiler to bound the number of allocated registers to ensure the
486c1c6a2a6STobias Grosser   /// resulting kernel is known to run with up to as many block dimensions
487c1c6a2a6STobias Grosser   /// as specified here.
488c1c6a2a6STobias Grosser   ///
489c1c6a2a6STobias Grosser   /// @param M         The module to add the annotations to.
490c1c6a2a6STobias Grosser   /// @param BlockDimX The size of block dimension X.
491c1c6a2a6STobias Grosser   /// @param BlockDimY The size of block dimension Y.
492c1c6a2a6STobias Grosser   /// @param BlockDimZ The size of block dimension Z.
493c1c6a2a6STobias Grosser   void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY,
494c1c6a2a6STobias Grosser                           Value *BlockDimZ);
495c1c6a2a6STobias Grosser 
49632837fe3STobias Grosser   /// Create GPU kernel.
49732837fe3STobias Grosser   ///
49832837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
49932837fe3STobias Grosser   ///
50032837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
50132837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
50232837fe3STobias Grosser 
50313c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
50413c78e4dSTobias Grosser   ///
50513c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
50613c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
50713c78e4dSTobias Grosser 
508aaabbbf8STobias Grosser   /// Generate code to compute the minimal offset at which an array is accessed.
509aaabbbf8STobias Grosser   ///
510aaabbbf8STobias Grosser   /// The offset of an array is the minimal array location accessed in a scop.
511aaabbbf8STobias Grosser   ///
512aaabbbf8STobias Grosser   /// Example:
513aaabbbf8STobias Grosser   ///
514aaabbbf8STobias Grosser   ///   for (long i = 0; i < 100; i++)
515aaabbbf8STobias Grosser   ///     A[i + 42] += ...
516aaabbbf8STobias Grosser   ///
517aaabbbf8STobias Grosser   ///   getArrayOffset(A) results in 42.
518aaabbbf8STobias Grosser   ///
519aaabbbf8STobias Grosser   /// @param Array The array for which to compute the offset.
520aaabbbf8STobias Grosser   /// @returns An llvm::Value that contains the offset of the array.
521aaabbbf8STobias Grosser   Value *getArrayOffset(gpu_array_info *Array);
522aaabbbf8STobias Grosser 
52300bb5a99STobias Grosser   /// Prepare the kernel arguments for kernel code generation
52400bb5a99STobias Grosser   ///
52500bb5a99STobias Grosser   /// @param Kernel The kernel to generate code for.
52600bb5a99STobias Grosser   /// @param FN     The function created for the kernel.
52700bb5a99STobias Grosser   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
52800bb5a99STobias Grosser 
52932837fe3STobias Grosser   /// Create kernel function.
53032837fe3STobias Grosser   ///
53132837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
53232837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
53332837fe3STobias Grosser   /// start block of this newly created function.
53432837fe3STobias Grosser   ///
53532837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
536edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
537f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by this
538f291c8d5SSiddharth Bhat   ///                         kernel.
539edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
540f291c8d5SSiddharth Bhat                             SetVector<Value *> &SubtreeValues,
541f291c8d5SSiddharth Bhat                             SetVector<Function *> &SubtreeFunctions);
54232837fe3STobias Grosser 
54332837fe3STobias Grosser   /// Create the declaration of a kernel function.
54432837fe3STobias Grosser   ///
54532837fe3STobias Grosser   /// The kernel function takes as arguments:
54632837fe3STobias Grosser   ///
54732837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
548f6044bd0STobias Grosser   ///   - Host iterators
549c84a1995STobias Grosser   ///   - Parameters
55032837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
55132837fe3STobias Grosser   ///
55232837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
553edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
554edb885cbSTobias Grosser   ///
55532837fe3STobias Grosser   /// @returns The newly declared function.
556edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
557edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
55832837fe3STobias Grosser 
559472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
560472f9654STobias Grosser   ///
561472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
562472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
563472f9654STobias Grosser 
5642f3073b5SPhilipp Schaad   /// Insert function calls to retrieve the SPIR group/local ids.
5652f3073b5SPhilipp Schaad   ///
5662f3073b5SPhilipp Schaad   /// @param The kernel to generate the function calls for.
5672f3073b5SPhilipp Schaad   void insertKernelCallsSPIR(ppcg_kernel *Kernel);
5682f3073b5SPhilipp Schaad 
569f291c8d5SSiddharth Bhat   /// Setup the creation of functions referenced by the GPU kernel.
570f291c8d5SSiddharth Bhat   ///
571f291c8d5SSiddharth Bhat   /// 1. Create new function declarations in GPUModule which are the same as
572f291c8d5SSiddharth Bhat   /// SubtreeFunctions.
573f291c8d5SSiddharth Bhat   ///
574f291c8d5SSiddharth Bhat   /// 2. Populate IslNodeBuilder::ValueMap with mappings from
575f291c8d5SSiddharth Bhat   /// old functions (that come from the original module) to new functions
576f291c8d5SSiddharth Bhat   /// (that are created within GPUModule). That way, we generate references
577f291c8d5SSiddharth Bhat   /// to the correct function (in GPUModule) in BlockGenerator.
578f291c8d5SSiddharth Bhat   ///
579f291c8d5SSiddharth Bhat   /// @see IslNodeBuilder::ValueMap
580f291c8d5SSiddharth Bhat   /// @see BlockGenerator::GlobalMap
581f291c8d5SSiddharth Bhat   /// @see BlockGenerator::getNewValue
582f291c8d5SSiddharth Bhat   /// @see GPUNodeBuilder::getReferencesInKernel.
583f291c8d5SSiddharth Bhat   ///
584f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by
585f291c8d5SSiddharth Bhat   ///                         this kernel.
586f291c8d5SSiddharth Bhat   void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions);
587f291c8d5SSiddharth Bhat 
588b513b491STobias Grosser   /// Create a global-to-shared or shared-to-global copy statement.
589b513b491STobias Grosser   ///
590b513b491STobias Grosser   /// @param CopyStmt The copy statement to generate code for
591b513b491STobias Grosser   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
592b513b491STobias Grosser 
593edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
594edb885cbSTobias Grosser   ///
595edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
596edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
597edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
598edb885cbSTobias Grosser 
5995260c041STobias Grosser   /// Create an in-kernel synchronization call.
6005260c041STobias Grosser   void createKernelSync();
6015260c041STobias Grosser 
60274dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
60374dc3cb4STobias Grosser   ///
60474dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
60574dc3cb4STobias Grosser   std::string createKernelASM();
60674dc3cb4STobias Grosser 
60774dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
60874dc3cb4STobias Grosser   ///
60974dc3cb4STobias Grosser   /// @param F The function to remove references to.
61074dc3cb4STobias Grosser   void clearDominators(Function *F);
61174dc3cb4STobias Grosser 
61274dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
61374dc3cb4STobias Grosser   ///
61474dc3cb4STobias Grosser   /// @param F The function to remove references to.
61574dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
61674dc3cb4STobias Grosser 
61774dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
61874dc3cb4STobias Grosser   ///
61974dc3cb4STobias Grosser   /// @param F The function to remove references to.
62074dc3cb4STobias Grosser   void clearLoops(Function *F);
62174dc3cb4STobias Grosser 
6228fc6cdfbSTobias Grosser   /// Check if the scop requires to be linked with CUDA's libdevice.
6238fc6cdfbSTobias Grosser   bool requiresCUDALibDevice();
6248fc6cdfbSTobias Grosser 
6258fc6cdfbSTobias Grosser   /// Link with the NVIDIA libdevice library (if needed and available).
6268fc6cdfbSTobias Grosser   void addCUDALibDevice();
6278fc6cdfbSTobias Grosser 
62832837fe3STobias Grosser   /// Finalize the generation of the kernel function.
62932837fe3STobias Grosser   ///
63032837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
63132837fe3STobias Grosser   /// dump its IR to stderr.
63257793596STobias Grosser   ///
63357793596STobias Grosser   /// @returns The Assembly string of the kernel.
63457793596STobias Grosser   std::string finalizeKernelFunction();
635fa7b0802STobias Grosser 
63651dfc275STobias Grosser   /// Finalize the generation of the kernel arguments.
63751dfc275STobias Grosser   ///
63851dfc275STobias Grosser   /// This function ensures that not-read-only scalars used in a kernel are
639a6d48f59SMichael Kruse   /// stored back to the global memory location they are backed with before
64051dfc275STobias Grosser   /// the kernel terminates.
64151dfc275STobias Grosser   ///
64251dfc275STobias Grosser   /// @params Kernel The kernel to finalize kernel arguments for.
64351dfc275STobias Grosser   void finalizeKernelArguments(ppcg_kernel *Kernel);
64451dfc275STobias Grosser 
6457287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
646fa7b0802STobias Grosser   void allocateDeviceArrays();
647fa7b0802STobias Grosser 
6487287aeddSTobias Grosser   /// Free all allocated device arrays.
6497287aeddSTobias Grosser   void freeDeviceArrays();
6507287aeddSTobias Grosser 
651fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
652fa7b0802STobias Grosser   ///
653fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
654fa7b0802STobias Grosser   Value *createCallInitContext();
655fa7b0802STobias Grosser 
65679a947c2STobias Grosser   /// Create a call to get the device pointer for a kernel allocation.
65779a947c2STobias Grosser   ///
65879a947c2STobias Grosser   /// @param Allocation The Polly GPU allocation
65979a947c2STobias Grosser   ///
66079a947c2STobias Grosser   /// @returns The device parameter corresponding to this allocation.
66179a947c2STobias Grosser   Value *createCallGetDevicePtr(Value *Allocation);
66279a947c2STobias Grosser 
663fa7b0802STobias Grosser   /// Create a call to free the GPU context.
664fa7b0802STobias Grosser   ///
665fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
666fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
667fa7b0802STobias Grosser 
6687287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
6697287aeddSTobias Grosser   ///
6707287aeddSTobias Grosser   /// @param Size The size of memory to allocate
6717287aeddSTobias Grosser   ///
6727287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
673fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
6747287aeddSTobias Grosser 
6757287aeddSTobias Grosser   /// Create a call to free a device array.
6767287aeddSTobias Grosser   ///
6777287aeddSTobias Grosser   /// @param Array The device array to free.
6787287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
67913c78e4dSTobias Grosser 
68013c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
68113c78e4dSTobias Grosser   ///
68213c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
68313c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
68413c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
68513c78e4dSTobias Grosser                                       Value *Size);
68613c78e4dSTobias Grosser 
68713c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
68813c78e4dSTobias Grosser   ///
68913c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
69013c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
69113c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
69213c78e4dSTobias Grosser                                       Value *Size);
69357793596STobias Grosser 
694abed4969SSiddharth Bhat   /// Create a call to synchronize Host & Device.
695abed4969SSiddharth Bhat   /// \note
696abed4969SSiddharth Bhat   /// This is to be used only with managed memory.
697abed4969SSiddharth Bhat   void createCallSynchronizeDevice();
698abed4969SSiddharth Bhat 
69957793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
70057793596STobias Grosser   ///
70157793596STobias Grosser   /// @param Buffer The string describing the kernel.
70257793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
70357793596STobias Grosser   ///
70457793596STobias Grosser   /// @returns A pointer to a kernel object
70557793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
70657793596STobias Grosser 
70757793596STobias Grosser   /// Create a call to free a GPU kernel.
70857793596STobias Grosser   ///
70957793596STobias Grosser   /// @param GPUKernel THe kernel to free.
71057793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
71179a947c2STobias Grosser 
71279a947c2STobias Grosser   /// Create a call to launch a GPU kernel.
71379a947c2STobias Grosser   ///
71479a947c2STobias Grosser   /// @param GPUKernel  The kernel to launch.
71579a947c2STobias Grosser   /// @param GridDimX   The size of the first grid dimension.
71679a947c2STobias Grosser   /// @param GridDimY   The size of the second grid dimension.
71779a947c2STobias Grosser   /// @param GridBlockX The size of the first block dimension.
71879a947c2STobias Grosser   /// @param GridBlockY The size of the second block dimension.
71979a947c2STobias Grosser   /// @param GridBlockZ The size of the third block dimension.
720a6d48f59SMichael Kruse   /// @param Parameters A pointer to an array that contains itself pointers to
72179a947c2STobias Grosser   ///                   the parameter values passed for each kernel argument.
72279a947c2STobias Grosser   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
72379a947c2STobias Grosser                               Value *GridDimY, Value *BlockDimX,
72479a947c2STobias Grosser                               Value *BlockDimY, Value *BlockDimZ,
72579a947c2STobias Grosser                               Value *Parameters);
7261fb9b64dSTobias Grosser };
7271fb9b64dSTobias Grosser 
72879f13b9aSSingapuram Sanjay Srivallabh std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) {
7291abd9ffaSSingapuram Sanjay Srivallabh   return "FUNC_" + S.getFunction().getName().str() + "_SCOP_" +
7301abd9ffaSSingapuram Sanjay Srivallabh          std::to_string(S.getID()) + "_KERNEL_" + std::to_string(Kernel_id);
73179f13b9aSSingapuram Sanjay Srivallabh }
73279f13b9aSSingapuram Sanjay Srivallabh 
733fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
734750160e2STobias Grosser   BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(),
735750160e2STobias Grosser                                  &*Builder.GetInsertPoint(), &DT, &LI);
736750160e2STobias Grosser   NewBB->setName("polly.acc.initialize");
737750160e2STobias Grosser   Builder.SetInsertPoint(&NewBB->front());
738750160e2STobias Grosser 
739fa7b0802STobias Grosser   GPUContext = createCallInitContext();
740abed4969SSiddharth Bhat 
741abed4969SSiddharth Bhat   if (!ManagedMemory)
742fa7b0802STobias Grosser     allocateDeviceArrays();
743fa7b0802STobias Grosser }
744fa7b0802STobias Grosser 
745fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
746abed4969SSiddharth Bhat   if (!ManagedMemory)
7477287aeddSTobias Grosser     freeDeviceArrays();
748abed4969SSiddharth Bhat 
749fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
750fa7b0802STobias Grosser   IslNodeBuilder::finalize();
751fa7b0802STobias Grosser }
752fa7b0802STobias Grosser 
753fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
754abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory will directly send host pointers "
755abed4969SSiddharth Bhat                            "to the kernel. There is no need for device arrays");
756fa7b0802STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
757fa7b0802STobias Grosser 
758fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
759fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
76013c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
7617287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
7627287aeddSTobias Grosser     DevArrayName.append(Array->name);
763fa7b0802STobias Grosser 
76413c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
765aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(Array);
766aaabbbf8STobias Grosser     if (Offset)
767aaabbbf8STobias Grosser       ArraySize = Builder.CreateSub(
768aaabbbf8STobias Grosser           ArraySize,
769aaabbbf8STobias Grosser           Builder.CreateMul(Offset,
770aaabbbf8STobias Grosser                             Builder.getInt64(ScopArray->getElemSizeInBytes())));
7717287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
7727287aeddSTobias Grosser     DevArray->setName(DevArrayName);
77313c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
774fa7b0802STobias Grosser   }
775fa7b0802STobias Grosser 
776fa7b0802STobias Grosser   isl_ast_build_free(Build);
777fa7b0802STobias Grosser }
778fa7b0802STobias Grosser 
779c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX,
780c1c6a2a6STobias Grosser                                         Value *BlockDimY, Value *BlockDimZ) {
781c1c6a2a6STobias Grosser   auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations");
782c1c6a2a6STobias Grosser 
783c1c6a2a6STobias Grosser   for (auto &F : *M) {
784c1c6a2a6STobias Grosser     if (F.getCallingConv() != CallingConv::PTX_Kernel)
785c1c6a2a6STobias Grosser       continue;
786c1c6a2a6STobias Grosser 
787c1c6a2a6STobias Grosser     Value *V[] = {BlockDimX, BlockDimY, BlockDimZ};
788c1c6a2a6STobias Grosser 
789c1c6a2a6STobias Grosser     Metadata *Elements[] = {
790c1c6a2a6STobias Grosser         ValueAsMetadata::get(&F),   MDString::get(M->getContext(), "maxntidx"),
791c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"),
792c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"),
793c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[2]),
794c1c6a2a6STobias Grosser     };
795c1c6a2a6STobias Grosser     MDNode *Node = MDNode::get(M->getContext(), Elements);
796c1c6a2a6STobias Grosser     AnnotationNode->addOperand(Node);
797c1c6a2a6STobias Grosser   }
798c1c6a2a6STobias Grosser }
799c1c6a2a6STobias Grosser 
8007287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
801abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not use device arrays");
80213c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
80313c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
8047287aeddSTobias Grosser }
8057287aeddSTobias Grosser 
80657793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
80757793596STobias Grosser   const char *Name = "polly_getKernel";
80857793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
80957793596STobias Grosser   Function *F = M->getFunction(Name);
81057793596STobias Grosser 
81157793596STobias Grosser   // If F is not available, declare it.
81257793596STobias Grosser   if (!F) {
81357793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
81457793596STobias Grosser     std::vector<Type *> Args;
81557793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
81657793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
81757793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
81857793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
81957793596STobias Grosser   }
82057793596STobias Grosser 
82157793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
82257793596STobias Grosser }
82357793596STobias Grosser 
82479a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
82579a947c2STobias Grosser   const char *Name = "polly_getDevicePtr";
82679a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
82779a947c2STobias Grosser   Function *F = M->getFunction(Name);
82879a947c2STobias Grosser 
82979a947c2STobias Grosser   // If F is not available, declare it.
83079a947c2STobias Grosser   if (!F) {
83179a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
83279a947c2STobias Grosser     std::vector<Type *> Args;
83379a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
83479a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
83579a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
83679a947c2STobias Grosser   }
83779a947c2STobias Grosser 
83879a947c2STobias Grosser   return Builder.CreateCall(F, {Allocation});
83979a947c2STobias Grosser }
84079a947c2STobias Grosser 
84179a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
84279a947c2STobias Grosser                                             Value *GridDimY, Value *BlockDimX,
84379a947c2STobias Grosser                                             Value *BlockDimY, Value *BlockDimZ,
84479a947c2STobias Grosser                                             Value *Parameters) {
84579a947c2STobias Grosser   const char *Name = "polly_launchKernel";
84679a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
84779a947c2STobias Grosser   Function *F = M->getFunction(Name);
84879a947c2STobias Grosser 
84979a947c2STobias Grosser   // If F is not available, declare it.
85079a947c2STobias Grosser   if (!F) {
85179a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
85279a947c2STobias Grosser     std::vector<Type *> Args;
85379a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
85479a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
85579a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
85679a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
85779a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
85879a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
85979a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
86079a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
86179a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
86279a947c2STobias Grosser   }
86379a947c2STobias Grosser 
864ff40087aSTobias Grosser   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
86579a947c2STobias Grosser                          BlockDimZ, Parameters});
86679a947c2STobias Grosser }
86779a947c2STobias Grosser 
86857793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
86957793596STobias Grosser   const char *Name = "polly_freeKernel";
87057793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
87157793596STobias Grosser   Function *F = M->getFunction(Name);
87257793596STobias Grosser 
87357793596STobias Grosser   // If F is not available, declare it.
87457793596STobias Grosser   if (!F) {
87557793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
87657793596STobias Grosser     std::vector<Type *> Args;
87757793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
87857793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
87957793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
88057793596STobias Grosser   }
88157793596STobias Grosser 
88257793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
88357793596STobias Grosser }
88457793596STobias Grosser 
8857287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
886abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not allocate or free memory "
887abed4969SSiddharth Bhat                            "for device");
8887287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
8897287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8907287aeddSTobias Grosser   Function *F = M->getFunction(Name);
8917287aeddSTobias Grosser 
8927287aeddSTobias Grosser   // If F is not available, declare it.
8937287aeddSTobias Grosser   if (!F) {
8947287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
8957287aeddSTobias Grosser     std::vector<Type *> Args;
8967287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
8977287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
8987287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
8997287aeddSTobias Grosser   }
9007287aeddSTobias Grosser 
9017287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
9027287aeddSTobias Grosser }
9037287aeddSTobias Grosser 
904fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
905abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not allocate or free memory "
906abed4969SSiddharth Bhat                            "for device");
907fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
908fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
909fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
910fa7b0802STobias Grosser 
911fa7b0802STobias Grosser   // If F is not available, declare it.
912fa7b0802STobias Grosser   if (!F) {
913fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
914fa7b0802STobias Grosser     std::vector<Type *> Args;
915fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
916fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
917fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
918fa7b0802STobias Grosser   }
919fa7b0802STobias Grosser 
920fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
921fa7b0802STobias Grosser }
922fa7b0802STobias Grosser 
92313c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
92413c78e4dSTobias Grosser                                                     Value *DeviceData,
92513c78e4dSTobias Grosser                                                     Value *Size) {
926abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not transfer memory between "
927abed4969SSiddharth Bhat                            "device and host");
92813c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
92913c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
93013c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
93113c78e4dSTobias Grosser 
93213c78e4dSTobias Grosser   // If F is not available, declare it.
93313c78e4dSTobias Grosser   if (!F) {
93413c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
93513c78e4dSTobias Grosser     std::vector<Type *> Args;
93613c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
93713c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
93813c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
93913c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
94013c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
94113c78e4dSTobias Grosser   }
94213c78e4dSTobias Grosser 
94313c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
94413c78e4dSTobias Grosser }
94513c78e4dSTobias Grosser 
94613c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
94713c78e4dSTobias Grosser                                                     Value *HostData,
94813c78e4dSTobias Grosser                                                     Value *Size) {
949abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not transfer memory between "
950abed4969SSiddharth Bhat                            "device and host");
95113c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
95213c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
95313c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
95413c78e4dSTobias Grosser 
95513c78e4dSTobias Grosser   // If F is not available, declare it.
95613c78e4dSTobias Grosser   if (!F) {
95713c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
95813c78e4dSTobias Grosser     std::vector<Type *> Args;
95913c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
96013c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
96113c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
96213c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
96313c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
96413c78e4dSTobias Grosser   }
96513c78e4dSTobias Grosser 
96613c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
96713c78e4dSTobias Grosser }
96813c78e4dSTobias Grosser 
969abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() {
970abed4969SSiddharth Bhat   assert(ManagedMemory && "explicit synchronization is only necessary for "
971abed4969SSiddharth Bhat                           "managed memory");
972abed4969SSiddharth Bhat   const char *Name = "polly_synchronizeDevice";
973abed4969SSiddharth Bhat   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
974abed4969SSiddharth Bhat   Function *F = M->getFunction(Name);
975abed4969SSiddharth Bhat 
976abed4969SSiddharth Bhat   // If F is not available, declare it.
977abed4969SSiddharth Bhat   if (!F) {
978abed4969SSiddharth Bhat     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
979abed4969SSiddharth Bhat     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
980abed4969SSiddharth Bhat     F = Function::Create(Ty, Linkage, Name, M);
981abed4969SSiddharth Bhat   }
982abed4969SSiddharth Bhat 
983abed4969SSiddharth Bhat   Builder.CreateCall(F);
984abed4969SSiddharth Bhat }
985abed4969SSiddharth Bhat 
986fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
98717f01968SSiddharth Bhat   const char *Name;
98817f01968SSiddharth Bhat 
98917f01968SSiddharth Bhat   switch (Runtime) {
99017f01968SSiddharth Bhat   case GPURuntime::CUDA:
99117f01968SSiddharth Bhat     Name = "polly_initContextCUDA";
99217f01968SSiddharth Bhat     break;
99317f01968SSiddharth Bhat   case GPURuntime::OpenCL:
99417f01968SSiddharth Bhat     Name = "polly_initContextCL";
99517f01968SSiddharth Bhat     break;
99617f01968SSiddharth Bhat   }
99717f01968SSiddharth Bhat 
998fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
999fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
1000fa7b0802STobias Grosser 
1001fa7b0802STobias Grosser   // If F is not available, declare it.
1002fa7b0802STobias Grosser   if (!F) {
1003fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1004fa7b0802STobias Grosser     std::vector<Type *> Args;
1005fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
1006fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
1007fa7b0802STobias Grosser   }
1008fa7b0802STobias Grosser 
1009fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
1010fa7b0802STobias Grosser }
1011fa7b0802STobias Grosser 
1012fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
1013fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
1014fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1015fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
1016fa7b0802STobias Grosser 
1017fa7b0802STobias Grosser   // If F is not available, declare it.
1018fa7b0802STobias Grosser   if (!F) {
1019fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1020fa7b0802STobias Grosser     std::vector<Type *> Args;
1021fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
1022fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
1023fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
1024fa7b0802STobias Grosser   }
1025fa7b0802STobias Grosser 
1026fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
1027fa7b0802STobias Grosser }
1028fa7b0802STobias Grosser 
10295260c041STobias Grosser /// Check if one string is a prefix of another.
10305260c041STobias Grosser ///
10315260c041STobias Grosser /// @param String The string in which to look for the prefix.
10325260c041STobias Grosser /// @param Prefix The prefix to look for.
10335260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
10345260c041STobias Grosser   return String.find(Prefix) == 0;
10355260c041STobias Grosser }
10365260c041STobias Grosser 
103713c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
1038f7face4bSSiddharth Bhat   isl::ast_build Build =
1039f7face4bSSiddharth Bhat       isl::ast_build::from_context(isl::manage(S.getContext()));
104013c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
104113c78e4dSTobias Grosser 
104213c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
1043f7face4bSSiddharth Bhat     isl::multi_pw_aff ArrayBound =
1044f7face4bSSiddharth Bhat         isl::manage(isl_multi_pw_aff_copy(Array->bound));
1045f7face4bSSiddharth Bhat 
1046f7face4bSSiddharth Bhat     isl::pw_aff OffsetDimZero = ArrayBound.get_pw_aff(0);
1047f7face4bSSiddharth Bhat     isl::ast_expr Res = Build.expr_from(OffsetDimZero);
104813c78e4dSTobias Grosser 
104913c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
1050f7face4bSSiddharth Bhat       isl::pw_aff Bound_I = ArrayBound.get_pw_aff(i);
1051f7face4bSSiddharth Bhat       isl::ast_expr Expr = Build.expr_from(Bound_I);
1052f7face4bSSiddharth Bhat       Res = Res.mul(Expr);
105313c78e4dSTobias Grosser     }
105413c78e4dSTobias Grosser 
1055f7face4bSSiddharth Bhat     Value *NumElements = ExprBuilder.create(Res.release());
1056b79f4d39STobias Grosser     if (NumElements->getType() != ArraySize->getType())
1057b79f4d39STobias Grosser       NumElements = Builder.CreateSExt(NumElements, ArraySize->getType());
105813c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
105913c78e4dSTobias Grosser   }
106013c78e4dSTobias Grosser   return ArraySize;
106113c78e4dSTobias Grosser }
106213c78e4dSTobias Grosser 
1063aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) {
1064aaabbbf8STobias Grosser   if (gpu_array_is_scalar(Array))
1065aaabbbf8STobias Grosser     return nullptr;
1066aaabbbf8STobias Grosser 
1067ccbf4b50SSiddharth Bhat   isl::ast_build Build =
1068ccbf4b50SSiddharth Bhat       isl::ast_build::from_context(isl::manage(S.getContext()));
1069aaabbbf8STobias Grosser 
1070ccbf4b50SSiddharth Bhat   isl::set Min = isl::manage(isl_set_copy(Array->extent)).lexmin();
1071aaabbbf8STobias Grosser 
1072ccbf4b50SSiddharth Bhat   isl::set ZeroSet = isl::set::universe(Min.get_space());
1073aaabbbf8STobias Grosser 
1074ccbf4b50SSiddharth Bhat   for (long i = 0; i < Min.dim(isl::dim::set); i++)
1075ccbf4b50SSiddharth Bhat     ZeroSet = ZeroSet.fix_si(isl::dim::set, i, 0);
1076aaabbbf8STobias Grosser 
1077ccbf4b50SSiddharth Bhat   if (Min.is_subset(ZeroSet)) {
1078aaabbbf8STobias Grosser     return nullptr;
1079aaabbbf8STobias Grosser   }
1080aaabbbf8STobias Grosser 
1081ccbf4b50SSiddharth Bhat   isl::ast_expr Result = isl::ast_expr::from_val(isl::val(Min.get_ctx(), 0));
1082aaabbbf8STobias Grosser 
1083ccbf4b50SSiddharth Bhat   for (long i = 0; i < Min.dim(isl::dim::set); i++) {
1084aaabbbf8STobias Grosser     if (i > 0) {
1085ccbf4b50SSiddharth Bhat       isl::pw_aff Bound_I =
1086ccbf4b50SSiddharth Bhat           isl::manage(isl_multi_pw_aff_get_pw_aff(Array->bound, i - 1));
1087ccbf4b50SSiddharth Bhat       isl::ast_expr BExpr = Build.expr_from(Bound_I);
1088ccbf4b50SSiddharth Bhat       Result = Result.mul(BExpr);
1089aaabbbf8STobias Grosser     }
1090ccbf4b50SSiddharth Bhat     isl::pw_aff DimMin = Min.dim_min(i);
1091ccbf4b50SSiddharth Bhat     isl::ast_expr MExpr = Build.expr_from(DimMin);
1092ccbf4b50SSiddharth Bhat     Result = Result.add(MExpr);
1093aaabbbf8STobias Grosser   }
1094aaabbbf8STobias Grosser 
1095ccbf4b50SSiddharth Bhat   return ExprBuilder.create(Result.release());
1096aaabbbf8STobias Grosser }
1097aaabbbf8STobias Grosser 
1098abed4969SSiddharth Bhat Value *GPUNodeBuilder::getOrCreateManagedDeviceArray(gpu_array_info *Array,
1099abed4969SSiddharth Bhat                                                      ScopArrayInfo *ArrayInfo) {
1100abed4969SSiddharth Bhat 
1101abed4969SSiddharth Bhat   assert(ManagedMemory && "Only used when you wish to get a host "
1102abed4969SSiddharth Bhat                           "pointer for sending data to the kernel, "
1103abed4969SSiddharth Bhat                           "with managed memory");
1104abed4969SSiddharth Bhat   std::map<ScopArrayInfo *, Value *>::iterator it;
1105abed4969SSiddharth Bhat   if ((it = DeviceAllocations.find(ArrayInfo)) != DeviceAllocations.end()) {
1106abed4969SSiddharth Bhat     return it->second;
1107abed4969SSiddharth Bhat   } else {
1108abed4969SSiddharth Bhat     Value *HostPtr;
1109abed4969SSiddharth Bhat 
1110abed4969SSiddharth Bhat     if (gpu_array_is_scalar(Array))
1111abed4969SSiddharth Bhat       HostPtr = BlockGen.getOrCreateAlloca(ArrayInfo);
1112abed4969SSiddharth Bhat     else
1113abed4969SSiddharth Bhat       HostPtr = ArrayInfo->getBasePtr();
1114edf9581eSSiddharth Bhat     HostPtr = getLatestValue(HostPtr);
1115abed4969SSiddharth Bhat 
1116abed4969SSiddharth Bhat     Value *Offset = getArrayOffset(Array);
1117abed4969SSiddharth Bhat     if (Offset) {
1118abed4969SSiddharth Bhat       HostPtr = Builder.CreatePointerCast(
1119abed4969SSiddharth Bhat           HostPtr, ArrayInfo->getElementType()->getPointerTo());
1120abed4969SSiddharth Bhat       HostPtr = Builder.CreateGEP(HostPtr, Offset);
1121abed4969SSiddharth Bhat     }
1122abed4969SSiddharth Bhat 
1123abed4969SSiddharth Bhat     HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
1124abed4969SSiddharth Bhat     DeviceAllocations[ArrayInfo] = HostPtr;
1125abed4969SSiddharth Bhat     return HostPtr;
1126abed4969SSiddharth Bhat   }
1127abed4969SSiddharth Bhat }
1128abed4969SSiddharth Bhat 
112913c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
113013c78e4dSTobias Grosser                                         enum DataDirection Direction) {
1131abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory needs no data transfers");
113213c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
113313c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
113413c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
113513c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
113613c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
113713c78e4dSTobias Grosser 
113813c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
1139aaabbbf8STobias Grosser   Value *Offset = getArrayOffset(Array);
114013c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
114113c78e4dSTobias Grosser 
1142b06ff457STobias Grosser   Value *HostPtr;
1143b06ff457STobias Grosser 
1144b06ff457STobias Grosser   if (gpu_array_is_scalar(Array))
1145b06ff457STobias Grosser     HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
1146b06ff457STobias Grosser   else
1147b06ff457STobias Grosser     HostPtr = ScopArray->getBasePtr();
1148edf9581eSSiddharth Bhat   HostPtr = getLatestValue(HostPtr);
114913c78e4dSTobias Grosser 
1150aaabbbf8STobias Grosser   if (Offset) {
1151aaabbbf8STobias Grosser     HostPtr = Builder.CreatePointerCast(
1152aaabbbf8STobias Grosser         HostPtr, ScopArray->getElementType()->getPointerTo());
1153aaabbbf8STobias Grosser     HostPtr = Builder.CreateGEP(HostPtr, Offset);
1154aaabbbf8STobias Grosser   }
1155aaabbbf8STobias Grosser 
115613c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
115713c78e4dSTobias Grosser 
1158aaabbbf8STobias Grosser   if (Offset) {
1159aaabbbf8STobias Grosser     Size = Builder.CreateSub(
1160ff40087aSTobias Grosser         Size, Builder.CreateMul(
1161ff40087aSTobias Grosser                   Offset, Builder.getInt64(ScopArray->getElemSizeInBytes())));
1162aaabbbf8STobias Grosser   }
1163aaabbbf8STobias Grosser 
116413c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
116513c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
116613c78e4dSTobias Grosser   else
116713c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
116813c78e4dSTobias Grosser 
116913c78e4dSTobias Grosser   isl_id_free(Id);
117013c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
117113c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
117213c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
117313c78e4dSTobias Grosser }
117413c78e4dSTobias Grosser 
11751fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
117632837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
117732837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
117832837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
117932837fe3STobias Grosser   isl_id_free(Id);
118032837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
118132837fe3STobias Grosser 
118232837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
118332837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
118432837fe3STobias Grosser     createKernel(UserStmt);
118532837fe3STobias Grosser     isl_ast_expr_free(Expr);
118632837fe3STobias Grosser     return;
118732837fe3STobias Grosser   }
11889e3db2b7SSiddharth Bhat   if (!strcmp(Str, "init_device")) {
11899e3db2b7SSiddharth Bhat     initializeAfterRTH();
11909e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
11919e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
11929e3db2b7SSiddharth Bhat     return;
11939e3db2b7SSiddharth Bhat   }
11949e3db2b7SSiddharth Bhat   if (!strcmp(Str, "clear_device")) {
11959e3db2b7SSiddharth Bhat     finalize();
11969e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
11979e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
11989e3db2b7SSiddharth Bhat     return;
11999e3db2b7SSiddharth Bhat   }
120013c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
1201abed4969SSiddharth Bhat     if (!ManagedMemory)
120213c78e4dSTobias Grosser       createDataTransfer(UserStmt, HOST_TO_DEVICE);
1203abed4969SSiddharth Bhat     else
1204abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1205abed4969SSiddharth Bhat 
120632837fe3STobias Grosser     isl_ast_expr_free(Expr);
120713c78e4dSTobias Grosser     return;
120813c78e4dSTobias Grosser   }
120913c78e4dSTobias Grosser 
121013c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
1211abed4969SSiddharth Bhat     if (!ManagedMemory) {
121213c78e4dSTobias Grosser       createDataTransfer(UserStmt, DEVICE_TO_HOST);
1213abed4969SSiddharth Bhat     } else {
1214abed4969SSiddharth Bhat       createCallSynchronizeDevice();
1215abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1216abed4969SSiddharth Bhat     }
121713c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
121838fc0aedSTobias Grosser     return;
121938fc0aedSTobias Grosser   }
122038fc0aedSTobias Grosser 
12215260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
12225260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
12235260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
12245260c041STobias Grosser   isl_id_free(Anno);
12255260c041STobias Grosser 
12265260c041STobias Grosser   switch (KernelStmt->type) {
12275260c041STobias Grosser   case ppcg_kernel_domain:
1228edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
12295260c041STobias Grosser     isl_ast_node_free(UserStmt);
12305260c041STobias Grosser     return;
12315260c041STobias Grosser   case ppcg_kernel_copy:
1232b513b491STobias Grosser     createKernelCopy(KernelStmt);
12335260c041STobias Grosser     isl_ast_expr_free(Expr);
12345260c041STobias Grosser     isl_ast_node_free(UserStmt);
12355260c041STobias Grosser     return;
12365260c041STobias Grosser   case ppcg_kernel_sync:
12375260c041STobias Grosser     createKernelSync();
12385260c041STobias Grosser     isl_ast_expr_free(Expr);
12395260c041STobias Grosser     isl_ast_node_free(UserStmt);
12405260c041STobias Grosser     return;
12415260c041STobias Grosser   }
12425260c041STobias Grosser 
12435260c041STobias Grosser   isl_ast_expr_free(Expr);
12445260c041STobias Grosser   isl_ast_node_free(UserStmt);
12455260c041STobias Grosser   return;
12465260c041STobias Grosser }
1247b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
1248b513b491STobias Grosser   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
1249b513b491STobias Grosser   LocalIndex = isl_ast_expr_address_of(LocalIndex);
1250b513b491STobias Grosser   Value *LocalAddr = ExprBuilder.create(LocalIndex);
1251b513b491STobias Grosser   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
1252b513b491STobias Grosser   Index = isl_ast_expr_address_of(Index);
1253b513b491STobias Grosser   Value *GlobalAddr = ExprBuilder.create(Index);
1254b513b491STobias Grosser 
1255b513b491STobias Grosser   if (KernelStmt->u.c.read) {
1256b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read");
1257b513b491STobias Grosser     Builder.CreateStore(Load, LocalAddr);
1258b513b491STobias Grosser   } else {
1259b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write");
1260b513b491STobias Grosser     Builder.CreateStore(Load, GlobalAddr);
1261b513b491STobias Grosser   }
1262b513b491STobias Grosser }
12635260c041STobias Grosser 
1264edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
1265edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
1266edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1267edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
1268edb885cbSTobias Grosser 
1269edb885cbSTobias Grosser   LoopToScevMapT LTS;
1270edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
1271edb885cbSTobias Grosser 
1272edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
1273edb885cbSTobias Grosser 
1274edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
1275edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
1276edb885cbSTobias Grosser   else
1277a82c4b5dSTobias Grosser     RegionGen.copyStmt(*Stmt, LTS, Indexes);
1278edb885cbSTobias Grosser }
1279edb885cbSTobias Grosser 
12805260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
12815260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12822f3073b5SPhilipp Schaad   const char *SpirName = "__gen_ocl_barrier_global";
128317f01968SSiddharth Bhat 
128417f01968SSiddharth Bhat   Function *Sync;
128517f01968SSiddharth Bhat 
128617f01968SSiddharth Bhat   switch (Arch) {
12872f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
12882f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
12892f3073b5SPhilipp Schaad     Sync = M->getFunction(SpirName);
12902f3073b5SPhilipp Schaad 
12912f3073b5SPhilipp Schaad     // If Sync is not available, declare it.
12922f3073b5SPhilipp Schaad     if (!Sync) {
12932f3073b5SPhilipp Schaad       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
12942f3073b5SPhilipp Schaad       std::vector<Type *> Args;
12952f3073b5SPhilipp Schaad       FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
12962f3073b5SPhilipp Schaad       Sync = Function::Create(Ty, Linkage, SpirName, M);
12972f3073b5SPhilipp Schaad       Sync->setCallingConv(CallingConv::SPIR_FUNC);
12982f3073b5SPhilipp Schaad     }
12992f3073b5SPhilipp Schaad     break;
130017f01968SSiddharth Bhat   case GPUArch::NVPTX64:
130117f01968SSiddharth Bhat     Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
130217f01968SSiddharth Bhat     break;
130317f01968SSiddharth Bhat   }
130417f01968SSiddharth Bhat 
13055260c041STobias Grosser   Builder.CreateCall(Sync, {});
13065260c041STobias Grosser }
13075260c041STobias Grosser 
1308edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
1309edb885cbSTobias Grosser ///
1310edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
1311edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
1312edb885cbSTobias Grosser ///
1313edb885cbSTobias Grosser /// @param Node The node to collect references for.
1314edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
1315edb885cbSTobias Grosser ///
1316edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
1317edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
1318edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
1319edb885cbSTobias Grosser     return isl_bool_true;
1320edb885cbSTobias Grosser 
1321edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
1322edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
1323edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
1324edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
1325edb885cbSTobias Grosser   isl_id_free(Id);
1326edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
1327edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
1328edb885cbSTobias Grosser 
1329edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
1330edb885cbSTobias Grosser     return isl_bool_true;
1331edb885cbSTobias Grosser 
1332edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
1333edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
1334edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1335edb885cbSTobias Grosser   isl_id_free(Id);
1336edb885cbSTobias Grosser 
133700bb5a99STobias Grosser   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
1338edb885cbSTobias Grosser 
1339edb885cbSTobias Grosser   return isl_bool_true;
1340edb885cbSTobias Grosser }
1341edb885cbSTobias Grosser 
13428fc6cdfbSTobias Grosser /// A list of functions that are available in NVIDIA's libdevice.
13438fc6cdfbSTobias Grosser const std::set<std::string> CUDALibDeviceFunctions = {
13448fc6cdfbSTobias Grosser     "exp",  "expf",  "expl",     "cos",       "cosf",
13458fc6cdfbSTobias Grosser     "sqrt", "sqrtf", "copysign", "copysignf", "copysignl"};
13468fc6cdfbSTobias Grosser 
13478fc6cdfbSTobias Grosser /// Return the corresponding CUDA libdevice function name for @p F.
13488fc6cdfbSTobias Grosser ///
13498fc6cdfbSTobias Grosser /// Return "" if we are not compiling for CUDA.
13508fc6cdfbSTobias Grosser std::string getCUDALibDeviceFuntion(Function *F) {
13518fc6cdfbSTobias Grosser   if (CUDALibDeviceFunctions.count(F->getName()))
13528fc6cdfbSTobias Grosser     return std::string("__nv_") + std::string(F->getName());
13538fc6cdfbSTobias Grosser 
13548fc6cdfbSTobias Grosser   return "";
13558fc6cdfbSTobias Grosser }
13568fc6cdfbSTobias Grosser 
1357f291c8d5SSiddharth Bhat /// Check if F is a function that we can code-generate in a GPU kernel.
13588fc6cdfbSTobias Grosser static bool isValidFunctionInKernel(llvm::Function *F, bool AllowLibDevice) {
1359f291c8d5SSiddharth Bhat   assert(F && "F is an invalid pointer");
1360f291c8d5SSiddharth Bhat   // We string compare against the name of the function to allow
136154491db6STobias Grosser   // all variants of the intrinsic "llvm.sqrt.*", "llvm.fabs", and
136254491db6STobias Grosser   // "llvm.copysign".
136354491db6STobias Grosser   const StringRef Name = F->getName();
13648fc6cdfbSTobias Grosser 
13658fc6cdfbSTobias Grosser   if (AllowLibDevice && getCUDALibDeviceFuntion(F).length() > 0)
13668fc6cdfbSTobias Grosser     return true;
13678fc6cdfbSTobias Grosser 
136854491db6STobias Grosser   return F->isIntrinsic() &&
136954491db6STobias Grosser          (Name.startswith("llvm.sqrt") || Name.startswith("llvm.fabs") ||
137054491db6STobias Grosser           Name.startswith("llvm.copysign"));
1371f291c8d5SSiddharth Bhat }
1372f291c8d5SSiddharth Bhat 
1373f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value.
1374f291c8d5SSiddharth Bhat ///
1375f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along
1376f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and
1377f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not
1378f291c8d5SSiddharth Bhat /// `Function`s.
1379f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); }
1380f291c8d5SSiddharth Bhat 
1381f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`.
1382f291c8d5SSiddharth Bhat static SetVector<Function *>
13838fc6cdfbSTobias Grosser getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues,
13848fc6cdfbSTobias Grosser                                  bool AllowCUDALibDevice) {
1385f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1386f291c8d5SSiddharth Bhat   for (Value *It : RawSubtreeValues) {
1387f291c8d5SSiddharth Bhat     Function *F = dyn_cast<Function>(It);
1388f291c8d5SSiddharth Bhat     if (F) {
13898fc6cdfbSTobias Grosser       assert(isValidFunctionInKernel(F, AllowCUDALibDevice) &&
13908fc6cdfbSTobias Grosser              "Code should have bailed out by "
1391f291c8d5SSiddharth Bhat              "this point if an invalid function "
1392f291c8d5SSiddharth Bhat              "were present in a kernel.");
1393f291c8d5SSiddharth Bhat       SubtreeFunctions.insert(F);
1394f291c8d5SSiddharth Bhat     }
1395f291c8d5SSiddharth Bhat   }
1396f291c8d5SSiddharth Bhat   return SubtreeFunctions;
1397f291c8d5SSiddharth Bhat }
1398f291c8d5SSiddharth Bhat 
1399f291c8d5SSiddharth Bhat std::pair<SetVector<Value *>, SetVector<Function *>>
1400f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
1401edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
1402edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
1403edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1404edb885cbSTobias Grosser   SubtreeReferences References = {
1405edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
1406edb885cbSTobias Grosser 
1407edb885cbSTobias Grosser   for (const auto &I : IDToValue)
1408edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
1409edb885cbSTobias Grosser 
1410edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
1411edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
1412edb885cbSTobias Grosser 
1413edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
1414edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
1415edb885cbSTobias Grosser 
1416edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
1417d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
1418edb885cbSTobias Grosser 
1419edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
1420edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1421edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, 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   isl_space_free(Space);
1428edb885cbSTobias Grosser 
1429edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
1430edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1431edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1432edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1433edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1434edb885cbSTobias Grosser     isl_id_free(Id);
1435edb885cbSTobias Grosser   }
1436edb885cbSTobias Grosser 
1437f291c8d5SSiddharth Bhat   // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions
1438f291c8d5SSiddharth Bhat   // SubtreeValues. This is important, because we should not lose any
1439f291c8d5SSiddharth Bhat   // SubtreeValues in the process of constructing the
1440f291c8d5SSiddharth Bhat   // "ValidSubtree{Values, Functions} sets. Nor should the set
1441f291c8d5SSiddharth Bhat   // ValidSubtree{Values, Functions} have any common element.
1442f291c8d5SSiddharth Bhat   auto ValidSubtreeValuesIt =
1443f291c8d5SSiddharth Bhat       make_filter_range(SubtreeValues, isValidSubtreeValue);
1444f291c8d5SSiddharth Bhat   SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(),
1445f291c8d5SSiddharth Bhat                                         ValidSubtreeValuesIt.end());
14468fc6cdfbSTobias Grosser 
14478fc6cdfbSTobias Grosser   bool AllowCUDALibDevice = Arch == GPUArch::NVPTX64;
14488fc6cdfbSTobias Grosser 
1449f291c8d5SSiddharth Bhat   SetVector<Function *> ValidSubtreeFunctions(
14508fc6cdfbSTobias Grosser       getFunctionsFromRawSubtreeValues(SubtreeValues, AllowCUDALibDevice));
1451f291c8d5SSiddharth Bhat 
1452a1b2086aSSiddharth Bhat   // @see IslNodeBuilder::getReferencesInSubtree
1453a1b2086aSSiddharth Bhat   SetVector<Value *> ReplacedValues;
1454a1b2086aSSiddharth Bhat   for (Value *V : ValidSubtreeValues) {
1455a1b2086aSSiddharth Bhat     auto It = ValueMap.find(V);
1456a1b2086aSSiddharth Bhat     if (It == ValueMap.end())
1457a1b2086aSSiddharth Bhat       ReplacedValues.insert(V);
1458a1b2086aSSiddharth Bhat     else
1459a1b2086aSSiddharth Bhat       ReplacedValues.insert(It->second);
1460a1b2086aSSiddharth Bhat   }
1461a1b2086aSSiddharth Bhat   return std::make_pair(ReplacedValues, ValidSubtreeFunctions);
1462edb885cbSTobias Grosser }
1463edb885cbSTobias Grosser 
146474dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
146574dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
146674dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
146774dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
146874dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
146974dc3cb4STobias Grosser 
147074dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
147174dc3cb4STobias Grosser     DT.eraseNode(BB);
147274dc3cb4STobias Grosser }
147374dc3cb4STobias Grosser 
147474dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
147574dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
147674dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
147774dc3cb4STobias Grosser     if (L)
147874dc3cb4STobias Grosser       SE.forgetLoop(L);
147974dc3cb4STobias Grosser   }
148074dc3cb4STobias Grosser }
148174dc3cb4STobias Grosser 
148274dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
148374dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
148474dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
148574dc3cb4STobias Grosser     if (L)
148674dc3cb4STobias Grosser       SE.forgetLoop(L);
148774dc3cb4STobias Grosser     LI.removeBlock(&BB);
148874dc3cb4STobias Grosser   }
148974dc3cb4STobias Grosser }
149074dc3cb4STobias Grosser 
149179a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
149279a947c2STobias Grosser   std::vector<Value *> Sizes;
14934d5820d1SSiddharth Bhat   isl::ast_build Context =
14944d5820d1SSiddharth Bhat       isl::ast_build::from_context(isl::manage(S.getContext()));
149579a947c2STobias Grosser 
14964d5820d1SSiddharth Bhat   isl::multi_pw_aff GridSizePwAffs =
14974d5820d1SSiddharth Bhat       isl::manage(isl_multi_pw_aff_copy(Kernel->grid_size));
149879a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
14994d5820d1SSiddharth Bhat     isl::pw_aff Size = GridSizePwAffs.get_pw_aff(i);
15004d5820d1SSiddharth Bhat     isl::ast_expr GridSize = Context.expr_from(Size);
15014d5820d1SSiddharth Bhat     Value *Res = ExprBuilder.create(GridSize.release());
150279a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
150379a947c2STobias Grosser     Sizes.push_back(Res);
150479a947c2STobias Grosser   }
150579a947c2STobias Grosser 
150679a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
150779a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
150879a947c2STobias Grosser 
150979a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
151079a947c2STobias Grosser }
151179a947c2STobias Grosser 
151279a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
151379a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
151479a947c2STobias Grosser   std::vector<Value *> Sizes;
151579a947c2STobias Grosser 
151679a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
151779a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
151879a947c2STobias Grosser     Sizes.push_back(Res);
151979a947c2STobias Grosser   }
152079a947c2STobias Grosser 
152179a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
152279a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
152379a947c2STobias Grosser 
152479a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
152579a947c2STobias Grosser }
152679a947c2STobias Grosser 
1527a90be207SSiddharth Bhat void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters,
1528a90be207SSiddharth Bhat                                           Instruction *Param, int Index) {
1529a90be207SSiddharth Bhat   Value *Slot = Builder.CreateGEP(
1530a90be207SSiddharth Bhat       Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1531a90be207SSiddharth Bhat   Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1532a90be207SSiddharth Bhat   Builder.CreateStore(ParamTyped, Slot);
1533a90be207SSiddharth Bhat }
1534a90be207SSiddharth Bhat 
153557693272STobias Grosser Value *
153657693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
153757693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
1538a90be207SSiddharth Bhat   const int NumArgs = F->arg_size();
1539a90be207SSiddharth Bhat   std::vector<int> ArgSizes(NumArgs);
1540a90be207SSiddharth Bhat 
1541a90be207SSiddharth Bhat   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs);
154279a947c2STobias Grosser 
154379a947c2STobias Grosser   BasicBlock *EntryBlock =
154479a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
154567726b32STobias Grosser   auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace();
154679a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
154767726b32STobias Grosser   Instruction *Parameters = new AllocaInst(
154867726b32STobias Grosser       ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator());
154979a947c2STobias Grosser 
155079a947c2STobias Grosser   int Index = 0;
155179a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
155279a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
155379a947c2STobias Grosser       continue;
155479a947c2STobias Grosser 
155579a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1556206e9e3bSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
155779a947c2STobias Grosser 
1558a90be207SSiddharth Bhat     ArgSizes[Index] = SAI->getElemSizeInBytes();
1559a90be207SSiddharth Bhat 
1560abed4969SSiddharth Bhat     Value *DevArray = nullptr;
1561abed4969SSiddharth Bhat     if (ManagedMemory) {
1562abed4969SSiddharth Bhat       DevArray = getOrCreateManagedDeviceArray(
1563abed4969SSiddharth Bhat           &Prog->array[i], const_cast<ScopArrayInfo *>(SAI));
1564abed4969SSiddharth Bhat     } else {
1565abed4969SSiddharth Bhat       DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
156679a947c2STobias Grosser       DevArray = createCallGetDevicePtr(DevArray);
1567abed4969SSiddharth Bhat     }
1568abed4969SSiddharth Bhat     assert(DevArray != nullptr && "Array to be offloaded to device not "
1569abed4969SSiddharth Bhat                                   "initialized");
1570aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(&Prog->array[i]);
1571aaabbbf8STobias Grosser 
1572aaabbbf8STobias Grosser     if (Offset) {
1573aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(
1574aaabbbf8STobias Grosser           DevArray, SAI->getElementType()->getPointerTo());
1575aaabbbf8STobias Grosser       DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset));
1576aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1577aaabbbf8STobias Grosser     }
1578fe74a7a1STobias Grosser     Value *Slot = Builder.CreateGEP(
1579fe74a7a1STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1580aaabbbf8STobias Grosser 
1581fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1582abed4969SSiddharth Bhat       Value *ValPtr = nullptr;
1583abed4969SSiddharth Bhat       if (ManagedMemory)
1584abed4969SSiddharth Bhat         ValPtr = DevArray;
1585abed4969SSiddharth Bhat       else
1586abed4969SSiddharth Bhat         ValPtr = BlockGen.getOrCreateAlloca(SAI);
1587abed4969SSiddharth Bhat 
1588abed4969SSiddharth Bhat       assert(ValPtr != nullptr && "ValPtr that should point to a valid object"
1589abed4969SSiddharth Bhat                                   " to be stored into Parameters");
1590fe74a7a1STobias Grosser       Value *ValPtrCast =
1591fe74a7a1STobias Grosser           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1592fe74a7a1STobias Grosser       Builder.CreateStore(ValPtrCast, Slot);
1593fe74a7a1STobias Grosser     } else {
159467726b32STobias Grosser       Instruction *Param =
159567726b32STobias Grosser           new AllocaInst(Builder.getInt8PtrTy(), AddressSpace,
159667726b32STobias Grosser                          Launch + "_param_" + std::to_string(Index),
159779a947c2STobias Grosser                          EntryBlock->getTerminator());
159879a947c2STobias Grosser       Builder.CreateStore(DevArray, Param);
159979a947c2STobias Grosser       Value *ParamTyped =
160079a947c2STobias Grosser           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
160179a947c2STobias Grosser       Builder.CreateStore(ParamTyped, Slot);
1602fe74a7a1STobias Grosser     }
160379a947c2STobias Grosser     Index++;
160479a947c2STobias Grosser   }
160579a947c2STobias Grosser 
1606a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1607a490147cSTobias Grosser 
1608a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1609a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1610a490147cSTobias Grosser     Value *Val = IDToValue[Id];
1611a490147cSTobias Grosser     isl_id_free(Id);
1612a90be207SSiddharth Bhat 
1613a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1614a90be207SSiddharth Bhat 
161567726b32STobias Grosser     Instruction *Param =
161667726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
161767726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1618a490147cSTobias Grosser                        EntryBlock->getTerminator());
1619a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
1620a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1621a490147cSTobias Grosser     Index++;
1622a490147cSTobias Grosser   }
1623a490147cSTobias Grosser 
1624d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1625d8b94bcaSTobias Grosser 
1626d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
1627d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1628d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
1629a1b2086aSSiddharth Bhat     if (ValueMap.count(Val))
1630a1b2086aSSiddharth Bhat       Val = ValueMap[Val];
1631d8b94bcaSTobias Grosser     isl_id_free(Id);
1632a90be207SSiddharth Bhat 
1633a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1634a90be207SSiddharth Bhat 
163567726b32STobias Grosser     Instruction *Param =
163667726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
163767726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1638d8b94bcaSTobias Grosser                        EntryBlock->getTerminator());
1639d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
1640a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1641d8b94bcaSTobias Grosser     Index++;
1642d8b94bcaSTobias Grosser   }
1643d8b94bcaSTobias Grosser 
164457693272STobias Grosser   for (auto Val : SubtreeValues) {
1645a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1646a90be207SSiddharth Bhat 
164767726b32STobias Grosser     Instruction *Param =
164867726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
164967726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
165057693272STobias Grosser                        EntryBlock->getTerminator());
165157693272STobias Grosser     Builder.CreateStore(Val, Param);
1652a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1653a90be207SSiddharth Bhat     Index++;
1654a90be207SSiddharth Bhat   }
1655a90be207SSiddharth Bhat 
1656a90be207SSiddharth Bhat   for (int i = 0; i < NumArgs; i++) {
1657a90be207SSiddharth Bhat     Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]);
1658a90be207SSiddharth Bhat     Instruction *Param =
1659a90be207SSiddharth Bhat         new AllocaInst(Builder.getInt32Ty(), AddressSpace,
1660a90be207SSiddharth Bhat                        Launch + "_param_size_" + std::to_string(i),
1661a90be207SSiddharth Bhat                        EntryBlock->getTerminator());
1662a90be207SSiddharth Bhat     Builder.CreateStore(Val, Param);
1663a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
166457693272STobias Grosser     Index++;
166557693272STobias Grosser   }
166657693272STobias Grosser 
166779a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
166879a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
166979a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
167079a947c2STobias Grosser }
167179a947c2STobias Grosser 
1672f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions(
1673f291c8d5SSiddharth Bhat     SetVector<Function *> SubtreeFunctions) {
1674f291c8d5SSiddharth Bhat   for (auto Fn : SubtreeFunctions) {
1675f291c8d5SSiddharth Bhat     const std::string ClonedFnName = Fn->getName();
1676f291c8d5SSiddharth Bhat     Function *Clone = GPUModule->getFunction(ClonedFnName);
1677f291c8d5SSiddharth Bhat     if (!Clone)
1678f291c8d5SSiddharth Bhat       Clone =
1679f291c8d5SSiddharth Bhat           Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage,
1680f291c8d5SSiddharth Bhat                            ClonedFnName, GPUModule.get());
1681f291c8d5SSiddharth Bhat     assert(Clone && "Expected cloned function to be initialized.");
1682f291c8d5SSiddharth Bhat     assert(ValueMap.find(Fn) == ValueMap.end() &&
1683f291c8d5SSiddharth Bhat            "Fn already present in ValueMap");
1684f291c8d5SSiddharth Bhat     ValueMap[Fn] = Clone;
1685f291c8d5SSiddharth Bhat   }
1686f291c8d5SSiddharth Bhat }
168732837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
168832837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
168932837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
169032837fe3STobias Grosser   isl_id_free(Id);
169132837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
169232837fe3STobias Grosser 
1693bc653f20STobias Grosser   if (Kernel->n_grid > 1)
1694bc653f20STobias Grosser     DeepestParallel =
1695bc653f20STobias Grosser         std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set));
1696bc653f20STobias Grosser   else
1697bc653f20STobias Grosser     DeepestSequential =
1698bc653f20STobias Grosser         std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set));
1699bc653f20STobias Grosser 
1700c1c6a2a6STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1701c1c6a2a6STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1702c1c6a2a6STobias Grosser 
1703f291c8d5SSiddharth Bhat   SetVector<Value *> SubtreeValues;
1704f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1705f291c8d5SSiddharth Bhat   std::tie(SubtreeValues, SubtreeFunctions) = getReferencesInKernel(Kernel);
1706edb885cbSTobias Grosser 
170732837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
170832837fe3STobias Grosser 
170932837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1710472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1711edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
1712587f1f57STobias Grosser   BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap;
1713b06ff457STobias Grosser   ScalarMap.clear();
171432837fe3STobias Grosser 
1715edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1716edb885cbSTobias Grosser 
1717edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
1718edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
1719edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
1720edb885cbSTobias Grosser   for (const Loop *L : Loops) {
1721edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1722edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1723edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1724edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1725edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1726edb885cbSTobias Grosser     SubtreeValues.insert(V);
1727edb885cbSTobias Grosser   }
1728edb885cbSTobias Grosser 
1729f291c8d5SSiddharth Bhat   createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions);
1730f291c8d5SSiddharth Bhat   setupKernelSubtreeFunctions(SubtreeFunctions);
173132837fe3STobias Grosser 
173259ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
173359ab0705STobias Grosser 
173451dfc275STobias Grosser   finalizeKernelArguments(Kernel);
173574dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
17362f3073b5SPhilipp Schaad   if (Arch == GPUArch::NVPTX64)
1737c1c6a2a6STobias Grosser     addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
173874dc3cb4STobias Grosser   clearDominators(F);
173974dc3cb4STobias Grosser   clearScalarEvolution(F);
174074dc3cb4STobias Grosser   clearLoops(F);
174174dc3cb4STobias Grosser 
1742472f9654STobias Grosser   IDToValue = HostIDs;
174332837fe3STobias Grosser 
1744b06ff457STobias Grosser   ValueMap = std::move(HostValueMap);
1745b06ff457STobias Grosser   ScalarMap = std::move(HostScalarMap);
1746edb885cbSTobias Grosser   EscapeMap.clear();
1747edb885cbSTobias Grosser   IDToSAI.clear();
174874dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
174974dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
17504d5a9172STobias Grosser     S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array);
175174dc3cb4STobias Grosser   LocalArrays.clear();
1752edb885cbSTobias Grosser 
175351dfc275STobias Grosser   std::string ASMString = finalizeKernelFunction();
175451dfc275STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
175557693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
175679a947c2STobias Grosser 
175779f13b9aSSingapuram Sanjay Srivallabh   std::string Name = getKernelFuncName(Kernel->id);
175857793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
175957793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
176057793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
176179a947c2STobias Grosser 
176279a947c2STobias Grosser   Value *GridDimX, *GridDimY;
176379a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
176479a947c2STobias Grosser 
176579a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
176679a947c2STobias Grosser                          BlockDimZ, Parameters);
176757793596STobias Grosser   createCallFreeKernel(GPUKernel);
1768b513b491STobias Grosser 
1769b513b491STobias Grosser   for (auto Id : KernelIds)
1770b513b491STobias Grosser     isl_id_free(Id);
1771b513b491STobias Grosser 
1772b513b491STobias Grosser   KernelIds.clear();
177332837fe3STobias Grosser }
177432837fe3STobias Grosser 
177532837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
177632837fe3STobias Grosser ///
177732837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
177832837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
1779d277fedaSSiddharth Bhat   std::string Ret = "";
178032837fe3STobias Grosser 
1781d277fedaSSiddharth Bhat   if (!is64Bit) {
1782d277fedaSSiddharth Bhat     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
178330caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1784d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1785d277fedaSSiddharth Bhat   } else {
1786d277fedaSSiddharth Bhat     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
178730caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1788d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1789d277fedaSSiddharth Bhat   }
179032837fe3STobias Grosser 
179132837fe3STobias Grosser   return Ret;
179232837fe3STobias Grosser }
179332837fe3STobias Grosser 
17942f3073b5SPhilipp Schaad /// Compute the DataLayout string for a SPIR kernel.
17952f3073b5SPhilipp Schaad ///
17962f3073b5SPhilipp Schaad /// @param is64Bit Are we looking for a 64 bit architecture?
17972f3073b5SPhilipp Schaad static std::string computeSPIRDataLayout(bool is64Bit) {
17982f3073b5SPhilipp Schaad   std::string Ret = "";
17992f3073b5SPhilipp Schaad 
18002f3073b5SPhilipp Schaad   if (!is64Bit) {
18012f3073b5SPhilipp Schaad     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
180230caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
18032f3073b5SPhilipp Schaad            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
18042f3073b5SPhilipp Schaad            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
18052f3073b5SPhilipp Schaad   } else {
18062f3073b5SPhilipp Schaad     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
180730caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
18082f3073b5SPhilipp Schaad            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
18092f3073b5SPhilipp Schaad            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
18102f3073b5SPhilipp Schaad   }
18112f3073b5SPhilipp Schaad 
18122f3073b5SPhilipp Schaad   return Ret;
18132f3073b5SPhilipp Schaad }
18142f3073b5SPhilipp Schaad 
1815edb885cbSTobias Grosser Function *
1816edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1817edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
181832837fe3STobias Grosser   std::vector<Type *> Args;
181979f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
182032837fe3STobias Grosser 
18212f3073b5SPhilipp Schaad   std::vector<Metadata *> MemoryType;
18222f3073b5SPhilipp Schaad 
182332837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
182432837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
182532837fe3STobias Grosser       continue;
182632837fe3STobias Grosser 
1827fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1828fe74a7a1STobias Grosser       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1829206e9e3bSTobias Grosser       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
1830fe74a7a1STobias Grosser       Args.push_back(SAI->getElementType());
18312f3073b5SPhilipp Schaad       MemoryType.push_back(
18322f3073b5SPhilipp Schaad           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1833fe74a7a1STobias Grosser     } else {
1834d277fedaSSiddharth Bhat       static const int UseGlobalMemory = 1;
1835d277fedaSSiddharth Bhat       Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory));
18362f3073b5SPhilipp Schaad       MemoryType.push_back(
18372f3073b5SPhilipp Schaad           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 1)));
183832837fe3STobias Grosser     }
1839fe74a7a1STobias Grosser   }
184032837fe3STobias Grosser 
1841f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1842f6044bd0STobias Grosser 
18432f3073b5SPhilipp Schaad   for (long i = 0; i < NumHostIters; i++) {
1844f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
18452f3073b5SPhilipp Schaad     MemoryType.push_back(
18462f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
18472f3073b5SPhilipp Schaad   }
1848f6044bd0STobias Grosser 
1849c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1850c84a1995STobias Grosser 
1851cf66ef26STobias Grosser   for (long i = 0; i < NumVars; i++) {
1852cf66ef26STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1853cf66ef26STobias Grosser     Value *Val = IDToValue[Id];
1854cf66ef26STobias Grosser     isl_id_free(Id);
1855cf66ef26STobias Grosser     Args.push_back(Val->getType());
18562f3073b5SPhilipp Schaad     MemoryType.push_back(
18572f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1858cf66ef26STobias Grosser   }
1859c84a1995STobias Grosser 
18602f3073b5SPhilipp Schaad   for (auto *V : SubtreeValues) {
1861edb885cbSTobias Grosser     Args.push_back(V->getType());
18622f3073b5SPhilipp Schaad     MemoryType.push_back(
18632f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
18642f3073b5SPhilipp Schaad   }
1865edb885cbSTobias Grosser 
186632837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
186732837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
186832837fe3STobias Grosser                               GPUModule.get());
186917f01968SSiddharth Bhat 
18702f3073b5SPhilipp Schaad   std::vector<Metadata *> EmptyStrings;
18712f3073b5SPhilipp Schaad 
18722f3073b5SPhilipp Schaad   for (unsigned int i = 0; i < MemoryType.size(); i++) {
18732f3073b5SPhilipp Schaad     EmptyStrings.push_back(MDString::get(FN->getContext(), ""));
18742f3073b5SPhilipp Schaad   }
18752f3073b5SPhilipp Schaad 
18762f3073b5SPhilipp Schaad   if (Arch == GPUArch::SPIR32 || Arch == GPUArch::SPIR64) {
18772f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_addr_space",
18782f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), MemoryType));
18792f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_name",
18802f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18812f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_access_qual",
18822f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18832f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_type",
18842f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18852f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_type_qual",
18862f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18872f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_base_type",
18882f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18892f3073b5SPhilipp Schaad   }
18902f3073b5SPhilipp Schaad 
189117f01968SSiddharth Bhat   switch (Arch) {
189217f01968SSiddharth Bhat   case GPUArch::NVPTX64:
189332837fe3STobias Grosser     FN->setCallingConv(CallingConv::PTX_Kernel);
189417f01968SSiddharth Bhat     break;
18952f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
18962f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
18972f3073b5SPhilipp Schaad     FN->setCallingConv(CallingConv::SPIR_KERNEL);
18982f3073b5SPhilipp Schaad     break;
189917f01968SSiddharth Bhat   }
190032837fe3STobias Grosser 
190132837fe3STobias Grosser   auto Arg = FN->arg_begin();
190232837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
190332837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
190432837fe3STobias Grosser       continue;
190532837fe3STobias Grosser 
1906edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
1907edb885cbSTobias Grosser 
1908edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1909206e9e3bSTobias Grosser     const ScopArrayInfo *SAI =
1910206e9e3bSTobias Grosser         ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id)));
1911edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
1912edb885cbSTobias Grosser     Value *Val = &*Arg;
1913edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1914edb885cbSTobias Grosser     isl_ast_build *Build =
1915edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
1916f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1917edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1918edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
19199e3db2b7SSiddharth Bhat           Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j));
1920edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
1921edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
1922edb885cbSTobias Grosser     }
1923edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
19244d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array);
192574dc3cb4STobias Grosser     LocalArrays.push_back(Val);
1926edb885cbSTobias Grosser 
1927edb885cbSTobias Grosser     isl_ast_build_free(Build);
1928b513b491STobias Grosser     KernelIds.push_back(Id);
1929edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
193032837fe3STobias Grosser     Arg++;
193132837fe3STobias Grosser   }
193232837fe3STobias Grosser 
1933f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1934f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1935f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
1936f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
1937f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1938f6044bd0STobias Grosser     Arg++;
1939f6044bd0STobias Grosser   }
1940f6044bd0STobias Grosser 
1941c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
1942c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1943c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
194412453403STobias Grosser     Value *Val = IDToValue[Id];
194512453403STobias Grosser     ValueMap[Val] = &*Arg;
1946c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
1947c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1948c84a1995STobias Grosser     Arg++;
1949c84a1995STobias Grosser   }
1950c84a1995STobias Grosser 
1951edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
1952edb885cbSTobias Grosser     Arg->setName(V->getName());
1953edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
1954edb885cbSTobias Grosser     Arg++;
1955edb885cbSTobias Grosser   }
1956edb885cbSTobias Grosser 
195732837fe3STobias Grosser   return FN;
195832837fe3STobias Grosser }
195932837fe3STobias Grosser 
1960472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
196117f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsBID[2];
196217f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsTID[3];
1963472f9654STobias Grosser 
196417f01968SSiddharth Bhat   switch (Arch) {
19652f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
19662f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
19672f3073b5SPhilipp Schaad     llvm_unreachable("Cannot generate NVVM intrinsics for SPIR");
196817f01968SSiddharth Bhat   case GPUArch::NVPTX64:
196917f01968SSiddharth Bhat     IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x;
197017f01968SSiddharth Bhat     IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y;
197117f01968SSiddharth Bhat 
197217f01968SSiddharth Bhat     IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x;
197317f01968SSiddharth Bhat     IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y;
197417f01968SSiddharth Bhat     IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z;
197517f01968SSiddharth Bhat     break;
197617f01968SSiddharth Bhat   }
1977472f9654STobias Grosser 
1978472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1979472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
1980472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1981472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1982472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1983472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1984472f9654STobias Grosser     IDToValue[Id] = Val;
1985472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1986472f9654STobias Grosser   };
1987472f9654STobias Grosser 
1988472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
1989472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1990472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
1991472f9654STobias Grosser   }
1992472f9654STobias Grosser 
1993472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
1994472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1995472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
1996472f9654STobias Grosser   }
1997472f9654STobias Grosser }
1998472f9654STobias Grosser 
19992f3073b5SPhilipp Schaad void GPUNodeBuilder::insertKernelCallsSPIR(ppcg_kernel *Kernel) {
20002f3073b5SPhilipp Schaad   const char *GroupName[3] = {"__gen_ocl_get_group_id0",
20012f3073b5SPhilipp Schaad                               "__gen_ocl_get_group_id1",
20022f3073b5SPhilipp Schaad                               "__gen_ocl_get_group_id2"};
20032f3073b5SPhilipp Schaad 
20042f3073b5SPhilipp Schaad   const char *LocalName[3] = {"__gen_ocl_get_local_id0",
20052f3073b5SPhilipp Schaad                               "__gen_ocl_get_local_id1",
20062f3073b5SPhilipp Schaad                               "__gen_ocl_get_local_id2"};
20072f3073b5SPhilipp Schaad 
20082f3073b5SPhilipp Schaad   auto createFunc = [this](const char *Name, __isl_take isl_id *Id) mutable {
20092f3073b5SPhilipp Schaad     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
20102f3073b5SPhilipp Schaad     Function *FN = M->getFunction(Name);
20112f3073b5SPhilipp Schaad 
20122f3073b5SPhilipp Schaad     // If FN is not available, declare it.
20132f3073b5SPhilipp Schaad     if (!FN) {
20142f3073b5SPhilipp Schaad       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
20152f3073b5SPhilipp Schaad       std::vector<Type *> Args;
20162f3073b5SPhilipp Schaad       FunctionType *Ty = FunctionType::get(Builder.getInt32Ty(), Args, false);
20172f3073b5SPhilipp Schaad       FN = Function::Create(Ty, Linkage, Name, M);
20182f3073b5SPhilipp Schaad       FN->setCallingConv(CallingConv::SPIR_FUNC);
20192f3073b5SPhilipp Schaad     }
20202f3073b5SPhilipp Schaad 
20212f3073b5SPhilipp Schaad     Value *Val = Builder.CreateCall(FN, {});
20222f3073b5SPhilipp Schaad     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
20232f3073b5SPhilipp Schaad     IDToValue[Id] = Val;
20242f3073b5SPhilipp Schaad     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
20252f3073b5SPhilipp Schaad   };
20262f3073b5SPhilipp Schaad 
20272f3073b5SPhilipp Schaad   for (int i = 0; i < Kernel->n_grid; ++i)
20282f3073b5SPhilipp Schaad     createFunc(GroupName[i], isl_id_list_get_id(Kernel->block_ids, i));
20292f3073b5SPhilipp Schaad 
20302f3073b5SPhilipp Schaad   for (int i = 0; i < Kernel->n_block; ++i)
20312f3073b5SPhilipp Schaad     createFunc(LocalName[i], isl_id_list_get_id(Kernel->thread_ids, i));
20322f3073b5SPhilipp Schaad }
20332f3073b5SPhilipp Schaad 
203400bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
203500bb5a99STobias Grosser   auto Arg = FN->arg_begin();
203600bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
203700bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
203800bb5a99STobias Grosser       continue;
203900bb5a99STobias Grosser 
204000bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2041206e9e3bSTobias Grosser     const ScopArrayInfo *SAI =
2042206e9e3bSTobias Grosser         ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id)));
204300bb5a99STobias Grosser     isl_id_free(Id);
204400bb5a99STobias Grosser 
204500bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
204600bb5a99STobias Grosser       Arg++;
204700bb5a99STobias Grosser       continue;
204800bb5a99STobias Grosser     }
204900bb5a99STobias Grosser 
2050fe74a7a1STobias Grosser     Value *Val = &*Arg;
2051fe74a7a1STobias Grosser 
2052fe74a7a1STobias Grosser     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
205300bb5a99STobias Grosser       Type *TypePtr = SAI->getElementType()->getPointerTo();
2054fe74a7a1STobias Grosser       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
2055fe74a7a1STobias Grosser       Val = Builder.CreateLoad(TypedArgPtr);
2056fe74a7a1STobias Grosser     }
2057fe74a7a1STobias Grosser 
2058fe74a7a1STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
205900bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
206000bb5a99STobias Grosser 
206100bb5a99STobias Grosser     Arg++;
206200bb5a99STobias Grosser   }
206300bb5a99STobias Grosser }
206400bb5a99STobias Grosser 
206551dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) {
206651dfc275STobias Grosser   auto *FN = Builder.GetInsertBlock()->getParent();
206751dfc275STobias Grosser   auto Arg = FN->arg_begin();
206851dfc275STobias Grosser 
206951dfc275STobias Grosser   bool StoredScalar = false;
207051dfc275STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
207151dfc275STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
207251dfc275STobias Grosser       continue;
207351dfc275STobias Grosser 
207451dfc275STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2075206e9e3bSTobias Grosser     const ScopArrayInfo *SAI =
2076206e9e3bSTobias Grosser         ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id)));
207751dfc275STobias Grosser     isl_id_free(Id);
207851dfc275STobias Grosser 
207951dfc275STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
208051dfc275STobias Grosser       Arg++;
208151dfc275STobias Grosser       continue;
208251dfc275STobias Grosser     }
208351dfc275STobias Grosser 
208451dfc275STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
208551dfc275STobias Grosser       Arg++;
208651dfc275STobias Grosser       continue;
208751dfc275STobias Grosser     }
208851dfc275STobias Grosser 
208951dfc275STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
209051dfc275STobias Grosser     Value *ArgPtr = &*Arg;
209151dfc275STobias Grosser     Type *TypePtr = SAI->getElementType()->getPointerTo();
209251dfc275STobias Grosser     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
209351dfc275STobias Grosser     Value *Val = Builder.CreateLoad(Alloca);
209451dfc275STobias Grosser     Builder.CreateStore(Val, TypedArgPtr);
209551dfc275STobias Grosser     StoredScalar = true;
209651dfc275STobias Grosser 
209751dfc275STobias Grosser     Arg++;
209851dfc275STobias Grosser   }
209951dfc275STobias Grosser 
2100*638316daSSiddharth Bhat   if (StoredScalar) {
210151dfc275STobias Grosser     /// In case more than one thread contains scalar stores, the generated
210251dfc275STobias Grosser     /// code might be incorrect, if we only store at the end of the kernel.
210351dfc275STobias Grosser     /// To support this case we need to store these scalars back at each
210451dfc275STobias Grosser     /// memory store or at least before each kernel barrier.
2105*638316daSSiddharth Bhat     if (Kernel->n_block != 0 || Kernel->n_grid != 0) {
210651dfc275STobias Grosser       BuildSuccessful = 0;
2107*638316daSSiddharth Bhat       DEBUG(
2108*638316daSSiddharth Bhat           dbgs() << getUniqueScopName(&S)
2109*638316daSSiddharth Bhat                  << " has a store to a scalar value that"
2110*638316daSSiddharth Bhat                     " would be undefined to run in parallel. Bailing out.\n";);
2111*638316daSSiddharth Bhat     }
2112*638316daSSiddharth Bhat   }
211351dfc275STobias Grosser }
211451dfc275STobias Grosser 
2115b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
2116b513b491STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
2117b513b491STobias Grosser 
2118b513b491STobias Grosser   for (int i = 0; i < Kernel->n_var; ++i) {
2119b513b491STobias Grosser     struct ppcg_kernel_var &Var = Kernel->var[i];
2120b513b491STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
2121206e9e3bSTobias Grosser     Type *EleTy = ScopArrayInfo::getFromId(isl::manage(Id))->getElementType();
2122b513b491STobias Grosser 
2123f919d8b3STobias Grosser     Type *ArrayTy = EleTy;
2124b513b491STobias Grosser     SmallVector<const SCEV *, 4> Sizes;
2125b513b491STobias Grosser 
2126f5aff704SRoman Gareev     Sizes.push_back(nullptr);
2127928d7573STobias Grosser     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
2128b513b491STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2129f919d8b3STobias Grosser       long Bound = isl_val_get_num_si(Val);
2130b513b491STobias Grosser       isl_val_free(Val);
2131b513b491STobias Grosser       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
2132928d7573STobias Grosser     }
2133928d7573STobias Grosser 
2134928d7573STobias Grosser     for (int j = Var.array->n_index - 1; j >= 0; --j) {
2135928d7573STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2136928d7573STobias Grosser       long Bound = isl_val_get_num_si(Val);
2137928d7573STobias Grosser       isl_val_free(Val);
2138b513b491STobias Grosser       ArrayTy = ArrayType::get(ArrayTy, Bound);
2139b513b491STobias Grosser     }
2140b513b491STobias Grosser 
2141130ca30fSTobias Grosser     const ScopArrayInfo *SAI;
2142130ca30fSTobias Grosser     Value *Allocation;
2143130ca30fSTobias Grosser     if (Var.type == ppcg_access_shared) {
2144130ca30fSTobias Grosser       auto GlobalVar = new GlobalVariable(
2145130ca30fSTobias Grosser           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
2146130ca30fSTobias Grosser           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
2147130ca30fSTobias Grosser       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
2148f919d8b3STobias Grosser       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
2149f919d8b3STobias Grosser 
2150130ca30fSTobias Grosser       Allocation = GlobalVar;
2151130ca30fSTobias Grosser     } else if (Var.type == ppcg_access_private) {
2152130ca30fSTobias Grosser       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
2153130ca30fSTobias Grosser     } else {
2154130ca30fSTobias Grosser       llvm_unreachable("unknown variable type");
2155130ca30fSTobias Grosser     }
21564d5a9172STobias Grosser     SAI =
21574d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array);
2158b513b491STobias Grosser     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
2159130ca30fSTobias Grosser     IDToValue[Id] = Allocation;
2160130ca30fSTobias Grosser     LocalArrays.push_back(Allocation);
2161b513b491STobias Grosser     KernelIds.push_back(Id);
2162b513b491STobias Grosser     IDToSAI[Id] = SAI;
2163b513b491STobias Grosser   }
2164b513b491STobias Grosser }
2165b513b491STobias Grosser 
2166f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction(
2167f291c8d5SSiddharth Bhat     ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues,
2168f291c8d5SSiddharth Bhat     SetVector<Function *> &SubtreeFunctions) {
216979f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
217032837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
217117f01968SSiddharth Bhat 
217217f01968SSiddharth Bhat   switch (Arch) {
217317f01968SSiddharth Bhat   case GPUArch::NVPTX64:
217417f01968SSiddharth Bhat     if (Runtime == GPURuntime::CUDA)
217532837fe3STobias Grosser       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
217617f01968SSiddharth Bhat     else if (Runtime == GPURuntime::OpenCL)
217717f01968SSiddharth Bhat       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl"));
217832837fe3STobias Grosser     GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
217917f01968SSiddharth Bhat     break;
21802f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
21812f3073b5SPhilipp Schaad     GPUModule->setTargetTriple(Triple::normalize("spir-unknown-unknown"));
21822f3073b5SPhilipp Schaad     GPUModule->setDataLayout(computeSPIRDataLayout(false /* is64Bit */));
21832f3073b5SPhilipp Schaad     break;
21842f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
21852f3073b5SPhilipp Schaad     GPUModule->setTargetTriple(Triple::normalize("spir64-unknown-unknown"));
21862f3073b5SPhilipp Schaad     GPUModule->setDataLayout(computeSPIRDataLayout(true /* is64Bit */));
21872f3073b5SPhilipp Schaad     break;
218817f01968SSiddharth Bhat   }
218932837fe3STobias Grosser 
2190edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
219132837fe3STobias Grosser 
219259ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
219332837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
219432837fe3STobias Grosser 
219559ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
219659ab0705STobias Grosser 
219732837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
219832837fe3STobias Grosser   Builder.CreateRetVoid();
219932837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
2200472f9654STobias Grosser 
2201629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
2202629109b6STobias Grosser 
220300bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
2204b513b491STobias Grosser   createKernelVariables(Kernel, FN);
22052f3073b5SPhilipp Schaad 
22062f3073b5SPhilipp Schaad   switch (Arch) {
22072f3073b5SPhilipp Schaad   case GPUArch::NVPTX64:
2208472f9654STobias Grosser     insertKernelIntrinsics(Kernel);
22092f3073b5SPhilipp Schaad     break;
22102f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
22112f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
22122f3073b5SPhilipp Schaad     insertKernelCallsSPIR(Kernel);
22132f3073b5SPhilipp Schaad     break;
22142f3073b5SPhilipp Schaad   }
221532837fe3STobias Grosser }
221632837fe3STobias Grosser 
221774dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
221817f01968SSiddharth Bhat   llvm::Triple GPUTriple;
221917f01968SSiddharth Bhat 
222017f01968SSiddharth Bhat   switch (Arch) {
222117f01968SSiddharth Bhat   case GPUArch::NVPTX64:
222217f01968SSiddharth Bhat     switch (Runtime) {
222317f01968SSiddharth Bhat     case GPURuntime::CUDA:
222417f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda"));
222517f01968SSiddharth Bhat       break;
222617f01968SSiddharth Bhat     case GPURuntime::OpenCL:
222717f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl"));
222817f01968SSiddharth Bhat       break;
222917f01968SSiddharth Bhat     }
223017f01968SSiddharth Bhat     break;
22312f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
22322f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
22332f3073b5SPhilipp Schaad     std::string SPIRAssembly;
22342f3073b5SPhilipp Schaad     raw_string_ostream IROstream(SPIRAssembly);
22352f3073b5SPhilipp Schaad     IROstream << *GPUModule;
22362f3073b5SPhilipp Schaad     IROstream.flush();
22372f3073b5SPhilipp Schaad     return SPIRAssembly;
223817f01968SSiddharth Bhat   }
223917f01968SSiddharth Bhat 
224074dc3cb4STobias Grosser   std::string ErrMsg;
224174dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
224274dc3cb4STobias Grosser 
224374dc3cb4STobias Grosser   if (!GPUTarget) {
224474dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
224574dc3cb4STobias Grosser     return "";
224674dc3cb4STobias Grosser   }
224774dc3cb4STobias Grosser 
224874dc3cb4STobias Grosser   TargetOptions Options;
224974dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
225017f01968SSiddharth Bhat 
225117f01968SSiddharth Bhat   std::string subtarget;
225217f01968SSiddharth Bhat 
225317f01968SSiddharth Bhat   switch (Arch) {
225417f01968SSiddharth Bhat   case GPUArch::NVPTX64:
225517f01968SSiddharth Bhat     subtarget = CudaVersion;
225617f01968SSiddharth Bhat     break;
22572f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
22582f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
22592f3073b5SPhilipp Schaad     llvm_unreachable("No subtarget for SPIR architecture");
226017f01968SSiddharth Bhat   }
226117f01968SSiddharth Bhat 
226217f01968SSiddharth Bhat   std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine(
226317f01968SSiddharth Bhat       GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>()));
226474dc3cb4STobias Grosser 
226574dc3cb4STobias Grosser   SmallString<0> ASMString;
226674dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
226774dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
226874dc3cb4STobias Grosser 
226974dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
227074dc3cb4STobias Grosser 
227174dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
227274dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
227374dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
227474dc3cb4STobias Grosser     return "";
227574dc3cb4STobias Grosser   }
227674dc3cb4STobias Grosser 
227774dc3cb4STobias Grosser   PM.run(*GPUModule);
227874dc3cb4STobias Grosser 
227974dc3cb4STobias Grosser   return ASMStream.str();
228074dc3cb4STobias Grosser }
228174dc3cb4STobias Grosser 
22828fc6cdfbSTobias Grosser bool GPUNodeBuilder::requiresCUDALibDevice() {
22838fc6cdfbSTobias Grosser   for (Function &F : GPUModule->functions()) {
22848fc6cdfbSTobias Grosser     if (!F.isDeclaration())
22858fc6cdfbSTobias Grosser       continue;
22868fc6cdfbSTobias Grosser 
22878fc6cdfbSTobias Grosser     std::string CUDALibDeviceFunc = getCUDALibDeviceFuntion(&F);
22888fc6cdfbSTobias Grosser     if (CUDALibDeviceFunc.length() != 0) {
22898fc6cdfbSTobias Grosser       F.setName(CUDALibDeviceFunc);
22908fc6cdfbSTobias Grosser       return true;
22918fc6cdfbSTobias Grosser     }
22928fc6cdfbSTobias Grosser   }
22938fc6cdfbSTobias Grosser 
22948fc6cdfbSTobias Grosser   return false;
22958fc6cdfbSTobias Grosser }
22968fc6cdfbSTobias Grosser 
22978fc6cdfbSTobias Grosser void GPUNodeBuilder::addCUDALibDevice() {
22988fc6cdfbSTobias Grosser   if (Arch != GPUArch::NVPTX64)
22998fc6cdfbSTobias Grosser     return;
23008fc6cdfbSTobias Grosser 
23018fc6cdfbSTobias Grosser   if (requiresCUDALibDevice()) {
23028fc6cdfbSTobias Grosser     SMDiagnostic Error;
23038fc6cdfbSTobias Grosser 
23048fc6cdfbSTobias Grosser     errs() << CUDALibDevice << "\n";
23058fc6cdfbSTobias Grosser     auto LibDeviceModule =
23068fc6cdfbSTobias Grosser         parseIRFile(CUDALibDevice, Error, GPUModule->getContext());
23078fc6cdfbSTobias Grosser 
23088fc6cdfbSTobias Grosser     if (!LibDeviceModule) {
23098fc6cdfbSTobias Grosser       BuildSuccessful = false;
23108fc6cdfbSTobias Grosser       report_fatal_error("Could not find or load libdevice. Skipping GPU "
23118fc6cdfbSTobias Grosser                          "kernel generation. Please set -polly-acc-libdevice "
23128fc6cdfbSTobias Grosser                          "accordingly.\n");
23138fc6cdfbSTobias Grosser       return;
23148fc6cdfbSTobias Grosser     }
23158fc6cdfbSTobias Grosser 
23168fc6cdfbSTobias Grosser     Linker L(*GPUModule);
23178fc6cdfbSTobias Grosser 
23188fc6cdfbSTobias Grosser     // Set an nvptx64 target triple to avoid linker warnings. The original
23198fc6cdfbSTobias Grosser     // triple of the libdevice files are nvptx-unknown-unknown.
23208fc6cdfbSTobias Grosser     LibDeviceModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
23218fc6cdfbSTobias Grosser     L.linkInModule(std::move(LibDeviceModule), Linker::LinkOnlyNeeded);
23228fc6cdfbSTobias Grosser   }
23238fc6cdfbSTobias Grosser }
23248fc6cdfbSTobias Grosser 
232557793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
232665d7f72fSSiddharth Bhat 
23275857b701STobias Grosser   if (verifyModule(*GPUModule)) {
232865d7f72fSSiddharth Bhat     DEBUG(dbgs() << "verifyModule failed on module:\n";
232965d7f72fSSiddharth Bhat           GPUModule->print(dbgs(), nullptr); dbgs() << "\n";);
2330a0fb8b23SSiddharth Bhat     DEBUG(dbgs() << "verifyModule Error:\n";
2331a0fb8b23SSiddharth Bhat           verifyModule(*GPUModule, &dbgs()););
233265d7f72fSSiddharth Bhat 
233365d7f72fSSiddharth Bhat     if (FailOnVerifyModuleFailure)
233465d7f72fSSiddharth Bhat       llvm_unreachable("VerifyModule failed.");
233565d7f72fSSiddharth Bhat 
23365857b701STobias Grosser     BuildSuccessful = false;
23375857b701STobias Grosser     return "";
23385857b701STobias Grosser   }
233932837fe3STobias Grosser 
23408fc6cdfbSTobias Grosser   addCUDALibDevice();
23418fc6cdfbSTobias Grosser 
234232837fe3STobias Grosser   if (DumpKernelIR)
234332837fe3STobias Grosser     outs() << *GPUModule << "\n";
234432837fe3STobias Grosser 
23452f3073b5SPhilipp Schaad   if (Arch != GPUArch::SPIR32 && Arch != GPUArch::SPIR64) {
23469a18d559STobias Grosser     // Optimize module.
23479a18d559STobias Grosser     llvm::legacy::PassManager OptPasses;
23489a18d559STobias Grosser     PassManagerBuilder PassBuilder;
23499a18d559STobias Grosser     PassBuilder.OptLevel = 3;
23509a18d559STobias Grosser     PassBuilder.SizeLevel = 0;
23519a18d559STobias Grosser     PassBuilder.populateModulePassManager(OptPasses);
23529a18d559STobias Grosser     OptPasses.run(*GPUModule);
23532f3073b5SPhilipp Schaad   }
23549a18d559STobias Grosser 
235574dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
235674dc3cb4STobias Grosser 
235774dc3cb4STobias Grosser   if (DumpKernelASM)
235874dc3cb4STobias Grosser     outs() << Assembly << "\n";
235974dc3cb4STobias Grosser 
236032837fe3STobias Grosser   GPUModule.release();
2361472f9654STobias Grosser   KernelIDs.clear();
236257793596STobias Grosser 
236357793596STobias Grosser   return Assembly;
236432837fe3STobias Grosser }
2365eadf76d3SSiddharth Bhat /// Construct an `isl_pw_aff_list` from a vector of `isl_pw_aff`
2366eadf76d3SSiddharth Bhat /// @param PwAffs The list of piecewise affine functions to create an
2367eadf76d3SSiddharth Bhat ///               `isl_pw_aff_list` from. We expect an rvalue ref because
2368eadf76d3SSiddharth Bhat ///               all the isl_pw_aff are used up by this function.
2369eadf76d3SSiddharth Bhat ///
2370eadf76d3SSiddharth Bhat /// @returns  The `isl_pw_aff_list`.
2371eadf76d3SSiddharth Bhat __isl_give isl_pw_aff_list *
2372eadf76d3SSiddharth Bhat createPwAffList(isl_ctx *Context,
2373eadf76d3SSiddharth Bhat                 const std::vector<__isl_take isl_pw_aff *> &&PwAffs) {
2374eadf76d3SSiddharth Bhat   isl_pw_aff_list *List = isl_pw_aff_list_alloc(Context, PwAffs.size());
2375eadf76d3SSiddharth Bhat 
2376eadf76d3SSiddharth Bhat   for (unsigned i = 0; i < PwAffs.size(); i++) {
2377eadf76d3SSiddharth Bhat     List = isl_pw_aff_list_insert(List, i, PwAffs[i]);
2378eadf76d3SSiddharth Bhat   }
2379eadf76d3SSiddharth Bhat   return List;
2380eadf76d3SSiddharth Bhat }
2381eadf76d3SSiddharth Bhat 
2382eadf76d3SSiddharth Bhat /// Align all the `PwAffs` such that they have the same parameter dimensions.
2383eadf76d3SSiddharth Bhat ///
2384eadf76d3SSiddharth Bhat /// We loop over all `pw_aff` and align all of their spaces together to
2385eadf76d3SSiddharth Bhat /// create a common space for all the `pw_aff`. This common space is the
2386eadf76d3SSiddharth Bhat /// `AlignSpace`. We then align all the `pw_aff` to this space. We start
2387eadf76d3SSiddharth Bhat /// with the given `SeedSpace`.
2388eadf76d3SSiddharth Bhat /// @param PwAffs    The list of piecewise affine functions we want to align.
2389eadf76d3SSiddharth Bhat ///                  This is an rvalue reference because the entire vector is
2390eadf76d3SSiddharth Bhat ///                  used up by the end of the operation.
2391eadf76d3SSiddharth Bhat /// @param SeedSpace The space to start the alignment process with.
2392eadf76d3SSiddharth Bhat /// @returns         A std::pair, whose first element is the aligned space,
2393eadf76d3SSiddharth Bhat ///                  whose second element is the vector of aligned piecewise
2394eadf76d3SSiddharth Bhat ///                  affines.
2395eadf76d3SSiddharth Bhat static std::pair<__isl_give isl_space *, std::vector<__isl_give isl_pw_aff *>>
2396eadf76d3SSiddharth Bhat alignPwAffs(const std::vector<__isl_take isl_pw_aff *> &&PwAffs,
2397eadf76d3SSiddharth Bhat             __isl_take isl_space *SeedSpace) {
2398eadf76d3SSiddharth Bhat   assert(SeedSpace && "Invalid seed space given.");
2399eadf76d3SSiddharth Bhat 
2400eadf76d3SSiddharth Bhat   isl_space *AlignSpace = SeedSpace;
2401eadf76d3SSiddharth Bhat   for (isl_pw_aff *PwAff : PwAffs) {
2402eadf76d3SSiddharth Bhat     isl_space *PwAffSpace = isl_pw_aff_get_domain_space(PwAff);
2403eadf76d3SSiddharth Bhat     AlignSpace = isl_space_align_params(AlignSpace, PwAffSpace);
2404eadf76d3SSiddharth Bhat   }
2405eadf76d3SSiddharth Bhat   std::vector<isl_pw_aff *> AdjustedPwAffs;
2406eadf76d3SSiddharth Bhat 
2407eadf76d3SSiddharth Bhat   for (unsigned i = 0; i < PwAffs.size(); i++) {
2408eadf76d3SSiddharth Bhat     isl_pw_aff *Adjusted = PwAffs[i];
2409eadf76d3SSiddharth Bhat     assert(Adjusted && "Invalid pw_aff given.");
2410eadf76d3SSiddharth Bhat     Adjusted = isl_pw_aff_align_params(Adjusted, isl_space_copy(AlignSpace));
2411eadf76d3SSiddharth Bhat     AdjustedPwAffs.push_back(Adjusted);
2412eadf76d3SSiddharth Bhat   }
2413eadf76d3SSiddharth Bhat   return std::make_pair(AlignSpace, AdjustedPwAffs);
2414eadf76d3SSiddharth Bhat }
241532837fe3STobias Grosser 
24169dfe4e7cSTobias Grosser namespace {
24179dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
24189dfe4e7cSTobias Grosser public:
24199dfe4e7cSTobias Grosser   static char ID;
24209dfe4e7cSTobias Grosser 
242117f01968SSiddharth Bhat   GPURuntime Runtime = GPURuntime::CUDA;
242217f01968SSiddharth Bhat 
242317f01968SSiddharth Bhat   GPUArch Architecture = GPUArch::NVPTX64;
242417f01968SSiddharth Bhat 
2425e938517eSTobias Grosser   /// The scop that is currently processed.
2426e938517eSTobias Grosser   Scop *S;
2427e938517eSTobias Grosser 
242838fc0aedSTobias Grosser   LoopInfo *LI;
242938fc0aedSTobias Grosser   DominatorTree *DT;
243038fc0aedSTobias Grosser   ScalarEvolution *SE;
243138fc0aedSTobias Grosser   const DataLayout *DL;
243238fc0aedSTobias Grosser   RegionInfo *RI;
243338fc0aedSTobias Grosser 
24349dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
24359dfe4e7cSTobias Grosser 
2436e938517eSTobias Grosser   /// Construct compilation options for PPCG.
2437e938517eSTobias Grosser   ///
2438e938517eSTobias Grosser   /// @returns The compilation options.
2439e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
2440e938517eSTobias Grosser     auto DebugOptions =
2441e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
2442e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
2443e938517eSTobias Grosser 
2444e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
2445e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
2446e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
2447e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
24488950ceadSTobias Grosser     DebugOptions->verbose = false;
2449e938517eSTobias Grosser 
2450e938517eSTobias Grosser     Options->debug = DebugOptions;
2451e938517eSTobias Grosser 
24529e3db2b7SSiddharth Bhat     Options->group_chains = false;
2453e938517eSTobias Grosser     Options->reschedule = true;
2454e938517eSTobias Grosser     Options->scale_tile_loops = false;
2455e938517eSTobias Grosser     Options->wrap = false;
2456e938517eSTobias Grosser 
2457e938517eSTobias Grosser     Options->non_negative_parameters = false;
2458e938517eSTobias Grosser     Options->ctx = nullptr;
2459e938517eSTobias Grosser     Options->sizes = nullptr;
2460e938517eSTobias Grosser 
24619e3db2b7SSiddharth Bhat     Options->tile = true;
24624eaedde5STobias Grosser     Options->tile_size = 32;
24634eaedde5STobias Grosser 
24649e3db2b7SSiddharth Bhat     Options->isolate_full_tiles = false;
24659e3db2b7SSiddharth Bhat 
2466130ca30fSTobias Grosser     Options->use_private_memory = PrivateMemory;
2467b513b491STobias Grosser     Options->use_shared_memory = SharedMemory;
2468b513b491STobias Grosser     Options->max_shared_memory = 48 * 1024;
2469e938517eSTobias Grosser 
2470e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
2471e938517eSTobias Grosser     Options->openmp = false;
2472e938517eSTobias Grosser     Options->linearize_device_arrays = true;
24739e3db2b7SSiddharth Bhat     Options->allow_gnu_extensions = false;
2474e938517eSTobias Grosser 
24759e3db2b7SSiddharth Bhat     Options->unroll_copy_shared = false;
24769e3db2b7SSiddharth Bhat     Options->unroll_gpu_tile = false;
24779e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
24789e3db2b7SSiddharth Bhat 
24799e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
24809e3db2b7SSiddharth Bhat     Options->hybrid = false;
2481e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
2482e938517eSTobias Grosser     Options->opencl_use_gpu = false;
2483e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
2484e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
2485e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
2486e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
2487e938517eSTobias Grosser 
2488e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
2489e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
2490e938517eSTobias Grosser 
2491e938517eSTobias Grosser     return Options;
2492e938517eSTobias Grosser   }
2493e938517eSTobias Grosser 
2494f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
2495f384594dSTobias Grosser   ///
2496f384594dSTobias Grosser   /// Instead of a normal access of the form:
2497f384594dSTobias Grosser   ///
2498f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
2499f384594dSTobias Grosser   ///
2500f384594dSTobias Grosser   /// a tagged access has the form
2501f384594dSTobias Grosser   ///
2502f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
2503f384594dSTobias Grosser   ///
2504f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
2505f384594dSTobias Grosser   /// triggered the access.
2506f384594dSTobias Grosser   ///
2507f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
2508f384594dSTobias Grosser   ///
2509f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
2510f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
2511f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
2512f384594dSTobias Grosser 
2513f384594dSTobias Grosser     for (auto &Stmt : *S)
2514f384594dSTobias Grosser       for (auto &Acc : Stmt)
2515f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
25161515f6b9STobias Grosser           isl_map *Relation = Acc->getAccessRelation().release();
2517f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
2518f384594dSTobias Grosser 
2519f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
2520f384594dSTobias Grosser           Space = isl_space_range(Space);
2521f384594dSTobias Grosser           Space = isl_space_from_range(Space);
2522fe46c3ffSTobias Grosser           Space =
2523fe46c3ffSTobias Grosser               isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
2524f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
2525f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
2526f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
2527f384594dSTobias Grosser         }
2528f384594dSTobias Grosser 
2529f384594dSTobias Grosser     return Accesses;
2530f384594dSTobias Grosser   }
2531f384594dSTobias Grosser 
2532f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
2533f384594dSTobias Grosser   ///
2534f384594dSTobias Grosser   /// @see getTaggedAccesses
2535f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
2536f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
2537f384594dSTobias Grosser   }
2538f384594dSTobias Grosser 
2539f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
2540f384594dSTobias Grosser   ///
2541f384594dSTobias Grosser   /// @see getTaggedAccesses
2542f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
2543f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
2544f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
2545f384594dSTobias Grosser   }
2546f384594dSTobias Grosser 
2547f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
2548f384594dSTobias Grosser   ///
2549f384594dSTobias Grosser   /// @see getTaggedAccesses
2550f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
2551f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
2552f384594dSTobias Grosser   }
2553f384594dSTobias Grosser 
2554aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
2555aef5196fSTobias Grosser   ///
2556aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
2557aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
2558aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
2559aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
2560aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
2561aef5196fSTobias Grosser   /// the data format that ppcg expects.
2562aef5196fSTobias Grosser   ///
2563aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
2564aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
2565aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
2566bd81a7eeSTobias Grosser         S->getIslCtx(),
2567bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
2568aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
2569aef5196fSTobias Grosser 
257025271b91STobias Grosser     for (const SCEV *P : S->parameters()) {
257125271b91STobias Grosser       isl_id *Id = S->getIdForParam(P);
2572aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2573aef5196fSTobias Grosser     }
2574aef5196fSTobias Grosser 
2575aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
257677eef90fSTobias Grosser       auto Id = Array->getBasePtrId().release();
2577aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2578aef5196fSTobias Grosser     }
2579aef5196fSTobias Grosser 
2580aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
2581aef5196fSTobias Grosser 
2582aef5196fSTobias Grosser     return Names;
2583aef5196fSTobias Grosser   }
2584aef5196fSTobias Grosser 
2585e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
2586e938517eSTobias Grosser   ///
2587f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
2588f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
2589f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
2590f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
2591e938517eSTobias Grosser   ///
2592e938517eSTobias Grosser   /// @returns A new ppcg scop.
2593e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
25949e3db2b7SSiddharth Bhat     MustKillsInfo KillsInfo = computeMustKillsInfo(*S);
25959e3db2b7SSiddharth Bhat 
2596e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
2597e938517eSTobias Grosser 
2598e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
2599a82f2d26SSiddharth Bhat     // enable live range reordering
2600a82f2d26SSiddharth Bhat     PPCGScop->options->live_range_reordering = 1;
2601e938517eSTobias Grosser 
2602e938517eSTobias Grosser     PPCGScop->start = 0;
2603e938517eSTobias Grosser     PPCGScop->end = 0;
2604e938517eSTobias Grosser 
2605f384594dSTobias Grosser     PPCGScop->context = S->getContext();
2606f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
26079e3db2b7SSiddharth Bhat     // TODO: investigate this further. PPCG calls collect_call_domains.
26089e3db2b7SSiddharth Bhat     PPCGScop->call = isl_union_set_from_set(S->getContext());
2609f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
2610f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
2611e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
2612f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
2613f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
2614f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
2615f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
2616e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
26179e3db2b7SSiddharth Bhat     PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.take();
26189e3db2b7SSiddharth Bhat     PPCGScop->must_kills = KillsInfo.MustKills.take();
26199e3db2b7SSiddharth Bhat 
2620e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
2621a82f2d26SSiddharth Bhat     PPCGScop->independence =
2622a82f2d26SSiddharth Bhat         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
2623e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
2624e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
2625e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
2626e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
2627e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
2628e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
2629e938517eSTobias Grosser 
2630f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
2631a82f2d26SSiddharth Bhat     // If we have something non-trivial to kill, add it to the schedule
2632a82f2d26SSiddharth Bhat     if (KillsInfo.KillsSchedule.get())
2633a82f2d26SSiddharth Bhat       PPCGScop->schedule = isl_schedule_sequence(
2634a82f2d26SSiddharth Bhat           PPCGScop->schedule, KillsInfo.KillsSchedule.take());
2635a82f2d26SSiddharth Bhat 
2636a82f2d26SSiddharth Bhat     PPCGScop->names = getNames();
2637e938517eSTobias Grosser     PPCGScop->pet = nullptr;
2638e938517eSTobias Grosser 
2639f384594dSTobias Grosser     compute_tagger(PPCGScop);
2640f384594dSTobias Grosser     compute_dependences(PPCGScop);
26419e3db2b7SSiddharth Bhat     eliminate_dead_code(PPCGScop);
2642f384594dSTobias Grosser 
2643e938517eSTobias Grosser     return PPCGScop;
2644e938517eSTobias Grosser   }
2645e938517eSTobias Grosser 
2646a6d48f59SMichael Kruse   /// Collect the array accesses in a statement.
264760f63b49STobias Grosser   ///
264860f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
264960f63b49STobias Grosser   ///
265060f63b49STobias Grosser   /// @returns A list of array accesses.
265160f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
265260f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
265360f63b49STobias Grosser 
265460f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
265560f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
265660f63b49STobias Grosser       Access->read = Acc->isRead();
265760f63b49STobias Grosser       Access->write = Acc->isWrite();
26581515f6b9STobias Grosser       Access->access = Acc->getAccessRelation().release();
265960f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
266060f63b49STobias Grosser       Space = isl_space_range(Space);
266160f63b49STobias Grosser       Space = isl_space_from_range(Space);
2662fe46c3ffSTobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
266360f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
266460f63b49STobias Grosser       Access->tagged_access =
26651515f6b9STobias Grosser           isl_map_domain_product(Acc->getAccessRelation().release(), Universe);
2666b513b491STobias Grosser       Access->exact_write = !Acc->isMayWrite();
2667fe46c3ffSTobias Grosser       Access->ref_id = Acc->getId().release();
266860f63b49STobias Grosser       Access->next = Accesses;
2669b513b491STobias Grosser       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
267060f63b49STobias Grosser       Accesses = Access;
267160f63b49STobias Grosser     }
267260f63b49STobias Grosser 
267360f63b49STobias Grosser     return Accesses;
267460f63b49STobias Grosser   }
267560f63b49STobias Grosser 
267669b46751STobias Grosser   /// Collect the list of GPU statements.
267769b46751STobias Grosser   ///
267869b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
267969b46751STobias Grosser   /// as well as a list with all memory accesses.
268069b46751STobias Grosser   ///
268169b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
268269b46751STobias Grosser   ///
268369b46751STobias Grosser   /// @returns A linked-list of statements.
268469b46751STobias Grosser   gpu_stmt *getStatements() {
268569b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
268669b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
268769b46751STobias Grosser 
268869b46751STobias Grosser     int i = 0;
268969b46751STobias Grosser     for (auto &Stmt : *S) {
269069b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
269169b46751STobias Grosser 
269269b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
269369b46751STobias Grosser 
269469b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
269569b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
269660f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
269769b46751STobias Grosser       i++;
269869b46751STobias Grosser     }
269969b46751STobias Grosser 
270069b46751STobias Grosser     return Stmts;
270169b46751STobias Grosser   }
270269b46751STobias Grosser 
270360f63b49STobias Grosser   /// Derive the extent of an array.
270460f63b49STobias Grosser   ///
2705d58acf86STobias Grosser   /// The extent of an array is the set of elements that are within the
2706d58acf86STobias Grosser   /// accessed array. For the inner dimensions, the extent constraints are
2707d58acf86STobias Grosser   /// 0 and the size of the corresponding array dimension. For the first
2708d58acf86STobias Grosser   /// (outermost) dimension, the extent constraints are the minimal and maximal
2709d58acf86STobias Grosser   /// subscript value for the first dimension.
271060f63b49STobias Grosser   ///
271160f63b49STobias Grosser   /// @param Array The array to derive the extent for.
271260f63b49STobias Grosser   ///
271360f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
271460f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
2715d58acf86STobias Grosser     unsigned NumDims = Array->getNumberOfDimensions();
271660f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
271760f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
2718d58acf86STobias Grosser     Accesses = isl_union_map_detect_equalities(Accesses);
271960f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
2720d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2721d58acf86STobias Grosser     AccessUSet = isl_union_set_detect_equalities(AccessUSet);
2722d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2723d58acf86STobias Grosser 
2724d58acf86STobias Grosser     if (isl_union_set_is_empty(AccessUSet)) {
2725d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
272677eef90fSTobias Grosser       return isl_set_empty(Array->getSpace().release());
2727d58acf86STobias Grosser     }
2728d58acf86STobias Grosser 
2729d58acf86STobias Grosser     if (Array->getNumberOfDimensions() == 0) {
2730d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
273177eef90fSTobias Grosser       return isl_set_universe(Array->getSpace().release());
2732d58acf86STobias Grosser     }
2733d58acf86STobias Grosser 
273460f63b49STobias Grosser     isl_set *AccessSet =
273577eef90fSTobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace().release());
273660f63b49STobias Grosser 
2737d58acf86STobias Grosser     isl_union_set_free(AccessUSet);
273877eef90fSTobias Grosser     isl_local_space *LS =
273977eef90fSTobias Grosser         isl_local_space_from_space(Array->getSpace().release());
2740d58acf86STobias Grosser 
2741d58acf86STobias Grosser     isl_pw_aff *Val =
2742d58acf86STobias Grosser         isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0));
2743d58acf86STobias Grosser 
2744d58acf86STobias Grosser     isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0);
2745d58acf86STobias Grosser     isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0);
2746d58acf86STobias Grosser     OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in,
2747d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
2748d58acf86STobias Grosser     OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in,
2749d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
275077eef90fSTobias Grosser     OuterMin = isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in,
275177eef90fSTobias Grosser                                        Array->getBasePtrId().release());
275277eef90fSTobias Grosser     OuterMax = isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in,
275377eef90fSTobias Grosser                                        Array->getBasePtrId().release());
2754d58acf86STobias Grosser 
275577eef90fSTobias Grosser     isl_set *Extent = isl_set_universe(Array->getSpace().release());
2756d58acf86STobias Grosser 
2757d58acf86STobias Grosser     Extent = isl_set_intersect(
2758d58acf86STobias Grosser         Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val)));
2759d58acf86STobias Grosser     Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val));
2760d58acf86STobias Grosser 
2761d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i)
2762d58acf86STobias Grosser       Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0);
2763d58acf86STobias Grosser 
2764b7f68b8cSSiddharth Bhat     for (unsigned i = 0; i < NumDims; ++i) {
2765d58acf86STobias Grosser       isl_pw_aff *PwAff =
276677eef90fSTobias Grosser           const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i).release());
2767b7f68b8cSSiddharth Bhat 
2768b7f68b8cSSiddharth Bhat       // isl_pw_aff can be NULL for zero dimension. Only in the case of a
2769b7f68b8cSSiddharth Bhat       // Fortran array will we have a legitimate dimension.
2770b7f68b8cSSiddharth Bhat       if (!PwAff) {
2771b7f68b8cSSiddharth Bhat         assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension");
2772b7f68b8cSSiddharth Bhat         continue;
2773b7f68b8cSSiddharth Bhat       }
2774b7f68b8cSSiddharth Bhat 
2775d58acf86STobias Grosser       isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain(
277677eef90fSTobias Grosser           isl_local_space_from_space(Array->getSpace().release()), isl_dim_set,
277777eef90fSTobias Grosser           i));
2778d58acf86STobias Grosser       PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in,
2779d58acf86STobias Grosser                                   isl_pw_aff_dim(Val, isl_dim_in));
2780d58acf86STobias Grosser       PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in,
2781d58acf86STobias Grosser                                       isl_pw_aff_get_tuple_id(Val, isl_dim_in));
2782d58acf86STobias Grosser       auto *Set = isl_pw_aff_gt_set(PwAff, Val);
2783d58acf86STobias Grosser       Extent = isl_set_intersect(Set, Extent);
2784d58acf86STobias Grosser     }
2785d58acf86STobias Grosser 
2786d58acf86STobias Grosser     return Extent;
278760f63b49STobias Grosser   }
278860f63b49STobias Grosser 
278960f63b49STobias Grosser   /// Derive the bounds of an array.
279060f63b49STobias Grosser   ///
279160f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
279260f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
279360f63b49STobias Grosser   /// ScopArrayInfo.
279460f63b49STobias Grosser   ///
279560f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
279660f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
279760f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
2798eadf76d3SSiddharth Bhat     std::vector<isl_pw_aff *> Bounds;
27999e3db2b7SSiddharth Bhat 
280060f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
280102293ed7STobias Grosser       if (isl_set_is_empty(PPCGArray.extent)) {
280202293ed7STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
280302293ed7STobias Grosser         isl_local_space *LS = isl_local_space_from_space(
280402293ed7STobias Grosser             isl_space_params(isl_set_get_space(Dom)));
280502293ed7STobias Grosser         isl_set_free(Dom);
28069e3db2b7SSiddharth Bhat         isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS));
2807eadf76d3SSiddharth Bhat         Bounds.push_back(Zero);
280802293ed7STobias Grosser       } else {
280960f63b49STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
281060f63b49STobias Grosser         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
281160f63b49STobias Grosser         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
281260f63b49STobias Grosser         isl_set_free(Dom);
281360f63b49STobias Grosser         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
281402293ed7STobias Grosser         isl_local_space *LS =
281502293ed7STobias Grosser             isl_local_space_from_space(isl_set_get_space(Dom));
281660f63b49STobias Grosser         isl_aff *One = isl_aff_zero_on_domain(LS);
281760f63b49STobias Grosser         One = isl_aff_add_constant_si(One, 1);
281860f63b49STobias Grosser         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
281960f63b49STobias Grosser         Bound = isl_pw_aff_gist(Bound, S->getContext());
2820eadf76d3SSiddharth Bhat         Bounds.push_back(Bound);
282160f63b49STobias Grosser       }
282202293ed7STobias Grosser     }
282360f63b49STobias Grosser 
282460f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
282577eef90fSTobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i).release();
282660f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
282760f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
282860f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
2829eadf76d3SSiddharth Bhat       Bounds.push_back(Bound);
283060f63b49STobias Grosser     }
28319e3db2b7SSiddharth Bhat 
2832eadf76d3SSiddharth Bhat     /// To construct a `isl_multi_pw_aff`, we need all the indivisual `pw_aff`
2833eadf76d3SSiddharth Bhat     /// to have the same parameter dimensions. So, we need to align them to an
2834eadf76d3SSiddharth Bhat     /// appropriate space.
2835eadf76d3SSiddharth Bhat     /// Scop::Context is _not_ an appropriate space, because when we have
2836eadf76d3SSiddharth Bhat     /// `-polly-ignore-parameter-bounds` enabled, the Scop::Context does not
2837eadf76d3SSiddharth Bhat     /// contain all parameter dimensions.
2838eadf76d3SSiddharth Bhat     /// So, use the helper `alignPwAffs` to align all the `isl_pw_aff` together.
2839eadf76d3SSiddharth Bhat     isl_space *SeedAlignSpace = S->getParamSpace();
2840eadf76d3SSiddharth Bhat     SeedAlignSpace = isl_space_add_dims(SeedAlignSpace, isl_dim_set, 1);
2841eadf76d3SSiddharth Bhat 
2842eadf76d3SSiddharth Bhat     isl_space *AlignSpace = nullptr;
2843eadf76d3SSiddharth Bhat     std::vector<isl_pw_aff *> AlignedBounds;
2844eadf76d3SSiddharth Bhat     std::tie(AlignSpace, AlignedBounds) =
2845eadf76d3SSiddharth Bhat         alignPwAffs(std::move(Bounds), SeedAlignSpace);
2846eadf76d3SSiddharth Bhat 
2847eadf76d3SSiddharth Bhat     assert(AlignSpace && "alignPwAffs did not initialise AlignSpace");
2848eadf76d3SSiddharth Bhat 
2849eadf76d3SSiddharth Bhat     isl_pw_aff_list *BoundsList =
2850eadf76d3SSiddharth Bhat         createPwAffList(S->getIslCtx(), std::move(AlignedBounds));
2851eadf76d3SSiddharth Bhat 
28529e3db2b7SSiddharth Bhat     isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent);
2853eadf76d3SSiddharth Bhat     BoundsSpace = isl_space_align_params(BoundsSpace, AlignSpace);
28549e3db2b7SSiddharth Bhat 
28559e3db2b7SSiddharth Bhat     assert(BoundsSpace && "Unable to access space of array.");
28569e3db2b7SSiddharth Bhat     assert(BoundsList && "Unable to access list of bounds.");
28579e3db2b7SSiddharth Bhat 
28589e3db2b7SSiddharth Bhat     PPCGArray.bound =
28599e3db2b7SSiddharth Bhat         isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList);
28609e3db2b7SSiddharth Bhat     assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly.");
286160f63b49STobias Grosser   }
286260f63b49STobias Grosser 
286360f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
286460f63b49STobias Grosser   ///
286560f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
286643f178bbSSiddharth Bhat   void createArrays(gpu_prog *PPCGProg,
286743f178bbSSiddharth Bhat                     const SmallVector<ScopArrayInfo *, 4> &ValidSAIs) {
286860f63b49STobias Grosser     int i = 0;
286943f178bbSSiddharth Bhat     for (auto &Array : ValidSAIs) {
287060f63b49STobias Grosser       std::string TypeName;
287160f63b49STobias Grosser       raw_string_ostream OS(TypeName);
287260f63b49STobias Grosser 
287360f63b49STobias Grosser       OS << *Array->getElementType();
287460f63b49STobias Grosser       TypeName = OS.str();
287560f63b49STobias Grosser 
287660f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
287760f63b49STobias Grosser 
287877eef90fSTobias Grosser       PPCGArray.space = Array->getSpace().release();
287960f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
288060f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
288160f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
288260f63b49STobias Grosser       PPCGArray.extent = nullptr;
288360f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
288460f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
288560f63b49STobias Grosser       PPCGArray.n_ref = 0;
288660f63b49STobias Grosser       PPCGArray.refs = nullptr;
288760f63b49STobias Grosser       PPCGArray.accessed = true;
2888fe74a7a1STobias Grosser       PPCGArray.read_only_scalar =
2889fe74a7a1STobias Grosser           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
289060f63b49STobias Grosser       PPCGArray.has_compound_element = false;
289160f63b49STobias Grosser       PPCGArray.local = false;
289260f63b49STobias Grosser       PPCGArray.declare_local = false;
289360f63b49STobias Grosser       PPCGArray.global = false;
289460f63b49STobias Grosser       PPCGArray.linearize = false;
289560f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
289613c78e4dSTobias Grosser       PPCGArray.user = Array;
289760f63b49STobias Grosser 
28989e3db2b7SSiddharth Bhat       PPCGArray.bound = nullptr;
289960f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
29002d010dafSTobias Grosser       i++;
2901b9fc860aSTobias Grosser 
2902b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
290360f63b49STobias Grosser     }
290460f63b49STobias Grosser   }
290560f63b49STobias Grosser 
290660f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
290760f63b49STobias Grosser   ///
290860f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
290960f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
291060f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
291160f63b49STobias Grosser 
2912d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
291377eef90fSTobias Grosser       isl_space *Space = Array->getSpace().release();
291460f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
291560f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
291660f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
291760f63b49STobias Grosser     }
291860f63b49STobias Grosser 
291960f63b49STobias Grosser     return Maps;
292060f63b49STobias Grosser   }
292160f63b49STobias Grosser 
2922e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
2923e938517eSTobias Grosser   ///
2924a6d48f59SMichael Kruse   /// @returns A new gpu program description.
2925e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
2926e938517eSTobias Grosser 
2927e938517eSTobias Grosser     if (!PPCGScop)
2928e938517eSTobias Grosser       return nullptr;
2929e938517eSTobias Grosser 
2930e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
2931e938517eSTobias Grosser 
2932e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
2933e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
2934aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
293560f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
293660f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
293760f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
293860f63b49STobias Grosser     PPCGProg->tagged_must_kill =
293960f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
294060f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
294160f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
29429e3db2b7SSiddharth Bhat     // TODO: verify that this assignment is correct.
2943e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
2944a82f2d26SSiddharth Bhat 
2945a82f2d26SSiddharth Bhat     // this needs to be set when live range reordering is enabled.
2946a82f2d26SSiddharth Bhat     // NOTE: I believe that is conservatively correct. I'm not sure
2947a82f2d26SSiddharth Bhat     //       what the semantics of this is.
2948a82f2d26SSiddharth Bhat     // Quoting PPCG/gpu.h: "Order dependences on non-scalars."
2949a82f2d26SSiddharth Bhat     PPCGProg->array_order =
2950a82f2d26SSiddharth Bhat         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
295169b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
295269b46751STobias Grosser     PPCGProg->stmts = getStatements();
295343f178bbSSiddharth Bhat 
295443f178bbSSiddharth Bhat     // Only consider arrays that have a non-empty extent.
295543f178bbSSiddharth Bhat     // Otherwise, this will cause us to consider the following kinds of
295643f178bbSSiddharth Bhat     // empty arrays:
295743f178bbSSiddharth Bhat     //     1. Invariant loads that are represented by SAI objects.
295843f178bbSSiddharth Bhat     //     2. Arrays with statically known zero size.
295943f178bbSSiddharth Bhat     auto ValidSAIsRange =
296043f178bbSSiddharth Bhat         make_filter_range(S->arrays(), [this](ScopArrayInfo *SAI) -> bool {
296143f178bbSSiddharth Bhat           return !isl::manage(getExtent(SAI)).is_empty();
296243f178bbSSiddharth Bhat         });
296343f178bbSSiddharth Bhat     SmallVector<ScopArrayInfo *, 4> ValidSAIs(ValidSAIsRange.begin(),
296443f178bbSSiddharth Bhat                                               ValidSAIsRange.end());
296543f178bbSSiddharth Bhat 
296643f178bbSSiddharth Bhat     PPCGProg->n_array =
296743f178bbSSiddharth Bhat         ValidSAIs.size(); // std::distance(S->array_begin(), S->array_end());
296860f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
296960f63b49STobias Grosser                                        PPCGProg->n_array);
297060f63b49STobias Grosser 
297143f178bbSSiddharth Bhat     createArrays(PPCGProg, ValidSAIs);
2972e938517eSTobias Grosser 
2973d58acf86STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
2974e938517eSTobias Grosser     return PPCGProg;
2975e938517eSTobias Grosser   }
2976e938517eSTobias Grosser 
297769b46751STobias Grosser   struct PrintGPUUserData {
297869b46751STobias Grosser     struct cuda_info *CudaInfo;
297969b46751STobias Grosser     struct gpu_prog *PPCGProg;
298069b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
298169b46751STobias Grosser   };
298269b46751STobias Grosser 
298369b46751STobias Grosser   /// Print a user statement node in the host code.
298469b46751STobias Grosser   ///
298569b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
298669b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
298769b46751STobias Grosser   /// host ast.
298869b46751STobias Grosser   ///
298969b46751STobias Grosser   /// @param P The printer to print to
299069b46751STobias Grosser   /// @param Options The printing options to use
299169b46751STobias Grosser   /// @param Node The node to print
299269b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
299369b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
299469b46751STobias Grosser   ///
299569b46751STobias Grosser   /// @returns A printer to which the output has been printed.
299669b46751STobias Grosser   static __isl_give isl_printer *
299769b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
299869b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
299969b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
300069b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
300169b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
300269b46751STobias Grosser 
300369b46751STobias Grosser     if (Id) {
300420251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
300520251734STobias Grosser 
300620251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
300720251734STobias Grosser       // otherwise try to call pet functionality that is not available in
300820251734STobias Grosser       // Polly.
300920251734STobias Grosser       if (IsUser) {
301020251734STobias Grosser         P = isl_printer_start_line(P);
301120251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
301220251734STobias Grosser         P = isl_printer_end_line(P);
301320251734STobias Grosser         isl_id_free(Id);
301420251734STobias Grosser         isl_ast_print_options_free(Options);
301520251734STobias Grosser         return P;
301620251734STobias Grosser       }
301720251734STobias Grosser 
301869b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
301969b46751STobias Grosser       isl_id_free(Id);
302069b46751STobias Grosser       Data->Kernels.push_back(Kernel);
302169b46751STobias Grosser     }
302269b46751STobias Grosser 
302369b46751STobias Grosser     return print_host_user(P, Options, Node, User);
302469b46751STobias Grosser   }
302569b46751STobias Grosser 
302669b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
302769b46751STobias Grosser   ///
302869b46751STobias Grosser   /// @param Kernel The kernel to print
302969b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
303069b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
303169b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
303269b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
303369b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
303469b46751STobias Grosser     char *String = isl_printer_get_str(P);
303569b46751STobias Grosser     printf("%s\n", String);
303669b46751STobias Grosser     free(String);
303769b46751STobias Grosser     isl_printer_free(P);
303869b46751STobias Grosser   }
303969b46751STobias Grosser 
304069b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
304169b46751STobias Grosser   ///
304269b46751STobias Grosser   /// @param Tree An AST describing GPU code
304369b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
304469b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
304569b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
304669b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
304769b46751STobias Grosser 
304869b46751STobias Grosser     PrintGPUUserData Data;
304969b46751STobias Grosser     Data.PPCGProg = PPCGProg;
305069b46751STobias Grosser 
305169b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
305269b46751STobias Grosser     Options =
305369b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
305469b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
305569b46751STobias Grosser     char *String = isl_printer_get_str(P);
305669b46751STobias Grosser     printf("# host\n");
305769b46751STobias Grosser     printf("%s\n", String);
305869b46751STobias Grosser     free(String);
305969b46751STobias Grosser     isl_printer_free(P);
306069b46751STobias Grosser 
306169b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
306269b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
306369b46751STobias Grosser       printKernel(Kernel);
306469b46751STobias Grosser     }
306569b46751STobias Grosser   }
306669b46751STobias Grosser 
3067f384594dSTobias Grosser   // Generate a GPU program using PPCG.
3068f384594dSTobias Grosser   //
3069f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
3070f384594dSTobias Grosser   //
3071f384594dSTobias Grosser   //  1) Compute new schedule for the program.
3072f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
3073f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
3074f384594dSTobias Grosser   //
3075f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
3076f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
3077f384594dSTobias Grosser   // strategy directly from this pass.
3078f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
3079f384594dSTobias Grosser 
3080f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
3081f384594dSTobias Grosser 
3082f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
3083f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
3084f384594dSTobias Grosser     PPCGGen->print = nullptr;
3085f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
308660c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
3087f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
3088f384594dSTobias Grosser     PPCGGen->tree = nullptr;
3089f384594dSTobias Grosser     PPCGGen->types.n = 0;
3090f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
3091f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
3092f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
3093f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
3094f384594dSTobias Grosser 
3095f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
3096f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
3097f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
30982341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
3099f384594dSTobias Grosser 
3100f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
3101f384594dSTobias Grosser 
3102aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
3103aef5196fSTobias Grosser 
3104b5563c68STobias Grosser     Schedule =
3105b5563c68STobias Grosser         isl_schedule_align_params(Schedule, S->getFullParamSpace().release());
3106b5563c68STobias Grosser 
310769b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
3108aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
3109*638316daSSiddharth Bhat       DEBUG(dbgs() << getUniqueScopName(S)
3110*638316daSSiddharth Bhat                    << " does not have permutable bands. Bailing out\n";);
311169b46751STobias Grosser     } else {
3112aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
311369b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
311469b46751STobias Grosser     }
3115aef5196fSTobias Grosser 
3116f384594dSTobias Grosser     if (DumpSchedule) {
3117f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
3118f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
3119f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
3120f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
3121f384594dSTobias Grosser       if (Schedule)
3122f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
3123f384594dSTobias Grosser       else
3124f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
3125f384594dSTobias Grosser 
3126f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
3127f384594dSTobias Grosser       isl_printer_free(P);
3128f384594dSTobias Grosser     }
3129f384594dSTobias Grosser 
313069b46751STobias Grosser     if (DumpCode) {
313169b46751STobias Grosser       printf("Code\n");
313269b46751STobias Grosser       printf("====\n");
313369b46751STobias Grosser       if (PPCGGen->tree)
313469b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
313569b46751STobias Grosser       else
313669b46751STobias Grosser         printf("No code generated\n");
313769b46751STobias Grosser     }
313869b46751STobias Grosser 
3139f384594dSTobias Grosser     isl_schedule_free(Schedule);
3140f384594dSTobias Grosser 
3141f384594dSTobias Grosser     return PPCGGen;
3142f384594dSTobias Grosser   }
3143f384594dSTobias Grosser 
3144f384594dSTobias Grosser   /// Free gpu_gen structure.
3145f384594dSTobias Grosser   ///
3146f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
3147f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
3148f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
3149f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
3150f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
3151f384594dSTobias Grosser     free(PPCGGen);
3152f384594dSTobias Grosser   }
3153f384594dSTobias Grosser 
3154b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
3155b307ed4dSTobias Grosser   ///
3156b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
3157b307ed4dSTobias Grosser   /// ourselves.
3158b307ed4dSTobias Grosser   ///
3159b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
3160b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
3161b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
3162b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
3163b307ed4dSTobias Grosser     free(PPCGScop->options);
3164b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
3165b307ed4dSTobias Grosser   }
3166b307ed4dSTobias Grosser 
316782f2af35STobias Grosser   /// Approximate the number of points in the set.
316882f2af35STobias Grosser   ///
316982f2af35STobias Grosser   /// This function returns an ast expression that overapproximates the number
317082f2af35STobias Grosser   /// of points in an isl set through the rectangular hull surrounding this set.
317182f2af35STobias Grosser   ///
317282f2af35STobias Grosser   /// @param Set   The set to count.
317382f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
317482f2af35STobias Grosser   ///              expression.
317582f2af35STobias Grosser   ///
317682f2af35STobias Grosser   /// @returns An approximation of the number of points in the set.
317782f2af35STobias Grosser   __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set,
317882f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
317982f2af35STobias Grosser 
318082f2af35STobias Grosser     isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1);
318182f2af35STobias Grosser     auto *Expr = isl_ast_expr_from_val(isl_val_copy(One));
318282f2af35STobias Grosser 
318382f2af35STobias Grosser     isl_space *Space = isl_set_get_space(Set);
318482f2af35STobias Grosser     Space = isl_space_params(Space);
318582f2af35STobias Grosser     auto *Univ = isl_set_universe(Space);
318682f2af35STobias Grosser     isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One);
318782f2af35STobias Grosser 
318882f2af35STobias Grosser     for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) {
318982f2af35STobias Grosser       isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i);
319082f2af35STobias Grosser       isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i);
319182f2af35STobias Grosser       isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min);
319282f2af35STobias Grosser       DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff));
319382f2af35STobias Grosser       auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize);
319482f2af35STobias Grosser       Expr = isl_ast_expr_mul(Expr, DimSizeExpr);
319582f2af35STobias Grosser     }
319682f2af35STobias Grosser 
319782f2af35STobias Grosser     isl_set_free(Set);
319882f2af35STobias Grosser     isl_pw_aff_free(OneAff);
319982f2af35STobias Grosser 
320082f2af35STobias Grosser     return Expr;
320182f2af35STobias Grosser   }
320282f2af35STobias Grosser 
320382f2af35STobias Grosser   /// Approximate a number of dynamic instructions executed by a given
320482f2af35STobias Grosser   /// statement.
320582f2af35STobias Grosser   ///
320682f2af35STobias Grosser   /// @param Stmt  The statement for which to compute the number of dynamic
320782f2af35STobias Grosser   ///              instructions.
320882f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
320982f2af35STobias Grosser   ///              expression.
321082f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
321182f2af35STobias Grosser   ///          by @p Stmt.
321282f2af35STobias Grosser   __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt,
321382f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
321482f2af35STobias Grosser     auto Iterations = approxPointsInSet(Stmt.getDomain(), Build);
321582f2af35STobias Grosser 
321682f2af35STobias Grosser     long InstCount = 0;
321782f2af35STobias Grosser 
321882f2af35STobias Grosser     if (Stmt.isBlockStmt()) {
321982f2af35STobias Grosser       auto *BB = Stmt.getBasicBlock();
322082f2af35STobias Grosser       InstCount = std::distance(BB->begin(), BB->end());
322182f2af35STobias Grosser     } else {
322282f2af35STobias Grosser       auto *R = Stmt.getRegion();
322382f2af35STobias Grosser 
322482f2af35STobias Grosser       for (auto *BB : R->blocks()) {
322582f2af35STobias Grosser         InstCount += std::distance(BB->begin(), BB->end());
322682f2af35STobias Grosser       }
322782f2af35STobias Grosser     }
322882f2af35STobias Grosser 
322982f2af35STobias Grosser     isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount);
323082f2af35STobias Grosser     auto *InstExpr = isl_ast_expr_from_val(InstVal);
323182f2af35STobias Grosser     return isl_ast_expr_mul(InstExpr, Iterations);
323282f2af35STobias Grosser   }
323382f2af35STobias Grosser 
323482f2af35STobias Grosser   /// Approximate dynamic instructions executed in scop.
323582f2af35STobias Grosser   ///
323682f2af35STobias Grosser   /// @param S     The scop for which to approximate dynamic instructions.
323782f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
323882f2af35STobias Grosser   ///              expression.
323982f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
324082f2af35STobias Grosser   ///          in @p S.
324182f2af35STobias Grosser   __isl_give isl_ast_expr *
324282f2af35STobias Grosser   getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) {
324382f2af35STobias Grosser     isl_ast_expr *Instructions;
324482f2af35STobias Grosser 
324582f2af35STobias Grosser     isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0);
324682f2af35STobias Grosser     Instructions = isl_ast_expr_from_val(Zero);
324782f2af35STobias Grosser 
324882f2af35STobias Grosser     for (ScopStmt &Stmt : S) {
324982f2af35STobias Grosser       isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build);
325082f2af35STobias Grosser       Instructions = isl_ast_expr_add(Instructions, StmtInstructions);
325182f2af35STobias Grosser     }
325282f2af35STobias Grosser     return Instructions;
325382f2af35STobias Grosser   }
325482f2af35STobias Grosser 
325582f2af35STobias Grosser   /// Create a check that ensures sufficient compute in scop.
325682f2af35STobias Grosser   ///
325782f2af35STobias Grosser   /// @param S     The scop for which to ensure sufficient compute.
325882f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
325982f2af35STobias Grosser   ///              expression.
326082f2af35STobias Grosser   /// @returns An expression that evaluates to TRUE in case of sufficient
326182f2af35STobias Grosser   ///          compute and to FALSE, otherwise.
326282f2af35STobias Grosser   __isl_give isl_ast_expr *
326382f2af35STobias Grosser   createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) {
326482f2af35STobias Grosser     auto Iterations = getNumberOfIterations(S, Build);
326582f2af35STobias Grosser     auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute);
326682f2af35STobias Grosser     auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal);
326782f2af35STobias Grosser     return isl_ast_expr_ge(Iterations, MinComputeExpr);
326882f2af35STobias Grosser   }
326982f2af35STobias Grosser 
3270f291c8d5SSiddharth Bhat   /// Check if the basic block contains a function we cannot codegen for GPU
3271f291c8d5SSiddharth Bhat   /// kernels.
3272f291c8d5SSiddharth Bhat   ///
3273f291c8d5SSiddharth Bhat   /// If this basic block does something with a `Function` other than calling
3274f291c8d5SSiddharth Bhat   /// a function that we support in a kernel, return true.
32758fc6cdfbSTobias Grosser   bool containsInvalidKernelFunctionInBlock(const BasicBlock *BB,
32768fc6cdfbSTobias Grosser                                             bool AllowCUDALibDevice) {
3277f291c8d5SSiddharth Bhat     for (const Instruction &Inst : *BB) {
3278f291c8d5SSiddharth Bhat       const CallInst *Call = dyn_cast<CallInst>(&Inst);
32798fc6cdfbSTobias Grosser       if (Call && isValidFunctionInKernel(Call->getCalledFunction(),
32808fc6cdfbSTobias Grosser                                           AllowCUDALibDevice)) {
3281f291c8d5SSiddharth Bhat         continue;
3282f291c8d5SSiddharth Bhat       }
3283f291c8d5SSiddharth Bhat 
3284bccaea57SSiddharth Bhat       for (Value *SrcVal : Inst.operands()) {
3285bccaea57SSiddharth Bhat         PointerType *p = dyn_cast<PointerType>(SrcVal->getType());
3286bccaea57SSiddharth Bhat         if (!p)
3287bccaea57SSiddharth Bhat           continue;
3288bccaea57SSiddharth Bhat         if (isa<FunctionType>(p->getElementType()))
3289bccaea57SSiddharth Bhat           return true;
3290bccaea57SSiddharth Bhat       }
3291f291c8d5SSiddharth Bhat     }
3292bccaea57SSiddharth Bhat     return false;
3293bccaea57SSiddharth Bhat   }
3294bccaea57SSiddharth Bhat 
3295f291c8d5SSiddharth Bhat   /// Return whether the Scop S uses functions in a way that we do not support.
32968fc6cdfbSTobias Grosser   bool containsInvalidKernelFunction(const Scop &S, bool AllowCUDALibDevice) {
3297bccaea57SSiddharth Bhat     for (auto &Stmt : S) {
3298bccaea57SSiddharth Bhat       if (Stmt.isBlockStmt()) {
32998fc6cdfbSTobias Grosser         if (containsInvalidKernelFunctionInBlock(Stmt.getBasicBlock(),
33008fc6cdfbSTobias Grosser                                                  AllowCUDALibDevice))
3301bccaea57SSiddharth Bhat           return true;
3302bccaea57SSiddharth Bhat       } else {
3303bccaea57SSiddharth Bhat         assert(Stmt.isRegionStmt() &&
3304bccaea57SSiddharth Bhat                "Stmt was neither block nor region statement");
3305bccaea57SSiddharth Bhat         for (const BasicBlock *BB : Stmt.getRegion()->blocks())
33068fc6cdfbSTobias Grosser           if (containsInvalidKernelFunctionInBlock(BB, AllowCUDALibDevice))
3307bccaea57SSiddharth Bhat             return true;
3308bccaea57SSiddharth Bhat       }
3309bccaea57SSiddharth Bhat     }
3310bccaea57SSiddharth Bhat     return false;
3311bccaea57SSiddharth Bhat   }
3312bccaea57SSiddharth Bhat 
331338fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
331438fc0aedSTobias Grosser   ///
331532837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
331632837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
331732837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
331838fc0aedSTobias Grosser     ScopAnnotator Annotator;
331938fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
332038fc0aedSTobias Grosser 
332138fc0aedSTobias Grosser     Region *R = &S->getRegion();
332238fc0aedSTobias Grosser 
332338fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
332438fc0aedSTobias Grosser 
332538fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
332638fc0aedSTobias Grosser 
332738fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
332838fc0aedSTobias Grosser 
332938fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
333038fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
333138fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
333238fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
333338fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
333438fc0aedSTobias Grosser     // code generating this scop.
333503346c27SSiddharth Bhat     BBPair StartExitBlocks;
333603346c27SSiddharth Bhat     BranchInst *CondBr = nullptr;
333703346c27SSiddharth Bhat     std::tie(StartExitBlocks, CondBr) =
33382d950f36SPhilip Pfaffe         executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI);
3339256070d8SAndreas Simbuerger     BasicBlock *StartBlock = std::get<0>(StartExitBlocks);
334038fc0aedSTobias Grosser 
334103346c27SSiddharth Bhat     assert(CondBr && "CondBr not initialized by executeScopConditionally");
334203346c27SSiddharth Bhat 
33432d950f36SPhilip Pfaffe     GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S,
334417f01968SSiddharth Bhat                                StartBlock, Prog, Runtime, Architecture);
3345acf80064SEli Friedman 
334638fc0aedSTobias Grosser     // TODO: Handle LICM
334738fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
334838fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
334938fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
3350cb1aef8dSTobias Grosser 
3351cb1aef8dSTobias Grosser     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx());
33522b852e2eSPhilip Pfaffe     isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build);
335382f2af35STobias Grosser     isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build);
335482f2af35STobias Grosser     Condition = isl_ast_expr_and(Condition, SufficientCompute);
3355cb1aef8dSTobias Grosser     isl_ast_build_free(Build);
3356cb1aef8dSTobias Grosser 
33579e3db2b7SSiddharth Bhat     // preload invariant loads. Note: This should happen before the RTC
33589e3db2b7SSiddharth Bhat     // because the RTC may depend on values that are invariant load hoisted.
33594ebeb356SSiddharth Bhat     if (!NodeBuilder.preloadInvariantLoads())
33604ebeb356SSiddharth Bhat       report_fatal_error("preloading invariant loads failed in function: " +
33614ebeb356SSiddharth Bhat                          S->getFunction().getName() +
33624ebeb356SSiddharth Bhat                          " | Scop Region: " + S->getNameStr());
33639e3db2b7SSiddharth Bhat 
3364cb1aef8dSTobias Grosser     Value *RTC = NodeBuilder.createRTC(Condition);
3365cb1aef8dSTobias Grosser     Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
3366cb1aef8dSTobias Grosser 
336738fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
3368fa7b0802STobias Grosser 
336938fc0aedSTobias Grosser     NodeBuilder.create(Root);
33705857b701STobias Grosser 
3371bc653f20STobias Grosser     /// In case a sequential kernel has more surrounding loops as any parallel
3372bc653f20STobias Grosser     /// kernel, the SCoP is probably mostly sequential. Hence, there is no
3373de244eb4STobias Grosser     /// point in running it on a GPU.
3374bc653f20STobias Grosser     if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel)
337503346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
3376bc653f20STobias Grosser 
33775857b701STobias Grosser     if (!NodeBuilder.BuildSuccessful)
337803346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
337938fc0aedSTobias Grosser   }
338038fc0aedSTobias Grosser 
3381e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
3382e938517eSTobias Grosser     S = &CurrentScop;
338338fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
338438fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
338538fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
33867b5a4dfdSTobias Grosser     DL = &S->getRegion().getEntry()->getModule()->getDataLayout();
338738fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
3388e938517eSTobias Grosser 
3389f291c8d5SSiddharth Bhat     // We currently do not support functions other than intrinsics inside
3390f291c8d5SSiddharth Bhat     // kernels, as code generation will need to offload function calls to the
3391f291c8d5SSiddharth Bhat     // kernel. This may lead to a kernel trying to call a function on the host.
3392bccaea57SSiddharth Bhat     // This also allows us to prevent codegen from trying to take the
3393bccaea57SSiddharth Bhat     // address of an intrinsic function to send to the kernel.
33948fc6cdfbSTobias Grosser     if (containsInvalidKernelFunction(CurrentScop,
33958fc6cdfbSTobias Grosser                                       Architecture == GPUArch::NVPTX64)) {
3396f291c8d5SSiddharth Bhat       DEBUG(
3397*638316daSSiddharth Bhat           dbgs() << getUniqueScopName(S)
3398*638316daSSiddharth Bhat                  << " contains function which cannot be materialised in a GPU "
3399f291c8d5SSiddharth Bhat                     "kernel. Bailing out.\n";);
3400bccaea57SSiddharth Bhat       return false;
3401f291c8d5SSiddharth Bhat     }
3402bccaea57SSiddharth Bhat 
3403e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
3404e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
3405f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
340638fc0aedSTobias Grosser 
340702ca346eSSingapuram Sanjay Srivallabh     if (PPCGGen->tree) {
340832837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
340902ca346eSSingapuram Sanjay Srivallabh       CurrentScop.markAsToBeSkipped();
3410*638316daSSiddharth Bhat     } else {
3411*638316daSSiddharth Bhat       DEBUG(dbgs() << getUniqueScopName(S)
3412*638316daSSiddharth Bhat                    << " has empty PPCGGen->tree. Bailing out.\n");
341302ca346eSSingapuram Sanjay Srivallabh     }
341438fc0aedSTobias Grosser 
3415b307ed4dSTobias Grosser     freeOptions(PPCGScop);
3416f384594dSTobias Grosser     freePPCGGen(PPCGGen);
3417e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
3418e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
3419e938517eSTobias Grosser 
3420e938517eSTobias Grosser     return true;
3421e938517eSTobias Grosser   }
34229dfe4e7cSTobias Grosser 
34239dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
34249dfe4e7cSTobias Grosser 
34259dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
34269dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
34279dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
34289dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
34295cc87e3aSPhilip Pfaffe     AU.addRequired<ScopDetectionWrapperPass>();
34309dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
34319dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
34329dfe4e7cSTobias Grosser 
34339dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
34349dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
34359dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
34369dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
34379dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
34385cc87e3aSPhilip Pfaffe     AU.addPreserved<ScopDetectionWrapperPass>();
34399dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
34409dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
34419dfe4e7cSTobias Grosser 
34429dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
34439dfe4e7cSTobias Grosser     //        region tree.
34449dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
34459dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
34469dfe4e7cSTobias Grosser   }
34479dfe4e7cSTobias Grosser };
344824222c73STobias Grosser } // namespace
34499dfe4e7cSTobias Grosser 
34509dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
34519dfe4e7cSTobias Grosser 
345217f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) {
345317f01968SSiddharth Bhat   PPCGCodeGeneration *generator = new PPCGCodeGeneration();
345417f01968SSiddharth Bhat   generator->Runtime = Runtime;
345517f01968SSiddharth Bhat   generator->Architecture = Arch;
345617f01968SSiddharth Bhat   return generator;
345717f01968SSiddharth Bhat }
34589dfe4e7cSTobias Grosser 
34599dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
34609dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
34619dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
34629dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
34639dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
34649dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
34659dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
34665cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
34679dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
34689dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
3469