19dfe4e7cSTobias Grosser //===------ PPCGCodeGeneration.cpp - Polly Accelerator Code Generation. ---===// 29dfe4e7cSTobias Grosser // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 69dfe4e7cSTobias Grosser // 79dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===// 89dfe4e7cSTobias Grosser // 99dfe4e7cSTobias Grosser // Take a scop created by ScopInfo and map it to GPU code using the ppcg 109dfe4e7cSTobias Grosser // GPU mapping strategy. 119dfe4e7cSTobias Grosser // 129dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===// 139dfe4e7cSTobias Grosser 1417f01968SSiddharth Bhat #include "polly/CodeGen/PPCGCodeGeneration.h" 1571dfb3ebSSiddharth Bhat #include "polly/CodeGen/CodeGeneration.h" 16cb1aef8dSTobias Grosser #include "polly/CodeGen/IslAst.h" 179dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h" 187b9f5ca2SSiddharth Bhat #include "polly/CodeGen/PerfMonitor.h" 1938fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h" 209dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h" 219dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h" 22f384594dSTobias Grosser #include "polly/Options.h" 23629109b6STobias Grosser #include "polly/ScopDetection.h" 249dfe4e7cSTobias Grosser #include "polly/ScopInfo.h" 2544596fe6SRiccardo Mori #include "polly/Support/ISLTools.h" 26edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h" 2774dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h" 2874dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h" 290133dc39SHeejin Ahn #include "llvm/IR/IntrinsicsNVPTX.h" 3074dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h" 31e1a98343STobias Grosser #include "llvm/IR/Verifier.h" 328fc6cdfbSTobias Grosser #include "llvm/IRReader/IRReader.h" 332c831971SMichael Kruse #include "llvm/InitializePasses.h" 348fc6cdfbSTobias Grosser #include "llvm/Linker/Linker.h" 3589b57061SReid Kleckner #include "llvm/MC/TargetRegistry.h" 36031bb165SMichael Kruse #include "llvm/Support/SourceMgr.h" 3774dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h" 389a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h" 39750160e2STobias Grosser #include "llvm/Transforms/Utils/BasicBlockUtils.h" 40f384594dSTobias Grosser #include "isl/union_map.h" 41e8227804SMichael Kruse #include <algorithm> 42f384594dSTobias Grosser 43e938517eSTobias Grosser extern "C" { 44a56f8f8eSTobias Grosser #include "ppcg/cuda.h" 45a56f8f8eSTobias Grosser #include "ppcg/gpu.h" 46a56f8f8eSTobias Grosser #include "ppcg/ppcg.h" 47e938517eSTobias Grosser } 48e938517eSTobias Grosser 499dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h" 509dfe4e7cSTobias Grosser 519dfe4e7cSTobias Grosser using namespace polly; 529dfe4e7cSTobias Grosser using namespace llvm; 539dfe4e7cSTobias Grosser 549dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg" 559dfe4e7cSTobias Grosser 56f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule", 57f384594dSTobias Grosser cl::desc("Dump the computed GPU Schedule"), 58681bd568STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 59f384594dSTobias Grosser cl::cat(PollyCategory)); 6069b46751STobias Grosser 6169b46751STobias Grosser static cl::opt<bool> 6269b46751STobias Grosser DumpCode("polly-acc-dump-code", 6369b46751STobias Grosser cl::desc("Dump C code describing the GPU mapping"), cl::Hidden, 6469b46751STobias Grosser cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory)); 6569b46751STobias Grosser 6632837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir", 6732837fe3STobias Grosser cl::desc("Dump the kernel LLVM-IR"), 6832837fe3STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 6932837fe3STobias Grosser cl::cat(PollyCategory)); 7032837fe3STobias Grosser 7174dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm", 7274dc3cb4STobias Grosser cl::desc("Dump the kernel assembly code"), 7374dc3cb4STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 7474dc3cb4STobias Grosser cl::cat(PollyCategory)); 7574dc3cb4STobias Grosser 7674dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath", 7774dc3cb4STobias Grosser cl::desc("Allow unsafe math optimizations"), 7874dc3cb4STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 7974dc3cb4STobias Grosser cl::cat(PollyCategory)); 80b513b491STobias Grosser static cl::opt<bool> SharedMemory("polly-acc-use-shared", 81b513b491STobias Grosser cl::desc("Use shared memory"), cl::Hidden, 82b513b491STobias Grosser cl::init(false), cl::ZeroOrMore, 83b513b491STobias Grosser cl::cat(PollyCategory)); 84130ca30fSTobias Grosser static cl::opt<bool> PrivateMemory("polly-acc-use-private", 85130ca30fSTobias Grosser cl::desc("Use private memory"), cl::Hidden, 86130ca30fSTobias Grosser cl::init(false), cl::ZeroOrMore, 87130ca30fSTobias Grosser cl::cat(PollyCategory)); 8874dc3cb4STobias Grosser 89c4a4af47SSiddharth Bhat bool polly::PollyManagedMemory; 90c4a4af47SSiddharth Bhat static cl::opt<bool, true> 91c4a4af47SSiddharth Bhat XManagedMemory("polly-acc-codegen-managed-memory", 92abed4969SSiddharth Bhat cl::desc("Generate Host kernel code assuming" 93abed4969SSiddharth Bhat " that all memory has been" 94abed4969SSiddharth Bhat " declared as managed memory"), 95c4a4af47SSiddharth Bhat cl::location(PollyManagedMemory), cl::Hidden, 96c4a4af47SSiddharth Bhat cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory)); 97abed4969SSiddharth Bhat 9865d7f72fSSiddharth Bhat static cl::opt<bool> 9965d7f72fSSiddharth Bhat FailOnVerifyModuleFailure("polly-acc-fail-on-verify-module-failure", 10065d7f72fSSiddharth Bhat cl::desc("Fail and generate a backtrace if" 10165d7f72fSSiddharth Bhat " verifyModule fails on the GPU " 10265d7f72fSSiddharth Bhat " kernel module."), 10365d7f72fSSiddharth Bhat cl::Hidden, cl::init(false), cl::ZeroOrMore, 10465d7f72fSSiddharth Bhat cl::cat(PollyCategory)); 10565d7f72fSSiddharth Bhat 1068fc6cdfbSTobias Grosser static cl::opt<std::string> CUDALibDevice( 1078fc6cdfbSTobias Grosser "polly-acc-libdevice", cl::desc("Path to CUDA libdevice"), cl::Hidden, 1088fc6cdfbSTobias Grosser cl::init("/usr/local/cuda/nvvm/libdevice/libdevice.compute_20.10.ll"), 1098fc6cdfbSTobias Grosser cl::ZeroOrMore, cl::cat(PollyCategory)); 1108fc6cdfbSTobias Grosser 11174dc3cb4STobias Grosser static cl::opt<std::string> 11274dc3cb4STobias Grosser CudaVersion("polly-acc-cuda-version", 11374dc3cb4STobias Grosser cl::desc("The CUDA version to compile for"), cl::Hidden, 11474dc3cb4STobias Grosser cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory)); 11574dc3cb4STobias Grosser 11682f2af35STobias Grosser static cl::opt<int> 11782f2af35STobias Grosser MinCompute("polly-acc-mincompute", 11882f2af35STobias Grosser cl::desc("Minimal number of compute statements to run on GPU."), 11982f2af35STobias Grosser cl::Hidden, cl::init(10 * 512 * 512)); 12082f2af35STobias Grosser 1213dcb5351SMichael Kruse GPURuntime polly::GPURuntimeChoice; 1223dcb5351SMichael Kruse static cl::opt<GPURuntime, true> XGPURuntimeChoice( 1233dcb5351SMichael Kruse "polly-gpu-runtime", cl::desc("The GPU Runtime API to target"), 1243dcb5351SMichael Kruse cl::values(clEnumValN(GPURuntime::CUDA, "libcudart", 1253dcb5351SMichael Kruse "use the CUDA Runtime API"), 1263dcb5351SMichael Kruse clEnumValN(GPURuntime::OpenCL, "libopencl", 1273dcb5351SMichael Kruse "use the OpenCL Runtime API")), 1283dcb5351SMichael Kruse cl::location(polly::GPURuntimeChoice), cl::init(GPURuntime::CUDA), 1293dcb5351SMichael Kruse cl::ZeroOrMore, cl::cat(PollyCategory)); 1303dcb5351SMichael Kruse 1313dcb5351SMichael Kruse GPUArch polly::GPUArchChoice; 1323dcb5351SMichael Kruse static cl::opt<GPUArch, true> 1333dcb5351SMichael Kruse XGPUArchChoice("polly-gpu-arch", cl::desc("The GPU Architecture to target"), 1343dcb5351SMichael Kruse cl::values(clEnumValN(GPUArch::NVPTX64, "nvptx64", 1353dcb5351SMichael Kruse "target NVIDIA 64-bit architecture"), 1363dcb5351SMichael Kruse clEnumValN(GPUArch::SPIR32, "spir32", 1373dcb5351SMichael Kruse "target SPIR 32-bit architecture"), 1383dcb5351SMichael Kruse clEnumValN(GPUArch::SPIR64, "spir64", 1393dcb5351SMichael Kruse "target SPIR 64-bit architecture")), 1403dcb5351SMichael Kruse cl::location(polly::GPUArchChoice), 1413dcb5351SMichael Kruse cl::init(GPUArch::NVPTX64), cl::ZeroOrMore, 1423dcb5351SMichael Kruse cl::cat(PollyCategory)); 1433dcb5351SMichael Kruse 1447b9f5ca2SSiddharth Bhat extern bool polly::PerfMonitoring; 1457b9f5ca2SSiddharth Bhat 146638316daSSiddharth Bhat /// Return a unique name for a Scop, which is the scop region with the 147638316daSSiddharth Bhat /// function name. 148638316daSSiddharth Bhat std::string getUniqueScopName(const Scop *S) { 149638316daSSiddharth Bhat return "Scop Region: " + S->getNameStr() + 150638316daSSiddharth Bhat " | Function: " + std::string(S->getFunction().getName()); 151638316daSSiddharth Bhat } 152638316daSSiddharth Bhat 153a82f2d26SSiddharth Bhat /// Used to store information PPCG wants for kills. This information is 154a82f2d26SSiddharth Bhat /// used by live range reordering. 155a82f2d26SSiddharth Bhat /// 156a82f2d26SSiddharth Bhat /// @see computeLiveRangeReordering 157a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGScop 158a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGProg 159a82f2d26SSiddharth Bhat struct MustKillsInfo { 160a82f2d26SSiddharth Bhat /// Collection of all kill statements that will be sequenced at the end of 161a82f2d26SSiddharth Bhat /// PPCGScop->schedule. 162a82f2d26SSiddharth Bhat /// 163a82f2d26SSiddharth Bhat /// The nodes in `KillsSchedule` will be merged using `isl_schedule_set` 164a82f2d26SSiddharth Bhat /// which merges schedules in *arbitrary* order. 165a82f2d26SSiddharth Bhat /// (we don't care about the order of the kills anyway). 166a82f2d26SSiddharth Bhat isl::schedule KillsSchedule; 167a82f2d26SSiddharth Bhat /// Map from kill statement instances to scalars that need to be 168a82f2d26SSiddharth Bhat /// killed. 169a82f2d26SSiddharth Bhat /// 170edfef5aeSSiddharth Bhat /// We currently derive kill information for: 171edfef5aeSSiddharth Bhat /// 1. phi nodes. PHI nodes are not alive outside the scop and can 172edfef5aeSSiddharth Bhat /// consequently all be killed. 173edfef5aeSSiddharth Bhat /// 2. Scalar arrays that are not used outside the Scop. This is 174edfef5aeSSiddharth Bhat /// checked by `isScalarUsesContainedInScop`. 175edfef5aeSSiddharth Bhat /// [params] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] } 176a82f2d26SSiddharth Bhat isl::union_map TaggedMustKills; 177a82f2d26SSiddharth Bhat 1789e3db2b7SSiddharth Bhat /// Tagged must kills stripped of the tags. 1799e3db2b7SSiddharth Bhat /// [params] -> { Stmt_phantom[] -> scalar_to_kill[] } 1809e3db2b7SSiddharth Bhat isl::union_map MustKills; 1819e3db2b7SSiddharth Bhat 1829b41d095Spatacca MustKillsInfo() : KillsSchedule() {} 183a82f2d26SSiddharth Bhat }; 184a82f2d26SSiddharth Bhat 185761e5b93SSiddharth Bhat /// Check if SAI's uses are entirely contained within Scop S. 186761e5b93SSiddharth Bhat /// If a scalar is used only with a Scop, we are free to kill it, as no data 187761e5b93SSiddharth Bhat /// can flow in/out of the value any more. 188761e5b93SSiddharth Bhat /// @see computeMustKillsInfo 189761e5b93SSiddharth Bhat static bool isScalarUsesContainedInScop(const Scop &S, 190761e5b93SSiddharth Bhat const ScopArrayInfo *SAI) { 191761e5b93SSiddharth Bhat assert(SAI->isValueKind() && "this function only deals with scalars." 192761e5b93SSiddharth Bhat " Dealing with arrays required alias analysis"); 193761e5b93SSiddharth Bhat 194761e5b93SSiddharth Bhat const Region &R = S.getRegion(); 195761e5b93SSiddharth Bhat for (User *U : SAI->getBasePtr()->users()) { 196761e5b93SSiddharth Bhat Instruction *I = dyn_cast<Instruction>(U); 197761e5b93SSiddharth Bhat assert(I && "invalid user of scop array info"); 198761e5b93SSiddharth Bhat if (!R.contains(I)) 199761e5b93SSiddharth Bhat return false; 200761e5b93SSiddharth Bhat } 201761e5b93SSiddharth Bhat return true; 202761e5b93SSiddharth Bhat } 203761e5b93SSiddharth Bhat 204a82f2d26SSiddharth Bhat /// Compute must-kills needed to enable live range reordering with PPCG. 205a82f2d26SSiddharth Bhat /// 206a82f2d26SSiddharth Bhat /// @params S The Scop to compute live range reordering information 207a82f2d26SSiddharth Bhat /// @returns live range reordering information that can be used to setup 208a82f2d26SSiddharth Bhat /// PPCG. 209a82f2d26SSiddharth Bhat static MustKillsInfo computeMustKillsInfo(const Scop &S) { 210b65ccc43STobias Grosser const isl::space ParamSpace = S.getParamSpace(); 211a82f2d26SSiddharth Bhat MustKillsInfo Info; 212a82f2d26SSiddharth Bhat 213761e5b93SSiddharth Bhat // 1. Collect all ScopArrayInfo that satisfy *any* of the criteria: 214761e5b93SSiddharth Bhat // 1.1 phi nodes in scop. 215761e5b93SSiddharth Bhat // 1.2 scalars that are only used within the scop 216a82f2d26SSiddharth Bhat SmallVector<isl::id, 4> KillMemIds; 217a82f2d26SSiddharth Bhat for (ScopArrayInfo *SAI : S.arrays()) { 218761e5b93SSiddharth Bhat if (SAI->isPHIKind() || 219761e5b93SSiddharth Bhat (SAI->isValueKind() && isScalarUsesContainedInScop(S, SAI))) 22077eef90fSTobias Grosser KillMemIds.push_back(isl::manage(SAI->getBasePtrId().release())); 221a82f2d26SSiddharth Bhat } 222a82f2d26SSiddharth Bhat 223bad3ebbaSRiccardo Mori Info.TaggedMustKills = isl::union_map::empty(ParamSpace.ctx()); 224bad3ebbaSRiccardo Mori Info.MustKills = isl::union_map::empty(ParamSpace.ctx()); 225a82f2d26SSiddharth Bhat 226a82f2d26SSiddharth Bhat // Initialising KillsSchedule to `isl_set_empty` creates an empty node in the 227a82f2d26SSiddharth Bhat // schedule: 228a82f2d26SSiddharth Bhat // - filter: "[control] -> { }" 229a82f2d26SSiddharth Bhat // So, we choose to not create this to keep the output a little nicer, 230a82f2d26SSiddharth Bhat // at the cost of some code complexity. 2319b41d095Spatacca Info.KillsSchedule = {}; 232a82f2d26SSiddharth Bhat 233edfef5aeSSiddharth Bhat for (isl::id &ToKillId : KillMemIds) { 234a82f2d26SSiddharth Bhat isl::id KillStmtId = isl::id::alloc( 235edfef5aeSSiddharth Bhat S.getIslCtx(), 236edfef5aeSSiddharth Bhat std::string("SKill_phantom_").append(ToKillId.get_name()), nullptr); 237a82f2d26SSiddharth Bhat 238a82f2d26SSiddharth Bhat // NOTE: construction of tagged_must_kill: 239a82f2d26SSiddharth Bhat // 2. We need to construct a map: 240edfef5aeSSiddharth Bhat // [param] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] } 241a82f2d26SSiddharth Bhat // To construct this, we use `isl_map_domain_product` on 2 maps`: 242edfef5aeSSiddharth Bhat // 2a. StmtToScalar: 243edfef5aeSSiddharth Bhat // [param] -> { Stmt_phantom[] -> scalar_to_kill[] } 244edfef5aeSSiddharth Bhat // 2b. PhantomRefToScalar: 245edfef5aeSSiddharth Bhat // [param] -> { ref_phantom[] -> scalar_to_kill[] } 246a82f2d26SSiddharth Bhat // 247a82f2d26SSiddharth Bhat // Combining these with `isl_map_domain_product` gives us 248a82f2d26SSiddharth Bhat // TaggedMustKill: 249edfef5aeSSiddharth Bhat // [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] } 250a82f2d26SSiddharth Bhat 251edfef5aeSSiddharth Bhat // 2a. [param] -> { Stmt[] -> scalar_to_kill[] } 252d70ea7feSTobias Grosser isl::map StmtToScalar = isl::map::universe(ParamSpace); 253edfef5aeSSiddharth Bhat StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::in, isl::id(KillStmtId)); 254edfef5aeSSiddharth Bhat StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::out, isl::id(ToKillId)); 255a82f2d26SSiddharth Bhat 256a82f2d26SSiddharth Bhat isl::id PhantomRefId = isl::id::alloc( 257edfef5aeSSiddharth Bhat S.getIslCtx(), std::string("ref_phantom") + ToKillId.get_name(), 258edfef5aeSSiddharth Bhat nullptr); 259a82f2d26SSiddharth Bhat 260edfef5aeSSiddharth Bhat // 2b. [param] -> { phantom_ref[] -> scalar_to_kill[] } 261d70ea7feSTobias Grosser isl::map PhantomRefToScalar = isl::map::universe(ParamSpace); 262edfef5aeSSiddharth Bhat PhantomRefToScalar = 263edfef5aeSSiddharth Bhat PhantomRefToScalar.set_tuple_id(isl::dim::in, PhantomRefId); 264edfef5aeSSiddharth Bhat PhantomRefToScalar = 265edfef5aeSSiddharth Bhat PhantomRefToScalar.set_tuple_id(isl::dim::out, ToKillId); 266a82f2d26SSiddharth Bhat 267edfef5aeSSiddharth Bhat // 2. [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] } 268edfef5aeSSiddharth Bhat isl::map TaggedMustKill = StmtToScalar.domain_product(PhantomRefToScalar); 269a82f2d26SSiddharth Bhat Info.TaggedMustKills = Info.TaggedMustKills.unite(TaggedMustKill); 270a82f2d26SSiddharth Bhat 2719e3db2b7SSiddharth Bhat // 2. [param] -> { Stmt[] -> scalar_to_kill[] } 2729e3db2b7SSiddharth Bhat Info.MustKills = Info.TaggedMustKills.domain_factor_domain(); 2739e3db2b7SSiddharth Bhat 274a82f2d26SSiddharth Bhat // 3. Create the kill schedule of the form: 275a82f2d26SSiddharth Bhat // "[param] -> { Stmt_phantom[] }" 276a82f2d26SSiddharth Bhat // Then add this to Info.KillsSchedule. 277a82f2d26SSiddharth Bhat isl::space KillStmtSpace = ParamSpace; 278a82f2d26SSiddharth Bhat KillStmtSpace = KillStmtSpace.set_tuple_id(isl::dim::set, KillStmtId); 279a82f2d26SSiddharth Bhat isl::union_set KillStmtDomain = isl::set::universe(KillStmtSpace); 280a82f2d26SSiddharth Bhat 281a82f2d26SSiddharth Bhat isl::schedule KillSchedule = isl::schedule::from_domain(KillStmtDomain); 2827c7978a1Spatacca if (!Info.KillsSchedule.is_null()) 2835f865032STobias Grosser Info.KillsSchedule = isl::manage( 2845f865032STobias Grosser isl_schedule_set(Info.KillsSchedule.release(), KillSchedule.copy())); 285a82f2d26SSiddharth Bhat else 286a82f2d26SSiddharth Bhat Info.KillsSchedule = KillSchedule; 287a82f2d26SSiddharth Bhat } 288a82f2d26SSiddharth Bhat 289a82f2d26SSiddharth Bhat return Info; 290a82f2d26SSiddharth Bhat } 291a82f2d26SSiddharth Bhat 29260c60025STobias Grosser /// Create the ast expressions for a ScopStmt. 29360c60025STobias Grosser /// 29460c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each 29560c60025STobias Grosser /// of the scheduled ScopStmts. 29660c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt( 29735de9009SSiddharth Bhat void *StmtT, __isl_take isl_ast_build *Build_C, 29860c60025STobias Grosser isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA, 29960c60025STobias Grosser isl_id *Id, void *User), 30060c60025STobias Grosser void *UserIndex, 30160c60025STobias Grosser isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User), 302edb885cbSTobias Grosser void *UserExpr) { 30360c60025STobias Grosser 304edb885cbSTobias Grosser ScopStmt *Stmt = (ScopStmt *)StmtT; 30560c60025STobias Grosser 30635de9009SSiddharth Bhat if (!Stmt || !Build_C) 307edb885cbSTobias Grosser return NULL; 308edb885cbSTobias Grosser 309718d04c6STobias Grosser isl::ast_build Build = isl::manage_copy(Build_C); 3100813bd16SRiccardo Mori isl::ctx Ctx = Build.ctx(); 31135de9009SSiddharth Bhat isl::id_to_ast_expr RefToExpr = isl::id_to_ast_expr::alloc(Ctx, 0); 312edb885cbSTobias Grosser 313cff9696eSTobias Grosser Stmt->setAstBuild(Build); 314cff9696eSTobias Grosser 315edb885cbSTobias Grosser for (MemoryAccess *Acc : *Stmt) { 31635de9009SSiddharth Bhat isl::map AddrFunc = Acc->getAddressFunction(); 317dcf8d696STobias Grosser AddrFunc = AddrFunc.intersect_domain(Stmt->getDomain()); 31835de9009SSiddharth Bhat 31935de9009SSiddharth Bhat isl::id RefId = Acc->getId(); 32035de9009SSiddharth Bhat isl::pw_multi_aff PMA = isl::pw_multi_aff::from_map(AddrFunc); 32135de9009SSiddharth Bhat 32235de9009SSiddharth Bhat isl::multi_pw_aff MPA = isl::multi_pw_aff(PMA); 32335de9009SSiddharth Bhat MPA = MPA.coalesce(); 32435de9009SSiddharth Bhat MPA = isl::manage(FunctionIndex(MPA.release(), RefId.get(), UserIndex)); 32535de9009SSiddharth Bhat 32635de9009SSiddharth Bhat isl::ast_expr Access = Build.access_from(MPA); 32735de9009SSiddharth Bhat Access = isl::manage(FunctionExpr(Access.release(), RefId.get(), UserExpr)); 32835de9009SSiddharth Bhat RefToExpr = RefToExpr.set(RefId, Access); 329edb885cbSTobias Grosser } 330edb885cbSTobias Grosser 33135de9009SSiddharth Bhat return RefToExpr.release(); 33260c60025STobias Grosser } 333f384594dSTobias Grosser 334a90be207SSiddharth Bhat /// Given a LLVM Type, compute its size in bytes, 335a90be207SSiddharth Bhat static int computeSizeInBytes(const Type *T) { 336a90be207SSiddharth Bhat int bytes = T->getPrimitiveSizeInBits() / 8; 337a90be207SSiddharth Bhat if (bytes == 0) 338a90be207SSiddharth Bhat bytes = T->getScalarSizeInBits() / 8; 339a90be207SSiddharth Bhat return bytes; 340a90be207SSiddharth Bhat } 341a90be207SSiddharth Bhat 34238fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST. 34338fc0aedSTobias Grosser /// 34438fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which 345a6d48f59SMichael Kruse /// generates code for general-purpose AST nodes, with special functionality 34638fc0aedSTobias Grosser /// for generating GPU specific user nodes. 34738fc0aedSTobias Grosser /// 34838fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser 34938fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder { 35038fc0aedSTobias Grosser public: 3512d950f36SPhilip Pfaffe GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, 35238fc0aedSTobias Grosser const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE, 353acf80064SEli Friedman DominatorTree &DT, Scop &S, BasicBlock *StartBlock, 35417f01968SSiddharth Bhat gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch) 3552d950f36SPhilip Pfaffe : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock), 35617f01968SSiddharth Bhat Prog(Prog), Runtime(Runtime), Arch(Arch) { 357edb885cbSTobias Grosser getExprBuilder().setIDToSAI(&IDToSAI); 358edb885cbSTobias Grosser } 35938fc0aedSTobias Grosser 360fa7b0802STobias Grosser /// Create after-run-time-check initialization code. 361fa7b0802STobias Grosser void initializeAfterRTH(); 362fa7b0802STobias Grosser 363fa7b0802STobias Grosser /// Finalize the generated scop. 36433ca0b0eSMichael Kruse void finalize() override; 365fa7b0802STobias Grosser 3665857b701STobias Grosser /// Track if the full build process was successful. 3675857b701STobias Grosser /// 3685857b701STobias Grosser /// This value is set to false, if throughout the build process an error 3695857b701STobias Grosser /// occurred which prevents us from generating valid GPU code. 3705857b701STobias Grosser bool BuildSuccessful = true; 3715857b701STobias Grosser 372bc653f20STobias Grosser /// The maximal number of loops surrounding a sequential kernel. 373bc653f20STobias Grosser unsigned DeepestSequential = 0; 374bc653f20STobias Grosser 375bc653f20STobias Grosser /// The maximal number of loops surrounding a parallel kernel. 376bc653f20STobias Grosser unsigned DeepestParallel = 0; 377bc653f20STobias Grosser 37879f13b9aSSingapuram Sanjay Srivallabh /// Return the name to set for the ptx_kernel. 37979f13b9aSSingapuram Sanjay Srivallabh std::string getKernelFuncName(int Kernel_id); 38079f13b9aSSingapuram Sanjay Srivallabh 38138fc0aedSTobias Grosser private: 38274dc3cb4STobias Grosser /// A vector of array base pointers for which a new ScopArrayInfo was created. 38374dc3cb4STobias Grosser /// 38474dc3cb4STobias Grosser /// This vector is used to delete the ScopArrayInfo when it is not needed any 38574dc3cb4STobias Grosser /// more. 38674dc3cb4STobias Grosser std::vector<Value *> LocalArrays; 38774dc3cb4STobias Grosser 38813c78e4dSTobias Grosser /// A map from ScopArrays to their corresponding device allocations. 38913c78e4dSTobias Grosser std::map<ScopArrayInfo *, Value *> DeviceAllocations; 3907287aeddSTobias Grosser 391fa7b0802STobias Grosser /// The current GPU context. 392fa7b0802STobias Grosser Value *GPUContext; 393fa7b0802STobias Grosser 394b513b491STobias Grosser /// The set of isl_ids allocated in the kernel 395b513b491STobias Grosser std::vector<isl_id *> KernelIds; 396b513b491STobias Grosser 39732837fe3STobias Grosser /// A module containing GPU code. 39832837fe3STobias Grosser /// 39932837fe3STobias Grosser /// This pointer is only set in case we are currently generating GPU code. 40032837fe3STobias Grosser std::unique_ptr<Module> GPUModule; 40132837fe3STobias Grosser 40232837fe3STobias Grosser /// The GPU program we generate code for. 40332837fe3STobias Grosser gpu_prog *Prog; 40432837fe3STobias Grosser 40517f01968SSiddharth Bhat /// The GPU Runtime implementation to use (OpenCL or CUDA). 40617f01968SSiddharth Bhat GPURuntime Runtime; 40717f01968SSiddharth Bhat 40817f01968SSiddharth Bhat /// The GPU Architecture to target. 40917f01968SSiddharth Bhat GPUArch Arch; 41017f01968SSiddharth Bhat 411472f9654STobias Grosser /// Class to free isl_ids. 412472f9654STobias Grosser class IslIdDeleter { 413472f9654STobias Grosser public: 414472f9654STobias Grosser void operator()(__isl_take isl_id *Id) { isl_id_free(Id); }; 415472f9654STobias Grosser }; 416472f9654STobias Grosser 417472f9654STobias Grosser /// A set containing all isl_ids allocated in a GPU kernel. 418472f9654STobias Grosser /// 419472f9654STobias Grosser /// By releasing this set all isl_ids will be freed. 420472f9654STobias Grosser std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs; 421472f9654STobias Grosser 422edb885cbSTobias Grosser IslExprBuilder::IDToScopArrayInfoTy IDToSAI; 423edb885cbSTobias Grosser 42438fc0aedSTobias Grosser /// Create code for user-defined AST nodes. 42538fc0aedSTobias Grosser /// 42638fc0aedSTobias Grosser /// These AST nodes can be of type: 42738fc0aedSTobias Grosser /// 42838fc0aedSTobias Grosser /// - ScopStmt: A computational statement (TODO) 42938fc0aedSTobias Grosser /// - Kernel: A GPU kernel call (TODO) 43013c78e4dSTobias Grosser /// - Data-Transfer: A GPU <-> CPU data-transfer 4315260c041STobias Grosser /// - In-kernel synchronization 4325260c041STobias Grosser /// - In-kernel memory copy statement 43338fc0aedSTobias Grosser /// 4341fb9b64dSTobias Grosser /// @param UserStmt The ast node to generate code for. 43533ca0b0eSMichael Kruse void createUser(__isl_take isl_ast_node *UserStmt) override; 43632837fe3STobias Grosser 43733ca0b0eSMichael Kruse void createFor(__isl_take isl_ast_node *Node) override; 43853c80387SPhilip Pfaffe 43913c78e4dSTobias Grosser enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST }; 44013c78e4dSTobias Grosser 44113c78e4dSTobias Grosser /// Create code for a data transfer statement 44213c78e4dSTobias Grosser /// 44313c78e4dSTobias Grosser /// @param TransferStmt The data transfer statement. 44413c78e4dSTobias Grosser /// @param Direction The direction in which to transfer data. 44513c78e4dSTobias Grosser void createDataTransfer(__isl_take isl_ast_node *TransferStmt, 44613c78e4dSTobias Grosser enum DataDirection Direction); 44713c78e4dSTobias Grosser 448edb885cbSTobias Grosser /// Find llvm::Values referenced in GPU kernel. 449edb885cbSTobias Grosser /// 450edb885cbSTobias Grosser /// @param Kernel The kernel to scan for llvm::Values 451edb885cbSTobias Grosser /// 452e53c924bSSiddharth Bhat /// @returns A tuple, whose: 453e53c924bSSiddharth Bhat /// - First element contains the set of values referenced by the 454e53c924bSSiddharth Bhat /// kernel 455e53c924bSSiddharth Bhat /// - Second element contains the set of functions referenced by the 456e53c924bSSiddharth Bhat /// kernel. All functions in the set satisfy 457e53c924bSSiddharth Bhat /// `isValidFunctionInKernel`. 458e53c924bSSiddharth Bhat /// - Third element contains loops that have induction variables 459e53c924bSSiddharth Bhat /// which are used in the kernel, *and* these loops are *neither* 460e53c924bSSiddharth Bhat /// in the scop, nor do they immediately surroung the Scop. 461e53c924bSSiddharth Bhat /// See [Code generation of induction variables of loops outside 462e53c924bSSiddharth Bhat /// Scops] 46343df2020STobias Grosser std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>, 46443df2020STobias Grosser isl::space> 465f291c8d5SSiddharth Bhat getReferencesInKernel(ppcg_kernel *Kernel); 466edb885cbSTobias Grosser 46779a947c2STobias Grosser /// Compute the sizes of the execution grid for a given kernel. 46879a947c2STobias Grosser /// 46979a947c2STobias Grosser /// @param Kernel The kernel to compute grid sizes for. 47079a947c2STobias Grosser /// 47179a947c2STobias Grosser /// @returns A tuple with grid sizes for X and Y dimension 47279a947c2STobias Grosser std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel); 47379a947c2STobias Grosser 474b99c1171STobias Grosser /// Get the managed array pointer for sending host pointers to the device. 475abed4969SSiddharth Bhat /// \note 476abed4969SSiddharth Bhat /// This is to be used only with managed memory 477b99c1171STobias Grosser Value *getManagedDeviceArray(gpu_array_info *Array, ScopArrayInfo *ArrayInfo); 478abed4969SSiddharth Bhat 47979a947c2STobias Grosser /// Compute the sizes of the thread blocks for a given kernel. 48079a947c2STobias Grosser /// 48179a947c2STobias Grosser /// @param Kernel The kernel to compute thread block sizes for. 48279a947c2STobias Grosser /// 48379a947c2STobias Grosser /// @returns A tuple with thread block sizes for X, Y, and Z dimensions. 48479a947c2STobias Grosser std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel); 48579a947c2STobias Grosser 486a90be207SSiddharth Bhat /// Store a specific kernel launch parameter in the array of kernel launch 487a90be207SSiddharth Bhat /// parameters. 488a90be207SSiddharth Bhat /// 489*ee6bd28fSNikita Popov /// @param ArrayTy Array type of \p Parameters. 490a90be207SSiddharth Bhat /// @param Parameters The list of parameters in which to store. 491a90be207SSiddharth Bhat /// @param Param The kernel launch parameter to store. 492a90be207SSiddharth Bhat /// @param Index The index in the parameter list, at which to store the 493a90be207SSiddharth Bhat /// parameter. 494*ee6bd28fSNikita Popov void insertStoreParameter(Type *ArrayTy, Instruction *Parameters, 495*ee6bd28fSNikita Popov Instruction *Param, int Index); 496a90be207SSiddharth Bhat 49779a947c2STobias Grosser /// Create kernel launch parameters. 49879a947c2STobias Grosser /// 49979a947c2STobias Grosser /// @param Kernel The kernel to create parameters for. 50079a947c2STobias Grosser /// @param F The kernel function that has been created. 50157693272STobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 50279a947c2STobias Grosser /// 50379a947c2STobias Grosser /// @returns A stack allocated array with pointers to the parameter 50479a947c2STobias Grosser /// values that are passed to the kernel. 50557693272STobias Grosser Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F, 50657693272STobias Grosser SetVector<Value *> SubtreeValues); 50779a947c2STobias Grosser 508b513b491STobias Grosser /// Create declarations for kernel variable. 509b513b491STobias Grosser /// 510b513b491STobias Grosser /// This includes shared memory declarations. 511b513b491STobias Grosser /// 512b513b491STobias Grosser /// @param Kernel The kernel definition to create variables for. 513b513b491STobias Grosser /// @param FN The function into which to generate the variables. 514b513b491STobias Grosser void createKernelVariables(ppcg_kernel *Kernel, Function *FN); 515b513b491STobias Grosser 516c1c6a2a6STobias Grosser /// Add CUDA annotations to module. 517c1c6a2a6STobias Grosser /// 518c1c6a2a6STobias Grosser /// Add a set of CUDA annotations that declares the maximal block dimensions 519c1c6a2a6STobias Grosser /// that will be used to execute the CUDA kernel. This allows the NVIDIA 520c1c6a2a6STobias Grosser /// PTX compiler to bound the number of allocated registers to ensure the 521c1c6a2a6STobias Grosser /// resulting kernel is known to run with up to as many block dimensions 522c1c6a2a6STobias Grosser /// as specified here. 523c1c6a2a6STobias Grosser /// 524c1c6a2a6STobias Grosser /// @param M The module to add the annotations to. 525c1c6a2a6STobias Grosser /// @param BlockDimX The size of block dimension X. 526c1c6a2a6STobias Grosser /// @param BlockDimY The size of block dimension Y. 527c1c6a2a6STobias Grosser /// @param BlockDimZ The size of block dimension Z. 528c1c6a2a6STobias Grosser void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY, 529c1c6a2a6STobias Grosser Value *BlockDimZ); 530c1c6a2a6STobias Grosser 53132837fe3STobias Grosser /// Create GPU kernel. 53232837fe3STobias Grosser /// 53332837fe3STobias Grosser /// Code generate the kernel described by @p KernelStmt. 53432837fe3STobias Grosser /// 53532837fe3STobias Grosser /// @param KernelStmt The ast node to generate kernel code for. 53632837fe3STobias Grosser void createKernel(__isl_take isl_ast_node *KernelStmt); 53732837fe3STobias Grosser 53813c78e4dSTobias Grosser /// Generate code that computes the size of an array. 53913c78e4dSTobias Grosser /// 54013c78e4dSTobias Grosser /// @param Array The array for which to compute a size. 54113c78e4dSTobias Grosser Value *getArraySize(gpu_array_info *Array); 54213c78e4dSTobias Grosser 543aaabbbf8STobias Grosser /// Generate code to compute the minimal offset at which an array is accessed. 544aaabbbf8STobias Grosser /// 545aaabbbf8STobias Grosser /// The offset of an array is the minimal array location accessed in a scop. 546aaabbbf8STobias Grosser /// 547aaabbbf8STobias Grosser /// Example: 548aaabbbf8STobias Grosser /// 549aaabbbf8STobias Grosser /// for (long i = 0; i < 100; i++) 550aaabbbf8STobias Grosser /// A[i + 42] += ... 551aaabbbf8STobias Grosser /// 552aaabbbf8STobias Grosser /// getArrayOffset(A) results in 42. 553aaabbbf8STobias Grosser /// 554aaabbbf8STobias Grosser /// @param Array The array for which to compute the offset. 555aaabbbf8STobias Grosser /// @returns An llvm::Value that contains the offset of the array. 556aaabbbf8STobias Grosser Value *getArrayOffset(gpu_array_info *Array); 557aaabbbf8STobias Grosser 55800bb5a99STobias Grosser /// Prepare the kernel arguments for kernel code generation 55900bb5a99STobias Grosser /// 56000bb5a99STobias Grosser /// @param Kernel The kernel to generate code for. 56100bb5a99STobias Grosser /// @param FN The function created for the kernel. 56200bb5a99STobias Grosser void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN); 56300bb5a99STobias Grosser 56432837fe3STobias Grosser /// Create kernel function. 56532837fe3STobias Grosser /// 56632837fe3STobias Grosser /// Create a kernel function located in a newly created module that can serve 56732837fe3STobias Grosser /// as target for device code generation. Set the Builder to point to the 56832837fe3STobias Grosser /// start block of this newly created function. 56932837fe3STobias Grosser /// 57032837fe3STobias Grosser /// @param Kernel The kernel to generate code for. 571edb885cbSTobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 572f291c8d5SSiddharth Bhat /// @param SubtreeFunctions The set of llvm::Functions referenced by this 573f291c8d5SSiddharth Bhat /// kernel. 574edb885cbSTobias Grosser void createKernelFunction(ppcg_kernel *Kernel, 575f291c8d5SSiddharth Bhat SetVector<Value *> &SubtreeValues, 576f291c8d5SSiddharth Bhat SetVector<Function *> &SubtreeFunctions); 57732837fe3STobias Grosser 57832837fe3STobias Grosser /// Create the declaration of a kernel function. 57932837fe3STobias Grosser /// 58032837fe3STobias Grosser /// The kernel function takes as arguments: 58132837fe3STobias Grosser /// 58232837fe3STobias Grosser /// - One i8 pointer for each external array reference used in the kernel. 583f6044bd0STobias Grosser /// - Host iterators 584c84a1995STobias Grosser /// - Parameters 58532837fe3STobias Grosser /// - Other LLVM Value references (TODO) 58632837fe3STobias Grosser /// 58732837fe3STobias Grosser /// @param Kernel The kernel to generate the function declaration for. 588edb885cbSTobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 589edb885cbSTobias Grosser /// 59032837fe3STobias Grosser /// @returns The newly declared function. 591edb885cbSTobias Grosser Function *createKernelFunctionDecl(ppcg_kernel *Kernel, 592edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues); 59332837fe3STobias Grosser 594472f9654STobias Grosser /// Insert intrinsic functions to obtain thread and block ids. 595472f9654STobias Grosser /// 596472f9654STobias Grosser /// @param The kernel to generate the intrinsic functions for. 597472f9654STobias Grosser void insertKernelIntrinsics(ppcg_kernel *Kernel); 598472f9654STobias Grosser 5992f3073b5SPhilipp Schaad /// Insert function calls to retrieve the SPIR group/local ids. 6002f3073b5SPhilipp Schaad /// 601d71493cbSPhilip Pfaffe /// @param Kernel The kernel to generate the function calls for. 602d71493cbSPhilip Pfaffe /// @param SizeTypeIs64Bit Whether size_t of the openCl device is 64bit. 603d71493cbSPhilip Pfaffe void insertKernelCallsSPIR(ppcg_kernel *Kernel, bool SizeTypeIs64bit); 6042f3073b5SPhilipp Schaad 605f291c8d5SSiddharth Bhat /// Setup the creation of functions referenced by the GPU kernel. 606f291c8d5SSiddharth Bhat /// 607f291c8d5SSiddharth Bhat /// 1. Create new function declarations in GPUModule which are the same as 608f291c8d5SSiddharth Bhat /// SubtreeFunctions. 609f291c8d5SSiddharth Bhat /// 610f291c8d5SSiddharth Bhat /// 2. Populate IslNodeBuilder::ValueMap with mappings from 611f291c8d5SSiddharth Bhat /// old functions (that come from the original module) to new functions 612f291c8d5SSiddharth Bhat /// (that are created within GPUModule). That way, we generate references 613f291c8d5SSiddharth Bhat /// to the correct function (in GPUModule) in BlockGenerator. 614f291c8d5SSiddharth Bhat /// 615f291c8d5SSiddharth Bhat /// @see IslNodeBuilder::ValueMap 616f291c8d5SSiddharth Bhat /// @see BlockGenerator::GlobalMap 617f291c8d5SSiddharth Bhat /// @see BlockGenerator::getNewValue 618f291c8d5SSiddharth Bhat /// @see GPUNodeBuilder::getReferencesInKernel. 619f291c8d5SSiddharth Bhat /// 620f291c8d5SSiddharth Bhat /// @param SubtreeFunctions The set of llvm::Functions referenced by 621f291c8d5SSiddharth Bhat /// this kernel. 622f291c8d5SSiddharth Bhat void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions); 623f291c8d5SSiddharth Bhat 624b513b491STobias Grosser /// Create a global-to-shared or shared-to-global copy statement. 625b513b491STobias Grosser /// 626b513b491STobias Grosser /// @param CopyStmt The copy statement to generate code for 627b513b491STobias Grosser void createKernelCopy(ppcg_kernel_stmt *CopyStmt); 628b513b491STobias Grosser 629edb885cbSTobias Grosser /// Create code for a ScopStmt called in @p Expr. 630edb885cbSTobias Grosser /// 631edb885cbSTobias Grosser /// @param Expr The expression containing the call. 632edb885cbSTobias Grosser /// @param KernelStmt The kernel statement referenced in the call. 633edb885cbSTobias Grosser void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt); 634edb885cbSTobias Grosser 6355260c041STobias Grosser /// Create an in-kernel synchronization call. 6365260c041STobias Grosser void createKernelSync(); 6375260c041STobias Grosser 63874dc3cb4STobias Grosser /// Create a PTX assembly string for the current GPU kernel. 63974dc3cb4STobias Grosser /// 64074dc3cb4STobias Grosser /// @returns A string containing the corresponding PTX assembly code. 64174dc3cb4STobias Grosser std::string createKernelASM(); 64274dc3cb4STobias Grosser 64374dc3cb4STobias Grosser /// Remove references from the dominator tree to the kernel function @p F. 64474dc3cb4STobias Grosser /// 64574dc3cb4STobias Grosser /// @param F The function to remove references to. 64674dc3cb4STobias Grosser void clearDominators(Function *F); 64774dc3cb4STobias Grosser 64874dc3cb4STobias Grosser /// Remove references from scalar evolution to the kernel function @p F. 64974dc3cb4STobias Grosser /// 65074dc3cb4STobias Grosser /// @param F The function to remove references to. 65174dc3cb4STobias Grosser void clearScalarEvolution(Function *F); 65274dc3cb4STobias Grosser 65374dc3cb4STobias Grosser /// Remove references from loop info to the kernel function @p F. 65474dc3cb4STobias Grosser /// 65574dc3cb4STobias Grosser /// @param F The function to remove references to. 65674dc3cb4STobias Grosser void clearLoops(Function *F); 65774dc3cb4STobias Grosser 6588fc6cdfbSTobias Grosser /// Check if the scop requires to be linked with CUDA's libdevice. 6598fc6cdfbSTobias Grosser bool requiresCUDALibDevice(); 6608fc6cdfbSTobias Grosser 6618fc6cdfbSTobias Grosser /// Link with the NVIDIA libdevice library (if needed and available). 6628fc6cdfbSTobias Grosser void addCUDALibDevice(); 6638fc6cdfbSTobias Grosser 66432837fe3STobias Grosser /// Finalize the generation of the kernel function. 66532837fe3STobias Grosser /// 66632837fe3STobias Grosser /// Free the LLVM-IR module corresponding to the kernel and -- if requested -- 66732837fe3STobias Grosser /// dump its IR to stderr. 66857793596STobias Grosser /// 66957793596STobias Grosser /// @returns The Assembly string of the kernel. 67057793596STobias Grosser std::string finalizeKernelFunction(); 671fa7b0802STobias Grosser 67251dfc275STobias Grosser /// Finalize the generation of the kernel arguments. 67351dfc275STobias Grosser /// 67451dfc275STobias Grosser /// This function ensures that not-read-only scalars used in a kernel are 675a6d48f59SMichael Kruse /// stored back to the global memory location they are backed with before 67651dfc275STobias Grosser /// the kernel terminates. 67751dfc275STobias Grosser /// 67851dfc275STobias Grosser /// @params Kernel The kernel to finalize kernel arguments for. 67951dfc275STobias Grosser void finalizeKernelArguments(ppcg_kernel *Kernel); 68051dfc275STobias Grosser 6817287aeddSTobias Grosser /// Create code that allocates memory to store arrays on device. 682fa7b0802STobias Grosser void allocateDeviceArrays(); 683fa7b0802STobias Grosser 684b99c1171STobias Grosser /// Create code to prepare the managed device pointers. 685b99c1171STobias Grosser void prepareManagedDeviceArrays(); 686b99c1171STobias Grosser 6877287aeddSTobias Grosser /// Free all allocated device arrays. 6887287aeddSTobias Grosser void freeDeviceArrays(); 6897287aeddSTobias Grosser 690fa7b0802STobias Grosser /// Create a call to initialize the GPU context. 691fa7b0802STobias Grosser /// 692fa7b0802STobias Grosser /// @returns A pointer to the newly initialized context. 693fa7b0802STobias Grosser Value *createCallInitContext(); 694fa7b0802STobias Grosser 69579a947c2STobias Grosser /// Create a call to get the device pointer for a kernel allocation. 69679a947c2STobias Grosser /// 69779a947c2STobias Grosser /// @param Allocation The Polly GPU allocation 69879a947c2STobias Grosser /// 69979a947c2STobias Grosser /// @returns The device parameter corresponding to this allocation. 70079a947c2STobias Grosser Value *createCallGetDevicePtr(Value *Allocation); 70179a947c2STobias Grosser 702fa7b0802STobias Grosser /// Create a call to free the GPU context. 703fa7b0802STobias Grosser /// 704fa7b0802STobias Grosser /// @param Context A pointer to an initialized GPU context. 705fa7b0802STobias Grosser void createCallFreeContext(Value *Context); 706fa7b0802STobias Grosser 7077287aeddSTobias Grosser /// Create a call to allocate memory on the device. 7087287aeddSTobias Grosser /// 7097287aeddSTobias Grosser /// @param Size The size of memory to allocate 7107287aeddSTobias Grosser /// 7117287aeddSTobias Grosser /// @returns A pointer that identifies this allocation. 712fa7b0802STobias Grosser Value *createCallAllocateMemoryForDevice(Value *Size); 7137287aeddSTobias Grosser 7147287aeddSTobias Grosser /// Create a call to free a device array. 7157287aeddSTobias Grosser /// 7167287aeddSTobias Grosser /// @param Array The device array to free. 7177287aeddSTobias Grosser void createCallFreeDeviceMemory(Value *Array); 71813c78e4dSTobias Grosser 71913c78e4dSTobias Grosser /// Create a call to copy data from host to device. 72013c78e4dSTobias Grosser /// 72113c78e4dSTobias Grosser /// @param HostPtr A pointer to the host data that should be copied. 72213c78e4dSTobias Grosser /// @param DevicePtr A device pointer specifying the location to copy to. 72313c78e4dSTobias Grosser void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr, 72413c78e4dSTobias Grosser Value *Size); 72513c78e4dSTobias Grosser 72613c78e4dSTobias Grosser /// Create a call to copy data from device to host. 72713c78e4dSTobias Grosser /// 72813c78e4dSTobias Grosser /// @param DevicePtr A pointer to the device data that should be copied. 72913c78e4dSTobias Grosser /// @param HostPtr A host pointer specifying the location to copy to. 73013c78e4dSTobias Grosser void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr, 73113c78e4dSTobias Grosser Value *Size); 73257793596STobias Grosser 733abed4969SSiddharth Bhat /// Create a call to synchronize Host & Device. 734abed4969SSiddharth Bhat /// \note 735abed4969SSiddharth Bhat /// This is to be used only with managed memory. 736abed4969SSiddharth Bhat void createCallSynchronizeDevice(); 737abed4969SSiddharth Bhat 73857793596STobias Grosser /// Create a call to get a kernel from an assembly string. 73957793596STobias Grosser /// 74057793596STobias Grosser /// @param Buffer The string describing the kernel. 74157793596STobias Grosser /// @param Entry The name of the kernel function to call. 74257793596STobias Grosser /// 74357793596STobias Grosser /// @returns A pointer to a kernel object 74457793596STobias Grosser Value *createCallGetKernel(Value *Buffer, Value *Entry); 74557793596STobias Grosser 74657793596STobias Grosser /// Create a call to free a GPU kernel. 74757793596STobias Grosser /// 74857793596STobias Grosser /// @param GPUKernel THe kernel to free. 74957793596STobias Grosser void createCallFreeKernel(Value *GPUKernel); 75079a947c2STobias Grosser 75179a947c2STobias Grosser /// Create a call to launch a GPU kernel. 75279a947c2STobias Grosser /// 75379a947c2STobias Grosser /// @param GPUKernel The kernel to launch. 75479a947c2STobias Grosser /// @param GridDimX The size of the first grid dimension. 75579a947c2STobias Grosser /// @param GridDimY The size of the second grid dimension. 75679a947c2STobias Grosser /// @param GridBlockX The size of the first block dimension. 75779a947c2STobias Grosser /// @param GridBlockY The size of the second block dimension. 75879a947c2STobias Grosser /// @param GridBlockZ The size of the third block dimension. 759a6d48f59SMichael Kruse /// @param Parameters A pointer to an array that contains itself pointers to 76079a947c2STobias Grosser /// the parameter values passed for each kernel argument. 76179a947c2STobias Grosser void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 76279a947c2STobias Grosser Value *GridDimY, Value *BlockDimX, 76379a947c2STobias Grosser Value *BlockDimY, Value *BlockDimZ, 76479a947c2STobias Grosser Value *Parameters); 7651fb9b64dSTobias Grosser }; 7661fb9b64dSTobias Grosser 76779f13b9aSSingapuram Sanjay Srivallabh std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) { 7681abd9ffaSSingapuram Sanjay Srivallabh return "FUNC_" + S.getFunction().getName().str() + "_SCOP_" + 7691abd9ffaSSingapuram Sanjay Srivallabh std::to_string(S.getID()) + "_KERNEL_" + std::to_string(Kernel_id); 77079f13b9aSSingapuram Sanjay Srivallabh } 77179f13b9aSSingapuram Sanjay Srivallabh 772fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() { 773750160e2STobias Grosser BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(), 774750160e2STobias Grosser &*Builder.GetInsertPoint(), &DT, &LI); 775750160e2STobias Grosser NewBB->setName("polly.acc.initialize"); 776750160e2STobias Grosser Builder.SetInsertPoint(&NewBB->front()); 777750160e2STobias Grosser 778fa7b0802STobias Grosser GPUContext = createCallInitContext(); 779abed4969SSiddharth Bhat 780c4a4af47SSiddharth Bhat if (!PollyManagedMemory) 781fa7b0802STobias Grosser allocateDeviceArrays(); 782b99c1171STobias Grosser else 783b99c1171STobias Grosser prepareManagedDeviceArrays(); 784fa7b0802STobias Grosser } 785fa7b0802STobias Grosser 786fa7b0802STobias Grosser void GPUNodeBuilder::finalize() { 787c4a4af47SSiddharth Bhat if (!PollyManagedMemory) 7887287aeddSTobias Grosser freeDeviceArrays(); 789abed4969SSiddharth Bhat 790fa7b0802STobias Grosser createCallFreeContext(GPUContext); 791fa7b0802STobias Grosser IslNodeBuilder::finalize(); 792fa7b0802STobias Grosser } 793fa7b0802STobias Grosser 794fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() { 795c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && 796c4a4af47SSiddharth Bhat "Managed memory will directly send host pointers " 797abed4969SSiddharth Bhat "to the kernel. There is no need for device arrays"); 7988ea1fc19STobias Grosser isl_ast_build *Build = isl_ast_build_from_context(S.getContext().release()); 799fa7b0802STobias Grosser 800fa7b0802STobias Grosser for (int i = 0; i < Prog->n_array; ++i) { 801fa7b0802STobias Grosser gpu_array_info *Array = &Prog->array[i]; 80213c78e4dSTobias Grosser auto *ScopArray = (ScopArrayInfo *)Array->user; 8037287aeddSTobias Grosser std::string DevArrayName("p_dev_array_"); 8047287aeddSTobias Grosser DevArrayName.append(Array->name); 805fa7b0802STobias Grosser 80613c78e4dSTobias Grosser Value *ArraySize = getArraySize(Array); 807aaabbbf8STobias Grosser Value *Offset = getArrayOffset(Array); 808aaabbbf8STobias Grosser if (Offset) 809aaabbbf8STobias Grosser ArraySize = Builder.CreateSub( 810aaabbbf8STobias Grosser ArraySize, 811aaabbbf8STobias Grosser Builder.CreateMul(Offset, 812aaabbbf8STobias Grosser Builder.getInt64(ScopArray->getElemSizeInBytes()))); 81334eeabbcSSiddharth Bhat const SCEV *SizeSCEV = SE.getSCEV(ArraySize); 81434eeabbcSSiddharth Bhat // It makes no sense to have an array of size 0. The CUDA API will 81534eeabbcSSiddharth Bhat // throw an error anyway if we invoke `cuMallocManaged` with size `0`. We 81634eeabbcSSiddharth Bhat // choose to be defensive and catch this at the compile phase. It is 81734eeabbcSSiddharth Bhat // most likely that we are doing something wrong with size computation. 81834eeabbcSSiddharth Bhat if (SizeSCEV->isZero()) { 81934eeabbcSSiddharth Bhat errs() << getUniqueScopName(&S) 82034eeabbcSSiddharth Bhat << " has computed array size 0: " << *ArraySize 82134eeabbcSSiddharth Bhat << " | for array: " << *(ScopArray->getBasePtr()) 82234eeabbcSSiddharth Bhat << ". This is illegal, exiting.\n"; 82334eeabbcSSiddharth Bhat report_fatal_error("array size was computed to be 0"); 82434eeabbcSSiddharth Bhat } 82534eeabbcSSiddharth Bhat 8267287aeddSTobias Grosser Value *DevArray = createCallAllocateMemoryForDevice(ArraySize); 8277287aeddSTobias Grosser DevArray->setName(DevArrayName); 82813c78e4dSTobias Grosser DeviceAllocations[ScopArray] = DevArray; 829fa7b0802STobias Grosser } 830fa7b0802STobias Grosser 831fa7b0802STobias Grosser isl_ast_build_free(Build); 832fa7b0802STobias Grosser } 833fa7b0802STobias Grosser 834b99c1171STobias Grosser void GPUNodeBuilder::prepareManagedDeviceArrays() { 835c4a4af47SSiddharth Bhat assert(PollyManagedMemory && 836b99c1171STobias Grosser "Device array most only be prepared in managed-memory mode"); 837b99c1171STobias Grosser for (int i = 0; i < Prog->n_array; ++i) { 838b99c1171STobias Grosser gpu_array_info *Array = &Prog->array[i]; 839b99c1171STobias Grosser ScopArrayInfo *ScopArray = (ScopArrayInfo *)Array->user; 840b99c1171STobias Grosser Value *HostPtr; 841b99c1171STobias Grosser 842b99c1171STobias Grosser if (gpu_array_is_scalar(Array)) 843b99c1171STobias Grosser HostPtr = BlockGen.getOrCreateAlloca(ScopArray); 844b99c1171STobias Grosser else 845b99c1171STobias Grosser HostPtr = ScopArray->getBasePtr(); 846b99c1171STobias Grosser HostPtr = getLatestValue(HostPtr); 847b99c1171STobias Grosser 848b99c1171STobias Grosser Value *Offset = getArrayOffset(Array); 849b99c1171STobias Grosser if (Offset) { 850b99c1171STobias Grosser HostPtr = Builder.CreatePointerCast( 851b99c1171STobias Grosser HostPtr, ScopArray->getElementType()->getPointerTo()); 8520ce9acf6SEli Friedman HostPtr = Builder.CreateGEP(ScopArray->getElementType(), HostPtr, Offset); 853b99c1171STobias Grosser } 854b99c1171STobias Grosser 855b99c1171STobias Grosser HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 856b99c1171STobias Grosser DeviceAllocations[ScopArray] = HostPtr; 857b99c1171STobias Grosser } 858b99c1171STobias Grosser } 859b99c1171STobias Grosser 860c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX, 861c1c6a2a6STobias Grosser Value *BlockDimY, Value *BlockDimZ) { 862c1c6a2a6STobias Grosser auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations"); 863c1c6a2a6STobias Grosser 864c1c6a2a6STobias Grosser for (auto &F : *M) { 865c1c6a2a6STobias Grosser if (F.getCallingConv() != CallingConv::PTX_Kernel) 866c1c6a2a6STobias Grosser continue; 867c1c6a2a6STobias Grosser 868c1c6a2a6STobias Grosser Value *V[] = {BlockDimX, BlockDimY, BlockDimZ}; 869c1c6a2a6STobias Grosser 870c1c6a2a6STobias Grosser Metadata *Elements[] = { 871c1c6a2a6STobias Grosser ValueAsMetadata::get(&F), MDString::get(M->getContext(), "maxntidx"), 872c1c6a2a6STobias Grosser ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"), 873c1c6a2a6STobias Grosser ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"), 874c1c6a2a6STobias Grosser ValueAsMetadata::get(V[2]), 875c1c6a2a6STobias Grosser }; 876c1c6a2a6STobias Grosser MDNode *Node = MDNode::get(M->getContext(), Elements); 877c1c6a2a6STobias Grosser AnnotationNode->addOperand(Node); 878c1c6a2a6STobias Grosser } 879c1c6a2a6STobias Grosser } 880c1c6a2a6STobias Grosser 8817287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() { 882c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && "Managed memory does not use device arrays"); 88313c78e4dSTobias Grosser for (auto &Array : DeviceAllocations) 88413c78e4dSTobias Grosser createCallFreeDeviceMemory(Array.second); 8857287aeddSTobias Grosser } 8867287aeddSTobias Grosser 88757793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) { 88857793596STobias Grosser const char *Name = "polly_getKernel"; 88957793596STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 89057793596STobias Grosser Function *F = M->getFunction(Name); 89157793596STobias Grosser 89257793596STobias Grosser // If F is not available, declare it. 89357793596STobias Grosser if (!F) { 89457793596STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 89557793596STobias Grosser std::vector<Type *> Args; 89657793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 89757793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 89857793596STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 89957793596STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 90057793596STobias Grosser } 90157793596STobias Grosser 90257793596STobias Grosser return Builder.CreateCall(F, {Buffer, Entry}); 90357793596STobias Grosser } 90457793596STobias Grosser 90579a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) { 90679a947c2STobias Grosser const char *Name = "polly_getDevicePtr"; 90779a947c2STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 90879a947c2STobias Grosser Function *F = M->getFunction(Name); 90979a947c2STobias Grosser 91079a947c2STobias Grosser // If F is not available, declare it. 91179a947c2STobias Grosser if (!F) { 91279a947c2STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 91379a947c2STobias Grosser std::vector<Type *> Args; 91479a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 91579a947c2STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 91679a947c2STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 91779a947c2STobias Grosser } 91879a947c2STobias Grosser 91979a947c2STobias Grosser return Builder.CreateCall(F, {Allocation}); 92079a947c2STobias Grosser } 92179a947c2STobias Grosser 92279a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 92379a947c2STobias Grosser Value *GridDimY, Value *BlockDimX, 92479a947c2STobias Grosser Value *BlockDimY, Value *BlockDimZ, 92579a947c2STobias Grosser Value *Parameters) { 92679a947c2STobias Grosser const char *Name = "polly_launchKernel"; 92779a947c2STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 92879a947c2STobias Grosser Function *F = M->getFunction(Name); 92979a947c2STobias Grosser 93079a947c2STobias Grosser // If F is not available, declare it. 93179a947c2STobias Grosser if (!F) { 93279a947c2STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 93379a947c2STobias Grosser std::vector<Type *> Args; 93479a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 93579a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 93679a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 93779a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 93879a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 93979a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 94079a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 94179a947c2STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 94279a947c2STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 94379a947c2STobias Grosser } 94479a947c2STobias Grosser 945ff40087aSTobias Grosser Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 94679a947c2STobias Grosser BlockDimZ, Parameters}); 94779a947c2STobias Grosser } 94879a947c2STobias Grosser 94957793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) { 95057793596STobias Grosser const char *Name = "polly_freeKernel"; 95157793596STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 95257793596STobias Grosser Function *F = M->getFunction(Name); 95357793596STobias Grosser 95457793596STobias Grosser // If F is not available, declare it. 95557793596STobias Grosser if (!F) { 95657793596STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 95757793596STobias Grosser std::vector<Type *> Args; 95857793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 95957793596STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 96057793596STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 96157793596STobias Grosser } 96257793596STobias Grosser 96357793596STobias Grosser Builder.CreateCall(F, {GPUKernel}); 96457793596STobias Grosser } 96557793596STobias Grosser 9667287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) { 967c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && 968c4a4af47SSiddharth Bhat "Managed memory does not allocate or free memory " 969abed4969SSiddharth Bhat "for device"); 9707287aeddSTobias Grosser const char *Name = "polly_freeDeviceMemory"; 9717287aeddSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 9727287aeddSTobias Grosser Function *F = M->getFunction(Name); 9737287aeddSTobias Grosser 9747287aeddSTobias Grosser // If F is not available, declare it. 9757287aeddSTobias Grosser if (!F) { 9767287aeddSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 9777287aeddSTobias Grosser std::vector<Type *> Args; 9787287aeddSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 9797287aeddSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 9807287aeddSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 9817287aeddSTobias Grosser } 9827287aeddSTobias Grosser 9837287aeddSTobias Grosser Builder.CreateCall(F, {Array}); 9847287aeddSTobias Grosser } 9857287aeddSTobias Grosser 986fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) { 987c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && 988c4a4af47SSiddharth Bhat "Managed memory does not allocate or free memory " 989abed4969SSiddharth Bhat "for device"); 990fa7b0802STobias Grosser const char *Name = "polly_allocateMemoryForDevice"; 991fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 992fa7b0802STobias Grosser Function *F = M->getFunction(Name); 993fa7b0802STobias Grosser 994fa7b0802STobias Grosser // If F is not available, declare it. 995fa7b0802STobias Grosser if (!F) { 996fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 997fa7b0802STobias Grosser std::vector<Type *> Args; 998fa7b0802STobias Grosser Args.push_back(Builder.getInt64Ty()); 999fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 1000fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 1001fa7b0802STobias Grosser } 1002fa7b0802STobias Grosser 1003fa7b0802STobias Grosser return Builder.CreateCall(F, {Size}); 1004fa7b0802STobias Grosser } 1005fa7b0802STobias Grosser 100613c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData, 100713c78e4dSTobias Grosser Value *DeviceData, 100813c78e4dSTobias Grosser Value *Size) { 1009c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && 1010c4a4af47SSiddharth Bhat "Managed memory does not transfer memory between " 1011abed4969SSiddharth Bhat "device and host"); 101213c78e4dSTobias Grosser const char *Name = "polly_copyFromHostToDevice"; 101313c78e4dSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 101413c78e4dSTobias Grosser Function *F = M->getFunction(Name); 101513c78e4dSTobias Grosser 101613c78e4dSTobias Grosser // If F is not available, declare it. 101713c78e4dSTobias Grosser if (!F) { 101813c78e4dSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 101913c78e4dSTobias Grosser std::vector<Type *> Args; 102013c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 102113c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 102213c78e4dSTobias Grosser Args.push_back(Builder.getInt64Ty()); 102313c78e4dSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 102413c78e4dSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 102513c78e4dSTobias Grosser } 102613c78e4dSTobias Grosser 102713c78e4dSTobias Grosser Builder.CreateCall(F, {HostData, DeviceData, Size}); 102813c78e4dSTobias Grosser } 102913c78e4dSTobias Grosser 103013c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData, 103113c78e4dSTobias Grosser Value *HostData, 103213c78e4dSTobias Grosser Value *Size) { 1033c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && 1034c4a4af47SSiddharth Bhat "Managed memory does not transfer memory between " 1035abed4969SSiddharth Bhat "device and host"); 103613c78e4dSTobias Grosser const char *Name = "polly_copyFromDeviceToHost"; 103713c78e4dSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 103813c78e4dSTobias Grosser Function *F = M->getFunction(Name); 103913c78e4dSTobias Grosser 104013c78e4dSTobias Grosser // If F is not available, declare it. 104113c78e4dSTobias Grosser if (!F) { 104213c78e4dSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 104313c78e4dSTobias Grosser std::vector<Type *> Args; 104413c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 104513c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 104613c78e4dSTobias Grosser Args.push_back(Builder.getInt64Ty()); 104713c78e4dSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 104813c78e4dSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 104913c78e4dSTobias Grosser } 105013c78e4dSTobias Grosser 105113c78e4dSTobias Grosser Builder.CreateCall(F, {DeviceData, HostData, Size}); 105213c78e4dSTobias Grosser } 105313c78e4dSTobias Grosser 1054abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() { 1055c4a4af47SSiddharth Bhat assert(PollyManagedMemory && "explicit synchronization is only necessary for " 1056abed4969SSiddharth Bhat "managed memory"); 1057abed4969SSiddharth Bhat const char *Name = "polly_synchronizeDevice"; 1058abed4969SSiddharth Bhat Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1059abed4969SSiddharth Bhat Function *F = M->getFunction(Name); 1060abed4969SSiddharth Bhat 1061abed4969SSiddharth Bhat // If F is not available, declare it. 1062abed4969SSiddharth Bhat if (!F) { 1063abed4969SSiddharth Bhat GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 1064abed4969SSiddharth Bhat FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false); 1065abed4969SSiddharth Bhat F = Function::Create(Ty, Linkage, Name, M); 1066abed4969SSiddharth Bhat } 1067abed4969SSiddharth Bhat 1068abed4969SSiddharth Bhat Builder.CreateCall(F); 1069abed4969SSiddharth Bhat } 1070abed4969SSiddharth Bhat 1071fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() { 107217f01968SSiddharth Bhat const char *Name; 107317f01968SSiddharth Bhat 107417f01968SSiddharth Bhat switch (Runtime) { 107517f01968SSiddharth Bhat case GPURuntime::CUDA: 107617f01968SSiddharth Bhat Name = "polly_initContextCUDA"; 107717f01968SSiddharth Bhat break; 107817f01968SSiddharth Bhat case GPURuntime::OpenCL: 107917f01968SSiddharth Bhat Name = "polly_initContextCL"; 108017f01968SSiddharth Bhat break; 108117f01968SSiddharth Bhat } 108217f01968SSiddharth Bhat 1083fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1084fa7b0802STobias Grosser Function *F = M->getFunction(Name); 1085fa7b0802STobias Grosser 1086fa7b0802STobias Grosser // If F is not available, declare it. 1087fa7b0802STobias Grosser if (!F) { 1088fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 1089fa7b0802STobias Grosser std::vector<Type *> Args; 1090fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 1091fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 1092fa7b0802STobias Grosser } 1093fa7b0802STobias Grosser 1094fa7b0802STobias Grosser return Builder.CreateCall(F, {}); 1095fa7b0802STobias Grosser } 1096fa7b0802STobias Grosser 1097fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) { 1098fa7b0802STobias Grosser const char *Name = "polly_freeContext"; 1099fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1100fa7b0802STobias Grosser Function *F = M->getFunction(Name); 1101fa7b0802STobias Grosser 1102fa7b0802STobias Grosser // If F is not available, declare it. 1103fa7b0802STobias Grosser if (!F) { 1104fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 1105fa7b0802STobias Grosser std::vector<Type *> Args; 1106fa7b0802STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 1107fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 1108fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 1109fa7b0802STobias Grosser } 1110fa7b0802STobias Grosser 1111fa7b0802STobias Grosser Builder.CreateCall(F, {Context}); 1112fa7b0802STobias Grosser } 1113fa7b0802STobias Grosser 11145260c041STobias Grosser /// Check if one string is a prefix of another. 11155260c041STobias Grosser /// 11165260c041STobias Grosser /// @param String The string in which to look for the prefix. 11175260c041STobias Grosser /// @param Prefix The prefix to look for. 11185260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) { 11195260c041STobias Grosser return String.find(Prefix) == 0; 11205260c041STobias Grosser } 11215260c041STobias Grosser 112213c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) { 1123b65ccc43STobias Grosser isl::ast_build Build = isl::ast_build::from_context(S.getContext()); 112413c78e4dSTobias Grosser Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size); 112513c78e4dSTobias Grosser 112613c78e4dSTobias Grosser if (!gpu_array_is_scalar(Array)) { 1127718d04c6STobias Grosser isl::multi_pw_aff ArrayBound = isl::manage_copy(Array->bound); 1128f7face4bSSiddharth Bhat 1129d3fdbda6SRiccardo Mori isl::pw_aff OffsetDimZero = ArrayBound.at(0); 1130f7face4bSSiddharth Bhat isl::ast_expr Res = Build.expr_from(OffsetDimZero); 113113c78e4dSTobias Grosser 113213c78e4dSTobias Grosser for (unsigned int i = 1; i < Array->n_index; i++) { 1133d3fdbda6SRiccardo Mori isl::pw_aff Bound_I = ArrayBound.at(i); 1134f7face4bSSiddharth Bhat isl::ast_expr Expr = Build.expr_from(Bound_I); 1135f7face4bSSiddharth Bhat Res = Res.mul(Expr); 113613c78e4dSTobias Grosser } 113713c78e4dSTobias Grosser 1138f7face4bSSiddharth Bhat Value *NumElements = ExprBuilder.create(Res.release()); 1139b79f4d39STobias Grosser if (NumElements->getType() != ArraySize->getType()) 1140b79f4d39STobias Grosser NumElements = Builder.CreateSExt(NumElements, ArraySize->getType()); 114113c78e4dSTobias Grosser ArraySize = Builder.CreateMul(ArraySize, NumElements); 114213c78e4dSTobias Grosser } 114313c78e4dSTobias Grosser return ArraySize; 114413c78e4dSTobias Grosser } 114513c78e4dSTobias Grosser 1146aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) { 1147aaabbbf8STobias Grosser if (gpu_array_is_scalar(Array)) 1148aaabbbf8STobias Grosser return nullptr; 1149aaabbbf8STobias Grosser 1150b65ccc43STobias Grosser isl::ast_build Build = isl::ast_build::from_context(S.getContext()); 1151aaabbbf8STobias Grosser 1152718d04c6STobias Grosser isl::set Min = isl::manage_copy(Array->extent).lexmin(); 1153aaabbbf8STobias Grosser 1154ccbf4b50SSiddharth Bhat isl::set ZeroSet = isl::set::universe(Min.get_space()); 1155aaabbbf8STobias Grosser 115644596fe6SRiccardo Mori for (unsigned i : rangeIslSize(0, Min.tuple_dim())) 1157ccbf4b50SSiddharth Bhat ZeroSet = ZeroSet.fix_si(isl::dim::set, i, 0); 1158aaabbbf8STobias Grosser 1159ccbf4b50SSiddharth Bhat if (Min.is_subset(ZeroSet)) { 1160aaabbbf8STobias Grosser return nullptr; 1161aaabbbf8STobias Grosser } 1162aaabbbf8STobias Grosser 11630813bd16SRiccardo Mori isl::ast_expr Result = isl::ast_expr::from_val(isl::val(Min.ctx(), 0)); 1164aaabbbf8STobias Grosser 116544596fe6SRiccardo Mori for (unsigned i : rangeIslSize(0, Min.tuple_dim())) { 1166aaabbbf8STobias Grosser if (i > 0) { 1167ccbf4b50SSiddharth Bhat isl::pw_aff Bound_I = 1168ccbf4b50SSiddharth Bhat isl::manage(isl_multi_pw_aff_get_pw_aff(Array->bound, i - 1)); 1169ccbf4b50SSiddharth Bhat isl::ast_expr BExpr = Build.expr_from(Bound_I); 1170ccbf4b50SSiddharth Bhat Result = Result.mul(BExpr); 1171aaabbbf8STobias Grosser } 1172ccbf4b50SSiddharth Bhat isl::pw_aff DimMin = Min.dim_min(i); 1173ccbf4b50SSiddharth Bhat isl::ast_expr MExpr = Build.expr_from(DimMin); 1174ccbf4b50SSiddharth Bhat Result = Result.add(MExpr); 1175aaabbbf8STobias Grosser } 1176aaabbbf8STobias Grosser 1177ccbf4b50SSiddharth Bhat return ExprBuilder.create(Result.release()); 1178aaabbbf8STobias Grosser } 1179aaabbbf8STobias Grosser 1180b99c1171STobias Grosser Value *GPUNodeBuilder::getManagedDeviceArray(gpu_array_info *Array, 1181abed4969SSiddharth Bhat ScopArrayInfo *ArrayInfo) { 1182c4a4af47SSiddharth Bhat assert(PollyManagedMemory && "Only used when you wish to get a host " 1183abed4969SSiddharth Bhat "pointer for sending data to the kernel, " 1184abed4969SSiddharth Bhat "with managed memory"); 1185abed4969SSiddharth Bhat std::map<ScopArrayInfo *, Value *>::iterator it; 1186b99c1171STobias Grosser it = DeviceAllocations.find(ArrayInfo); 1187b99c1171STobias Grosser assert(it != DeviceAllocations.end() && 1188b99c1171STobias Grosser "Device array expected to be available"); 1189abed4969SSiddharth Bhat return it->second; 1190abed4969SSiddharth Bhat } 1191abed4969SSiddharth Bhat 119213c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt, 119313c78e4dSTobias Grosser enum DataDirection Direction) { 1194c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && "Managed memory needs no data transfers"); 119513c78e4dSTobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt); 119613c78e4dSTobias Grosser isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0); 119713c78e4dSTobias Grosser isl_id *Id = isl_ast_expr_get_id(Arg); 119813c78e4dSTobias Grosser auto Array = (gpu_array_info *)isl_id_get_user(Id); 119913c78e4dSTobias Grosser auto ScopArray = (ScopArrayInfo *)(Array->user); 120013c78e4dSTobias Grosser 120113c78e4dSTobias Grosser Value *Size = getArraySize(Array); 1202aaabbbf8STobias Grosser Value *Offset = getArrayOffset(Array); 120313c78e4dSTobias Grosser Value *DevPtr = DeviceAllocations[ScopArray]; 120413c78e4dSTobias Grosser 1205b06ff457STobias Grosser Value *HostPtr; 1206b06ff457STobias Grosser 1207b06ff457STobias Grosser if (gpu_array_is_scalar(Array)) 1208b06ff457STobias Grosser HostPtr = BlockGen.getOrCreateAlloca(ScopArray); 1209b06ff457STobias Grosser else 1210b06ff457STobias Grosser HostPtr = ScopArray->getBasePtr(); 1211edf9581eSSiddharth Bhat HostPtr = getLatestValue(HostPtr); 121213c78e4dSTobias Grosser 1213aaabbbf8STobias Grosser if (Offset) { 1214aaabbbf8STobias Grosser HostPtr = Builder.CreatePointerCast( 1215aaabbbf8STobias Grosser HostPtr, ScopArray->getElementType()->getPointerTo()); 12160ce9acf6SEli Friedman HostPtr = Builder.CreateGEP(ScopArray->getElementType(), HostPtr, Offset); 1217aaabbbf8STobias Grosser } 1218aaabbbf8STobias Grosser 121913c78e4dSTobias Grosser HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 122013c78e4dSTobias Grosser 1221aaabbbf8STobias Grosser if (Offset) { 1222aaabbbf8STobias Grosser Size = Builder.CreateSub( 1223ff40087aSTobias Grosser Size, Builder.CreateMul( 1224ff40087aSTobias Grosser Offset, Builder.getInt64(ScopArray->getElemSizeInBytes()))); 1225aaabbbf8STobias Grosser } 1226aaabbbf8STobias Grosser 122713c78e4dSTobias Grosser if (Direction == HOST_TO_DEVICE) 122813c78e4dSTobias Grosser createCallCopyFromHostToDevice(HostPtr, DevPtr, Size); 122913c78e4dSTobias Grosser else 123013c78e4dSTobias Grosser createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size); 123113c78e4dSTobias Grosser 123213c78e4dSTobias Grosser isl_id_free(Id); 123313c78e4dSTobias Grosser isl_ast_expr_free(Arg); 123413c78e4dSTobias Grosser isl_ast_expr_free(Expr); 123513c78e4dSTobias Grosser isl_ast_node_free(TransferStmt); 123613c78e4dSTobias Grosser } 123713c78e4dSTobias Grosser 12381fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) { 123932837fe3STobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt); 124032837fe3STobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 124132837fe3STobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr); 124232837fe3STobias Grosser isl_id_free(Id); 124332837fe3STobias Grosser isl_ast_expr_free(StmtExpr); 124432837fe3STobias Grosser 124532837fe3STobias Grosser const char *Str = isl_id_get_name(Id); 124632837fe3STobias Grosser if (!strcmp(Str, "kernel")) { 124732837fe3STobias Grosser createKernel(UserStmt); 124862acb344STobias Grosser if (PollyManagedMemory) 124962acb344STobias Grosser createCallSynchronizeDevice(); 125032837fe3STobias Grosser isl_ast_expr_free(Expr); 125132837fe3STobias Grosser return; 125232837fe3STobias Grosser } 12539e3db2b7SSiddharth Bhat if (!strcmp(Str, "init_device")) { 12549e3db2b7SSiddharth Bhat initializeAfterRTH(); 12559e3db2b7SSiddharth Bhat isl_ast_node_free(UserStmt); 12569e3db2b7SSiddharth Bhat isl_ast_expr_free(Expr); 12579e3db2b7SSiddharth Bhat return; 12589e3db2b7SSiddharth Bhat } 12599e3db2b7SSiddharth Bhat if (!strcmp(Str, "clear_device")) { 12609e3db2b7SSiddharth Bhat finalize(); 12619e3db2b7SSiddharth Bhat isl_ast_node_free(UserStmt); 12629e3db2b7SSiddharth Bhat isl_ast_expr_free(Expr); 12639e3db2b7SSiddharth Bhat return; 12649e3db2b7SSiddharth Bhat } 126513c78e4dSTobias Grosser if (isPrefix(Str, "to_device")) { 1266c4a4af47SSiddharth Bhat if (!PollyManagedMemory) 126713c78e4dSTobias Grosser createDataTransfer(UserStmt, HOST_TO_DEVICE); 1268abed4969SSiddharth Bhat else 1269abed4969SSiddharth Bhat isl_ast_node_free(UserStmt); 1270abed4969SSiddharth Bhat 127132837fe3STobias Grosser isl_ast_expr_free(Expr); 127213c78e4dSTobias Grosser return; 127313c78e4dSTobias Grosser } 127413c78e4dSTobias Grosser 127513c78e4dSTobias Grosser if (isPrefix(Str, "from_device")) { 1276c4a4af47SSiddharth Bhat if (!PollyManagedMemory) { 127713c78e4dSTobias Grosser createDataTransfer(UserStmt, DEVICE_TO_HOST); 1278abed4969SSiddharth Bhat } else { 1279abed4969SSiddharth Bhat isl_ast_node_free(UserStmt); 1280abed4969SSiddharth Bhat } 128113c78e4dSTobias Grosser isl_ast_expr_free(Expr); 128238fc0aedSTobias Grosser return; 128338fc0aedSTobias Grosser } 128438fc0aedSTobias Grosser 12855260c041STobias Grosser isl_id *Anno = isl_ast_node_get_annotation(UserStmt); 12865260c041STobias Grosser struct ppcg_kernel_stmt *KernelStmt = 12875260c041STobias Grosser (struct ppcg_kernel_stmt *)isl_id_get_user(Anno); 12885260c041STobias Grosser isl_id_free(Anno); 12895260c041STobias Grosser 12905260c041STobias Grosser switch (KernelStmt->type) { 12915260c041STobias Grosser case ppcg_kernel_domain: 1292edb885cbSTobias Grosser createScopStmt(Expr, KernelStmt); 12935260c041STobias Grosser isl_ast_node_free(UserStmt); 12945260c041STobias Grosser return; 12955260c041STobias Grosser case ppcg_kernel_copy: 1296b513b491STobias Grosser createKernelCopy(KernelStmt); 12975260c041STobias Grosser isl_ast_expr_free(Expr); 12985260c041STobias Grosser isl_ast_node_free(UserStmt); 12995260c041STobias Grosser return; 13005260c041STobias Grosser case ppcg_kernel_sync: 13015260c041STobias Grosser createKernelSync(); 13025260c041STobias Grosser isl_ast_expr_free(Expr); 13035260c041STobias Grosser isl_ast_node_free(UserStmt); 13045260c041STobias Grosser return; 13055260c041STobias Grosser } 13065260c041STobias Grosser 13075260c041STobias Grosser isl_ast_expr_free(Expr); 13085260c041STobias Grosser isl_ast_node_free(UserStmt); 13095260c041STobias Grosser } 131053c80387SPhilip Pfaffe 131153c80387SPhilip Pfaffe void GPUNodeBuilder::createFor(__isl_take isl_ast_node *Node) { 1312d3fdbda6SRiccardo Mori createForSequential(isl::manage(Node).as<isl::ast_node_for>(), false); 131353c80387SPhilip Pfaffe } 131453c80387SPhilip Pfaffe 1315b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) { 1316b513b491STobias Grosser isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index); 1317b513b491STobias Grosser LocalIndex = isl_ast_expr_address_of(LocalIndex); 1318b513b491STobias Grosser Value *LocalAddr = ExprBuilder.create(LocalIndex); 1319b513b491STobias Grosser isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index); 1320b513b491STobias Grosser Index = isl_ast_expr_address_of(Index); 1321b513b491STobias Grosser Value *GlobalAddr = ExprBuilder.create(Index); 1322ee423d93SNikita Popov Type *IndexTy = GlobalAddr->getType()->getPointerElementType(); 1323b513b491STobias Grosser 1324b513b491STobias Grosser if (KernelStmt->u.c.read) { 13259c486eb3SMichael Kruse LoadInst *Load = Builder.CreateLoad(IndexTy, GlobalAddr, "shared.read"); 1326b513b491STobias Grosser Builder.CreateStore(Load, LocalAddr); 1327b513b491STobias Grosser } else { 13289c486eb3SMichael Kruse LoadInst *Load = Builder.CreateLoad(IndexTy, LocalAddr, "shared.write"); 1329b513b491STobias Grosser Builder.CreateStore(Load, GlobalAddr); 1330b513b491STobias Grosser } 1331b513b491STobias Grosser } 13325260c041STobias Grosser 1333edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr, 1334edb885cbSTobias Grosser ppcg_kernel_stmt *KernelStmt) { 1335edb885cbSTobias Grosser auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1336edb885cbSTobias Grosser isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr; 1337edb885cbSTobias Grosser 1338edb885cbSTobias Grosser LoopToScevMapT LTS; 1339edb885cbSTobias Grosser LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end()); 1340edb885cbSTobias Grosser 1341edb885cbSTobias Grosser createSubstitutions(Expr, Stmt, LTS); 1342edb885cbSTobias Grosser 1343edb885cbSTobias Grosser if (Stmt->isBlockStmt()) 1344edb885cbSTobias Grosser BlockGen.copyStmt(*Stmt, LTS, Indexes); 1345edb885cbSTobias Grosser else 1346a82c4b5dSTobias Grosser RegionGen.copyStmt(*Stmt, LTS, Indexes); 1347edb885cbSTobias Grosser } 1348edb885cbSTobias Grosser 13495260c041STobias Grosser void GPUNodeBuilder::createKernelSync() { 13505260c041STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13512f3073b5SPhilipp Schaad const char *SpirName = "__gen_ocl_barrier_global"; 135217f01968SSiddharth Bhat 135317f01968SSiddharth Bhat Function *Sync; 135417f01968SSiddharth Bhat 135517f01968SSiddharth Bhat switch (Arch) { 13562f3073b5SPhilipp Schaad case GPUArch::SPIR64: 13572f3073b5SPhilipp Schaad case GPUArch::SPIR32: 13582f3073b5SPhilipp Schaad Sync = M->getFunction(SpirName); 13592f3073b5SPhilipp Schaad 13602f3073b5SPhilipp Schaad // If Sync is not available, declare it. 13612f3073b5SPhilipp Schaad if (!Sync) { 13622f3073b5SPhilipp Schaad GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 13632f3073b5SPhilipp Schaad std::vector<Type *> Args; 13642f3073b5SPhilipp Schaad FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 13652f3073b5SPhilipp Schaad Sync = Function::Create(Ty, Linkage, SpirName, M); 13662f3073b5SPhilipp Schaad Sync->setCallingConv(CallingConv::SPIR_FUNC); 13672f3073b5SPhilipp Schaad } 13682f3073b5SPhilipp Schaad break; 136917f01968SSiddharth Bhat case GPUArch::NVPTX64: 137017f01968SSiddharth Bhat Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0); 137117f01968SSiddharth Bhat break; 137217f01968SSiddharth Bhat } 137317f01968SSiddharth Bhat 13745260c041STobias Grosser Builder.CreateCall(Sync, {}); 13755260c041STobias Grosser } 13765260c041STobias Grosser 1377edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node 1378edb885cbSTobias Grosser /// 1379edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring 1380edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore. 1381edb885cbSTobias Grosser /// 1382edb885cbSTobias Grosser /// @param Node The node to collect references for. 1383edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected. 1384edb885cbSTobias Grosser /// 1385edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully. 1386edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) { 1387edb885cbSTobias Grosser if (isl_ast_node_get_type(Node) != isl_ast_node_user) 1388edb885cbSTobias Grosser return isl_bool_true; 1389edb885cbSTobias Grosser 1390edb885cbSTobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node); 1391edb885cbSTobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 1392edb885cbSTobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr); 1393edb885cbSTobias Grosser const char *Str = isl_id_get_name(Id); 1394edb885cbSTobias Grosser isl_id_free(Id); 1395edb885cbSTobias Grosser isl_ast_expr_free(StmtExpr); 1396edb885cbSTobias Grosser isl_ast_expr_free(Expr); 1397edb885cbSTobias Grosser 1398edb885cbSTobias Grosser if (!isPrefix(Str, "Stmt")) 1399edb885cbSTobias Grosser return isl_bool_true; 1400edb885cbSTobias Grosser 1401edb885cbSTobias Grosser Id = isl_ast_node_get_annotation(Node); 1402edb885cbSTobias Grosser auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id); 1403edb885cbSTobias Grosser auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1404edb885cbSTobias Grosser isl_id_free(Id); 1405edb885cbSTobias Grosser 140600bb5a99STobias Grosser addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */); 1407edb885cbSTobias Grosser 1408edb885cbSTobias Grosser return isl_bool_true; 1409edb885cbSTobias Grosser } 1410edb885cbSTobias Grosser 14118fc6cdfbSTobias Grosser /// A list of functions that are available in NVIDIA's libdevice. 14128fc6cdfbSTobias Grosser const std::set<std::string> CUDALibDeviceFunctions = { 141356572c6aSSiddharth Bhat "exp", "expf", "expl", "cos", "cosf", "sqrt", "sqrtf", 141456572c6aSSiddharth Bhat "copysign", "copysignf", "copysignl", "log", "logf", "powi", "powif"}; 141556572c6aSSiddharth Bhat 141656572c6aSSiddharth Bhat // A map from intrinsics to their corresponding libdevice functions. 141756572c6aSSiddharth Bhat const std::map<std::string, std::string> IntrinsicToLibdeviceFunc = { 141856572c6aSSiddharth Bhat {"llvm.exp.f64", "exp"}, 141956572c6aSSiddharth Bhat {"llvm.exp.f32", "expf"}, 14206aac2773SBjorn Pettersson {"llvm.powi.f64.i32", "powi"}, 14216aac2773SBjorn Pettersson {"llvm.powi.f32.i32", "powif"}}; 14228fc6cdfbSTobias Grosser 142366a05ad6SPhilip Pfaffe /// Return the corresponding CUDA libdevice function name @p Name. 142456572c6aSSiddharth Bhat /// Note that this function will try to convert instrinsics in the list 142556572c6aSSiddharth Bhat /// IntrinsicToLibdeviceFunc into libdevice functions. 142656572c6aSSiddharth Bhat /// This is because some intrinsics such as `exp` 142756572c6aSSiddharth Bhat /// are not supported by the NVPTX backend. 142856572c6aSSiddharth Bhat /// If this restriction of the backend is lifted, we should refactor our code 142956572c6aSSiddharth Bhat /// so that we use intrinsics whenever possible. 14308fc6cdfbSTobias Grosser /// 14318fc6cdfbSTobias Grosser /// Return "" if we are not compiling for CUDA. 14321a53b732SMichael Kruse std::string getCUDALibDeviceFuntion(StringRef NameRef) { 14331a53b732SMichael Kruse std::string Name = NameRef.str(); 143466a05ad6SPhilip Pfaffe auto It = IntrinsicToLibdeviceFunc.find(Name); 143556572c6aSSiddharth Bhat if (It != IntrinsicToLibdeviceFunc.end()) 143666a05ad6SPhilip Pfaffe return getCUDALibDeviceFuntion(It->second); 143756572c6aSSiddharth Bhat 143866a05ad6SPhilip Pfaffe if (CUDALibDeviceFunctions.count(Name)) 14391a53b732SMichael Kruse return ("__nv_" + Name); 14408fc6cdfbSTobias Grosser 14418fc6cdfbSTobias Grosser return ""; 14428fc6cdfbSTobias Grosser } 14438fc6cdfbSTobias Grosser 1444f291c8d5SSiddharth Bhat /// Check if F is a function that we can code-generate in a GPU kernel. 14458fc6cdfbSTobias Grosser static bool isValidFunctionInKernel(llvm::Function *F, bool AllowLibDevice) { 1446f291c8d5SSiddharth Bhat assert(F && "F is an invalid pointer"); 1447f291c8d5SSiddharth Bhat // We string compare against the name of the function to allow 144854491db6STobias Grosser // all variants of the intrinsic "llvm.sqrt.*", "llvm.fabs", and 144954491db6STobias Grosser // "llvm.copysign". 145054491db6STobias Grosser const StringRef Name = F->getName(); 14518fc6cdfbSTobias Grosser 145266a05ad6SPhilip Pfaffe if (AllowLibDevice && getCUDALibDeviceFuntion(Name).length() > 0) 14538fc6cdfbSTobias Grosser return true; 14548fc6cdfbSTobias Grosser 145554491db6STobias Grosser return F->isIntrinsic() && 145654491db6STobias Grosser (Name.startswith("llvm.sqrt") || Name.startswith("llvm.fabs") || 145756572c6aSSiddharth Bhat Name.startswith("llvm.copysign")); 1458f291c8d5SSiddharth Bhat } 1459f291c8d5SSiddharth Bhat 1460f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value. 1461f291c8d5SSiddharth Bhat /// 1462f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along 1463f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and 1464f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not 1465f291c8d5SSiddharth Bhat /// `Function`s. 1466f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); } 1467f291c8d5SSiddharth Bhat 1468f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`. 1469f291c8d5SSiddharth Bhat static SetVector<Function *> 14708fc6cdfbSTobias Grosser getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues, 14718fc6cdfbSTobias Grosser bool AllowCUDALibDevice) { 1472f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions; 1473f291c8d5SSiddharth Bhat for (Value *It : RawSubtreeValues) { 1474f291c8d5SSiddharth Bhat Function *F = dyn_cast<Function>(It); 1475f291c8d5SSiddharth Bhat if (F) { 14768fc6cdfbSTobias Grosser assert(isValidFunctionInKernel(F, AllowCUDALibDevice) && 14778fc6cdfbSTobias Grosser "Code should have bailed out by " 1478f291c8d5SSiddharth Bhat "this point if an invalid function " 1479f291c8d5SSiddharth Bhat "were present in a kernel."); 1480f291c8d5SSiddharth Bhat SubtreeFunctions.insert(F); 1481f291c8d5SSiddharth Bhat } 1482f291c8d5SSiddharth Bhat } 1483f291c8d5SSiddharth Bhat return SubtreeFunctions; 1484f291c8d5SSiddharth Bhat } 1485f291c8d5SSiddharth Bhat 148643df2020STobias Grosser std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>, 148743df2020STobias Grosser isl::space> 1488f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) { 1489edb885cbSTobias Grosser SetVector<Value *> SubtreeValues; 1490edb885cbSTobias Grosser SetVector<const SCEV *> SCEVs; 1491edb885cbSTobias Grosser SetVector<const Loop *> Loops; 149243df2020STobias Grosser isl::space ParamSpace = isl::space(S.getIslCtx(), 0, 0).params(); 1493edb885cbSTobias Grosser SubtreeReferences References = { 149443df2020STobias Grosser LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator(), 149543df2020STobias Grosser &ParamSpace}; 1496edb885cbSTobias Grosser 1497edb885cbSTobias Grosser for (const auto &I : IDToValue) 1498edb885cbSTobias Grosser SubtreeValues.insert(I.second); 1499edb885cbSTobias Grosser 1500e53c924bSSiddharth Bhat // NOTE: this is populated in IslNodeBuilder::addParameters 1501e53c924bSSiddharth Bhat // See [Code generation of induction variables of loops outside Scops]. 1502e53c924bSSiddharth Bhat for (const auto &I : OutsideLoopIterations) 1503e53c924bSSiddharth Bhat SubtreeValues.insert(cast<SCEVUnknown>(I.second)->getValue()); 1504e53c924bSSiddharth Bhat 1505edb885cbSTobias Grosser isl_ast_node_foreach_descendant_top_down( 1506edb885cbSTobias Grosser Kernel->tree, collectReferencesInGPUStmt, &References); 1507edb885cbSTobias Grosser 1508e53c924bSSiddharth Bhat for (const SCEV *Expr : SCEVs) { 1509edb885cbSTobias Grosser findValues(Expr, SE, SubtreeValues); 1510e53c924bSSiddharth Bhat findLoops(Expr, Loops); 1511e53c924bSSiddharth Bhat } 1512e53c924bSSiddharth Bhat 1513e53c924bSSiddharth Bhat Loops.remove_if([this](const Loop *L) { 1514e53c924bSSiddharth Bhat return S.contains(L) || L->contains(S.getEntry()); 1515e53c924bSSiddharth Bhat }); 1516edb885cbSTobias Grosser 1517edb885cbSTobias Grosser for (auto &SAI : S.arrays()) 1518d7754a12SRoman Gareev SubtreeValues.remove(SAI->getBasePtr()); 1519edb885cbSTobias Grosser 1520b65ccc43STobias Grosser isl_space *Space = S.getParamSpace().release(); 15213044dc51SMichael Kruse for (long i = 0, n = isl_space_dim(Space, isl_dim_param); i < n; i++) { 1522edb885cbSTobias Grosser isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i); 1523edb885cbSTobias Grosser assert(IDToValue.count(Id)); 1524edb885cbSTobias Grosser Value *Val = IDToValue[Id]; 1525edb885cbSTobias Grosser SubtreeValues.remove(Val); 1526edb885cbSTobias Grosser isl_id_free(Id); 1527edb885cbSTobias Grosser } 1528edb885cbSTobias Grosser isl_space_free(Space); 1529edb885cbSTobias Grosser 15303044dc51SMichael Kruse for (long i = 0, n = isl_space_dim(Kernel->space, isl_dim_set); i < n; i++) { 1531edb885cbSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1532edb885cbSTobias Grosser assert(IDToValue.count(Id)); 1533edb885cbSTobias Grosser Value *Val = IDToValue[Id]; 1534edb885cbSTobias Grosser SubtreeValues.remove(Val); 1535edb885cbSTobias Grosser isl_id_free(Id); 1536edb885cbSTobias Grosser } 1537edb885cbSTobias Grosser 1538f291c8d5SSiddharth Bhat // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions 1539f291c8d5SSiddharth Bhat // SubtreeValues. This is important, because we should not lose any 1540f291c8d5SSiddharth Bhat // SubtreeValues in the process of constructing the 1541f291c8d5SSiddharth Bhat // "ValidSubtree{Values, Functions} sets. Nor should the set 1542f291c8d5SSiddharth Bhat // ValidSubtree{Values, Functions} have any common element. 1543f291c8d5SSiddharth Bhat auto ValidSubtreeValuesIt = 1544f291c8d5SSiddharth Bhat make_filter_range(SubtreeValues, isValidSubtreeValue); 1545f291c8d5SSiddharth Bhat SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(), 1546f291c8d5SSiddharth Bhat ValidSubtreeValuesIt.end()); 15478fc6cdfbSTobias Grosser 15488fc6cdfbSTobias Grosser bool AllowCUDALibDevice = Arch == GPUArch::NVPTX64; 15498fc6cdfbSTobias Grosser 1550f291c8d5SSiddharth Bhat SetVector<Function *> ValidSubtreeFunctions( 15518fc6cdfbSTobias Grosser getFunctionsFromRawSubtreeValues(SubtreeValues, AllowCUDALibDevice)); 1552f291c8d5SSiddharth Bhat 1553a1b2086aSSiddharth Bhat // @see IslNodeBuilder::getReferencesInSubtree 1554a1b2086aSSiddharth Bhat SetVector<Value *> ReplacedValues; 1555a1b2086aSSiddharth Bhat for (Value *V : ValidSubtreeValues) { 1556a1b2086aSSiddharth Bhat auto It = ValueMap.find(V); 1557a1b2086aSSiddharth Bhat if (It == ValueMap.end()) 1558a1b2086aSSiddharth Bhat ReplacedValues.insert(V); 1559a1b2086aSSiddharth Bhat else 1560a1b2086aSSiddharth Bhat ReplacedValues.insert(It->second); 1561a1b2086aSSiddharth Bhat } 156243df2020STobias Grosser return std::make_tuple(ReplacedValues, ValidSubtreeFunctions, Loops, 156343df2020STobias Grosser ParamSpace); 1564edb885cbSTobias Grosser } 1565edb885cbSTobias Grosser 156674dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) { 156774dc3cb4STobias Grosser DomTreeNode *N = DT.getNode(&F->getEntryBlock()); 156874dc3cb4STobias Grosser std::vector<BasicBlock *> Nodes; 156974dc3cb4STobias Grosser for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I) 157074dc3cb4STobias Grosser Nodes.push_back(I->getBlock()); 157174dc3cb4STobias Grosser 157274dc3cb4STobias Grosser for (BasicBlock *BB : Nodes) 157374dc3cb4STobias Grosser DT.eraseNode(BB); 157474dc3cb4STobias Grosser } 157574dc3cb4STobias Grosser 157674dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) { 15774d50ab86SPhilip Pfaffe for (BasicBlock &BB : *F) { 15784d50ab86SPhilip Pfaffe Loop *L = LI.getLoopFor(&BB); 157974dc3cb4STobias Grosser if (L) 158074dc3cb4STobias Grosser SE.forgetLoop(L); 158174dc3cb4STobias Grosser } 15824d50ab86SPhilip Pfaffe } 158374dc3cb4STobias Grosser 158474dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) { 1585c06a6380SPhilip Pfaffe SmallSet<Loop *, 1> WorkList; 15864d50ab86SPhilip Pfaffe for (BasicBlock &BB : *F) { 15874d50ab86SPhilip Pfaffe Loop *L = LI.getLoopFor(&BB); 15884d50ab86SPhilip Pfaffe if (L) 1589c06a6380SPhilip Pfaffe WorkList.insert(L); 15904d50ab86SPhilip Pfaffe } 1591c06a6380SPhilip Pfaffe for (auto *L : WorkList) 1592c06a6380SPhilip Pfaffe LI.erase(L); 159374dc3cb4STobias Grosser } 159474dc3cb4STobias Grosser 159579a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) { 159679a947c2STobias Grosser std::vector<Value *> Sizes; 15978ea1fc19STobias Grosser isl::ast_build Context = isl::ast_build::from_context(S.getContext()); 159879a947c2STobias Grosser 1599718d04c6STobias Grosser isl::multi_pw_aff GridSizePwAffs = isl::manage_copy(Kernel->grid_size); 160079a947c2STobias Grosser for (long i = 0; i < Kernel->n_grid; i++) { 1601d3fdbda6SRiccardo Mori isl::pw_aff Size = GridSizePwAffs.at(i); 16024d5820d1SSiddharth Bhat isl::ast_expr GridSize = Context.expr_from(Size); 16034d5820d1SSiddharth Bhat Value *Res = ExprBuilder.create(GridSize.release()); 160479a947c2STobias Grosser Res = Builder.CreateTrunc(Res, Builder.getInt32Ty()); 160579a947c2STobias Grosser Sizes.push_back(Res); 160679a947c2STobias Grosser } 160779a947c2STobias Grosser 160879a947c2STobias Grosser for (long i = Kernel->n_grid; i < 3; i++) 160979a947c2STobias Grosser Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 161079a947c2STobias Grosser 161179a947c2STobias Grosser return std::make_tuple(Sizes[0], Sizes[1]); 161279a947c2STobias Grosser } 161379a947c2STobias Grosser 161479a947c2STobias Grosser std::tuple<Value *, Value *, Value *> 161579a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) { 161679a947c2STobias Grosser std::vector<Value *> Sizes; 161779a947c2STobias Grosser 161879a947c2STobias Grosser for (long i = 0; i < Kernel->n_block; i++) { 161979a947c2STobias Grosser Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]); 162079a947c2STobias Grosser Sizes.push_back(Res); 162179a947c2STobias Grosser } 162279a947c2STobias Grosser 162379a947c2STobias Grosser for (long i = Kernel->n_block; i < 3; i++) 162479a947c2STobias Grosser Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 162579a947c2STobias Grosser 162679a947c2STobias Grosser return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]); 162779a947c2STobias Grosser } 162879a947c2STobias Grosser 1629*ee6bd28fSNikita Popov void GPUNodeBuilder::insertStoreParameter(Type *ArrayTy, 1630*ee6bd28fSNikita Popov Instruction *Parameters, 1631a90be207SSiddharth Bhat Instruction *Param, int Index) { 1632a90be207SSiddharth Bhat Value *Slot = Builder.CreateGEP( 1633*ee6bd28fSNikita Popov ArrayTy, Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1634a90be207SSiddharth Bhat Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 1635a90be207SSiddharth Bhat Builder.CreateStore(ParamTyped, Slot); 1636a90be207SSiddharth Bhat } 1637a90be207SSiddharth Bhat 163857693272STobias Grosser Value * 163957693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F, 164057693272STobias Grosser SetVector<Value *> SubtreeValues) { 1641a90be207SSiddharth Bhat const int NumArgs = F->arg_size(); 1642a90be207SSiddharth Bhat std::vector<int> ArgSizes(NumArgs); 1643a90be207SSiddharth Bhat 164450139f0fSPhilipp Schaad // If we are using the OpenCL Runtime, we need to add the kernel argument 164550139f0fSPhilipp Schaad // sizes to the end of the launch-parameter list, so OpenCL can determine 164650139f0fSPhilipp Schaad // how big the respective kernel arguments are. 164750139f0fSPhilipp Schaad // Here we need to reserve adequate space for that. 164850139f0fSPhilipp Schaad Type *ArrayTy; 164950139f0fSPhilipp Schaad if (Runtime == GPURuntime::OpenCL) 165050139f0fSPhilipp Schaad ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs); 165150139f0fSPhilipp Schaad else 165250139f0fSPhilipp Schaad ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), NumArgs); 165379a947c2STobias Grosser 165479a947c2STobias Grosser BasicBlock *EntryBlock = 165579a947c2STobias Grosser &Builder.GetInsertBlock()->getParent()->getEntryBlock(); 165667726b32STobias Grosser auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace(); 165779a947c2STobias Grosser std::string Launch = "polly_launch_" + std::to_string(Kernel->id); 165867726b32STobias Grosser Instruction *Parameters = new AllocaInst( 165967726b32STobias Grosser ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator()); 166079a947c2STobias Grosser 166179a947c2STobias Grosser int Index = 0; 166279a947c2STobias Grosser for (long i = 0; i < Prog->n_array; i++) { 166379a947c2STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 166479a947c2STobias Grosser continue; 166579a947c2STobias Grosser 166679a947c2STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1667206e9e3bSTobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id)); 166879a947c2STobias Grosser 166950139f0fSPhilipp Schaad if (Runtime == GPURuntime::OpenCL) 1670a90be207SSiddharth Bhat ArgSizes[Index] = SAI->getElemSizeInBytes(); 1671a90be207SSiddharth Bhat 1672abed4969SSiddharth Bhat Value *DevArray = nullptr; 1673c4a4af47SSiddharth Bhat if (PollyManagedMemory) { 1674b99c1171STobias Grosser DevArray = getManagedDeviceArray(&Prog->array[i], 1675b99c1171STobias Grosser const_cast<ScopArrayInfo *>(SAI)); 1676abed4969SSiddharth Bhat } else { 1677abed4969SSiddharth Bhat DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)]; 167879a947c2STobias Grosser DevArray = createCallGetDevicePtr(DevArray); 1679abed4969SSiddharth Bhat } 1680abed4969SSiddharth Bhat assert(DevArray != nullptr && "Array to be offloaded to device not " 1681abed4969SSiddharth Bhat "initialized"); 1682aaabbbf8STobias Grosser Value *Offset = getArrayOffset(&Prog->array[i]); 1683aaabbbf8STobias Grosser 1684aaabbbf8STobias Grosser if (Offset) { 1685aaabbbf8STobias Grosser DevArray = Builder.CreatePointerCast( 1686aaabbbf8STobias Grosser DevArray, SAI->getElementType()->getPointerTo()); 16870ce9acf6SEli Friedman DevArray = Builder.CreateGEP(SAI->getElementType(), DevArray, 16880ce9acf6SEli Friedman Builder.CreateNeg(Offset)); 1689aaabbbf8STobias Grosser DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy()); 1690aaabbbf8STobias Grosser } 1691fe74a7a1STobias Grosser Value *Slot = Builder.CreateGEP( 16920ce9acf6SEli Friedman ArrayTy, Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1693aaabbbf8STobias Grosser 1694fe74a7a1STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1695abed4969SSiddharth Bhat Value *ValPtr = nullptr; 1696c4a4af47SSiddharth Bhat if (PollyManagedMemory) 1697abed4969SSiddharth Bhat ValPtr = DevArray; 1698abed4969SSiddharth Bhat else 1699abed4969SSiddharth Bhat ValPtr = BlockGen.getOrCreateAlloca(SAI); 1700abed4969SSiddharth Bhat 1701abed4969SSiddharth Bhat assert(ValPtr != nullptr && "ValPtr that should point to a valid object" 1702abed4969SSiddharth Bhat " to be stored into Parameters"); 1703fe74a7a1STobias Grosser Value *ValPtrCast = 1704fe74a7a1STobias Grosser Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy()); 1705fe74a7a1STobias Grosser Builder.CreateStore(ValPtrCast, Slot); 1706fe74a7a1STobias Grosser } else { 170767726b32STobias Grosser Instruction *Param = 170867726b32STobias Grosser new AllocaInst(Builder.getInt8PtrTy(), AddressSpace, 170967726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 171079a947c2STobias Grosser EntryBlock->getTerminator()); 171179a947c2STobias Grosser Builder.CreateStore(DevArray, Param); 171279a947c2STobias Grosser Value *ParamTyped = 171379a947c2STobias Grosser Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 171479a947c2STobias Grosser Builder.CreateStore(ParamTyped, Slot); 1715fe74a7a1STobias Grosser } 171679a947c2STobias Grosser Index++; 171779a947c2STobias Grosser } 171879a947c2STobias Grosser 1719a490147cSTobias Grosser int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1720a490147cSTobias Grosser 1721a490147cSTobias Grosser for (long i = 0; i < NumHostIters; i++) { 1722a490147cSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1723a490147cSTobias Grosser Value *Val = IDToValue[Id]; 1724a490147cSTobias Grosser isl_id_free(Id); 1725a90be207SSiddharth Bhat 172650139f0fSPhilipp Schaad if (Runtime == GPURuntime::OpenCL) 1727a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1728a90be207SSiddharth Bhat 172967726b32STobias Grosser Instruction *Param = 173067726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 173167726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 1732a490147cSTobias Grosser EntryBlock->getTerminator()); 1733a490147cSTobias Grosser Builder.CreateStore(Val, Param); 1734*ee6bd28fSNikita Popov insertStoreParameter(ArrayTy, Parameters, Param, Index); 1735a490147cSTobias Grosser Index++; 1736a490147cSTobias Grosser } 1737a490147cSTobias Grosser 1738d8b94bcaSTobias Grosser int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1739d8b94bcaSTobias Grosser 1740d8b94bcaSTobias Grosser for (long i = 0; i < NumVars; i++) { 1741d8b94bcaSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1742d8b94bcaSTobias Grosser Value *Val = IDToValue[Id]; 1743a1b2086aSSiddharth Bhat if (ValueMap.count(Val)) 1744a1b2086aSSiddharth Bhat Val = ValueMap[Val]; 1745d8b94bcaSTobias Grosser isl_id_free(Id); 1746a90be207SSiddharth Bhat 174750139f0fSPhilipp Schaad if (Runtime == GPURuntime::OpenCL) 1748a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1749a90be207SSiddharth Bhat 175067726b32STobias Grosser Instruction *Param = 175167726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 175267726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 1753d8b94bcaSTobias Grosser EntryBlock->getTerminator()); 1754d8b94bcaSTobias Grosser Builder.CreateStore(Val, Param); 1755*ee6bd28fSNikita Popov insertStoreParameter(ArrayTy, Parameters, Param, Index); 1756d8b94bcaSTobias Grosser Index++; 1757d8b94bcaSTobias Grosser } 1758d8b94bcaSTobias Grosser 175957693272STobias Grosser for (auto Val : SubtreeValues) { 176050139f0fSPhilipp Schaad if (Runtime == GPURuntime::OpenCL) 1761a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1762a90be207SSiddharth Bhat 176367726b32STobias Grosser Instruction *Param = 176467726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 176567726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 176657693272STobias Grosser EntryBlock->getTerminator()); 176757693272STobias Grosser Builder.CreateStore(Val, Param); 1768*ee6bd28fSNikita Popov insertStoreParameter(ArrayTy, Parameters, Param, Index); 1769a90be207SSiddharth Bhat Index++; 1770a90be207SSiddharth Bhat } 1771a90be207SSiddharth Bhat 177250139f0fSPhilipp Schaad if (Runtime == GPURuntime::OpenCL) { 1773a90be207SSiddharth Bhat for (int i = 0; i < NumArgs; i++) { 1774a90be207SSiddharth Bhat Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]); 1775a90be207SSiddharth Bhat Instruction *Param = 1776a90be207SSiddharth Bhat new AllocaInst(Builder.getInt32Ty(), AddressSpace, 1777a90be207SSiddharth Bhat Launch + "_param_size_" + std::to_string(i), 1778a90be207SSiddharth Bhat EntryBlock->getTerminator()); 1779a90be207SSiddharth Bhat Builder.CreateStore(Val, Param); 1780*ee6bd28fSNikita Popov insertStoreParameter(ArrayTy, Parameters, Param, Index); 178157693272STobias Grosser Index++; 178257693272STobias Grosser } 178350139f0fSPhilipp Schaad } 178457693272STobias Grosser 178579a947c2STobias Grosser auto Location = EntryBlock->getTerminator(); 178679a947c2STobias Grosser return new BitCastInst(Parameters, Builder.getInt8PtrTy(), 178779a947c2STobias Grosser Launch + "_params_i8ptr", Location); 178879a947c2STobias Grosser } 178979a947c2STobias Grosser 1790f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions( 1791f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions) { 1792f291c8d5SSiddharth Bhat for (auto Fn : SubtreeFunctions) { 17931a53b732SMichael Kruse const std::string ClonedFnName = Fn->getName().str(); 1794f291c8d5SSiddharth Bhat Function *Clone = GPUModule->getFunction(ClonedFnName); 1795f291c8d5SSiddharth Bhat if (!Clone) 1796f291c8d5SSiddharth Bhat Clone = 1797f291c8d5SSiddharth Bhat Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage, 1798f291c8d5SSiddharth Bhat ClonedFnName, GPUModule.get()); 1799f291c8d5SSiddharth Bhat assert(Clone && "Expected cloned function to be initialized."); 1800f291c8d5SSiddharth Bhat assert(ValueMap.find(Fn) == ValueMap.end() && 1801f291c8d5SSiddharth Bhat "Fn already present in ValueMap"); 1802f291c8d5SSiddharth Bhat ValueMap[Fn] = Clone; 1803f291c8d5SSiddharth Bhat } 1804f291c8d5SSiddharth Bhat } 180532837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) { 180632837fe3STobias Grosser isl_id *Id = isl_ast_node_get_annotation(KernelStmt); 180732837fe3STobias Grosser ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id); 180832837fe3STobias Grosser isl_id_free(Id); 180932837fe3STobias Grosser isl_ast_node_free(KernelStmt); 181032837fe3STobias Grosser 1811bc653f20STobias Grosser if (Kernel->n_grid > 1) 1812e8227804SMichael Kruse DeepestParallel = std::max( 1813e8227804SMichael Kruse DeepestParallel, (unsigned)isl_space_dim(Kernel->space, isl_dim_set)); 1814bc653f20STobias Grosser else 1815e8227804SMichael Kruse DeepestSequential = std::max( 1816e8227804SMichael Kruse DeepestSequential, (unsigned)isl_space_dim(Kernel->space, isl_dim_set)); 1817bc653f20STobias Grosser 1818c1c6a2a6STobias Grosser Value *BlockDimX, *BlockDimY, *BlockDimZ; 1819c1c6a2a6STobias Grosser std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel); 1820c1c6a2a6STobias Grosser 1821f291c8d5SSiddharth Bhat SetVector<Value *> SubtreeValues; 1822f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions; 1823e53c924bSSiddharth Bhat SetVector<const Loop *> Loops; 182443df2020STobias Grosser isl::space ParamSpace; 182543df2020STobias Grosser std::tie(SubtreeValues, SubtreeFunctions, Loops, ParamSpace) = 1826e53c924bSSiddharth Bhat getReferencesInKernel(Kernel); 1827edb885cbSTobias Grosser 182843df2020STobias Grosser // Add parameters that appear only in the access function to the kernel 182943df2020STobias Grosser // space. This is important to make sure that all isl_ids are passed as 183043df2020STobias Grosser // parameters to the kernel, even though we may not have all parameters 183143df2020STobias Grosser // in the context to improve compile time. 183243df2020STobias Grosser Kernel->space = isl_space_align_params(Kernel->space, ParamSpace.release()); 183343df2020STobias Grosser 183432837fe3STobias Grosser assert(Kernel->tree && "Device AST of kernel node is empty"); 183532837fe3STobias Grosser 183632837fe3STobias Grosser Instruction &HostInsertPoint = *Builder.GetInsertPoint(); 1837472f9654STobias Grosser IslExprBuilder::IDToValueTy HostIDs = IDToValue; 1838edb885cbSTobias Grosser ValueMapT HostValueMap = ValueMap; 1839587f1f57STobias Grosser BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap; 1840b06ff457STobias Grosser ScalarMap.clear(); 1841c52b71dbSTobias Grosser BlockGenerator::EscapeUsersAllocaMapTy HostEscapeMap = EscapeMap; 1842c52b71dbSTobias Grosser EscapeMap.clear(); 184332837fe3STobias Grosser 1844edb885cbSTobias Grosser // Create for all loops we depend on values that contain the current loop 1845edb885cbSTobias Grosser // iteration. These values are necessary to generate code for SCEVs that 1846edb885cbSTobias Grosser // depend on such loops. As a result we need to pass them to the subfunction. 1847edb885cbSTobias Grosser for (const Loop *L : Loops) { 1848edb885cbSTobias Grosser const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)), 1849edb885cbSTobias Grosser SE.getUnknown(Builder.getInt64(1)), 1850edb885cbSTobias Grosser L, SCEV::FlagAnyWrap); 1851edb885cbSTobias Grosser Value *V = generateSCEV(OuterLIV); 1852edb885cbSTobias Grosser OutsideLoopIterations[L] = SE.getUnknown(V); 1853edb885cbSTobias Grosser SubtreeValues.insert(V); 1854edb885cbSTobias Grosser } 1855edb885cbSTobias Grosser 1856f291c8d5SSiddharth Bhat createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions); 1857f291c8d5SSiddharth Bhat setupKernelSubtreeFunctions(SubtreeFunctions); 185832837fe3STobias Grosser 185959ab0705STobias Grosser create(isl_ast_node_copy(Kernel->tree)); 186059ab0705STobias Grosser 186151dfc275STobias Grosser finalizeKernelArguments(Kernel); 186274dc3cb4STobias Grosser Function *F = Builder.GetInsertBlock()->getParent(); 18632f3073b5SPhilipp Schaad if (Arch == GPUArch::NVPTX64) 1864c1c6a2a6STobias Grosser addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ); 186574dc3cb4STobias Grosser clearDominators(F); 186674dc3cb4STobias Grosser clearScalarEvolution(F); 186774dc3cb4STobias Grosser clearLoops(F); 186874dc3cb4STobias Grosser 1869472f9654STobias Grosser IDToValue = HostIDs; 187032837fe3STobias Grosser 1871b06ff457STobias Grosser ValueMap = std::move(HostValueMap); 1872b06ff457STobias Grosser ScalarMap = std::move(HostScalarMap); 1873c52b71dbSTobias Grosser EscapeMap = std::move(HostEscapeMap); 1874edb885cbSTobias Grosser IDToSAI.clear(); 187574dc3cb4STobias Grosser Annotator.resetAlternativeAliasBases(); 187674dc3cb4STobias Grosser for (auto &BasePtr : LocalArrays) 18774d5a9172STobias Grosser S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array); 187874dc3cb4STobias Grosser LocalArrays.clear(); 1879edb885cbSTobias Grosser 188051dfc275STobias Grosser std::string ASMString = finalizeKernelFunction(); 188151dfc275STobias Grosser Builder.SetInsertPoint(&HostInsertPoint); 188257693272STobias Grosser Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues); 188379a947c2STobias Grosser 188479f13b9aSSingapuram Sanjay Srivallabh std::string Name = getKernelFuncName(Kernel->id); 188557793596STobias Grosser Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name); 188657793596STobias Grosser Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name"); 188757793596STobias Grosser Value *GPUKernel = createCallGetKernel(KernelString, NameString); 188879a947c2STobias Grosser 188979a947c2STobias Grosser Value *GridDimX, *GridDimY; 189079a947c2STobias Grosser std::tie(GridDimX, GridDimY) = getGridSizes(Kernel); 189179a947c2STobias Grosser 189279a947c2STobias Grosser createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 189379a947c2STobias Grosser BlockDimZ, Parameters); 189457793596STobias Grosser createCallFreeKernel(GPUKernel); 1895b513b491STobias Grosser 1896b513b491STobias Grosser for (auto Id : KernelIds) 1897b513b491STobias Grosser isl_id_free(Id); 1898b513b491STobias Grosser 1899b513b491STobias Grosser KernelIds.clear(); 190032837fe3STobias Grosser } 190132837fe3STobias Grosser 190232837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend. 190332837fe3STobias Grosser /// 190432837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture? 190532837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) { 1906d277fedaSSiddharth Bhat std::string Ret = ""; 190732837fe3STobias Grosser 1908d277fedaSSiddharth Bhat if (!is64Bit) { 1909d277fedaSSiddharth Bhat Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 191030caae6dSTobias Grosser "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1911d277fedaSSiddharth Bhat "64-v128:128:128-n16:32:64"; 1912d277fedaSSiddharth Bhat } else { 1913d277fedaSSiddharth Bhat Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 191430caae6dSTobias Grosser "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1915d277fedaSSiddharth Bhat "64-v128:128:128-n16:32:64"; 1916d277fedaSSiddharth Bhat } 191732837fe3STobias Grosser 191832837fe3STobias Grosser return Ret; 191932837fe3STobias Grosser } 192032837fe3STobias Grosser 19212f3073b5SPhilipp Schaad /// Compute the DataLayout string for a SPIR kernel. 19222f3073b5SPhilipp Schaad /// 19232f3073b5SPhilipp Schaad /// @param is64Bit Are we looking for a 64 bit architecture? 19242f3073b5SPhilipp Schaad static std::string computeSPIRDataLayout(bool is64Bit) { 19252f3073b5SPhilipp Schaad std::string Ret = ""; 19262f3073b5SPhilipp Schaad 19272f3073b5SPhilipp Schaad if (!is64Bit) { 19282f3073b5SPhilipp Schaad Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 192930caae6dSTobias Grosser "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:" 19302f3073b5SPhilipp Schaad "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:" 19312f3073b5SPhilipp Schaad "256:256-v256:256:256-v512:512:512-v1024:1024:1024"; 19322f3073b5SPhilipp Schaad } else { 19332f3073b5SPhilipp Schaad Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 193430caae6dSTobias Grosser "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:" 19352f3073b5SPhilipp Schaad "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:" 19362f3073b5SPhilipp Schaad "256:256-v256:256:256-v512:512:512-v1024:1024:1024"; 19372f3073b5SPhilipp Schaad } 19382f3073b5SPhilipp Schaad 19392f3073b5SPhilipp Schaad return Ret; 19402f3073b5SPhilipp Schaad } 19412f3073b5SPhilipp Schaad 1942edb885cbSTobias Grosser Function * 1943edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel, 1944edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues) { 194532837fe3STobias Grosser std::vector<Type *> Args; 194679f13b9aSSingapuram Sanjay Srivallabh std::string Identifier = getKernelFuncName(Kernel->id); 194732837fe3STobias Grosser 19482f3073b5SPhilipp Schaad std::vector<Metadata *> MemoryType; 19492f3073b5SPhilipp Schaad 195032837fe3STobias Grosser for (long i = 0; i < Prog->n_array; i++) { 195132837fe3STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 195232837fe3STobias Grosser continue; 195332837fe3STobias Grosser 1954fe74a7a1STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1955fe74a7a1STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1956206e9e3bSTobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id)); 1957fe74a7a1STobias Grosser Args.push_back(SAI->getElementType()); 19582f3073b5SPhilipp Schaad MemoryType.push_back( 19592f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 1960fe74a7a1STobias Grosser } else { 1961d277fedaSSiddharth Bhat static const int UseGlobalMemory = 1; 1962d277fedaSSiddharth Bhat Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory)); 19632f3073b5SPhilipp Schaad MemoryType.push_back( 19642f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 1))); 196532837fe3STobias Grosser } 1966fe74a7a1STobias Grosser } 196732837fe3STobias Grosser 1968f6044bd0STobias Grosser int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1969f6044bd0STobias Grosser 19702f3073b5SPhilipp Schaad for (long i = 0; i < NumHostIters; i++) { 1971f6044bd0STobias Grosser Args.push_back(Builder.getInt64Ty()); 19722f3073b5SPhilipp Schaad MemoryType.push_back( 19732f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 19742f3073b5SPhilipp Schaad } 1975f6044bd0STobias Grosser 1976c84a1995STobias Grosser int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1977c84a1995STobias Grosser 1978cf66ef26STobias Grosser for (long i = 0; i < NumVars; i++) { 1979cf66ef26STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1980cf66ef26STobias Grosser Value *Val = IDToValue[Id]; 1981cf66ef26STobias Grosser isl_id_free(Id); 1982cf66ef26STobias Grosser Args.push_back(Val->getType()); 19832f3073b5SPhilipp Schaad MemoryType.push_back( 19842f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 1985cf66ef26STobias Grosser } 1986c84a1995STobias Grosser 19872f3073b5SPhilipp Schaad for (auto *V : SubtreeValues) { 1988edb885cbSTobias Grosser Args.push_back(V->getType()); 19892f3073b5SPhilipp Schaad MemoryType.push_back( 19902f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 19912f3073b5SPhilipp Schaad } 1992edb885cbSTobias Grosser 199332837fe3STobias Grosser auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false); 199432837fe3STobias Grosser auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier, 199532837fe3STobias Grosser GPUModule.get()); 199617f01968SSiddharth Bhat 19972f3073b5SPhilipp Schaad std::vector<Metadata *> EmptyStrings; 19982f3073b5SPhilipp Schaad 19992f3073b5SPhilipp Schaad for (unsigned int i = 0; i < MemoryType.size(); i++) { 20002f3073b5SPhilipp Schaad EmptyStrings.push_back(MDString::get(FN->getContext(), "")); 20012f3073b5SPhilipp Schaad } 20022f3073b5SPhilipp Schaad 20032f3073b5SPhilipp Schaad if (Arch == GPUArch::SPIR32 || Arch == GPUArch::SPIR64) { 20042f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_addr_space", 20052f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), MemoryType)); 20062f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_name", 20072f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 20082f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_access_qual", 20092f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 20102f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_type", 20112f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 20122f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_type_qual", 20132f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 20142f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_base_type", 20152f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 20162f3073b5SPhilipp Schaad } 20172f3073b5SPhilipp Schaad 201817f01968SSiddharth Bhat switch (Arch) { 201917f01968SSiddharth Bhat case GPUArch::NVPTX64: 202032837fe3STobias Grosser FN->setCallingConv(CallingConv::PTX_Kernel); 202117f01968SSiddharth Bhat break; 20222f3073b5SPhilipp Schaad case GPUArch::SPIR32: 20232f3073b5SPhilipp Schaad case GPUArch::SPIR64: 20242f3073b5SPhilipp Schaad FN->setCallingConv(CallingConv::SPIR_KERNEL); 20252f3073b5SPhilipp Schaad break; 202617f01968SSiddharth Bhat } 202732837fe3STobias Grosser 202832837fe3STobias Grosser auto Arg = FN->arg_begin(); 202932837fe3STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 203032837fe3STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 203132837fe3STobias Grosser continue; 203232837fe3STobias Grosser 2033edb885cbSTobias Grosser Arg->setName(Kernel->array[i].array->name); 2034edb885cbSTobias Grosser 2035edb885cbSTobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 2036718d04c6STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage_copy(Id)); 2037edb885cbSTobias Grosser Type *EleTy = SAI->getElementType(); 2038edb885cbSTobias Grosser Value *Val = &*Arg; 2039edb885cbSTobias Grosser SmallVector<const SCEV *, 4> Sizes; 2040edb885cbSTobias Grosser isl_ast_build *Build = 2041edb885cbSTobias Grosser isl_ast_build_from_context(isl_set_copy(Prog->context)); 2042f5aff704SRoman Gareev Sizes.push_back(nullptr); 20433044dc51SMichael Kruse for (long j = 1, n = Kernel->array[i].array->n_index; j < n; j++) { 2044edb885cbSTobias Grosser isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff( 20459e3db2b7SSiddharth Bhat Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j)); 2046edb885cbSTobias Grosser auto V = ExprBuilder.create(DimSize); 2047edb885cbSTobias Grosser Sizes.push_back(SE.getSCEV(V)); 2048edb885cbSTobias Grosser } 2049edb885cbSTobias Grosser const ScopArrayInfo *SAIRep = 20504d5a9172STobias Grosser S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array); 205174dc3cb4STobias Grosser LocalArrays.push_back(Val); 2052edb885cbSTobias Grosser 2053edb885cbSTobias Grosser isl_ast_build_free(Build); 2054b513b491STobias Grosser KernelIds.push_back(Id); 2055edb885cbSTobias Grosser IDToSAI[Id] = SAIRep; 205632837fe3STobias Grosser Arg++; 205732837fe3STobias Grosser } 205832837fe3STobias Grosser 2059f6044bd0STobias Grosser for (long i = 0; i < NumHostIters; i++) { 2060f6044bd0STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 2061f6044bd0STobias Grosser Arg->setName(isl_id_get_name(Id)); 2062f6044bd0STobias Grosser IDToValue[Id] = &*Arg; 2063f6044bd0STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 2064f6044bd0STobias Grosser Arg++; 2065f6044bd0STobias Grosser } 2066f6044bd0STobias Grosser 2067c84a1995STobias Grosser for (long i = 0; i < NumVars; i++) { 2068c84a1995STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 2069c84a1995STobias Grosser Arg->setName(isl_id_get_name(Id)); 207012453403STobias Grosser Value *Val = IDToValue[Id]; 207112453403STobias Grosser ValueMap[Val] = &*Arg; 2072c84a1995STobias Grosser IDToValue[Id] = &*Arg; 2073c84a1995STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 2074c84a1995STobias Grosser Arg++; 2075c84a1995STobias Grosser } 2076c84a1995STobias Grosser 2077edb885cbSTobias Grosser for (auto *V : SubtreeValues) { 2078edb885cbSTobias Grosser Arg->setName(V->getName()); 2079edb885cbSTobias Grosser ValueMap[V] = &*Arg; 2080edb885cbSTobias Grosser Arg++; 2081edb885cbSTobias Grosser } 2082edb885cbSTobias Grosser 208332837fe3STobias Grosser return FN; 208432837fe3STobias Grosser } 208532837fe3STobias Grosser 2086472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) { 208717f01968SSiddharth Bhat Intrinsic::ID IntrinsicsBID[2]; 208817f01968SSiddharth Bhat Intrinsic::ID IntrinsicsTID[3]; 2089472f9654STobias Grosser 209017f01968SSiddharth Bhat switch (Arch) { 20912f3073b5SPhilipp Schaad case GPUArch::SPIR64: 20922f3073b5SPhilipp Schaad case GPUArch::SPIR32: 20932f3073b5SPhilipp Schaad llvm_unreachable("Cannot generate NVVM intrinsics for SPIR"); 209417f01968SSiddharth Bhat case GPUArch::NVPTX64: 209517f01968SSiddharth Bhat IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x; 209617f01968SSiddharth Bhat IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y; 209717f01968SSiddharth Bhat 209817f01968SSiddharth Bhat IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x; 209917f01968SSiddharth Bhat IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y; 210017f01968SSiddharth Bhat IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z; 210117f01968SSiddharth Bhat break; 210217f01968SSiddharth Bhat } 2103472f9654STobias Grosser 2104472f9654STobias Grosser auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable { 2105472f9654STobias Grosser std::string Name = isl_id_get_name(Id); 2106472f9654STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 2107472f9654STobias Grosser Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr); 2108472f9654STobias Grosser Value *Val = Builder.CreateCall(IntrinsicFn, {}); 2109472f9654STobias Grosser Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 2110472f9654STobias Grosser IDToValue[Id] = Val; 2111472f9654STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 2112472f9654STobias Grosser }; 2113472f9654STobias Grosser 2114472f9654STobias Grosser for (int i = 0; i < Kernel->n_grid; ++i) { 2115472f9654STobias Grosser isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i); 2116472f9654STobias Grosser addId(Id, IntrinsicsBID[i]); 2117472f9654STobias Grosser } 2118472f9654STobias Grosser 2119472f9654STobias Grosser for (int i = 0; i < Kernel->n_block; ++i) { 2120472f9654STobias Grosser isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i); 2121472f9654STobias Grosser addId(Id, IntrinsicsTID[i]); 2122472f9654STobias Grosser } 2123472f9654STobias Grosser } 2124472f9654STobias Grosser 2125d71493cbSPhilip Pfaffe void GPUNodeBuilder::insertKernelCallsSPIR(ppcg_kernel *Kernel, 2126d71493cbSPhilip Pfaffe bool SizeTypeIs64bit) { 21272f3073b5SPhilipp Schaad const char *GroupName[3] = {"__gen_ocl_get_group_id0", 21282f3073b5SPhilipp Schaad "__gen_ocl_get_group_id1", 21292f3073b5SPhilipp Schaad "__gen_ocl_get_group_id2"}; 21302f3073b5SPhilipp Schaad 21312f3073b5SPhilipp Schaad const char *LocalName[3] = {"__gen_ocl_get_local_id0", 21322f3073b5SPhilipp Schaad "__gen_ocl_get_local_id1", 21332f3073b5SPhilipp Schaad "__gen_ocl_get_local_id2"}; 2134d71493cbSPhilip Pfaffe IntegerType *SizeT = 2135d71493cbSPhilip Pfaffe SizeTypeIs64bit ? Builder.getInt64Ty() : Builder.getInt32Ty(); 21362f3073b5SPhilipp Schaad 2137d71493cbSPhilip Pfaffe auto createFunc = [this](const char *Name, __isl_take isl_id *Id, 2138d71493cbSPhilip Pfaffe IntegerType *SizeT) mutable { 21392f3073b5SPhilipp Schaad Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 21402f3073b5SPhilipp Schaad Function *FN = M->getFunction(Name); 21412f3073b5SPhilipp Schaad 21422f3073b5SPhilipp Schaad // If FN is not available, declare it. 21432f3073b5SPhilipp Schaad if (!FN) { 21442f3073b5SPhilipp Schaad GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 21452f3073b5SPhilipp Schaad std::vector<Type *> Args; 2146d71493cbSPhilip Pfaffe FunctionType *Ty = FunctionType::get(SizeT, Args, false); 21472f3073b5SPhilipp Schaad FN = Function::Create(Ty, Linkage, Name, M); 21482f3073b5SPhilipp Schaad FN->setCallingConv(CallingConv::SPIR_FUNC); 21492f3073b5SPhilipp Schaad } 21502f3073b5SPhilipp Schaad 21512f3073b5SPhilipp Schaad Value *Val = Builder.CreateCall(FN, {}); 2152d71493cbSPhilip Pfaffe if (SizeT == Builder.getInt32Ty()) 21532f3073b5SPhilipp Schaad Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 21542f3073b5SPhilipp Schaad IDToValue[Id] = Val; 21552f3073b5SPhilipp Schaad KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 21562f3073b5SPhilipp Schaad }; 21572f3073b5SPhilipp Schaad 21582f3073b5SPhilipp Schaad for (int i = 0; i < Kernel->n_grid; ++i) 2159d71493cbSPhilip Pfaffe createFunc(GroupName[i], isl_id_list_get_id(Kernel->block_ids, i), SizeT); 21602f3073b5SPhilipp Schaad 21612f3073b5SPhilipp Schaad for (int i = 0; i < Kernel->n_block; ++i) 2162d71493cbSPhilip Pfaffe createFunc(LocalName[i], isl_id_list_get_id(Kernel->thread_ids, i), SizeT); 21632f3073b5SPhilipp Schaad } 21642f3073b5SPhilipp Schaad 216500bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) { 216600bb5a99STobias Grosser auto Arg = FN->arg_begin(); 216700bb5a99STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 216800bb5a99STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 216900bb5a99STobias Grosser continue; 217000bb5a99STobias Grosser 217100bb5a99STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 2172718d04c6STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage_copy(Id)); 217300bb5a99STobias Grosser isl_id_free(Id); 217400bb5a99STobias Grosser 217500bb5a99STobias Grosser if (SAI->getNumberOfDimensions() > 0) { 217600bb5a99STobias Grosser Arg++; 217700bb5a99STobias Grosser continue; 217800bb5a99STobias Grosser } 217900bb5a99STobias Grosser 2180fe74a7a1STobias Grosser Value *Val = &*Arg; 2181fe74a7a1STobias Grosser 2182fe74a7a1STobias Grosser if (!gpu_array_is_read_only_scalar(&Prog->array[i])) { 218300bb5a99STobias Grosser Type *TypePtr = SAI->getElementType()->getPointerTo(); 2184fe74a7a1STobias Grosser Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr); 21859c486eb3SMichael Kruse Val = Builder.CreateLoad(SAI->getElementType(), TypedArgPtr); 2186fe74a7a1STobias Grosser } 2187fe74a7a1STobias Grosser 2188fe74a7a1STobias Grosser Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 218900bb5a99STobias Grosser Builder.CreateStore(Val, Alloca); 219000bb5a99STobias Grosser 219100bb5a99STobias Grosser Arg++; 219200bb5a99STobias Grosser } 219300bb5a99STobias Grosser } 219400bb5a99STobias Grosser 219551dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) { 219651dfc275STobias Grosser auto *FN = Builder.GetInsertBlock()->getParent(); 219751dfc275STobias Grosser auto Arg = FN->arg_begin(); 219851dfc275STobias Grosser 219951dfc275STobias Grosser bool StoredScalar = false; 220051dfc275STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 220151dfc275STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 220251dfc275STobias Grosser continue; 220351dfc275STobias Grosser 220451dfc275STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 2205718d04c6STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage_copy(Id)); 220651dfc275STobias Grosser isl_id_free(Id); 220751dfc275STobias Grosser 220851dfc275STobias Grosser if (SAI->getNumberOfDimensions() > 0) { 220951dfc275STobias Grosser Arg++; 221051dfc275STobias Grosser continue; 221151dfc275STobias Grosser } 221251dfc275STobias Grosser 221351dfc275STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 221451dfc275STobias Grosser Arg++; 221551dfc275STobias Grosser continue; 221651dfc275STobias Grosser } 221751dfc275STobias Grosser 221851dfc275STobias Grosser Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 221951dfc275STobias Grosser Value *ArgPtr = &*Arg; 222051dfc275STobias Grosser Type *TypePtr = SAI->getElementType()->getPointerTo(); 222151dfc275STobias Grosser Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr); 22229c486eb3SMichael Kruse Value *Val = Builder.CreateLoad(SAI->getElementType(), Alloca); 222351dfc275STobias Grosser Builder.CreateStore(Val, TypedArgPtr); 222451dfc275STobias Grosser StoredScalar = true; 222551dfc275STobias Grosser 222651dfc275STobias Grosser Arg++; 222751dfc275STobias Grosser } 222851dfc275STobias Grosser 2229638316daSSiddharth Bhat if (StoredScalar) { 223051dfc275STobias Grosser /// In case more than one thread contains scalar stores, the generated 223151dfc275STobias Grosser /// code might be incorrect, if we only store at the end of the kernel. 223251dfc275STobias Grosser /// To support this case we need to store these scalars back at each 223351dfc275STobias Grosser /// memory store or at least before each kernel barrier. 2234638316daSSiddharth Bhat if (Kernel->n_block != 0 || Kernel->n_grid != 0) { 223551dfc275STobias Grosser BuildSuccessful = 0; 2236349506a9SNicola Zaghen LLVM_DEBUG( 2237638316daSSiddharth Bhat dbgs() << getUniqueScopName(&S) 2238638316daSSiddharth Bhat << " has a store to a scalar value that" 2239638316daSSiddharth Bhat " would be undefined to run in parallel. Bailing out.\n";); 2240638316daSSiddharth Bhat } 2241638316daSSiddharth Bhat } 224251dfc275STobias Grosser } 224351dfc275STobias Grosser 2244b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) { 2245b513b491STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 2246b513b491STobias Grosser 2247b513b491STobias Grosser for (int i = 0; i < Kernel->n_var; ++i) { 2248b513b491STobias Grosser struct ppcg_kernel_var &Var = Kernel->var[i]; 2249b513b491STobias Grosser isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set); 2250206e9e3bSTobias Grosser Type *EleTy = ScopArrayInfo::getFromId(isl::manage(Id))->getElementType(); 2251b513b491STobias Grosser 2252f919d8b3STobias Grosser Type *ArrayTy = EleTy; 2253b513b491STobias Grosser SmallVector<const SCEV *, 4> Sizes; 2254b513b491STobias Grosser 2255f5aff704SRoman Gareev Sizes.push_back(nullptr); 2256928d7573STobias Grosser for (unsigned int j = 1; j < Var.array->n_index; ++j) { 2257b513b491STobias Grosser isl_val *Val = isl_vec_get_element_val(Var.size, j); 2258f919d8b3STobias Grosser long Bound = isl_val_get_num_si(Val); 2259b513b491STobias Grosser isl_val_free(Val); 2260b513b491STobias Grosser Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound)); 2261928d7573STobias Grosser } 2262928d7573STobias Grosser 2263928d7573STobias Grosser for (int j = Var.array->n_index - 1; j >= 0; --j) { 2264928d7573STobias Grosser isl_val *Val = isl_vec_get_element_val(Var.size, j); 2265928d7573STobias Grosser long Bound = isl_val_get_num_si(Val); 2266928d7573STobias Grosser isl_val_free(Val); 2267b513b491STobias Grosser ArrayTy = ArrayType::get(ArrayTy, Bound); 2268b513b491STobias Grosser } 2269b513b491STobias Grosser 2270130ca30fSTobias Grosser const ScopArrayInfo *SAI; 2271130ca30fSTobias Grosser Value *Allocation; 2272130ca30fSTobias Grosser if (Var.type == ppcg_access_shared) { 2273130ca30fSTobias Grosser auto GlobalVar = new GlobalVariable( 2274130ca30fSTobias Grosser *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name, 2275130ca30fSTobias Grosser nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3); 2276f7b3ae65SMichael Kruse GlobalVar->setAlignment(llvm::Align(EleTy->getPrimitiveSizeInBits() / 8)); 2277f919d8b3STobias Grosser GlobalVar->setInitializer(Constant::getNullValue(ArrayTy)); 2278f919d8b3STobias Grosser 2279130ca30fSTobias Grosser Allocation = GlobalVar; 2280130ca30fSTobias Grosser } else if (Var.type == ppcg_access_private) { 2281130ca30fSTobias Grosser Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array"); 2282130ca30fSTobias Grosser } else { 2283130ca30fSTobias Grosser llvm_unreachable("unknown variable type"); 2284130ca30fSTobias Grosser } 22854d5a9172STobias Grosser SAI = 22864d5a9172STobias Grosser S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array); 228700fd43b3SPhilip Pfaffe Id = isl_id_alloc(S.getIslCtx().get(), Var.name, nullptr); 2288130ca30fSTobias Grosser IDToValue[Id] = Allocation; 2289130ca30fSTobias Grosser LocalArrays.push_back(Allocation); 2290b513b491STobias Grosser KernelIds.push_back(Id); 2291b513b491STobias Grosser IDToSAI[Id] = SAI; 2292b513b491STobias Grosser } 2293b513b491STobias Grosser } 2294b513b491STobias Grosser 2295f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction( 2296f291c8d5SSiddharth Bhat ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues, 2297f291c8d5SSiddharth Bhat SetVector<Function *> &SubtreeFunctions) { 229879f13b9aSSingapuram Sanjay Srivallabh std::string Identifier = getKernelFuncName(Kernel->id); 229932837fe3STobias Grosser GPUModule.reset(new Module(Identifier, Builder.getContext())); 230017f01968SSiddharth Bhat 230117f01968SSiddharth Bhat switch (Arch) { 230217f01968SSiddharth Bhat case GPUArch::NVPTX64: 230317f01968SSiddharth Bhat if (Runtime == GPURuntime::CUDA) 230432837fe3STobias Grosser GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda")); 230517f01968SSiddharth Bhat else if (Runtime == GPURuntime::OpenCL) 230617f01968SSiddharth Bhat GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl")); 230732837fe3STobias Grosser GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */)); 230817f01968SSiddharth Bhat break; 23092f3073b5SPhilipp Schaad case GPUArch::SPIR32: 23102f3073b5SPhilipp Schaad GPUModule->setTargetTriple(Triple::normalize("spir-unknown-unknown")); 23112f3073b5SPhilipp Schaad GPUModule->setDataLayout(computeSPIRDataLayout(false /* is64Bit */)); 23122f3073b5SPhilipp Schaad break; 23132f3073b5SPhilipp Schaad case GPUArch::SPIR64: 23142f3073b5SPhilipp Schaad GPUModule->setTargetTriple(Triple::normalize("spir64-unknown-unknown")); 23152f3073b5SPhilipp Schaad GPUModule->setDataLayout(computeSPIRDataLayout(true /* is64Bit */)); 23162f3073b5SPhilipp Schaad break; 231717f01968SSiddharth Bhat } 231832837fe3STobias Grosser 2319edb885cbSTobias Grosser Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues); 232032837fe3STobias Grosser 232159ab0705STobias Grosser BasicBlock *PrevBlock = Builder.GetInsertBlock(); 232232837fe3STobias Grosser auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN); 232332837fe3STobias Grosser 232459ab0705STobias Grosser DT.addNewBlock(EntryBlock, PrevBlock); 232559ab0705STobias Grosser 232632837fe3STobias Grosser Builder.SetInsertPoint(EntryBlock); 232732837fe3STobias Grosser Builder.CreateRetVoid(); 232832837fe3STobias Grosser Builder.SetInsertPoint(EntryBlock, EntryBlock->begin()); 2329472f9654STobias Grosser 2330629109b6STobias Grosser ScopDetection::markFunctionAsInvalid(FN); 2331629109b6STobias Grosser 233200bb5a99STobias Grosser prepareKernelArguments(Kernel, FN); 2333b513b491STobias Grosser createKernelVariables(Kernel, FN); 23342f3073b5SPhilipp Schaad 23352f3073b5SPhilipp Schaad switch (Arch) { 23362f3073b5SPhilipp Schaad case GPUArch::NVPTX64: 2337472f9654STobias Grosser insertKernelIntrinsics(Kernel); 23382f3073b5SPhilipp Schaad break; 23392f3073b5SPhilipp Schaad case GPUArch::SPIR32: 2340d71493cbSPhilip Pfaffe insertKernelCallsSPIR(Kernel, false); 2341d71493cbSPhilip Pfaffe break; 23422f3073b5SPhilipp Schaad case GPUArch::SPIR64: 2343d71493cbSPhilip Pfaffe insertKernelCallsSPIR(Kernel, true); 23442f3073b5SPhilipp Schaad break; 23452f3073b5SPhilipp Schaad } 234632837fe3STobias Grosser } 234732837fe3STobias Grosser 234874dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() { 234917f01968SSiddharth Bhat llvm::Triple GPUTriple; 235017f01968SSiddharth Bhat 235117f01968SSiddharth Bhat switch (Arch) { 235217f01968SSiddharth Bhat case GPUArch::NVPTX64: 235317f01968SSiddharth Bhat switch (Runtime) { 235417f01968SSiddharth Bhat case GPURuntime::CUDA: 235517f01968SSiddharth Bhat GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda")); 235617f01968SSiddharth Bhat break; 235717f01968SSiddharth Bhat case GPURuntime::OpenCL: 235817f01968SSiddharth Bhat GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl")); 235917f01968SSiddharth Bhat break; 236017f01968SSiddharth Bhat } 236117f01968SSiddharth Bhat break; 23622f3073b5SPhilipp Schaad case GPUArch::SPIR64: 23632f3073b5SPhilipp Schaad case GPUArch::SPIR32: 23642f3073b5SPhilipp Schaad std::string SPIRAssembly; 23652f3073b5SPhilipp Schaad raw_string_ostream IROstream(SPIRAssembly); 23662f3073b5SPhilipp Schaad IROstream << *GPUModule; 23672f3073b5SPhilipp Schaad IROstream.flush(); 23682f3073b5SPhilipp Schaad return SPIRAssembly; 236917f01968SSiddharth Bhat } 237017f01968SSiddharth Bhat 237174dc3cb4STobias Grosser std::string ErrMsg; 237274dc3cb4STobias Grosser auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg); 237374dc3cb4STobias Grosser 237474dc3cb4STobias Grosser if (!GPUTarget) { 237574dc3cb4STobias Grosser errs() << ErrMsg << "\n"; 237674dc3cb4STobias Grosser return ""; 237774dc3cb4STobias Grosser } 237874dc3cb4STobias Grosser 237974dc3cb4STobias Grosser TargetOptions Options; 238074dc3cb4STobias Grosser Options.UnsafeFPMath = FastMath; 238117f01968SSiddharth Bhat 238217f01968SSiddharth Bhat std::string subtarget; 238317f01968SSiddharth Bhat 238417f01968SSiddharth Bhat switch (Arch) { 238517f01968SSiddharth Bhat case GPUArch::NVPTX64: 238617f01968SSiddharth Bhat subtarget = CudaVersion; 238717f01968SSiddharth Bhat break; 23882f3073b5SPhilipp Schaad case GPUArch::SPIR32: 23892f3073b5SPhilipp Schaad case GPUArch::SPIR64: 23902f3073b5SPhilipp Schaad llvm_unreachable("No subtarget for SPIR architecture"); 239117f01968SSiddharth Bhat } 239217f01968SSiddharth Bhat 239317f01968SSiddharth Bhat std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine( 239417f01968SSiddharth Bhat GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>())); 239574dc3cb4STobias Grosser 239674dc3cb4STobias Grosser SmallString<0> ASMString; 239774dc3cb4STobias Grosser raw_svector_ostream ASMStream(ASMString); 239874dc3cb4STobias Grosser llvm::legacy::PassManager PM; 239974dc3cb4STobias Grosser 240074dc3cb4STobias Grosser PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis())); 240174dc3cb4STobias Grosser 24021dfede31SReid Kleckner if (TargetM->addPassesToEmitFile(PM, ASMStream, nullptr, CGFT_AssemblyFile, 24039a45114bSPeter Collingbourne true /* verify */)) { 240474dc3cb4STobias Grosser errs() << "The target does not support generation of this file type!\n"; 240574dc3cb4STobias Grosser return ""; 240674dc3cb4STobias Grosser } 240774dc3cb4STobias Grosser 240874dc3cb4STobias Grosser PM.run(*GPUModule); 240974dc3cb4STobias Grosser 24101a53b732SMichael Kruse return ASMStream.str().str(); 241174dc3cb4STobias Grosser } 241274dc3cb4STobias Grosser 24138fc6cdfbSTobias Grosser bool GPUNodeBuilder::requiresCUDALibDevice() { 24145b307cdbSTobias Grosser bool RequiresLibDevice = false; 24158fc6cdfbSTobias Grosser for (Function &F : GPUModule->functions()) { 24168fc6cdfbSTobias Grosser if (!F.isDeclaration()) 24178fc6cdfbSTobias Grosser continue; 24188fc6cdfbSTobias Grosser 241966a05ad6SPhilip Pfaffe const std::string CUDALibDeviceFunc = getCUDALibDeviceFuntion(F.getName()); 24208fc6cdfbSTobias Grosser if (CUDALibDeviceFunc.length() != 0) { 242156572c6aSSiddharth Bhat // We need to handle the case where a module looks like this: 242256572c6aSSiddharth Bhat // @expf(..) 242356572c6aSSiddharth Bhat // @llvm.exp.f64(..) 242456572c6aSSiddharth Bhat // Both of these functions would be renamed to `__nv_expf`. 242556572c6aSSiddharth Bhat // 242656572c6aSSiddharth Bhat // So, we must first check for the existence of the libdevice function. 242756572c6aSSiddharth Bhat // If this exists, we replace our current function with it. 242856572c6aSSiddharth Bhat // 242956572c6aSSiddharth Bhat // If it does not exist, we rename the current function to the 243056572c6aSSiddharth Bhat // libdevice functiono name. 243156572c6aSSiddharth Bhat if (Function *Replacement = F.getParent()->getFunction(CUDALibDeviceFunc)) 243256572c6aSSiddharth Bhat F.replaceAllUsesWith(Replacement); 243356572c6aSSiddharth Bhat else 24348fc6cdfbSTobias Grosser F.setName(CUDALibDeviceFunc); 24355b307cdbSTobias Grosser RequiresLibDevice = true; 24368fc6cdfbSTobias Grosser } 24378fc6cdfbSTobias Grosser } 24388fc6cdfbSTobias Grosser 24395b307cdbSTobias Grosser return RequiresLibDevice; 24408fc6cdfbSTobias Grosser } 24418fc6cdfbSTobias Grosser 24428fc6cdfbSTobias Grosser void GPUNodeBuilder::addCUDALibDevice() { 24438fc6cdfbSTobias Grosser if (Arch != GPUArch::NVPTX64) 24448fc6cdfbSTobias Grosser return; 24458fc6cdfbSTobias Grosser 24468fc6cdfbSTobias Grosser if (requiresCUDALibDevice()) { 24478fc6cdfbSTobias Grosser SMDiagnostic Error; 24488fc6cdfbSTobias Grosser 24498fc6cdfbSTobias Grosser errs() << CUDALibDevice << "\n"; 24508fc6cdfbSTobias Grosser auto LibDeviceModule = 24518fc6cdfbSTobias Grosser parseIRFile(CUDALibDevice, Error, GPUModule->getContext()); 24528fc6cdfbSTobias Grosser 24538fc6cdfbSTobias Grosser if (!LibDeviceModule) { 24548fc6cdfbSTobias Grosser BuildSuccessful = false; 24558fc6cdfbSTobias Grosser report_fatal_error("Could not find or load libdevice. Skipping GPU " 24568fc6cdfbSTobias Grosser "kernel generation. Please set -polly-acc-libdevice " 24578fc6cdfbSTobias Grosser "accordingly.\n"); 24588fc6cdfbSTobias Grosser return; 24598fc6cdfbSTobias Grosser } 24608fc6cdfbSTobias Grosser 24618fc6cdfbSTobias Grosser Linker L(*GPUModule); 24628fc6cdfbSTobias Grosser 24638fc6cdfbSTobias Grosser // Set an nvptx64 target triple to avoid linker warnings. The original 24648fc6cdfbSTobias Grosser // triple of the libdevice files are nvptx-unknown-unknown. 24658fc6cdfbSTobias Grosser LibDeviceModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda")); 24668fc6cdfbSTobias Grosser L.linkInModule(std::move(LibDeviceModule), Linker::LinkOnlyNeeded); 24678fc6cdfbSTobias Grosser } 24688fc6cdfbSTobias Grosser } 24698fc6cdfbSTobias Grosser 247057793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() { 247165d7f72fSSiddharth Bhat 24725857b701STobias Grosser if (verifyModule(*GPUModule)) { 2473349506a9SNicola Zaghen LLVM_DEBUG(dbgs() << "verifyModule failed on module:\n"; 247465d7f72fSSiddharth Bhat GPUModule->print(dbgs(), nullptr); dbgs() << "\n";); 2475349506a9SNicola Zaghen LLVM_DEBUG(dbgs() << "verifyModule Error:\n"; 2476a0fb8b23SSiddharth Bhat verifyModule(*GPUModule, &dbgs());); 247765d7f72fSSiddharth Bhat 247865d7f72fSSiddharth Bhat if (FailOnVerifyModuleFailure) 247965d7f72fSSiddharth Bhat llvm_unreachable("VerifyModule failed."); 248065d7f72fSSiddharth Bhat 24815857b701STobias Grosser BuildSuccessful = false; 24825857b701STobias Grosser return ""; 24835857b701STobias Grosser } 248432837fe3STobias Grosser 24858fc6cdfbSTobias Grosser addCUDALibDevice(); 24868fc6cdfbSTobias Grosser 248732837fe3STobias Grosser if (DumpKernelIR) 248832837fe3STobias Grosser outs() << *GPUModule << "\n"; 248932837fe3STobias Grosser 24902f3073b5SPhilipp Schaad if (Arch != GPUArch::SPIR32 && Arch != GPUArch::SPIR64) { 24919a18d559STobias Grosser // Optimize module. 24929a18d559STobias Grosser llvm::legacy::PassManager OptPasses; 24939a18d559STobias Grosser PassManagerBuilder PassBuilder; 24949a18d559STobias Grosser PassBuilder.OptLevel = 3; 24959a18d559STobias Grosser PassBuilder.SizeLevel = 0; 24969a18d559STobias Grosser PassBuilder.populateModulePassManager(OptPasses); 24979a18d559STobias Grosser OptPasses.run(*GPUModule); 24982f3073b5SPhilipp Schaad } 24999a18d559STobias Grosser 250074dc3cb4STobias Grosser std::string Assembly = createKernelASM(); 250174dc3cb4STobias Grosser 250274dc3cb4STobias Grosser if (DumpKernelASM) 250374dc3cb4STobias Grosser outs() << Assembly << "\n"; 250474dc3cb4STobias Grosser 250532837fe3STobias Grosser GPUModule.release(); 2506472f9654STobias Grosser KernelIDs.clear(); 250757793596STobias Grosser 250857793596STobias Grosser return Assembly; 250932837fe3STobias Grosser } 2510eadf76d3SSiddharth Bhat /// Construct an `isl_pw_aff_list` from a vector of `isl_pw_aff` 2511eadf76d3SSiddharth Bhat /// @param PwAffs The list of piecewise affine functions to create an 2512eadf76d3SSiddharth Bhat /// `isl_pw_aff_list` from. We expect an rvalue ref because 2513eadf76d3SSiddharth Bhat /// all the isl_pw_aff are used up by this function. 2514eadf76d3SSiddharth Bhat /// 2515eadf76d3SSiddharth Bhat /// @returns The `isl_pw_aff_list`. 2516eadf76d3SSiddharth Bhat __isl_give isl_pw_aff_list * 2517eadf76d3SSiddharth Bhat createPwAffList(isl_ctx *Context, 2518eadf76d3SSiddharth Bhat const std::vector<__isl_take isl_pw_aff *> &&PwAffs) { 2519eadf76d3SSiddharth Bhat isl_pw_aff_list *List = isl_pw_aff_list_alloc(Context, PwAffs.size()); 2520eadf76d3SSiddharth Bhat 2521eadf76d3SSiddharth Bhat for (unsigned i = 0; i < PwAffs.size(); i++) { 2522eadf76d3SSiddharth Bhat List = isl_pw_aff_list_insert(List, i, PwAffs[i]); 2523eadf76d3SSiddharth Bhat } 2524eadf76d3SSiddharth Bhat return List; 2525eadf76d3SSiddharth Bhat } 2526eadf76d3SSiddharth Bhat 2527eadf76d3SSiddharth Bhat /// Align all the `PwAffs` such that they have the same parameter dimensions. 2528eadf76d3SSiddharth Bhat /// 2529eadf76d3SSiddharth Bhat /// We loop over all `pw_aff` and align all of their spaces together to 2530eadf76d3SSiddharth Bhat /// create a common space for all the `pw_aff`. This common space is the 2531eadf76d3SSiddharth Bhat /// `AlignSpace`. We then align all the `pw_aff` to this space. We start 2532eadf76d3SSiddharth Bhat /// with the given `SeedSpace`. 2533eadf76d3SSiddharth Bhat /// @param PwAffs The list of piecewise affine functions we want to align. 2534eadf76d3SSiddharth Bhat /// This is an rvalue reference because the entire vector is 2535eadf76d3SSiddharth Bhat /// used up by the end of the operation. 2536eadf76d3SSiddharth Bhat /// @param SeedSpace The space to start the alignment process with. 2537eadf76d3SSiddharth Bhat /// @returns A std::pair, whose first element is the aligned space, 2538eadf76d3SSiddharth Bhat /// whose second element is the vector of aligned piecewise 2539eadf76d3SSiddharth Bhat /// affines. 2540eadf76d3SSiddharth Bhat static std::pair<__isl_give isl_space *, std::vector<__isl_give isl_pw_aff *>> 2541eadf76d3SSiddharth Bhat alignPwAffs(const std::vector<__isl_take isl_pw_aff *> &&PwAffs, 2542eadf76d3SSiddharth Bhat __isl_take isl_space *SeedSpace) { 2543eadf76d3SSiddharth Bhat assert(SeedSpace && "Invalid seed space given."); 2544eadf76d3SSiddharth Bhat 2545eadf76d3SSiddharth Bhat isl_space *AlignSpace = SeedSpace; 2546eadf76d3SSiddharth Bhat for (isl_pw_aff *PwAff : PwAffs) { 2547eadf76d3SSiddharth Bhat isl_space *PwAffSpace = isl_pw_aff_get_domain_space(PwAff); 2548eadf76d3SSiddharth Bhat AlignSpace = isl_space_align_params(AlignSpace, PwAffSpace); 2549eadf76d3SSiddharth Bhat } 2550eadf76d3SSiddharth Bhat std::vector<isl_pw_aff *> AdjustedPwAffs; 2551eadf76d3SSiddharth Bhat 2552eadf76d3SSiddharth Bhat for (unsigned i = 0; i < PwAffs.size(); i++) { 2553eadf76d3SSiddharth Bhat isl_pw_aff *Adjusted = PwAffs[i]; 2554eadf76d3SSiddharth Bhat assert(Adjusted && "Invalid pw_aff given."); 2555eadf76d3SSiddharth Bhat Adjusted = isl_pw_aff_align_params(Adjusted, isl_space_copy(AlignSpace)); 2556eadf76d3SSiddharth Bhat AdjustedPwAffs.push_back(Adjusted); 2557eadf76d3SSiddharth Bhat } 2558eadf76d3SSiddharth Bhat return std::make_pair(AlignSpace, AdjustedPwAffs); 2559eadf76d3SSiddharth Bhat } 256032837fe3STobias Grosser 25619dfe4e7cSTobias Grosser namespace { 25629dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass { 25639dfe4e7cSTobias Grosser public: 25649dfe4e7cSTobias Grosser static char ID; 25659dfe4e7cSTobias Grosser 256617f01968SSiddharth Bhat GPURuntime Runtime = GPURuntime::CUDA; 256717f01968SSiddharth Bhat 256817f01968SSiddharth Bhat GPUArch Architecture = GPUArch::NVPTX64; 256917f01968SSiddharth Bhat 2570e938517eSTobias Grosser /// The scop that is currently processed. 2571e938517eSTobias Grosser Scop *S; 2572e938517eSTobias Grosser 257338fc0aedSTobias Grosser LoopInfo *LI; 257438fc0aedSTobias Grosser DominatorTree *DT; 257538fc0aedSTobias Grosser ScalarEvolution *SE; 257638fc0aedSTobias Grosser const DataLayout *DL; 257738fc0aedSTobias Grosser RegionInfo *RI; 257838fc0aedSTobias Grosser 25793dcb5351SMichael Kruse PPCGCodeGeneration() : ScopPass(ID) { 25803dcb5351SMichael Kruse // Apply defaults. 25813dcb5351SMichael Kruse Runtime = GPURuntimeChoice; 25823dcb5351SMichael Kruse Architecture = GPUArchChoice; 25833dcb5351SMichael Kruse } 25849dfe4e7cSTobias Grosser 2585e938517eSTobias Grosser /// Construct compilation options for PPCG. 2586e938517eSTobias Grosser /// 2587e938517eSTobias Grosser /// @returns The compilation options. 2588e938517eSTobias Grosser ppcg_options *createPPCGOptions() { 2589e938517eSTobias Grosser auto DebugOptions = 2590e938517eSTobias Grosser (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options)); 2591e938517eSTobias Grosser auto Options = (ppcg_options *)malloc(sizeof(ppcg_options)); 2592e938517eSTobias Grosser 2593e938517eSTobias Grosser DebugOptions->dump_schedule_constraints = false; 2594e938517eSTobias Grosser DebugOptions->dump_schedule = false; 2595e938517eSTobias Grosser DebugOptions->dump_final_schedule = false; 2596e938517eSTobias Grosser DebugOptions->dump_sizes = false; 25978950ceadSTobias Grosser DebugOptions->verbose = false; 2598e938517eSTobias Grosser 2599e938517eSTobias Grosser Options->debug = DebugOptions; 2600e938517eSTobias Grosser 26019e3db2b7SSiddharth Bhat Options->group_chains = false; 2602e938517eSTobias Grosser Options->reschedule = true; 2603e938517eSTobias Grosser Options->scale_tile_loops = false; 2604e938517eSTobias Grosser Options->wrap = false; 2605e938517eSTobias Grosser 2606e938517eSTobias Grosser Options->non_negative_parameters = false; 2607e938517eSTobias Grosser Options->ctx = nullptr; 2608e938517eSTobias Grosser Options->sizes = nullptr; 2609e938517eSTobias Grosser 26109e3db2b7SSiddharth Bhat Options->tile = true; 26114eaedde5STobias Grosser Options->tile_size = 32; 26124eaedde5STobias Grosser 26139e3db2b7SSiddharth Bhat Options->isolate_full_tiles = false; 26149e3db2b7SSiddharth Bhat 2615130ca30fSTobias Grosser Options->use_private_memory = PrivateMemory; 2616b513b491STobias Grosser Options->use_shared_memory = SharedMemory; 2617b513b491STobias Grosser Options->max_shared_memory = 48 * 1024; 2618e938517eSTobias Grosser 2619e938517eSTobias Grosser Options->target = PPCG_TARGET_CUDA; 2620e938517eSTobias Grosser Options->openmp = false; 2621e938517eSTobias Grosser Options->linearize_device_arrays = true; 26229e3db2b7SSiddharth Bhat Options->allow_gnu_extensions = false; 2623e938517eSTobias Grosser 26249e3db2b7SSiddharth Bhat Options->unroll_copy_shared = false; 26259e3db2b7SSiddharth Bhat Options->unroll_gpu_tile = false; 26269e3db2b7SSiddharth Bhat Options->live_range_reordering = true; 26279e3db2b7SSiddharth Bhat 26289e3db2b7SSiddharth Bhat Options->live_range_reordering = true; 26299e3db2b7SSiddharth Bhat Options->hybrid = false; 2630e938517eSTobias Grosser Options->opencl_compiler_options = nullptr; 2631e938517eSTobias Grosser Options->opencl_use_gpu = false; 2632e938517eSTobias Grosser Options->opencl_n_include_file = 0; 2633e938517eSTobias Grosser Options->opencl_include_files = nullptr; 2634e938517eSTobias Grosser Options->opencl_print_kernel_types = false; 2635e938517eSTobias Grosser Options->opencl_embed_kernel_code = false; 2636e938517eSTobias Grosser 2637e938517eSTobias Grosser Options->save_schedule_file = nullptr; 2638e938517eSTobias Grosser Options->load_schedule_file = nullptr; 2639e938517eSTobias Grosser 2640e938517eSTobias Grosser return Options; 2641e938517eSTobias Grosser } 2642e938517eSTobias Grosser 2643f384594dSTobias Grosser /// Get a tagged access relation containing all accesses of type @p AccessTy. 2644f384594dSTobias Grosser /// 2645f384594dSTobias Grosser /// Instead of a normal access of the form: 2646f384594dSTobias Grosser /// 2647f384594dSTobias Grosser /// Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)] 2648f384594dSTobias Grosser /// 2649f384594dSTobias Grosser /// a tagged access has the form 2650f384594dSTobias Grosser /// 2651f384594dSTobias Grosser /// [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)] 2652f384594dSTobias Grosser /// 2653f384594dSTobias Grosser /// where 'id' is an additional space that references the memory access that 2654f384594dSTobias Grosser /// triggered the access. 2655f384594dSTobias Grosser /// 2656f384594dSTobias Grosser /// @param AccessTy The type of the memory accesses to collect. 2657f384594dSTobias Grosser /// 2658f384594dSTobias Grosser /// @return The relation describing all tagged memory accesses. 2659f384594dSTobias Grosser isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) { 2660b65ccc43STobias Grosser isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace().release()); 2661f384594dSTobias Grosser 2662f384594dSTobias Grosser for (auto &Stmt : *S) 2663f384594dSTobias Grosser for (auto &Acc : Stmt) 2664f384594dSTobias Grosser if (Acc->getType() == AccessTy) { 26651515f6b9STobias Grosser isl_map *Relation = Acc->getAccessRelation().release(); 2666dcf8d696STobias Grosser Relation = 2667dcf8d696STobias Grosser isl_map_intersect_domain(Relation, Stmt.getDomain().release()); 2668f384594dSTobias Grosser 2669f384594dSTobias Grosser isl_space *Space = isl_map_get_space(Relation); 2670f384594dSTobias Grosser Space = isl_space_range(Space); 2671f384594dSTobias Grosser Space = isl_space_from_range(Space); 2672fe46c3ffSTobias Grosser Space = 2673fe46c3ffSTobias Grosser isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release()); 2674f384594dSTobias Grosser isl_map *Universe = isl_map_universe(Space); 2675f384594dSTobias Grosser Relation = isl_map_domain_product(Relation, Universe); 2676f384594dSTobias Grosser Accesses = isl_union_map_add_map(Accesses, Relation); 2677f384594dSTobias Grosser } 2678f384594dSTobias Grosser 2679f384594dSTobias Grosser return Accesses; 2680f384594dSTobias Grosser } 2681f384594dSTobias Grosser 2682f384594dSTobias Grosser /// Get the set of all read accesses, tagged with the access id. 2683f384594dSTobias Grosser /// 2684f384594dSTobias Grosser /// @see getTaggedAccesses 2685f384594dSTobias Grosser isl_union_map *getTaggedReads() { 2686f384594dSTobias Grosser return getTaggedAccesses(MemoryAccess::READ); 2687f384594dSTobias Grosser } 2688f384594dSTobias Grosser 2689f384594dSTobias Grosser /// Get the set of all may (and must) accesses, tagged with the access id. 2690f384594dSTobias Grosser /// 2691f384594dSTobias Grosser /// @see getTaggedAccesses 2692f384594dSTobias Grosser isl_union_map *getTaggedMayWrites() { 2693f384594dSTobias Grosser return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE), 2694f384594dSTobias Grosser getTaggedAccesses(MemoryAccess::MUST_WRITE)); 2695f384594dSTobias Grosser } 2696f384594dSTobias Grosser 2697f384594dSTobias Grosser /// Get the set of all must accesses, tagged with the access id. 2698f384594dSTobias Grosser /// 2699f384594dSTobias Grosser /// @see getTaggedAccesses 2700f384594dSTobias Grosser isl_union_map *getTaggedMustWrites() { 2701f384594dSTobias Grosser return getTaggedAccesses(MemoryAccess::MUST_WRITE); 2702f384594dSTobias Grosser } 2703f384594dSTobias Grosser 2704aef5196fSTobias Grosser /// Collect parameter and array names as isl_ids. 2705aef5196fSTobias Grosser /// 2706aef5196fSTobias Grosser /// To reason about the different parameters and arrays used, ppcg requires 2707aef5196fSTobias Grosser /// a list of all isl_ids in use. As PPCG traditionally performs 2708aef5196fSTobias Grosser /// source-to-source compilation each of these isl_ids is mapped to the 2709aef5196fSTobias Grosser /// expression that represents it. As we do not have a corresponding 2710aef5196fSTobias Grosser /// expression in Polly, we just map each id to a 'zero' expression to match 2711aef5196fSTobias Grosser /// the data format that ppcg expects. 2712aef5196fSTobias Grosser /// 2713aef5196fSTobias Grosser /// @returns Retun a map from collected ids to 'zero' ast expressions. 2714aef5196fSTobias Grosser __isl_give isl_id_to_ast_expr *getNames() { 2715aef5196fSTobias Grosser auto *Names = isl_id_to_ast_expr_alloc( 271600fd43b3SPhilip Pfaffe S->getIslCtx().get(), 2717bd81a7eeSTobias Grosser S->getNumParams() + std::distance(S->array_begin(), S->array_end())); 271800fd43b3SPhilip Pfaffe auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx().get())); 2719aef5196fSTobias Grosser 272025271b91STobias Grosser for (const SCEV *P : S->parameters()) { 27219a63570bSTobias Grosser isl_id *Id = S->getIdForParam(P).release(); 2722aef5196fSTobias Grosser Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2723aef5196fSTobias Grosser } 2724aef5196fSTobias Grosser 2725aef5196fSTobias Grosser for (auto &Array : S->arrays()) { 272677eef90fSTobias Grosser auto Id = Array->getBasePtrId().release(); 2727aef5196fSTobias Grosser Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2728aef5196fSTobias Grosser } 2729aef5196fSTobias Grosser 2730aef5196fSTobias Grosser isl_ast_expr_free(Zero); 2731aef5196fSTobias Grosser 2732aef5196fSTobias Grosser return Names; 2733aef5196fSTobias Grosser } 2734aef5196fSTobias Grosser 2735e938517eSTobias Grosser /// Create a new PPCG scop from the current scop. 2736e938517eSTobias Grosser /// 2737f384594dSTobias Grosser /// The PPCG scop is initialized with data from the current polly::Scop. From 2738f384594dSTobias Grosser /// this initial data, the data-dependences in the PPCG scop are initialized. 2739f384594dSTobias Grosser /// We do not use Polly's dependence analysis for now, to ensure we match 2740f384594dSTobias Grosser /// the PPCG default behaviour more closely. 2741e938517eSTobias Grosser /// 2742e938517eSTobias Grosser /// @returns A new ppcg scop. 2743e938517eSTobias Grosser ppcg_scop *createPPCGScop() { 27449e3db2b7SSiddharth Bhat MustKillsInfo KillsInfo = computeMustKillsInfo(*S); 27459e3db2b7SSiddharth Bhat 2746e938517eSTobias Grosser auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop)); 2747e938517eSTobias Grosser 2748e938517eSTobias Grosser PPCGScop->options = createPPCGOptions(); 2749a82f2d26SSiddharth Bhat // enable live range reordering 2750a82f2d26SSiddharth Bhat PPCGScop->options->live_range_reordering = 1; 2751e938517eSTobias Grosser 2752e938517eSTobias Grosser PPCGScop->start = 0; 2753e938517eSTobias Grosser PPCGScop->end = 0; 2754e938517eSTobias Grosser 27558ea1fc19STobias Grosser PPCGScop->context = S->getContext().release(); 275631df6f31STobias Grosser PPCGScop->domain = S->getDomains().release(); 27579e3db2b7SSiddharth Bhat // TODO: investigate this further. PPCG calls collect_call_domains. 27588ea1fc19STobias Grosser PPCGScop->call = isl_union_set_from_set(S->getContext().release()); 2759f384594dSTobias Grosser PPCGScop->tagged_reads = getTaggedReads(); 27605ab39ff2STobias Grosser PPCGScop->reads = S->getReads().release(); 2761e938517eSTobias Grosser PPCGScop->live_in = nullptr; 2762f384594dSTobias Grosser PPCGScop->tagged_may_writes = getTaggedMayWrites(); 27635ab39ff2STobias Grosser PPCGScop->may_writes = S->getWrites().release(); 2764f384594dSTobias Grosser PPCGScop->tagged_must_writes = getTaggedMustWrites(); 27655ab39ff2STobias Grosser PPCGScop->must_writes = S->getMustWrites().release(); 2766e938517eSTobias Grosser PPCGScop->live_out = nullptr; 27678dae41a1STobias Grosser PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.release(); 27688dae41a1STobias Grosser PPCGScop->must_kills = KillsInfo.MustKills.release(); 27699e3db2b7SSiddharth Bhat 2770e938517eSTobias Grosser PPCGScop->tagger = nullptr; 2771a82f2d26SSiddharth Bhat PPCGScop->independence = 2772a82f2d26SSiddharth Bhat isl_union_map_empty(isl_set_get_space(PPCGScop->context)); 2773e938517eSTobias Grosser PPCGScop->dep_flow = nullptr; 2774e938517eSTobias Grosser PPCGScop->tagged_dep_flow = nullptr; 2775e938517eSTobias Grosser PPCGScop->dep_false = nullptr; 2776e938517eSTobias Grosser PPCGScop->dep_forced = nullptr; 2777e938517eSTobias Grosser PPCGScop->dep_order = nullptr; 2778e938517eSTobias Grosser PPCGScop->tagged_dep_order = nullptr; 2779e938517eSTobias Grosser 278061bd3a48STobias Grosser PPCGScop->schedule = S->getScheduleTree().release(); 2781a82f2d26SSiddharth Bhat // If we have something non-trivial to kill, add it to the schedule 2782a82f2d26SSiddharth Bhat if (KillsInfo.KillsSchedule.get()) 2783a82f2d26SSiddharth Bhat PPCGScop->schedule = isl_schedule_sequence( 27848dae41a1STobias Grosser PPCGScop->schedule, KillsInfo.KillsSchedule.release()); 2785a82f2d26SSiddharth Bhat 2786a82f2d26SSiddharth Bhat PPCGScop->names = getNames(); 2787e938517eSTobias Grosser PPCGScop->pet = nullptr; 2788e938517eSTobias Grosser 2789f384594dSTobias Grosser compute_tagger(PPCGScop); 2790f384594dSTobias Grosser compute_dependences(PPCGScop); 27919e3db2b7SSiddharth Bhat eliminate_dead_code(PPCGScop); 2792f384594dSTobias Grosser 2793e938517eSTobias Grosser return PPCGScop; 2794e938517eSTobias Grosser } 2795e938517eSTobias Grosser 2796a6d48f59SMichael Kruse /// Collect the array accesses in a statement. 279760f63b49STobias Grosser /// 279860f63b49STobias Grosser /// @param Stmt The statement for which to collect the accesses. 279960f63b49STobias Grosser /// 280060f63b49STobias Grosser /// @returns A list of array accesses. 280160f63b49STobias Grosser gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) { 280260f63b49STobias Grosser gpu_stmt_access *Accesses = nullptr; 280360f63b49STobias Grosser 280460f63b49STobias Grosser for (MemoryAccess *Acc : Stmt) { 280500fd43b3SPhilip Pfaffe auto Access = 280600fd43b3SPhilip Pfaffe isl_alloc_type(S->getIslCtx().get(), struct gpu_stmt_access); 280760f63b49STobias Grosser Access->read = Acc->isRead(); 280860f63b49STobias Grosser Access->write = Acc->isWrite(); 28091515f6b9STobias Grosser Access->access = Acc->getAccessRelation().release(); 281060f63b49STobias Grosser isl_space *Space = isl_map_get_space(Access->access); 281160f63b49STobias Grosser Space = isl_space_range(Space); 281260f63b49STobias Grosser Space = isl_space_from_range(Space); 2813fe46c3ffSTobias Grosser Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release()); 281460f63b49STobias Grosser isl_map *Universe = isl_map_universe(Space); 281560f63b49STobias Grosser Access->tagged_access = 28161515f6b9STobias Grosser isl_map_domain_product(Acc->getAccessRelation().release(), Universe); 2817b513b491STobias Grosser Access->exact_write = !Acc->isMayWrite(); 2818fe46c3ffSTobias Grosser Access->ref_id = Acc->getId().release(); 281960f63b49STobias Grosser Access->next = Accesses; 2820b513b491STobias Grosser Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions(); 2821ecb94a03STobias Grosser // TODO: Also mark one-element accesses to arrays as fixed-element. 2822ecb94a03STobias Grosser Access->fixed_element = 2823ecb94a03STobias Grosser Acc->isLatestScalarKind() ? isl_bool_true : isl_bool_false; 282460f63b49STobias Grosser Accesses = Access; 282560f63b49STobias Grosser } 282660f63b49STobias Grosser 282760f63b49STobias Grosser return Accesses; 282860f63b49STobias Grosser } 282960f63b49STobias Grosser 283069b46751STobias Grosser /// Collect the list of GPU statements. 283169b46751STobias Grosser /// 283269b46751STobias Grosser /// Each statement has an id, a pointer to the underlying data structure, 283369b46751STobias Grosser /// as well as a list with all memory accesses. 283469b46751STobias Grosser /// 283569b46751STobias Grosser /// TODO: Initialize the list of memory accesses. 283669b46751STobias Grosser /// 283769b46751STobias Grosser /// @returns A linked-list of statements. 283869b46751STobias Grosser gpu_stmt *getStatements() { 283900fd43b3SPhilip Pfaffe gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx().get(), struct gpu_stmt, 284069b46751STobias Grosser std::distance(S->begin(), S->end())); 284169b46751STobias Grosser 284269b46751STobias Grosser int i = 0; 284369b46751STobias Grosser for (auto &Stmt : *S) { 284469b46751STobias Grosser gpu_stmt *GPUStmt = &Stmts[i]; 284569b46751STobias Grosser 2846dcf8d696STobias Grosser GPUStmt->id = Stmt.getDomainId().release(); 284769b46751STobias Grosser 284869b46751STobias Grosser // We use the pet stmt pointer to keep track of the Polly statements. 284969b46751STobias Grosser GPUStmt->stmt = (pet_stmt *)&Stmt; 285060f63b49STobias Grosser GPUStmt->accesses = getStmtAccesses(Stmt); 285169b46751STobias Grosser i++; 285269b46751STobias Grosser } 285369b46751STobias Grosser 285469b46751STobias Grosser return Stmts; 285569b46751STobias Grosser } 285669b46751STobias Grosser 285760f63b49STobias Grosser /// Derive the extent of an array. 285860f63b49STobias Grosser /// 2859d58acf86STobias Grosser /// The extent of an array is the set of elements that are within the 2860d58acf86STobias Grosser /// accessed array. For the inner dimensions, the extent constraints are 2861d58acf86STobias Grosser /// 0 and the size of the corresponding array dimension. For the first 2862d58acf86STobias Grosser /// (outermost) dimension, the extent constraints are the minimal and maximal 2863d58acf86STobias Grosser /// subscript value for the first dimension. 286460f63b49STobias Grosser /// 286560f63b49STobias Grosser /// @param Array The array to derive the extent for. 286660f63b49STobias Grosser /// 286760f63b49STobias Grosser /// @returns An isl_set describing the extent of the array. 2868d2e57981STobias Grosser isl::set getExtent(ScopArrayInfo *Array) { 2869d58acf86STobias Grosser unsigned NumDims = Array->getNumberOfDimensions(); 2870fa03cb76STobias Grosser 2871fa03cb76STobias Grosser if (Array->getNumberOfDimensions() == 0) 2872fa03cb76STobias Grosser return isl::set::universe(Array->getSpace()); 2873fa03cb76STobias Grosser 2874fa03cb76STobias Grosser isl::union_map Accesses = S->getAccesses(Array); 2875d2e57981STobias Grosser isl::union_set AccessUSet = Accesses.range(); 2876d2e57981STobias Grosser AccessUSet = AccessUSet.coalesce(); 2877d2e57981STobias Grosser AccessUSet = AccessUSet.detect_equalities(); 2878d2e57981STobias Grosser AccessUSet = AccessUSet.coalesce(); 2879d58acf86STobias Grosser 2880d2e57981STobias Grosser if (AccessUSet.is_empty()) 2881d2e57981STobias Grosser return isl::set::empty(Array->getSpace()); 2882d58acf86STobias Grosser 2883d2e57981STobias Grosser isl::set AccessSet = AccessUSet.extract_set(Array->getSpace()); 288460f63b49STobias Grosser 2885d2e57981STobias Grosser isl::local_space LS = isl::local_space(Array->getSpace()); 2886d58acf86STobias Grosser 2887d2e57981STobias Grosser isl::pw_aff Val = isl::aff::var_on_domain(LS, isl::dim::set, 0); 2888d2e57981STobias Grosser isl::pw_aff OuterMin = AccessSet.dim_min(0); 2889d2e57981STobias Grosser isl::pw_aff OuterMax = AccessSet.dim_max(0); 289044596fe6SRiccardo Mori OuterMin = OuterMin.add_dims(isl::dim::in, 289144596fe6SRiccardo Mori unsignedFromIslSize(Val.dim(isl::dim::in))); 289244596fe6SRiccardo Mori OuterMax = OuterMax.add_dims(isl::dim::in, 289344596fe6SRiccardo Mori unsignedFromIslSize(Val.dim(isl::dim::in))); 2894d2e57981STobias Grosser OuterMin = OuterMin.set_tuple_id(isl::dim::in, Array->getBasePtrId()); 2895d2e57981STobias Grosser OuterMax = OuterMax.set_tuple_id(isl::dim::in, Array->getBasePtrId()); 2896d58acf86STobias Grosser 2897d2e57981STobias Grosser isl::set Extent = isl::set::universe(Array->getSpace()); 2898d58acf86STobias Grosser 2899d2e57981STobias Grosser Extent = Extent.intersect(OuterMin.le_set(Val)); 2900d2e57981STobias Grosser Extent = Extent.intersect(OuterMax.ge_set(Val)); 2901d58acf86STobias Grosser 2902d58acf86STobias Grosser for (unsigned i = 1; i < NumDims; ++i) 2903d2e57981STobias Grosser Extent = Extent.lower_bound_si(isl::dim::set, i, 0); 2904d58acf86STobias Grosser 2905b7f68b8cSSiddharth Bhat for (unsigned i = 0; i < NumDims; ++i) { 2906d2e57981STobias Grosser isl::pw_aff PwAff = Array->getDimensionSizePw(i); 2907b7f68b8cSSiddharth Bhat 2908b7f68b8cSSiddharth Bhat // isl_pw_aff can be NULL for zero dimension. Only in the case of a 2909b7f68b8cSSiddharth Bhat // Fortran array will we have a legitimate dimension. 2910d2e57981STobias Grosser if (PwAff.is_null()) { 2911b7f68b8cSSiddharth Bhat assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension"); 2912b7f68b8cSSiddharth Bhat continue; 2913b7f68b8cSSiddharth Bhat } 2914b7f68b8cSSiddharth Bhat 2915d2e57981STobias Grosser isl::pw_aff Val = isl::aff::var_on_domain( 2916d2e57981STobias Grosser isl::local_space(Array->getSpace()), isl::dim::set, i); 291744596fe6SRiccardo Mori PwAff = PwAff.add_dims(isl::dim::in, 291844596fe6SRiccardo Mori unsignedFromIslSize(Val.dim(isl::dim::in))); 2919d2e57981STobias Grosser PwAff = PwAff.set_tuple_id(isl::dim::in, Val.get_tuple_id(isl::dim::in)); 2920d2e57981STobias Grosser isl::set Set = PwAff.gt_set(Val); 2921d2e57981STobias Grosser Extent = Set.intersect(Extent); 2922d58acf86STobias Grosser } 2923d58acf86STobias Grosser 2924d58acf86STobias Grosser return Extent; 292560f63b49STobias Grosser } 292660f63b49STobias Grosser 292760f63b49STobias Grosser /// Derive the bounds of an array. 292860f63b49STobias Grosser /// 292960f63b49STobias Grosser /// For the first dimension we derive the bound of the array from the extent 293060f63b49STobias Grosser /// of this dimension. For inner dimensions we obtain their size directly from 293160f63b49STobias Grosser /// ScopArrayInfo. 293260f63b49STobias Grosser /// 293360f63b49STobias Grosser /// @param PPCGArray The array to compute bounds for. 293460f63b49STobias Grosser /// @param Array The polly array from which to take the information. 293560f63b49STobias Grosser void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) { 2936eadf76d3SSiddharth Bhat std::vector<isl_pw_aff *> Bounds; 29379e3db2b7SSiddharth Bhat 293860f63b49STobias Grosser if (PPCGArray.n_index > 0) { 293902293ed7STobias Grosser if (isl_set_is_empty(PPCGArray.extent)) { 294002293ed7STobias Grosser isl_set *Dom = isl_set_copy(PPCGArray.extent); 294102293ed7STobias Grosser isl_local_space *LS = isl_local_space_from_space( 294202293ed7STobias Grosser isl_space_params(isl_set_get_space(Dom))); 294302293ed7STobias Grosser isl_set_free(Dom); 29449e3db2b7SSiddharth Bhat isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS)); 2945eadf76d3SSiddharth Bhat Bounds.push_back(Zero); 294602293ed7STobias Grosser } else { 294760f63b49STobias Grosser isl_set *Dom = isl_set_copy(PPCGArray.extent); 294860f63b49STobias Grosser Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1); 294960f63b49STobias Grosser isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0); 295060f63b49STobias Grosser isl_set_free(Dom); 295160f63b49STobias Grosser Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound)); 295202293ed7STobias Grosser isl_local_space *LS = 295302293ed7STobias Grosser isl_local_space_from_space(isl_set_get_space(Dom)); 295460f63b49STobias Grosser isl_aff *One = isl_aff_zero_on_domain(LS); 295560f63b49STobias Grosser One = isl_aff_add_constant_si(One, 1); 295660f63b49STobias Grosser Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One)); 29578ea1fc19STobias Grosser Bound = isl_pw_aff_gist(Bound, S->getContext().release()); 2958eadf76d3SSiddharth Bhat Bounds.push_back(Bound); 295960f63b49STobias Grosser } 296002293ed7STobias Grosser } 296160f63b49STobias Grosser 296260f63b49STobias Grosser for (unsigned i = 1; i < PPCGArray.n_index; ++i) { 296377eef90fSTobias Grosser isl_pw_aff *Bound = Array->getDimensionSizePw(i).release(); 296460f63b49STobias Grosser auto LS = isl_pw_aff_get_domain_space(Bound); 296560f63b49STobias Grosser auto Aff = isl_multi_aff_zero(LS); 2966e2950f46SSiddharth Bhat 2967e2950f46SSiddharth Bhat // We need types to work out, which is why we perform this weird dance 2968e2950f46SSiddharth Bhat // with `Aff` and `Bound`. Consider this example: 2969e2950f46SSiddharth Bhat 2970e2950f46SSiddharth Bhat // LS: [p] -> { [] } 2971e2950f46SSiddharth Bhat // Zero: [p] -> { [] } | Implicitly, is [p] -> { ~ -> [] }. 2972e2950f46SSiddharth Bhat // This `~` is used to denote a "null space" (which is different from 2973e2950f46SSiddharth Bhat // a *zero dimensional* space), which is something that ISL does not 2974e2950f46SSiddharth Bhat // show you when pretty printing. 2975e2950f46SSiddharth Bhat 2976e2950f46SSiddharth Bhat // Bound: [p] -> { [] -> [(10p)] } | Here, the [] is a *zero dimensional* 2977e2950f46SSiddharth Bhat // space, not a "null space" which does not exist at all. 2978e2950f46SSiddharth Bhat 2979e2950f46SSiddharth Bhat // When we pullback (precompose) `Bound` with `Zero`, we get: 2980e2950f46SSiddharth Bhat // Bound . Zero = 2981e2950f46SSiddharth Bhat // ([p] -> { [] -> [(10p)] }) . ([p] -> {~ -> [] }) = 2982e2950f46SSiddharth Bhat // [p] -> { ~ -> [(10p)] } = 2983e2950f46SSiddharth Bhat // [p] -> [(10p)] (as ISL pretty prints it) 2984e2950f46SSiddharth Bhat // Bound Pullback: [p] -> { [(10p)] } 2985e2950f46SSiddharth Bhat 2986e2950f46SSiddharth Bhat // We want this kind of an expression for Bound, without a 2987e2950f46SSiddharth Bhat // zero dimensional input, but with a "null space" input for the types 2988e2950f46SSiddharth Bhat // to work out later on, as far as I (Siddharth Bhat) understand. 2989e2950f46SSiddharth Bhat // I was unable to find a reference to this in the ISL manual. 2990e2950f46SSiddharth Bhat // References: Tobias Grosser. 2991e2950f46SSiddharth Bhat 299260f63b49STobias Grosser Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff); 2993eadf76d3SSiddharth Bhat Bounds.push_back(Bound); 299460f63b49STobias Grosser } 29959e3db2b7SSiddharth Bhat 2996eadf76d3SSiddharth Bhat /// To construct a `isl_multi_pw_aff`, we need all the indivisual `pw_aff` 2997eadf76d3SSiddharth Bhat /// to have the same parameter dimensions. So, we need to align them to an 2998eadf76d3SSiddharth Bhat /// appropriate space. 2999eadf76d3SSiddharth Bhat /// Scop::Context is _not_ an appropriate space, because when we have 3000eadf76d3SSiddharth Bhat /// `-polly-ignore-parameter-bounds` enabled, the Scop::Context does not 3001eadf76d3SSiddharth Bhat /// contain all parameter dimensions. 3002eadf76d3SSiddharth Bhat /// So, use the helper `alignPwAffs` to align all the `isl_pw_aff` together. 3003b65ccc43STobias Grosser isl_space *SeedAlignSpace = S->getParamSpace().release(); 3004eadf76d3SSiddharth Bhat SeedAlignSpace = isl_space_add_dims(SeedAlignSpace, isl_dim_set, 1); 3005eadf76d3SSiddharth Bhat 3006eadf76d3SSiddharth Bhat isl_space *AlignSpace = nullptr; 3007eadf76d3SSiddharth Bhat std::vector<isl_pw_aff *> AlignedBounds; 3008eadf76d3SSiddharth Bhat std::tie(AlignSpace, AlignedBounds) = 3009eadf76d3SSiddharth Bhat alignPwAffs(std::move(Bounds), SeedAlignSpace); 3010eadf76d3SSiddharth Bhat 3011eadf76d3SSiddharth Bhat assert(AlignSpace && "alignPwAffs did not initialise AlignSpace"); 3012eadf76d3SSiddharth Bhat 3013eadf76d3SSiddharth Bhat isl_pw_aff_list *BoundsList = 301400fd43b3SPhilip Pfaffe createPwAffList(S->getIslCtx().get(), std::move(AlignedBounds)); 3015eadf76d3SSiddharth Bhat 30169e3db2b7SSiddharth Bhat isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent); 3017eadf76d3SSiddharth Bhat BoundsSpace = isl_space_align_params(BoundsSpace, AlignSpace); 30189e3db2b7SSiddharth Bhat 30199e3db2b7SSiddharth Bhat assert(BoundsSpace && "Unable to access space of array."); 30209e3db2b7SSiddharth Bhat assert(BoundsList && "Unable to access list of bounds."); 30219e3db2b7SSiddharth Bhat 30229e3db2b7SSiddharth Bhat PPCGArray.bound = 30239e3db2b7SSiddharth Bhat isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList); 30249e3db2b7SSiddharth Bhat assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly."); 302560f63b49STobias Grosser } 302660f63b49STobias Grosser 302760f63b49STobias Grosser /// Create the arrays for @p PPCGProg. 302860f63b49STobias Grosser /// 302960f63b49STobias Grosser /// @param PPCGProg The program to compute the arrays for. 303043f178bbSSiddharth Bhat void createArrays(gpu_prog *PPCGProg, 303143f178bbSSiddharth Bhat const SmallVector<ScopArrayInfo *, 4> &ValidSAIs) { 303260f63b49STobias Grosser int i = 0; 303343f178bbSSiddharth Bhat for (auto &Array : ValidSAIs) { 303460f63b49STobias Grosser std::string TypeName; 303560f63b49STobias Grosser raw_string_ostream OS(TypeName); 303660f63b49STobias Grosser 303760f63b49STobias Grosser OS << *Array->getElementType(); 303860f63b49STobias Grosser TypeName = OS.str(); 303960f63b49STobias Grosser 304060f63b49STobias Grosser gpu_array_info &PPCGArray = PPCGProg->array[i]; 304160f63b49STobias Grosser 304277eef90fSTobias Grosser PPCGArray.space = Array->getSpace().release(); 304360f63b49STobias Grosser PPCGArray.type = strdup(TypeName.c_str()); 304434eeabbcSSiddharth Bhat PPCGArray.size = DL->getTypeAllocSize(Array->getElementType()); 304560f63b49STobias Grosser PPCGArray.name = strdup(Array->getName().c_str()); 304660f63b49STobias Grosser PPCGArray.extent = nullptr; 304760f63b49STobias Grosser PPCGArray.n_index = Array->getNumberOfDimensions(); 3048d2e57981STobias Grosser PPCGArray.extent = getExtent(Array).release(); 304960f63b49STobias Grosser PPCGArray.n_ref = 0; 305060f63b49STobias Grosser PPCGArray.refs = nullptr; 305160f63b49STobias Grosser PPCGArray.accessed = true; 3052fe74a7a1STobias Grosser PPCGArray.read_only_scalar = 3053fe74a7a1STobias Grosser Array->isReadOnly() && Array->getNumberOfDimensions() == 0; 305460f63b49STobias Grosser PPCGArray.has_compound_element = false; 305560f63b49STobias Grosser PPCGArray.local = false; 305660f63b49STobias Grosser PPCGArray.declare_local = false; 305760f63b49STobias Grosser PPCGArray.global = false; 305860f63b49STobias Grosser PPCGArray.linearize = false; 305960f63b49STobias Grosser PPCGArray.dep_order = nullptr; 306013c78e4dSTobias Grosser PPCGArray.user = Array; 306160f63b49STobias Grosser 30629e3db2b7SSiddharth Bhat PPCGArray.bound = nullptr; 306360f63b49STobias Grosser setArrayBounds(PPCGArray, Array); 30642d010dafSTobias Grosser i++; 3065b9fc860aSTobias Grosser 3066b9fc860aSTobias Grosser collect_references(PPCGProg, &PPCGArray); 3067ecb94a03STobias Grosser PPCGArray.only_fixed_element = only_fixed_element_accessed(&PPCGArray); 306860f63b49STobias Grosser } 306960f63b49STobias Grosser } 307060f63b49STobias Grosser 307160f63b49STobias Grosser /// Create an identity map between the arrays in the scop. 307260f63b49STobias Grosser /// 307360f63b49STobias Grosser /// @returns An identity map between the arrays in the scop. 307460f63b49STobias Grosser isl_union_map *getArrayIdentity() { 3075b65ccc43STobias Grosser isl_union_map *Maps = isl_union_map_empty(S->getParamSpace().release()); 307660f63b49STobias Grosser 3077d7754a12SRoman Gareev for (auto &Array : S->arrays()) { 307877eef90fSTobias Grosser isl_space *Space = Array->getSpace().release(); 307960f63b49STobias Grosser Space = isl_space_map_from_set(Space); 308060f63b49STobias Grosser isl_map *Identity = isl_map_identity(Space); 308160f63b49STobias Grosser Maps = isl_union_map_add_map(Maps, Identity); 308260f63b49STobias Grosser } 308360f63b49STobias Grosser 308460f63b49STobias Grosser return Maps; 308560f63b49STobias Grosser } 308660f63b49STobias Grosser 3087e938517eSTobias Grosser /// Create a default-initialized PPCG GPU program. 3088e938517eSTobias Grosser /// 3089a6d48f59SMichael Kruse /// @returns A new gpu program description. 3090e938517eSTobias Grosser gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) { 3091e938517eSTobias Grosser 3092e938517eSTobias Grosser if (!PPCGScop) 3093e938517eSTobias Grosser return nullptr; 3094e938517eSTobias Grosser 309500fd43b3SPhilip Pfaffe auto PPCGProg = isl_calloc_type(S->getIslCtx().get(), struct gpu_prog); 3096e938517eSTobias Grosser 309700fd43b3SPhilip Pfaffe PPCGProg->ctx = S->getIslCtx().get(); 3098e938517eSTobias Grosser PPCGProg->scop = PPCGScop; 3099aef5196fSTobias Grosser PPCGProg->context = isl_set_copy(PPCGScop->context); 310060f63b49STobias Grosser PPCGProg->read = isl_union_map_copy(PPCGScop->reads); 310160f63b49STobias Grosser PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes); 310260f63b49STobias Grosser PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes); 310360f63b49STobias Grosser PPCGProg->tagged_must_kill = 310460f63b49STobias Grosser isl_union_map_copy(PPCGScop->tagged_must_kills); 310560f63b49STobias Grosser PPCGProg->to_inner = getArrayIdentity(); 310660f63b49STobias Grosser PPCGProg->to_outer = getArrayIdentity(); 31079e3db2b7SSiddharth Bhat // TODO: verify that this assignment is correct. 3108e938517eSTobias Grosser PPCGProg->any_to_outer = nullptr; 310969b46751STobias Grosser PPCGProg->n_stmts = std::distance(S->begin(), S->end()); 311069b46751STobias Grosser PPCGProg->stmts = getStatements(); 311143f178bbSSiddharth Bhat 311243f178bbSSiddharth Bhat // Only consider arrays that have a non-empty extent. 311343f178bbSSiddharth Bhat // Otherwise, this will cause us to consider the following kinds of 311443f178bbSSiddharth Bhat // empty arrays: 311543f178bbSSiddharth Bhat // 1. Invariant loads that are represented by SAI objects. 311643f178bbSSiddharth Bhat // 2. Arrays with statically known zero size. 311743f178bbSSiddharth Bhat auto ValidSAIsRange = 311843f178bbSSiddharth Bhat make_filter_range(S->arrays(), [this](ScopArrayInfo *SAI) -> bool { 3119d2e57981STobias Grosser return !getExtent(SAI).is_empty(); 312043f178bbSSiddharth Bhat }); 312143f178bbSSiddharth Bhat SmallVector<ScopArrayInfo *, 4> ValidSAIs(ValidSAIsRange.begin(), 312243f178bbSSiddharth Bhat ValidSAIsRange.end()); 312343f178bbSSiddharth Bhat 312443f178bbSSiddharth Bhat PPCGProg->n_array = 312543f178bbSSiddharth Bhat ValidSAIs.size(); // std::distance(S->array_begin(), S->array_end()); 312658166b13SMichael Kruse PPCGProg->array = isl_calloc_array( 312758166b13SMichael Kruse S->getIslCtx().get(), struct gpu_array_info, PPCGProg->n_array); 312860f63b49STobias Grosser 312943f178bbSSiddharth Bhat createArrays(PPCGProg, ValidSAIs); 3130e938517eSTobias Grosser 3131ecb94a03STobias Grosser PPCGProg->array_order = nullptr; 3132ecb94a03STobias Grosser collect_order_dependences(PPCGProg); 3133ecb94a03STobias Grosser 3134d58acf86STobias Grosser PPCGProg->may_persist = compute_may_persist(PPCGProg); 3135e938517eSTobias Grosser return PPCGProg; 3136e938517eSTobias Grosser } 3137e938517eSTobias Grosser 313869b46751STobias Grosser struct PrintGPUUserData { 313969b46751STobias Grosser struct cuda_info *CudaInfo; 314069b46751STobias Grosser struct gpu_prog *PPCGProg; 314169b46751STobias Grosser std::vector<ppcg_kernel *> Kernels; 314269b46751STobias Grosser }; 314369b46751STobias Grosser 314469b46751STobias Grosser /// Print a user statement node in the host code. 314569b46751STobias Grosser /// 314669b46751STobias Grosser /// We use ppcg's printing facilities to print the actual statement and 314769b46751STobias Grosser /// additionally build up a list of all kernels that are encountered in the 314869b46751STobias Grosser /// host ast. 314969b46751STobias Grosser /// 315069b46751STobias Grosser /// @param P The printer to print to 315169b46751STobias Grosser /// @param Options The printing options to use 315269b46751STobias Grosser /// @param Node The node to print 315369b46751STobias Grosser /// @param User A user pointer to carry additional data. This pointer is 315469b46751STobias Grosser /// expected to be of type PrintGPUUserData. 315569b46751STobias Grosser /// 315669b46751STobias Grosser /// @returns A printer to which the output has been printed. 315769b46751STobias Grosser static __isl_give isl_printer * 315869b46751STobias Grosser printHostUser(__isl_take isl_printer *P, 315969b46751STobias Grosser __isl_take isl_ast_print_options *Options, 316069b46751STobias Grosser __isl_take isl_ast_node *Node, void *User) { 316169b46751STobias Grosser auto Data = (struct PrintGPUUserData *)User; 316269b46751STobias Grosser auto Id = isl_ast_node_get_annotation(Node); 316369b46751STobias Grosser 316469b46751STobias Grosser if (Id) { 316520251734STobias Grosser bool IsUser = !strcmp(isl_id_get_name(Id), "user"); 316620251734STobias Grosser 316720251734STobias Grosser // If this is a user statement, format it ourselves as ppcg would 316820251734STobias Grosser // otherwise try to call pet functionality that is not available in 316920251734STobias Grosser // Polly. 317020251734STobias Grosser if (IsUser) { 317120251734STobias Grosser P = isl_printer_start_line(P); 317220251734STobias Grosser P = isl_printer_print_ast_node(P, Node); 317320251734STobias Grosser P = isl_printer_end_line(P); 317420251734STobias Grosser isl_id_free(Id); 317520251734STobias Grosser isl_ast_print_options_free(Options); 317620251734STobias Grosser return P; 317720251734STobias Grosser } 317820251734STobias Grosser 317969b46751STobias Grosser auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id); 318069b46751STobias Grosser isl_id_free(Id); 318169b46751STobias Grosser Data->Kernels.push_back(Kernel); 318269b46751STobias Grosser } 318369b46751STobias Grosser 318469b46751STobias Grosser return print_host_user(P, Options, Node, User); 318569b46751STobias Grosser } 318669b46751STobias Grosser 318769b46751STobias Grosser /// Print C code corresponding to the control flow in @p Kernel. 318869b46751STobias Grosser /// 318969b46751STobias Grosser /// @param Kernel The kernel to print 319069b46751STobias Grosser void printKernel(ppcg_kernel *Kernel) { 319100fd43b3SPhilip Pfaffe auto *P = isl_printer_to_str(S->getIslCtx().get()); 319269b46751STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C); 319300fd43b3SPhilip Pfaffe auto *Options = isl_ast_print_options_alloc(S->getIslCtx().get()); 319469b46751STobias Grosser P = isl_ast_node_print(Kernel->tree, P, Options); 319569b46751STobias Grosser char *String = isl_printer_get_str(P); 3196936c74adSSiddharth Bhat outs() << String << "\n"; 319769b46751STobias Grosser free(String); 319869b46751STobias Grosser isl_printer_free(P); 319969b46751STobias Grosser } 320069b46751STobias Grosser 320169b46751STobias Grosser /// Print C code corresponding to the GPU code described by @p Tree. 320269b46751STobias Grosser /// 320369b46751STobias Grosser /// @param Tree An AST describing GPU code 320469b46751STobias Grosser /// @param PPCGProg The PPCG program from which @Tree has been constructed. 320569b46751STobias Grosser void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) { 320600fd43b3SPhilip Pfaffe auto *P = isl_printer_to_str(S->getIslCtx().get()); 320769b46751STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C); 320869b46751STobias Grosser 320969b46751STobias Grosser PrintGPUUserData Data; 321069b46751STobias Grosser Data.PPCGProg = PPCGProg; 321169b46751STobias Grosser 321200fd43b3SPhilip Pfaffe auto *Options = isl_ast_print_options_alloc(S->getIslCtx().get()); 321369b46751STobias Grosser Options = 321469b46751STobias Grosser isl_ast_print_options_set_print_user(Options, printHostUser, &Data); 321569b46751STobias Grosser P = isl_ast_node_print(Tree, P, Options); 321669b46751STobias Grosser char *String = isl_printer_get_str(P); 3217936c74adSSiddharth Bhat outs() << "# host\n"; 3218936c74adSSiddharth Bhat outs() << String << "\n"; 321969b46751STobias Grosser free(String); 322069b46751STobias Grosser isl_printer_free(P); 322169b46751STobias Grosser 322269b46751STobias Grosser for (auto Kernel : Data.Kernels) { 3223936c74adSSiddharth Bhat outs() << "# kernel" << Kernel->id << "\n"; 322469b46751STobias Grosser printKernel(Kernel); 322569b46751STobias Grosser } 322669b46751STobias Grosser } 322769b46751STobias Grosser 3228f384594dSTobias Grosser // Generate a GPU program using PPCG. 3229f384594dSTobias Grosser // 3230f384594dSTobias Grosser // GPU mapping consists of multiple steps: 3231f384594dSTobias Grosser // 3232f384594dSTobias Grosser // 1) Compute new schedule for the program. 3233f384594dSTobias Grosser // 2) Map schedule to GPU (TODO) 3234f384594dSTobias Grosser // 3) Generate code for new schedule (TODO) 3235f384594dSTobias Grosser // 3236f384594dSTobias Grosser // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer 3237f384594dSTobias Grosser // is mostly CPU specific. Instead, we use PPCG's GPU code generation 3238f384594dSTobias Grosser // strategy directly from this pass. 3239f384594dSTobias Grosser gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) { 3240f384594dSTobias Grosser 324100fd43b3SPhilip Pfaffe auto PPCGGen = isl_calloc_type(S->getIslCtx().get(), struct gpu_gen); 3242f384594dSTobias Grosser 324300fd43b3SPhilip Pfaffe PPCGGen->ctx = S->getIslCtx().get(); 3244f384594dSTobias Grosser PPCGGen->options = PPCGScop->options; 3245f384594dSTobias Grosser PPCGGen->print = nullptr; 3246f384594dSTobias Grosser PPCGGen->print_user = nullptr; 324760c60025STobias Grosser PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt; 3248f384594dSTobias Grosser PPCGGen->prog = PPCGProg; 3249f384594dSTobias Grosser PPCGGen->tree = nullptr; 3250f384594dSTobias Grosser PPCGGen->types.n = 0; 3251f384594dSTobias Grosser PPCGGen->types.name = nullptr; 3252f384594dSTobias Grosser PPCGGen->sizes = nullptr; 3253f384594dSTobias Grosser PPCGGen->used_sizes = nullptr; 3254f384594dSTobias Grosser PPCGGen->kernel_id = 0; 3255f384594dSTobias Grosser 3256f384594dSTobias Grosser // Set scheduling strategy to same strategy PPCG is using. 325707e7cb94SMichael Kruse isl_options_set_schedule_serialize_sccs(PPCGGen->ctx, false); 3258f384594dSTobias Grosser isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true); 3259f384594dSTobias Grosser isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true); 32602341fe9eSTobias Grosser isl_options_set_schedule_whole_component(PPCGGen->ctx, false); 3261f384594dSTobias Grosser 3262f384594dSTobias Grosser isl_schedule *Schedule = get_schedule(PPCGGen); 3263f384594dSTobias Grosser 3264e32498c9STobias Grosser int has_permutable = has_any_permutable_node(Schedule); 3265e32498c9STobias Grosser 3266b5563c68STobias Grosser Schedule = 3267b5563c68STobias Grosser isl_schedule_align_params(Schedule, S->getFullParamSpace().release()); 3268b5563c68STobias Grosser 326969b46751STobias Grosser if (!has_permutable || has_permutable < 0) { 3270aef5196fSTobias Grosser Schedule = isl_schedule_free(Schedule); 3271349506a9SNicola Zaghen LLVM_DEBUG(dbgs() << getUniqueScopName(S) 3272638316daSSiddharth Bhat << " does not have permutable bands. Bailing out\n";); 327369b46751STobias Grosser } else { 3274861a387fSTobias Grosser const bool CreateTransferToFromDevice = !PollyManagedMemory; 3275861a387fSTobias Grosser Schedule = map_to_device(PPCGGen, Schedule, CreateTransferToFromDevice); 327669b46751STobias Grosser PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule)); 327769b46751STobias Grosser } 3278aef5196fSTobias Grosser 3279f384594dSTobias Grosser if (DumpSchedule) { 328000fd43b3SPhilip Pfaffe isl_printer *P = isl_printer_to_str(S->getIslCtx().get()); 3281f384594dSTobias Grosser P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK); 3282f384594dSTobias Grosser P = isl_printer_print_str(P, "Schedule\n"); 3283f384594dSTobias Grosser P = isl_printer_print_str(P, "========\n"); 3284f384594dSTobias Grosser if (Schedule) 3285f384594dSTobias Grosser P = isl_printer_print_schedule(P, Schedule); 3286f384594dSTobias Grosser else 3287f384594dSTobias Grosser P = isl_printer_print_str(P, "No schedule found\n"); 3288f384594dSTobias Grosser 3289936c74adSSiddharth Bhat outs() << isl_printer_get_str(P) << "\n"; 3290f384594dSTobias Grosser isl_printer_free(P); 3291f384594dSTobias Grosser } 3292f384594dSTobias Grosser 329369b46751STobias Grosser if (DumpCode) { 3294936c74adSSiddharth Bhat outs() << "Code\n"; 3295936c74adSSiddharth Bhat outs() << "====\n"; 329669b46751STobias Grosser if (PPCGGen->tree) 329769b46751STobias Grosser printGPUTree(PPCGGen->tree, PPCGProg); 329869b46751STobias Grosser else 3299936c74adSSiddharth Bhat outs() << "No code generated\n"; 330069b46751STobias Grosser } 330169b46751STobias Grosser 3302f384594dSTobias Grosser isl_schedule_free(Schedule); 3303f384594dSTobias Grosser 3304f384594dSTobias Grosser return PPCGGen; 3305f384594dSTobias Grosser } 3306f384594dSTobias Grosser 3307f384594dSTobias Grosser /// Free gpu_gen structure. 3308f384594dSTobias Grosser /// 3309f384594dSTobias Grosser /// @param PPCGGen The ppcg_gen object to free. 3310f384594dSTobias Grosser void freePPCGGen(gpu_gen *PPCGGen) { 3311f384594dSTobias Grosser isl_ast_node_free(PPCGGen->tree); 3312f384594dSTobias Grosser isl_union_map_free(PPCGGen->sizes); 3313f384594dSTobias Grosser isl_union_map_free(PPCGGen->used_sizes); 3314f384594dSTobias Grosser free(PPCGGen); 3315f384594dSTobias Grosser } 3316f384594dSTobias Grosser 3317b307ed4dSTobias Grosser /// Free the options in the ppcg scop structure. 3318b307ed4dSTobias Grosser /// 3319b307ed4dSTobias Grosser /// ppcg is not freeing these options for us. To avoid leaks we do this 3320b307ed4dSTobias Grosser /// ourselves. 3321b307ed4dSTobias Grosser /// 3322b307ed4dSTobias Grosser /// @param PPCGScop The scop referencing the options to free. 3323b307ed4dSTobias Grosser void freeOptions(ppcg_scop *PPCGScop) { 3324b307ed4dSTobias Grosser free(PPCGScop->options->debug); 3325b307ed4dSTobias Grosser PPCGScop->options->debug = nullptr; 3326b307ed4dSTobias Grosser free(PPCGScop->options); 3327b307ed4dSTobias Grosser PPCGScop->options = nullptr; 3328b307ed4dSTobias Grosser } 3329b307ed4dSTobias Grosser 333082f2af35STobias Grosser /// Approximate the number of points in the set. 333182f2af35STobias Grosser /// 333282f2af35STobias Grosser /// This function returns an ast expression that overapproximates the number 333382f2af35STobias Grosser /// of points in an isl set through the rectangular hull surrounding this set. 333482f2af35STobias Grosser /// 333582f2af35STobias Grosser /// @param Set The set to count. 333682f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 333782f2af35STobias Grosser /// expression. 333882f2af35STobias Grosser /// 333982f2af35STobias Grosser /// @returns An approximation of the number of points in the set. 334082f2af35STobias Grosser __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set, 334182f2af35STobias Grosser __isl_keep isl_ast_build *Build) { 334282f2af35STobias Grosser 334382f2af35STobias Grosser isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1); 334482f2af35STobias Grosser auto *Expr = isl_ast_expr_from_val(isl_val_copy(One)); 334582f2af35STobias Grosser 334682f2af35STobias Grosser isl_space *Space = isl_set_get_space(Set); 334782f2af35STobias Grosser Space = isl_space_params(Space); 334882f2af35STobias Grosser auto *Univ = isl_set_universe(Space); 334982f2af35STobias Grosser isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One); 335082f2af35STobias Grosser 33513044dc51SMichael Kruse for (long i = 0, n = isl_set_dim(Set, isl_dim_set); i < n; i++) { 335282f2af35STobias Grosser isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i); 335382f2af35STobias Grosser isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i); 335482f2af35STobias Grosser isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min); 335582f2af35STobias Grosser DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff)); 335682f2af35STobias Grosser auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize); 335782f2af35STobias Grosser Expr = isl_ast_expr_mul(Expr, DimSizeExpr); 335882f2af35STobias Grosser } 335982f2af35STobias Grosser 336082f2af35STobias Grosser isl_set_free(Set); 336182f2af35STobias Grosser isl_pw_aff_free(OneAff); 336282f2af35STobias Grosser 336382f2af35STobias Grosser return Expr; 336482f2af35STobias Grosser } 336582f2af35STobias Grosser 336682f2af35STobias Grosser /// Approximate a number of dynamic instructions executed by a given 336782f2af35STobias Grosser /// statement. 336882f2af35STobias Grosser /// 336982f2af35STobias Grosser /// @param Stmt The statement for which to compute the number of dynamic 337082f2af35STobias Grosser /// instructions. 337182f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 337282f2af35STobias Grosser /// expression. 337382f2af35STobias Grosser /// @returns An approximation of the number of dynamic instructions executed 337482f2af35STobias Grosser /// by @p Stmt. 337582f2af35STobias Grosser __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt, 337682f2af35STobias Grosser __isl_keep isl_ast_build *Build) { 3377dcf8d696STobias Grosser auto Iterations = approxPointsInSet(Stmt.getDomain().release(), Build); 337882f2af35STobias Grosser 337982f2af35STobias Grosser long InstCount = 0; 338082f2af35STobias Grosser 338182f2af35STobias Grosser if (Stmt.isBlockStmt()) { 338282f2af35STobias Grosser auto *BB = Stmt.getBasicBlock(); 338382f2af35STobias Grosser InstCount = std::distance(BB->begin(), BB->end()); 338482f2af35STobias Grosser } else { 338582f2af35STobias Grosser auto *R = Stmt.getRegion(); 338682f2af35STobias Grosser 338782f2af35STobias Grosser for (auto *BB : R->blocks()) { 338882f2af35STobias Grosser InstCount += std::distance(BB->begin(), BB->end()); 338982f2af35STobias Grosser } 339082f2af35STobias Grosser } 339182f2af35STobias Grosser 339200fd43b3SPhilip Pfaffe isl_val *InstVal = isl_val_int_from_si(S->getIslCtx().get(), InstCount); 339382f2af35STobias Grosser auto *InstExpr = isl_ast_expr_from_val(InstVal); 339482f2af35STobias Grosser return isl_ast_expr_mul(InstExpr, Iterations); 339582f2af35STobias Grosser } 339682f2af35STobias Grosser 339782f2af35STobias Grosser /// Approximate dynamic instructions executed in scop. 339882f2af35STobias Grosser /// 339982f2af35STobias Grosser /// @param S The scop for which to approximate dynamic instructions. 340082f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 340182f2af35STobias Grosser /// expression. 340282f2af35STobias Grosser /// @returns An approximation of the number of dynamic instructions executed 340382f2af35STobias Grosser /// in @p S. 340482f2af35STobias Grosser __isl_give isl_ast_expr * 340582f2af35STobias Grosser getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) { 340682f2af35STobias Grosser isl_ast_expr *Instructions; 340782f2af35STobias Grosser 340800fd43b3SPhilip Pfaffe isl_val *Zero = isl_val_int_from_si(S.getIslCtx().get(), 0); 340982f2af35STobias Grosser Instructions = isl_ast_expr_from_val(Zero); 341082f2af35STobias Grosser 341182f2af35STobias Grosser for (ScopStmt &Stmt : S) { 341282f2af35STobias Grosser isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build); 341382f2af35STobias Grosser Instructions = isl_ast_expr_add(Instructions, StmtInstructions); 341482f2af35STobias Grosser } 341582f2af35STobias Grosser return Instructions; 341682f2af35STobias Grosser } 341782f2af35STobias Grosser 341882f2af35STobias Grosser /// Create a check that ensures sufficient compute in scop. 341982f2af35STobias Grosser /// 342082f2af35STobias Grosser /// @param S The scop for which to ensure sufficient compute. 342182f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 342282f2af35STobias Grosser /// expression. 342382f2af35STobias Grosser /// @returns An expression that evaluates to TRUE in case of sufficient 342482f2af35STobias Grosser /// compute and to FALSE, otherwise. 342582f2af35STobias Grosser __isl_give isl_ast_expr * 342682f2af35STobias Grosser createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) { 342782f2af35STobias Grosser auto Iterations = getNumberOfIterations(S, Build); 342800fd43b3SPhilip Pfaffe auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx().get(), MinCompute); 342982f2af35STobias Grosser auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal); 343082f2af35STobias Grosser return isl_ast_expr_ge(Iterations, MinComputeExpr); 343182f2af35STobias Grosser } 343282f2af35STobias Grosser 3433f291c8d5SSiddharth Bhat /// Check if the basic block contains a function we cannot codegen for GPU 3434f291c8d5SSiddharth Bhat /// kernels. 3435f291c8d5SSiddharth Bhat /// 3436f291c8d5SSiddharth Bhat /// If this basic block does something with a `Function` other than calling 3437f291c8d5SSiddharth Bhat /// a function that we support in a kernel, return true. 34388fc6cdfbSTobias Grosser bool containsInvalidKernelFunctionInBlock(const BasicBlock *BB, 34398fc6cdfbSTobias Grosser bool AllowCUDALibDevice) { 3440f291c8d5SSiddharth Bhat for (const Instruction &Inst : *BB) { 3441f291c8d5SSiddharth Bhat const CallInst *Call = dyn_cast<CallInst>(&Inst); 34428fc6cdfbSTobias Grosser if (Call && isValidFunctionInKernel(Call->getCalledFunction(), 344378027437SSiddharth Bhat AllowCUDALibDevice)) 3444f291c8d5SSiddharth Bhat continue; 3445f291c8d5SSiddharth Bhat 344678027437SSiddharth Bhat for (Value *Op : Inst.operands()) 344778027437SSiddharth Bhat // Look for (<func-type>*) among operands of Inst 344878027437SSiddharth Bhat if (auto PtrTy = dyn_cast<PointerType>(Op->getType())) { 3449ee423d93SNikita Popov if (isa<FunctionType>(PtrTy->getPointerElementType())) { 3450349506a9SNicola Zaghen LLVM_DEBUG(dbgs() 3451349506a9SNicola Zaghen << Inst << " has illegal use of function in kernel.\n"); 3452bccaea57SSiddharth Bhat return true; 3453bccaea57SSiddharth Bhat } 3454f291c8d5SSiddharth Bhat } 345578027437SSiddharth Bhat } 3456bccaea57SSiddharth Bhat return false; 3457bccaea57SSiddharth Bhat } 3458bccaea57SSiddharth Bhat 3459f291c8d5SSiddharth Bhat /// Return whether the Scop S uses functions in a way that we do not support. 34608fc6cdfbSTobias Grosser bool containsInvalidKernelFunction(const Scop &S, bool AllowCUDALibDevice) { 3461bccaea57SSiddharth Bhat for (auto &Stmt : S) { 3462bccaea57SSiddharth Bhat if (Stmt.isBlockStmt()) { 34638fc6cdfbSTobias Grosser if (containsInvalidKernelFunctionInBlock(Stmt.getBasicBlock(), 34648fc6cdfbSTobias Grosser AllowCUDALibDevice)) 3465bccaea57SSiddharth Bhat return true; 3466bccaea57SSiddharth Bhat } else { 3467bccaea57SSiddharth Bhat assert(Stmt.isRegionStmt() && 3468bccaea57SSiddharth Bhat "Stmt was neither block nor region statement"); 3469bccaea57SSiddharth Bhat for (const BasicBlock *BB : Stmt.getRegion()->blocks()) 34708fc6cdfbSTobias Grosser if (containsInvalidKernelFunctionInBlock(BB, AllowCUDALibDevice)) 3471bccaea57SSiddharth Bhat return true; 3472bccaea57SSiddharth Bhat } 3473bccaea57SSiddharth Bhat } 3474bccaea57SSiddharth Bhat return false; 3475bccaea57SSiddharth Bhat } 3476bccaea57SSiddharth Bhat 347738fc0aedSTobias Grosser /// Generate code for a given GPU AST described by @p Root. 347838fc0aedSTobias Grosser /// 347932837fe3STobias Grosser /// @param Root An isl_ast_node pointing to the root of the GPU AST. 348032837fe3STobias Grosser /// @param Prog The GPU Program to generate code for. 348132837fe3STobias Grosser void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) { 348238fc0aedSTobias Grosser ScopAnnotator Annotator; 348338fc0aedSTobias Grosser Annotator.buildAliasScopes(*S); 348438fc0aedSTobias Grosser 348538fc0aedSTobias Grosser Region *R = &S->getRegion(); 348638fc0aedSTobias Grosser 348738fc0aedSTobias Grosser simplifyRegion(R, DT, LI, RI); 348838fc0aedSTobias Grosser 348938fc0aedSTobias Grosser BasicBlock *EnteringBB = R->getEnteringBlock(); 349038fc0aedSTobias Grosser 349155cfb1fbSNikita Popov PollyIRBuilder Builder(EnteringBB->getContext(), ConstantFolder(), 349255cfb1fbSNikita Popov IRInserter(Annotator)); 349355cfb1fbSNikita Popov Builder.SetInsertPoint(EnteringBB->getTerminator()); 349438fc0aedSTobias Grosser 349538fc0aedSTobias Grosser // Only build the run-time condition and parameters _after_ having 349638fc0aedSTobias Grosser // introduced the conditional branch. This is important as the conditional 349738fc0aedSTobias Grosser // branch will guard the original scop from new induction variables that 349838fc0aedSTobias Grosser // the SCEVExpander may introduce while code generating the parameters and 349938fc0aedSTobias Grosser // which may introduce scalar dependences that prevent us from correctly 350038fc0aedSTobias Grosser // code generating this scop. 350103346c27SSiddharth Bhat BBPair StartExitBlocks; 350203346c27SSiddharth Bhat BranchInst *CondBr = nullptr; 350303346c27SSiddharth Bhat std::tie(StartExitBlocks, CondBr) = 35042d950f36SPhilip Pfaffe executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI); 3505256070d8SAndreas Simbuerger BasicBlock *StartBlock = std::get<0>(StartExitBlocks); 350638fc0aedSTobias Grosser 350703346c27SSiddharth Bhat assert(CondBr && "CondBr not initialized by executeScopConditionally"); 350803346c27SSiddharth Bhat 35092d950f36SPhilip Pfaffe GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S, 351017f01968SSiddharth Bhat StartBlock, Prog, Runtime, Architecture); 3511acf80064SEli Friedman 351238fc0aedSTobias Grosser // TODO: Handle LICM 351338fc0aedSTobias Grosser auto SplitBlock = StartBlock->getSinglePredecessor(); 351438fc0aedSTobias Grosser Builder.SetInsertPoint(SplitBlock->getTerminator()); 3515cb1aef8dSTobias Grosser 351600fd43b3SPhilip Pfaffe isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx().get()); 35174170d6cdSpatacca isl::ast_expr Condition = 35184170d6cdSpatacca IslAst::buildRunCondition(*S, isl::manage_copy(Build)); 351982f2af35STobias Grosser isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build); 35204170d6cdSpatacca Condition = 35214170d6cdSpatacca isl::manage(isl_ast_expr_and(Condition.release(), SufficientCompute)); 3522cb1aef8dSTobias Grosser isl_ast_build_free(Build); 3523cb1aef8dSTobias Grosser 35249e3db2b7SSiddharth Bhat // preload invariant loads. Note: This should happen before the RTC 35259e3db2b7SSiddharth Bhat // because the RTC may depend on values that are invariant load hoisted. 352671dfb3ebSSiddharth Bhat if (!NodeBuilder.preloadInvariantLoads()) { 35272fb847fbSTobias Grosser // Patch the introduced branch condition to ensure that we always execute 35282fb847fbSTobias Grosser // the original SCoP. 35292fb847fbSTobias Grosser auto *FalseI1 = Builder.getFalse(); 35302fb847fbSTobias Grosser auto *SplitBBTerm = Builder.GetInsertBlock()->getTerminator(); 35312fb847fbSTobias Grosser SplitBBTerm->setOperand(0, FalseI1); 35322fb847fbSTobias Grosser 3533349506a9SNicola Zaghen LLVM_DEBUG(dbgs() << "preloading invariant loads failed in function: " + 35344ebeb356SSiddharth Bhat S->getFunction().getName() + 35354ebeb356SSiddharth Bhat " | Scop Region: " + S->getNameStr()); 353671dfb3ebSSiddharth Bhat // adjust the dominator tree accordingly. 353771dfb3ebSSiddharth Bhat auto *ExitingBlock = StartBlock->getUniqueSuccessor(); 353871dfb3ebSSiddharth Bhat assert(ExitingBlock); 353971dfb3ebSSiddharth Bhat auto *MergeBlock = ExitingBlock->getUniqueSuccessor(); 354071dfb3ebSSiddharth Bhat assert(MergeBlock); 354171dfb3ebSSiddharth Bhat polly::markBlockUnreachable(*StartBlock, Builder); 354271dfb3ebSSiddharth Bhat polly::markBlockUnreachable(*ExitingBlock, Builder); 354371dfb3ebSSiddharth Bhat auto *ExitingBB = S->getExitingBlock(); 354471dfb3ebSSiddharth Bhat assert(ExitingBB); 35459e3db2b7SSiddharth Bhat 354671dfb3ebSSiddharth Bhat DT->changeImmediateDominator(MergeBlock, ExitingBB); 354771dfb3ebSSiddharth Bhat DT->eraseNode(ExitingBlock); 354871dfb3ebSSiddharth Bhat isl_ast_node_free(Root); 354971dfb3ebSSiddharth Bhat } else { 355071dfb3ebSSiddharth Bhat 35517b9f5ca2SSiddharth Bhat if (polly::PerfMonitoring) { 35527b9f5ca2SSiddharth Bhat PerfMonitor P(*S, EnteringBB->getParent()->getParent()); 35537b9f5ca2SSiddharth Bhat P.initialize(); 35547b9f5ca2SSiddharth Bhat P.insertRegionStart(SplitBlock->getTerminator()); 35557b9f5ca2SSiddharth Bhat 35567b9f5ca2SSiddharth Bhat // TODO: actually think if this is the correct exiting block to place 35577b9f5ca2SSiddharth Bhat // the `end` performance marker. Invariant load hoisting changes 35587b9f5ca2SSiddharth Bhat // the CFG in a way that I do not precisely understand, so I 35597b9f5ca2SSiddharth Bhat // (Siddharth<[email protected]>) should come back to this and 35607b9f5ca2SSiddharth Bhat // think about which exiting block to use. 35617b9f5ca2SSiddharth Bhat auto *ExitingBlock = StartBlock->getUniqueSuccessor(); 35627b9f5ca2SSiddharth Bhat assert(ExitingBlock); 35637b9f5ca2SSiddharth Bhat BasicBlock *MergeBlock = ExitingBlock->getUniqueSuccessor(); 35647b9f5ca2SSiddharth Bhat P.insertRegionEnd(MergeBlock->getTerminator()); 35657b9f5ca2SSiddharth Bhat } 35667b9f5ca2SSiddharth Bhat 356771dfb3ebSSiddharth Bhat NodeBuilder.addParameters(S->getContext().release()); 35684170d6cdSpatacca Value *RTC = NodeBuilder.createRTC(Condition.release()); 3569cb1aef8dSTobias Grosser Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC); 3570cb1aef8dSTobias Grosser 357138fc0aedSTobias Grosser Builder.SetInsertPoint(&*StartBlock->begin()); 3572fa7b0802STobias Grosser 357338fc0aedSTobias Grosser NodeBuilder.create(Root); 357471dfb3ebSSiddharth Bhat } 35755857b701STobias Grosser 3576bc653f20STobias Grosser /// In case a sequential kernel has more surrounding loops as any parallel 3577bc653f20STobias Grosser /// kernel, the SCoP is probably mostly sequential. Hence, there is no 3578de244eb4STobias Grosser /// point in running it on a GPU. 3579bc653f20STobias Grosser if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel) 358003346c27SSiddharth Bhat CondBr->setOperand(0, Builder.getFalse()); 3581bc653f20STobias Grosser 35825857b701STobias Grosser if (!NodeBuilder.BuildSuccessful) 358303346c27SSiddharth Bhat CondBr->setOperand(0, Builder.getFalse()); 358438fc0aedSTobias Grosser } 358538fc0aedSTobias Grosser 3586e938517eSTobias Grosser bool runOnScop(Scop &CurrentScop) override { 3587e938517eSTobias Grosser S = &CurrentScop; 358838fc0aedSTobias Grosser LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 358938fc0aedSTobias Grosser DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 359038fc0aedSTobias Grosser SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 35917b5a4dfdSTobias Grosser DL = &S->getRegion().getEntry()->getModule()->getDataLayout(); 359238fc0aedSTobias Grosser RI = &getAnalysis<RegionInfoPass>().getRegionInfo(); 3593e938517eSTobias Grosser 3594349506a9SNicola Zaghen LLVM_DEBUG(dbgs() << "PPCGCodeGen running on : " << getUniqueScopName(S) 3595656e6295SSiddharth Bhat << " | loop depth: " << S->getMaxLoopDepth() << "\n"); 3596656e6295SSiddharth Bhat 3597f291c8d5SSiddharth Bhat // We currently do not support functions other than intrinsics inside 3598f291c8d5SSiddharth Bhat // kernels, as code generation will need to offload function calls to the 3599f291c8d5SSiddharth Bhat // kernel. This may lead to a kernel trying to call a function on the host. 3600bccaea57SSiddharth Bhat // This also allows us to prevent codegen from trying to take the 3601bccaea57SSiddharth Bhat // address of an intrinsic function to send to the kernel. 36028fc6cdfbSTobias Grosser if (containsInvalidKernelFunction(CurrentScop, 36038fc6cdfbSTobias Grosser Architecture == GPUArch::NVPTX64)) { 3604349506a9SNicola Zaghen LLVM_DEBUG( 3605638316daSSiddharth Bhat dbgs() << getUniqueScopName(S) 3606638316daSSiddharth Bhat << " contains function which cannot be materialised in a GPU " 3607f291c8d5SSiddharth Bhat "kernel. Bailing out.\n";); 3608bccaea57SSiddharth Bhat return false; 3609f291c8d5SSiddharth Bhat } 3610bccaea57SSiddharth Bhat 3611e938517eSTobias Grosser auto PPCGScop = createPPCGScop(); 3612e938517eSTobias Grosser auto PPCGProg = createPPCGProg(PPCGScop); 3613f384594dSTobias Grosser auto PPCGGen = generateGPU(PPCGScop, PPCGProg); 361438fc0aedSTobias Grosser 361502ca346eSSingapuram Sanjay Srivallabh if (PPCGGen->tree) { 361632837fe3STobias Grosser generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg); 361702ca346eSSingapuram Sanjay Srivallabh CurrentScop.markAsToBeSkipped(); 3618638316daSSiddharth Bhat } else { 3619349506a9SNicola Zaghen LLVM_DEBUG(dbgs() << getUniqueScopName(S) 3620638316daSSiddharth Bhat << " has empty PPCGGen->tree. Bailing out.\n"); 362102ca346eSSingapuram Sanjay Srivallabh } 362238fc0aedSTobias Grosser 3623b307ed4dSTobias Grosser freeOptions(PPCGScop); 3624f384594dSTobias Grosser freePPCGGen(PPCGGen); 3625e938517eSTobias Grosser gpu_prog_free(PPCGProg); 3626e938517eSTobias Grosser ppcg_scop_free(PPCGScop); 3627e938517eSTobias Grosser 3628e938517eSTobias Grosser return true; 3629e938517eSTobias Grosser } 36309dfe4e7cSTobias Grosser 36319dfe4e7cSTobias Grosser void printScop(raw_ostream &, Scop &) const override {} 36329dfe4e7cSTobias Grosser 36339dfe4e7cSTobias Grosser void getAnalysisUsage(AnalysisUsage &AU) const override { 3634a4f447c2SMichael Kruse ScopPass::getAnalysisUsage(AU); 3635a4f447c2SMichael Kruse 36369dfe4e7cSTobias Grosser AU.addRequired<DominatorTreeWrapperPass>(); 36379dfe4e7cSTobias Grosser AU.addRequired<RegionInfoPass>(); 36389dfe4e7cSTobias Grosser AU.addRequired<ScalarEvolutionWrapperPass>(); 36395cc87e3aSPhilip Pfaffe AU.addRequired<ScopDetectionWrapperPass>(); 36409dfe4e7cSTobias Grosser AU.addRequired<ScopInfoRegionPass>(); 36419dfe4e7cSTobias Grosser AU.addRequired<LoopInfoWrapperPass>(); 36429dfe4e7cSTobias Grosser 36439dfe4e7cSTobias Grosser // FIXME: We do not yet add regions for the newly generated code to the 36449dfe4e7cSTobias Grosser // region tree. 36459dfe4e7cSTobias Grosser } 36469dfe4e7cSTobias Grosser }; 364724222c73STobias Grosser } // namespace 36489dfe4e7cSTobias Grosser 36499dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1; 36509dfe4e7cSTobias Grosser 365117f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) { 365217f01968SSiddharth Bhat PPCGCodeGeneration *generator = new PPCGCodeGeneration(); 365317f01968SSiddharth Bhat generator->Runtime = Runtime; 365417f01968SSiddharth Bhat generator->Architecture = Arch; 365517f01968SSiddharth Bhat return generator; 365617f01968SSiddharth Bhat } 36579dfe4e7cSTobias Grosser 36589dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg", 36599dfe4e7cSTobias Grosser "Polly - Apply PPCG translation to SCOP", false, false) 36609dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo); 36619dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 36629dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 36639dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 36649dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 36655cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass); 36669dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg", 36679dfe4e7cSTobias Grosser "Polly - Apply PPCG translation to SCOP", false, false) 3668