19dfe4e7cSTobias Grosser //===------ PPCGCodeGeneration.cpp - Polly Accelerator Code Generation. ---===// 29dfe4e7cSTobias Grosser // 39dfe4e7cSTobias Grosser // The LLVM Compiler Infrastructure 49dfe4e7cSTobias Grosser // 59dfe4e7cSTobias Grosser // This file is distributed under the University of Illinois Open Source 69dfe4e7cSTobias Grosser // License. See LICENSE.TXT for details. 79dfe4e7cSTobias Grosser // 89dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===// 99dfe4e7cSTobias Grosser // 109dfe4e7cSTobias Grosser // Take a scop created by ScopInfo and map it to GPU code using the ppcg 119dfe4e7cSTobias Grosser // GPU mapping strategy. 129dfe4e7cSTobias Grosser // 139dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===// 149dfe4e7cSTobias Grosser 1517f01968SSiddharth Bhat #include "polly/CodeGen/PPCGCodeGeneration.h" 16cb1aef8dSTobias Grosser #include "polly/CodeGen/IslAst.h" 179dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h" 1838fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h" 199dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h" 209dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h" 21f384594dSTobias Grosser #include "polly/Options.h" 22629109b6STobias Grosser #include "polly/ScopDetection.h" 239dfe4e7cSTobias Grosser #include "polly/ScopInfo.h" 24edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h" 2574dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h" 269dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h" 279dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h" 289dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h" 299dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 3074dc3cb4STobias Grosser #include "llvm/Analysis/TargetLibraryInfo.h" 3174dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h" 3274dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h" 33e1a98343STobias Grosser #include "llvm/IR/Verifier.h" 3474dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h" 3574dc3cb4STobias Grosser #include "llvm/Support/TargetSelect.h" 3674dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h" 379a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h" 38750160e2STobias Grosser #include "llvm/Transforms/Utils/BasicBlockUtils.h" 399dfe4e7cSTobias Grosser 40f384594dSTobias Grosser #include "isl/union_map.h" 41f384594dSTobias Grosser 42e938517eSTobias Grosser extern "C" { 43a56f8f8eSTobias Grosser #include "ppcg/cuda.h" 44a56f8f8eSTobias Grosser #include "ppcg/gpu.h" 45a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h" 46a56f8f8eSTobias Grosser #include "ppcg/ppcg.h" 47a56f8f8eSTobias Grosser #include "ppcg/schedule.h" 48e938517eSTobias Grosser } 49e938517eSTobias Grosser 509dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h" 519dfe4e7cSTobias Grosser 529dfe4e7cSTobias Grosser using namespace polly; 539dfe4e7cSTobias Grosser using namespace llvm; 549dfe4e7cSTobias Grosser 559dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg" 569dfe4e7cSTobias Grosser 57f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule", 58f384594dSTobias Grosser cl::desc("Dump the computed GPU Schedule"), 59681bd568STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 60f384594dSTobias Grosser cl::cat(PollyCategory)); 6169b46751STobias Grosser 6269b46751STobias Grosser static cl::opt<bool> 6369b46751STobias Grosser DumpCode("polly-acc-dump-code", 6469b46751STobias Grosser cl::desc("Dump C code describing the GPU mapping"), cl::Hidden, 6569b46751STobias Grosser cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory)); 6669b46751STobias Grosser 6732837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir", 6832837fe3STobias Grosser cl::desc("Dump the kernel LLVM-IR"), 6932837fe3STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 7032837fe3STobias Grosser cl::cat(PollyCategory)); 7132837fe3STobias Grosser 7274dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm", 7374dc3cb4STobias Grosser cl::desc("Dump the kernel assembly code"), 7474dc3cb4STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 7574dc3cb4STobias Grosser cl::cat(PollyCategory)); 7674dc3cb4STobias Grosser 7774dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath", 7874dc3cb4STobias Grosser cl::desc("Allow unsafe math optimizations"), 7974dc3cb4STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 8074dc3cb4STobias Grosser cl::cat(PollyCategory)); 81b513b491STobias Grosser static cl::opt<bool> SharedMemory("polly-acc-use-shared", 82b513b491STobias Grosser cl::desc("Use shared memory"), cl::Hidden, 83b513b491STobias Grosser cl::init(false), cl::ZeroOrMore, 84b513b491STobias Grosser cl::cat(PollyCategory)); 85130ca30fSTobias Grosser static cl::opt<bool> PrivateMemory("polly-acc-use-private", 86130ca30fSTobias Grosser cl::desc("Use private memory"), cl::Hidden, 87130ca30fSTobias Grosser cl::init(false), cl::ZeroOrMore, 88130ca30fSTobias Grosser cl::cat(PollyCategory)); 8974dc3cb4STobias Grosser 90abed4969SSiddharth Bhat static cl::opt<bool> ManagedMemory("polly-acc-codegen-managed-memory", 91abed4969SSiddharth Bhat cl::desc("Generate Host kernel code assuming" 92abed4969SSiddharth Bhat " that all memory has been" 93abed4969SSiddharth Bhat " declared as managed memory"), 94abed4969SSiddharth Bhat cl::Hidden, cl::init(false), cl::ZeroOrMore, 95abed4969SSiddharth Bhat cl::cat(PollyCategory)); 96abed4969SSiddharth Bhat 9765d7f72fSSiddharth Bhat static cl::opt<bool> 9865d7f72fSSiddharth Bhat FailOnVerifyModuleFailure("polly-acc-fail-on-verify-module-failure", 9965d7f72fSSiddharth Bhat cl::desc("Fail and generate a backtrace if" 10065d7f72fSSiddharth Bhat " verifyModule fails on the GPU " 10165d7f72fSSiddharth Bhat " kernel module."), 10265d7f72fSSiddharth Bhat cl::Hidden, cl::init(false), cl::ZeroOrMore, 10365d7f72fSSiddharth Bhat cl::cat(PollyCategory)); 10465d7f72fSSiddharth Bhat 10574dc3cb4STobias Grosser static cl::opt<std::string> 10674dc3cb4STobias Grosser CudaVersion("polly-acc-cuda-version", 10774dc3cb4STobias Grosser cl::desc("The CUDA version to compile for"), cl::Hidden, 10874dc3cb4STobias Grosser cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory)); 10974dc3cb4STobias Grosser 11082f2af35STobias Grosser static cl::opt<int> 11182f2af35STobias Grosser MinCompute("polly-acc-mincompute", 11282f2af35STobias Grosser cl::desc("Minimal number of compute statements to run on GPU."), 11382f2af35STobias Grosser cl::Hidden, cl::init(10 * 512 * 512)); 11482f2af35STobias Grosser 115a82f2d26SSiddharth Bhat /// Used to store information PPCG wants for kills. This information is 116a82f2d26SSiddharth Bhat /// used by live range reordering. 117a82f2d26SSiddharth Bhat /// 118a82f2d26SSiddharth Bhat /// @see computeLiveRangeReordering 119a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGScop 120a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGProg 121a82f2d26SSiddharth Bhat struct MustKillsInfo { 122a82f2d26SSiddharth Bhat /// Collection of all kill statements that will be sequenced at the end of 123a82f2d26SSiddharth Bhat /// PPCGScop->schedule. 124a82f2d26SSiddharth Bhat /// 125a82f2d26SSiddharth Bhat /// The nodes in `KillsSchedule` will be merged using `isl_schedule_set` 126a82f2d26SSiddharth Bhat /// which merges schedules in *arbitrary* order. 127a82f2d26SSiddharth Bhat /// (we don't care about the order of the kills anyway). 128a82f2d26SSiddharth Bhat isl::schedule KillsSchedule; 129a82f2d26SSiddharth Bhat /// Map from kill statement instances to scalars that need to be 130a82f2d26SSiddharth Bhat /// killed. 131a82f2d26SSiddharth Bhat /// 132a82f2d26SSiddharth Bhat /// We currently only derive kill information for phi nodes, as phi nodes 133a82f2d26SSiddharth Bhat /// allow us to easily derive kill information. PHI nodes are not alive 134a82f2d26SSiddharth Bhat /// outside the scop and can consequently all be "killed". [params] -> { 135a82f2d26SSiddharth Bhat /// [Stmt_phantom[] -> ref_phantom[]] -> phi_ref[] } 136a82f2d26SSiddharth Bhat isl::union_map TaggedMustKills; 137a82f2d26SSiddharth Bhat 138a82f2d26SSiddharth Bhat MustKillsInfo() : KillsSchedule(nullptr), TaggedMustKills(nullptr){}; 139a82f2d26SSiddharth Bhat }; 140a82f2d26SSiddharth Bhat 141761e5b93SSiddharth Bhat /// Check if SAI's uses are entirely contained within Scop S. 142761e5b93SSiddharth Bhat /// If a scalar is used only with a Scop, we are free to kill it, as no data 143761e5b93SSiddharth Bhat /// can flow in/out of the value any more. 144761e5b93SSiddharth Bhat /// @see computeMustKillsInfo 145761e5b93SSiddharth Bhat static bool isScalarUsesContainedInScop(const Scop &S, 146761e5b93SSiddharth Bhat const ScopArrayInfo *SAI) { 147761e5b93SSiddharth Bhat assert(SAI->isValueKind() && "this function only deals with scalars." 148761e5b93SSiddharth Bhat " Dealing with arrays required alias analysis"); 149761e5b93SSiddharth Bhat 150761e5b93SSiddharth Bhat const Region &R = S.getRegion(); 151761e5b93SSiddharth Bhat for (User *U : SAI->getBasePtr()->users()) { 152761e5b93SSiddharth Bhat Instruction *I = dyn_cast<Instruction>(U); 153761e5b93SSiddharth Bhat assert(I && "invalid user of scop array info"); 154761e5b93SSiddharth Bhat if (!R.contains(I)) 155761e5b93SSiddharth Bhat return false; 156761e5b93SSiddharth Bhat } 157761e5b93SSiddharth Bhat return true; 158761e5b93SSiddharth Bhat } 159761e5b93SSiddharth Bhat 160a82f2d26SSiddharth Bhat /// Compute must-kills needed to enable live range reordering with PPCG. 161a82f2d26SSiddharth Bhat /// 162a82f2d26SSiddharth Bhat /// @params S The Scop to compute live range reordering information 163a82f2d26SSiddharth Bhat /// @returns live range reordering information that can be used to setup 164a82f2d26SSiddharth Bhat /// PPCG. 165a82f2d26SSiddharth Bhat static MustKillsInfo computeMustKillsInfo(const Scop &S) { 166a82f2d26SSiddharth Bhat const isl::space ParamSpace(isl::manage(S.getParamSpace())); 167a82f2d26SSiddharth Bhat MustKillsInfo Info; 168a82f2d26SSiddharth Bhat 169761e5b93SSiddharth Bhat // 1. Collect all ScopArrayInfo that satisfy *any* of the criteria: 170761e5b93SSiddharth Bhat // 1.1 phi nodes in scop. 171761e5b93SSiddharth Bhat // 1.2 scalars that are only used within the scop 172a82f2d26SSiddharth Bhat SmallVector<isl::id, 4> KillMemIds; 173a82f2d26SSiddharth Bhat for (ScopArrayInfo *SAI : S.arrays()) { 174761e5b93SSiddharth Bhat if (SAI->isPHIKind() || 175761e5b93SSiddharth Bhat (SAI->isValueKind() && isScalarUsesContainedInScop(S, SAI))) 176a82f2d26SSiddharth Bhat KillMemIds.push_back(isl::manage(SAI->getBasePtrId())); 177a82f2d26SSiddharth Bhat } 178a82f2d26SSiddharth Bhat 179a82f2d26SSiddharth Bhat Info.TaggedMustKills = isl::union_map::empty(isl::space(ParamSpace)); 180a82f2d26SSiddharth Bhat 181a82f2d26SSiddharth Bhat // Initialising KillsSchedule to `isl_set_empty` creates an empty node in the 182a82f2d26SSiddharth Bhat // schedule: 183a82f2d26SSiddharth Bhat // - filter: "[control] -> { }" 184a82f2d26SSiddharth Bhat // So, we choose to not create this to keep the output a little nicer, 185a82f2d26SSiddharth Bhat // at the cost of some code complexity. 186a82f2d26SSiddharth Bhat Info.KillsSchedule = nullptr; 187a82f2d26SSiddharth Bhat 188a82f2d26SSiddharth Bhat for (isl::id &phiId : KillMemIds) { 189a82f2d26SSiddharth Bhat isl::id KillStmtId = isl::id::alloc( 190a82f2d26SSiddharth Bhat S.getIslCtx(), std::string("SKill_phantom_").append(phiId.get_name()), 191a82f2d26SSiddharth Bhat nullptr); 192a82f2d26SSiddharth Bhat 193a82f2d26SSiddharth Bhat // NOTE: construction of tagged_must_kill: 194a82f2d26SSiddharth Bhat // 2. We need to construct a map: 195a82f2d26SSiddharth Bhat // [param] -> { [Stmt_phantom[] -> ref_phantom[]] -> phi_ref } 196a82f2d26SSiddharth Bhat // To construct this, we use `isl_map_domain_product` on 2 maps`: 197a82f2d26SSiddharth Bhat // 2a. StmtToPhi: 198a82f2d26SSiddharth Bhat // [param] -> { Stmt_phantom[] -> phi_ref[] } 199a82f2d26SSiddharth Bhat // 2b. PhantomRefToPhi: 200a82f2d26SSiddharth Bhat // [param] -> { ref_phantom[] -> phi_ref[] } 201a82f2d26SSiddharth Bhat // 202a82f2d26SSiddharth Bhat // Combining these with `isl_map_domain_product` gives us 203a82f2d26SSiddharth Bhat // TaggedMustKill: 204a82f2d26SSiddharth Bhat // [param] -> { [Stmt[] -> phantom_ref[]] -> memref[] } 205a82f2d26SSiddharth Bhat 206a82f2d26SSiddharth Bhat // 2a. [param] -> { S_2[] -> phi_ref[] } 207a82f2d26SSiddharth Bhat isl::map StmtToPhi = isl::map::universe(isl::space(ParamSpace)); 208a82f2d26SSiddharth Bhat StmtToPhi = StmtToPhi.set_tuple_id(isl::dim::in, isl::id(KillStmtId)); 209a82f2d26SSiddharth Bhat StmtToPhi = StmtToPhi.set_tuple_id(isl::dim::out, isl::id(phiId)); 210a82f2d26SSiddharth Bhat 211a82f2d26SSiddharth Bhat isl::id PhantomRefId = isl::id::alloc( 212a82f2d26SSiddharth Bhat S.getIslCtx(), std::string("ref_phantom") + phiId.get_name(), nullptr); 213a82f2d26SSiddharth Bhat 214a82f2d26SSiddharth Bhat // 2b. [param] -> { phantom_ref[] -> memref[] } 215a82f2d26SSiddharth Bhat isl::map PhantomRefToPhi = isl::map::universe(isl::space(ParamSpace)); 216a82f2d26SSiddharth Bhat PhantomRefToPhi = PhantomRefToPhi.set_tuple_id(isl::dim::in, PhantomRefId); 217a82f2d26SSiddharth Bhat PhantomRefToPhi = PhantomRefToPhi.set_tuple_id(isl::dim::out, phiId); 218a82f2d26SSiddharth Bhat 219a82f2d26SSiddharth Bhat // 2. [param] -> { [Stmt[] -> phantom_ref[]] -> memref[] } 220a82f2d26SSiddharth Bhat isl::map TaggedMustKill = StmtToPhi.domain_product(PhantomRefToPhi); 221a82f2d26SSiddharth Bhat Info.TaggedMustKills = Info.TaggedMustKills.unite(TaggedMustKill); 222a82f2d26SSiddharth Bhat 223a82f2d26SSiddharth Bhat // 3. Create the kill schedule of the form: 224a82f2d26SSiddharth Bhat // "[param] -> { Stmt_phantom[] }" 225a82f2d26SSiddharth Bhat // Then add this to Info.KillsSchedule. 226a82f2d26SSiddharth Bhat isl::space KillStmtSpace = ParamSpace; 227a82f2d26SSiddharth Bhat KillStmtSpace = KillStmtSpace.set_tuple_id(isl::dim::set, KillStmtId); 228a82f2d26SSiddharth Bhat isl::union_set KillStmtDomain = isl::set::universe(KillStmtSpace); 229a82f2d26SSiddharth Bhat 230a82f2d26SSiddharth Bhat isl::schedule KillSchedule = isl::schedule::from_domain(KillStmtDomain); 231a82f2d26SSiddharth Bhat if (Info.KillsSchedule) 232a82f2d26SSiddharth Bhat Info.KillsSchedule = Info.KillsSchedule.set(KillSchedule); 233a82f2d26SSiddharth Bhat else 234a82f2d26SSiddharth Bhat Info.KillsSchedule = KillSchedule; 235a82f2d26SSiddharth Bhat } 236a82f2d26SSiddharth Bhat 237a82f2d26SSiddharth Bhat return Info; 238a82f2d26SSiddharth Bhat } 239a82f2d26SSiddharth Bhat 24060c60025STobias Grosser /// Create the ast expressions for a ScopStmt. 24160c60025STobias Grosser /// 24260c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each 24360c60025STobias Grosser /// of the scheduled ScopStmts. 24460c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt( 245edb885cbSTobias Grosser void *StmtT, isl_ast_build *Build, 24660c60025STobias Grosser isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA, 24760c60025STobias Grosser isl_id *Id, void *User), 24860c60025STobias Grosser void *UserIndex, 24960c60025STobias Grosser isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User), 250edb885cbSTobias Grosser void *UserExpr) { 25160c60025STobias Grosser 252edb885cbSTobias Grosser ScopStmt *Stmt = (ScopStmt *)StmtT; 25360c60025STobias Grosser 254edb885cbSTobias Grosser isl_ctx *Ctx; 255edb885cbSTobias Grosser 256edb885cbSTobias Grosser if (!Stmt || !Build) 257edb885cbSTobias Grosser return NULL; 258edb885cbSTobias Grosser 259edb885cbSTobias Grosser Ctx = isl_ast_build_get_ctx(Build); 260edb885cbSTobias Grosser isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0); 261edb885cbSTobias Grosser 262edb885cbSTobias Grosser for (MemoryAccess *Acc : *Stmt) { 263edb885cbSTobias Grosser isl_map *AddrFunc = Acc->getAddressFunction(); 264edb885cbSTobias Grosser AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain()); 265edb885cbSTobias Grosser isl_id *RefId = Acc->getId(); 266edb885cbSTobias Grosser isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc); 267edb885cbSTobias Grosser isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA); 268edb885cbSTobias Grosser MPA = isl_multi_pw_aff_coalesce(MPA); 269edb885cbSTobias Grosser MPA = FunctionIndex(MPA, RefId, UserIndex); 270edb885cbSTobias Grosser isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA); 271edb885cbSTobias Grosser Access = FunctionExpr(Access, RefId, UserExpr); 272edb885cbSTobias Grosser RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access); 273edb885cbSTobias Grosser } 274edb885cbSTobias Grosser 275edb885cbSTobias Grosser return RefToExpr; 27660c60025STobias Grosser } 277f384594dSTobias Grosser 278a90be207SSiddharth Bhat /// Given a LLVM Type, compute its size in bytes, 279a90be207SSiddharth Bhat static int computeSizeInBytes(const Type *T) { 280a90be207SSiddharth Bhat int bytes = T->getPrimitiveSizeInBits() / 8; 281a90be207SSiddharth Bhat if (bytes == 0) 282a90be207SSiddharth Bhat bytes = T->getScalarSizeInBits() / 8; 283a90be207SSiddharth Bhat return bytes; 284a90be207SSiddharth Bhat } 285a90be207SSiddharth Bhat 28638fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST. 28738fc0aedSTobias Grosser /// 28838fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which 289a6d48f59SMichael Kruse /// generates code for general-purpose AST nodes, with special functionality 29038fc0aedSTobias Grosser /// for generating GPU specific user nodes. 29138fc0aedSTobias Grosser /// 29238fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser 29338fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder { 29438fc0aedSTobias Grosser public: 2952d950f36SPhilip Pfaffe GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, 29638fc0aedSTobias Grosser const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE, 297acf80064SEli Friedman DominatorTree &DT, Scop &S, BasicBlock *StartBlock, 29817f01968SSiddharth Bhat gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch) 2992d950f36SPhilip Pfaffe : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock), 30017f01968SSiddharth Bhat Prog(Prog), Runtime(Runtime), Arch(Arch) { 301edb885cbSTobias Grosser getExprBuilder().setIDToSAI(&IDToSAI); 302edb885cbSTobias Grosser } 30338fc0aedSTobias Grosser 304fa7b0802STobias Grosser /// Create after-run-time-check initialization code. 305fa7b0802STobias Grosser void initializeAfterRTH(); 306fa7b0802STobias Grosser 307fa7b0802STobias Grosser /// Finalize the generated scop. 308fa7b0802STobias Grosser virtual void finalize(); 309fa7b0802STobias Grosser 3105857b701STobias Grosser /// Track if the full build process was successful. 3115857b701STobias Grosser /// 3125857b701STobias Grosser /// This value is set to false, if throughout the build process an error 3135857b701STobias Grosser /// occurred which prevents us from generating valid GPU code. 3145857b701STobias Grosser bool BuildSuccessful = true; 3155857b701STobias Grosser 316bc653f20STobias Grosser /// The maximal number of loops surrounding a sequential kernel. 317bc653f20STobias Grosser unsigned DeepestSequential = 0; 318bc653f20STobias Grosser 319bc653f20STobias Grosser /// The maximal number of loops surrounding a parallel kernel. 320bc653f20STobias Grosser unsigned DeepestParallel = 0; 321bc653f20STobias Grosser 32279f13b9aSSingapuram Sanjay Srivallabh /// Return the name to set for the ptx_kernel. 32379f13b9aSSingapuram Sanjay Srivallabh std::string getKernelFuncName(int Kernel_id); 32479f13b9aSSingapuram Sanjay Srivallabh 32538fc0aedSTobias Grosser private: 32674dc3cb4STobias Grosser /// A vector of array base pointers for which a new ScopArrayInfo was created. 32774dc3cb4STobias Grosser /// 32874dc3cb4STobias Grosser /// This vector is used to delete the ScopArrayInfo when it is not needed any 32974dc3cb4STobias Grosser /// more. 33074dc3cb4STobias Grosser std::vector<Value *> LocalArrays; 33174dc3cb4STobias Grosser 33213c78e4dSTobias Grosser /// A map from ScopArrays to their corresponding device allocations. 33313c78e4dSTobias Grosser std::map<ScopArrayInfo *, Value *> DeviceAllocations; 3347287aeddSTobias Grosser 335fa7b0802STobias Grosser /// The current GPU context. 336fa7b0802STobias Grosser Value *GPUContext; 337fa7b0802STobias Grosser 338b513b491STobias Grosser /// The set of isl_ids allocated in the kernel 339b513b491STobias Grosser std::vector<isl_id *> KernelIds; 340b513b491STobias Grosser 34132837fe3STobias Grosser /// A module containing GPU code. 34232837fe3STobias Grosser /// 34332837fe3STobias Grosser /// This pointer is only set in case we are currently generating GPU code. 34432837fe3STobias Grosser std::unique_ptr<Module> GPUModule; 34532837fe3STobias Grosser 34632837fe3STobias Grosser /// The GPU program we generate code for. 34732837fe3STobias Grosser gpu_prog *Prog; 34832837fe3STobias Grosser 34917f01968SSiddharth Bhat /// The GPU Runtime implementation to use (OpenCL or CUDA). 35017f01968SSiddharth Bhat GPURuntime Runtime; 35117f01968SSiddharth Bhat 35217f01968SSiddharth Bhat /// The GPU Architecture to target. 35317f01968SSiddharth Bhat GPUArch Arch; 35417f01968SSiddharth Bhat 355472f9654STobias Grosser /// Class to free isl_ids. 356472f9654STobias Grosser class IslIdDeleter { 357472f9654STobias Grosser public: 358472f9654STobias Grosser void operator()(__isl_take isl_id *Id) { isl_id_free(Id); }; 359472f9654STobias Grosser }; 360472f9654STobias Grosser 361472f9654STobias Grosser /// A set containing all isl_ids allocated in a GPU kernel. 362472f9654STobias Grosser /// 363472f9654STobias Grosser /// By releasing this set all isl_ids will be freed. 364472f9654STobias Grosser std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs; 365472f9654STobias Grosser 366edb885cbSTobias Grosser IslExprBuilder::IDToScopArrayInfoTy IDToSAI; 367edb885cbSTobias Grosser 36838fc0aedSTobias Grosser /// Create code for user-defined AST nodes. 36938fc0aedSTobias Grosser /// 37038fc0aedSTobias Grosser /// These AST nodes can be of type: 37138fc0aedSTobias Grosser /// 37238fc0aedSTobias Grosser /// - ScopStmt: A computational statement (TODO) 37338fc0aedSTobias Grosser /// - Kernel: A GPU kernel call (TODO) 37413c78e4dSTobias Grosser /// - Data-Transfer: A GPU <-> CPU data-transfer 3755260c041STobias Grosser /// - In-kernel synchronization 3765260c041STobias Grosser /// - In-kernel memory copy statement 37738fc0aedSTobias Grosser /// 3781fb9b64dSTobias Grosser /// @param UserStmt The ast node to generate code for. 3791fb9b64dSTobias Grosser virtual void createUser(__isl_take isl_ast_node *UserStmt); 38032837fe3STobias Grosser 38113c78e4dSTobias Grosser enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST }; 38213c78e4dSTobias Grosser 38313c78e4dSTobias Grosser /// Create code for a data transfer statement 38413c78e4dSTobias Grosser /// 38513c78e4dSTobias Grosser /// @param TransferStmt The data transfer statement. 38613c78e4dSTobias Grosser /// @param Direction The direction in which to transfer data. 38713c78e4dSTobias Grosser void createDataTransfer(__isl_take isl_ast_node *TransferStmt, 38813c78e4dSTobias Grosser enum DataDirection Direction); 38913c78e4dSTobias Grosser 390edb885cbSTobias Grosser /// Find llvm::Values referenced in GPU kernel. 391edb885cbSTobias Grosser /// 392edb885cbSTobias Grosser /// @param Kernel The kernel to scan for llvm::Values 393edb885cbSTobias Grosser /// 394f291c8d5SSiddharth Bhat /// @returns A pair, whose first element contains the set of values 395f291c8d5SSiddharth Bhat /// referenced by the kernel, and whose second element contains the 396f291c8d5SSiddharth Bhat /// set of functions referenced by the kernel. All functions in the 397f291c8d5SSiddharth Bhat /// second set satisfy isValidFunctionInKernel. 398f291c8d5SSiddharth Bhat std::pair<SetVector<Value *>, SetVector<Function *>> 399f291c8d5SSiddharth Bhat getReferencesInKernel(ppcg_kernel *Kernel); 400edb885cbSTobias Grosser 40179a947c2STobias Grosser /// Compute the sizes of the execution grid for a given kernel. 40279a947c2STobias Grosser /// 40379a947c2STobias Grosser /// @param Kernel The kernel to compute grid sizes for. 40479a947c2STobias Grosser /// 40579a947c2STobias Grosser /// @returns A tuple with grid sizes for X and Y dimension 40679a947c2STobias Grosser std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel); 40779a947c2STobias Grosser 408abed4969SSiddharth Bhat /// Creates a array that can be sent to the kernel on the device using a 409abed4969SSiddharth Bhat /// host pointer. This is required for managed memory, when we directly send 410abed4969SSiddharth Bhat /// host pointers to the device. 411abed4969SSiddharth Bhat /// \note 412abed4969SSiddharth Bhat /// This is to be used only with managed memory 413abed4969SSiddharth Bhat Value *getOrCreateManagedDeviceArray(gpu_array_info *Array, 414abed4969SSiddharth Bhat ScopArrayInfo *ArrayInfo); 415abed4969SSiddharth Bhat 41679a947c2STobias Grosser /// Compute the sizes of the thread blocks for a given kernel. 41779a947c2STobias Grosser /// 41879a947c2STobias Grosser /// @param Kernel The kernel to compute thread block sizes for. 41979a947c2STobias Grosser /// 42079a947c2STobias Grosser /// @returns A tuple with thread block sizes for X, Y, and Z dimensions. 42179a947c2STobias Grosser std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel); 42279a947c2STobias Grosser 423a90be207SSiddharth Bhat /// Store a specific kernel launch parameter in the array of kernel launch 424a90be207SSiddharth Bhat /// parameters. 425a90be207SSiddharth Bhat /// 426a90be207SSiddharth Bhat /// @param Parameters The list of parameters in which to store. 427a90be207SSiddharth Bhat /// @param Param The kernel launch parameter to store. 428a90be207SSiddharth Bhat /// @param Index The index in the parameter list, at which to store the 429a90be207SSiddharth Bhat /// parameter. 430a90be207SSiddharth Bhat void insertStoreParameter(Instruction *Parameters, Instruction *Param, 431a90be207SSiddharth Bhat int Index); 432a90be207SSiddharth Bhat 43379a947c2STobias Grosser /// Create kernel launch parameters. 43479a947c2STobias Grosser /// 43579a947c2STobias Grosser /// @param Kernel The kernel to create parameters for. 43679a947c2STobias Grosser /// @param F The kernel function that has been created. 43757693272STobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 43879a947c2STobias Grosser /// 43979a947c2STobias Grosser /// @returns A stack allocated array with pointers to the parameter 44079a947c2STobias Grosser /// values that are passed to the kernel. 44157693272STobias Grosser Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F, 44257693272STobias Grosser SetVector<Value *> SubtreeValues); 44379a947c2STobias Grosser 444b513b491STobias Grosser /// Create declarations for kernel variable. 445b513b491STobias Grosser /// 446b513b491STobias Grosser /// This includes shared memory declarations. 447b513b491STobias Grosser /// 448b513b491STobias Grosser /// @param Kernel The kernel definition to create variables for. 449b513b491STobias Grosser /// @param FN The function into which to generate the variables. 450b513b491STobias Grosser void createKernelVariables(ppcg_kernel *Kernel, Function *FN); 451b513b491STobias Grosser 452c1c6a2a6STobias Grosser /// Add CUDA annotations to module. 453c1c6a2a6STobias Grosser /// 454c1c6a2a6STobias Grosser /// Add a set of CUDA annotations that declares the maximal block dimensions 455c1c6a2a6STobias Grosser /// that will be used to execute the CUDA kernel. This allows the NVIDIA 456c1c6a2a6STobias Grosser /// PTX compiler to bound the number of allocated registers to ensure the 457c1c6a2a6STobias Grosser /// resulting kernel is known to run with up to as many block dimensions 458c1c6a2a6STobias Grosser /// as specified here. 459c1c6a2a6STobias Grosser /// 460c1c6a2a6STobias Grosser /// @param M The module to add the annotations to. 461c1c6a2a6STobias Grosser /// @param BlockDimX The size of block dimension X. 462c1c6a2a6STobias Grosser /// @param BlockDimY The size of block dimension Y. 463c1c6a2a6STobias Grosser /// @param BlockDimZ The size of block dimension Z. 464c1c6a2a6STobias Grosser void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY, 465c1c6a2a6STobias Grosser Value *BlockDimZ); 466c1c6a2a6STobias Grosser 46732837fe3STobias Grosser /// Create GPU kernel. 46832837fe3STobias Grosser /// 46932837fe3STobias Grosser /// Code generate the kernel described by @p KernelStmt. 47032837fe3STobias Grosser /// 47132837fe3STobias Grosser /// @param KernelStmt The ast node to generate kernel code for. 47232837fe3STobias Grosser void createKernel(__isl_take isl_ast_node *KernelStmt); 47332837fe3STobias Grosser 47413c78e4dSTobias Grosser /// Generate code that computes the size of an array. 47513c78e4dSTobias Grosser /// 47613c78e4dSTobias Grosser /// @param Array The array for which to compute a size. 47713c78e4dSTobias Grosser Value *getArraySize(gpu_array_info *Array); 47813c78e4dSTobias Grosser 479aaabbbf8STobias Grosser /// Generate code to compute the minimal offset at which an array is accessed. 480aaabbbf8STobias Grosser /// 481aaabbbf8STobias Grosser /// The offset of an array is the minimal array location accessed in a scop. 482aaabbbf8STobias Grosser /// 483aaabbbf8STobias Grosser /// Example: 484aaabbbf8STobias Grosser /// 485aaabbbf8STobias Grosser /// for (long i = 0; i < 100; i++) 486aaabbbf8STobias Grosser /// A[i + 42] += ... 487aaabbbf8STobias Grosser /// 488aaabbbf8STobias Grosser /// getArrayOffset(A) results in 42. 489aaabbbf8STobias Grosser /// 490aaabbbf8STobias Grosser /// @param Array The array for which to compute the offset. 491aaabbbf8STobias Grosser /// @returns An llvm::Value that contains the offset of the array. 492aaabbbf8STobias Grosser Value *getArrayOffset(gpu_array_info *Array); 493aaabbbf8STobias Grosser 49400bb5a99STobias Grosser /// Prepare the kernel arguments for kernel code generation 49500bb5a99STobias Grosser /// 49600bb5a99STobias Grosser /// @param Kernel The kernel to generate code for. 49700bb5a99STobias Grosser /// @param FN The function created for the kernel. 49800bb5a99STobias Grosser void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN); 49900bb5a99STobias Grosser 50032837fe3STobias Grosser /// Create kernel function. 50132837fe3STobias Grosser /// 50232837fe3STobias Grosser /// Create a kernel function located in a newly created module that can serve 50332837fe3STobias Grosser /// as target for device code generation. Set the Builder to point to the 50432837fe3STobias Grosser /// start block of this newly created function. 50532837fe3STobias Grosser /// 50632837fe3STobias Grosser /// @param Kernel The kernel to generate code for. 507edb885cbSTobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 508f291c8d5SSiddharth Bhat /// @param SubtreeFunctions The set of llvm::Functions referenced by this 509f291c8d5SSiddharth Bhat /// kernel. 510edb885cbSTobias Grosser void createKernelFunction(ppcg_kernel *Kernel, 511f291c8d5SSiddharth Bhat SetVector<Value *> &SubtreeValues, 512f291c8d5SSiddharth Bhat SetVector<Function *> &SubtreeFunctions); 51332837fe3STobias Grosser 51432837fe3STobias Grosser /// Create the declaration of a kernel function. 51532837fe3STobias Grosser /// 51632837fe3STobias Grosser /// The kernel function takes as arguments: 51732837fe3STobias Grosser /// 51832837fe3STobias Grosser /// - One i8 pointer for each external array reference used in the kernel. 519f6044bd0STobias Grosser /// - Host iterators 520c84a1995STobias Grosser /// - Parameters 52132837fe3STobias Grosser /// - Other LLVM Value references (TODO) 52232837fe3STobias Grosser /// 52332837fe3STobias Grosser /// @param Kernel The kernel to generate the function declaration for. 524edb885cbSTobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 525edb885cbSTobias Grosser /// 52632837fe3STobias Grosser /// @returns The newly declared function. 527edb885cbSTobias Grosser Function *createKernelFunctionDecl(ppcg_kernel *Kernel, 528edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues); 52932837fe3STobias Grosser 530472f9654STobias Grosser /// Insert intrinsic functions to obtain thread and block ids. 531472f9654STobias Grosser /// 532472f9654STobias Grosser /// @param The kernel to generate the intrinsic functions for. 533472f9654STobias Grosser void insertKernelIntrinsics(ppcg_kernel *Kernel); 534472f9654STobias Grosser 535f291c8d5SSiddharth Bhat /// Setup the creation of functions referenced by the GPU kernel. 536f291c8d5SSiddharth Bhat /// 537f291c8d5SSiddharth Bhat /// 1. Create new function declarations in GPUModule which are the same as 538f291c8d5SSiddharth Bhat /// SubtreeFunctions. 539f291c8d5SSiddharth Bhat /// 540f291c8d5SSiddharth Bhat /// 2. Populate IslNodeBuilder::ValueMap with mappings from 541f291c8d5SSiddharth Bhat /// old functions (that come from the original module) to new functions 542f291c8d5SSiddharth Bhat /// (that are created within GPUModule). That way, we generate references 543f291c8d5SSiddharth Bhat /// to the correct function (in GPUModule) in BlockGenerator. 544f291c8d5SSiddharth Bhat /// 545f291c8d5SSiddharth Bhat /// @see IslNodeBuilder::ValueMap 546f291c8d5SSiddharth Bhat /// @see BlockGenerator::GlobalMap 547f291c8d5SSiddharth Bhat /// @see BlockGenerator::getNewValue 548f291c8d5SSiddharth Bhat /// @see GPUNodeBuilder::getReferencesInKernel. 549f291c8d5SSiddharth Bhat /// 550f291c8d5SSiddharth Bhat /// @param SubtreeFunctions The set of llvm::Functions referenced by 551f291c8d5SSiddharth Bhat /// this kernel. 552f291c8d5SSiddharth Bhat void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions); 553f291c8d5SSiddharth Bhat 554b513b491STobias Grosser /// Create a global-to-shared or shared-to-global copy statement. 555b513b491STobias Grosser /// 556b513b491STobias Grosser /// @param CopyStmt The copy statement to generate code for 557b513b491STobias Grosser void createKernelCopy(ppcg_kernel_stmt *CopyStmt); 558b513b491STobias Grosser 559edb885cbSTobias Grosser /// Create code for a ScopStmt called in @p Expr. 560edb885cbSTobias Grosser /// 561edb885cbSTobias Grosser /// @param Expr The expression containing the call. 562edb885cbSTobias Grosser /// @param KernelStmt The kernel statement referenced in the call. 563edb885cbSTobias Grosser void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt); 564edb885cbSTobias Grosser 5655260c041STobias Grosser /// Create an in-kernel synchronization call. 5665260c041STobias Grosser void createKernelSync(); 5675260c041STobias Grosser 56874dc3cb4STobias Grosser /// Create a PTX assembly string for the current GPU kernel. 56974dc3cb4STobias Grosser /// 57074dc3cb4STobias Grosser /// @returns A string containing the corresponding PTX assembly code. 57174dc3cb4STobias Grosser std::string createKernelASM(); 57274dc3cb4STobias Grosser 57374dc3cb4STobias Grosser /// Remove references from the dominator tree to the kernel function @p F. 57474dc3cb4STobias Grosser /// 57574dc3cb4STobias Grosser /// @param F The function to remove references to. 57674dc3cb4STobias Grosser void clearDominators(Function *F); 57774dc3cb4STobias Grosser 57874dc3cb4STobias Grosser /// Remove references from scalar evolution to the kernel function @p F. 57974dc3cb4STobias Grosser /// 58074dc3cb4STobias Grosser /// @param F The function to remove references to. 58174dc3cb4STobias Grosser void clearScalarEvolution(Function *F); 58274dc3cb4STobias Grosser 58374dc3cb4STobias Grosser /// Remove references from loop info to the kernel function @p F. 58474dc3cb4STobias Grosser /// 58574dc3cb4STobias Grosser /// @param F The function to remove references to. 58674dc3cb4STobias Grosser void clearLoops(Function *F); 58774dc3cb4STobias Grosser 58832837fe3STobias Grosser /// Finalize the generation of the kernel function. 58932837fe3STobias Grosser /// 59032837fe3STobias Grosser /// Free the LLVM-IR module corresponding to the kernel and -- if requested -- 59132837fe3STobias Grosser /// dump its IR to stderr. 59257793596STobias Grosser /// 59357793596STobias Grosser /// @returns The Assembly string of the kernel. 59457793596STobias Grosser std::string finalizeKernelFunction(); 595fa7b0802STobias Grosser 59651dfc275STobias Grosser /// Finalize the generation of the kernel arguments. 59751dfc275STobias Grosser /// 59851dfc275STobias Grosser /// This function ensures that not-read-only scalars used in a kernel are 599a6d48f59SMichael Kruse /// stored back to the global memory location they are backed with before 60051dfc275STobias Grosser /// the kernel terminates. 60151dfc275STobias Grosser /// 60251dfc275STobias Grosser /// @params Kernel The kernel to finalize kernel arguments for. 60351dfc275STobias Grosser void finalizeKernelArguments(ppcg_kernel *Kernel); 60451dfc275STobias Grosser 6057287aeddSTobias Grosser /// Create code that allocates memory to store arrays on device. 606fa7b0802STobias Grosser void allocateDeviceArrays(); 607fa7b0802STobias Grosser 6087287aeddSTobias Grosser /// Free all allocated device arrays. 6097287aeddSTobias Grosser void freeDeviceArrays(); 6107287aeddSTobias Grosser 611fa7b0802STobias Grosser /// Create a call to initialize the GPU context. 612fa7b0802STobias Grosser /// 613fa7b0802STobias Grosser /// @returns A pointer to the newly initialized context. 614fa7b0802STobias Grosser Value *createCallInitContext(); 615fa7b0802STobias Grosser 61679a947c2STobias Grosser /// Create a call to get the device pointer for a kernel allocation. 61779a947c2STobias Grosser /// 61879a947c2STobias Grosser /// @param Allocation The Polly GPU allocation 61979a947c2STobias Grosser /// 62079a947c2STobias Grosser /// @returns The device parameter corresponding to this allocation. 62179a947c2STobias Grosser Value *createCallGetDevicePtr(Value *Allocation); 62279a947c2STobias Grosser 623fa7b0802STobias Grosser /// Create a call to free the GPU context. 624fa7b0802STobias Grosser /// 625fa7b0802STobias Grosser /// @param Context A pointer to an initialized GPU context. 626fa7b0802STobias Grosser void createCallFreeContext(Value *Context); 627fa7b0802STobias Grosser 6287287aeddSTobias Grosser /// Create a call to allocate memory on the device. 6297287aeddSTobias Grosser /// 6307287aeddSTobias Grosser /// @param Size The size of memory to allocate 6317287aeddSTobias Grosser /// 6327287aeddSTobias Grosser /// @returns A pointer that identifies this allocation. 633fa7b0802STobias Grosser Value *createCallAllocateMemoryForDevice(Value *Size); 6347287aeddSTobias Grosser 6357287aeddSTobias Grosser /// Create a call to free a device array. 6367287aeddSTobias Grosser /// 6377287aeddSTobias Grosser /// @param Array The device array to free. 6387287aeddSTobias Grosser void createCallFreeDeviceMemory(Value *Array); 63913c78e4dSTobias Grosser 64013c78e4dSTobias Grosser /// Create a call to copy data from host to device. 64113c78e4dSTobias Grosser /// 64213c78e4dSTobias Grosser /// @param HostPtr A pointer to the host data that should be copied. 64313c78e4dSTobias Grosser /// @param DevicePtr A device pointer specifying the location to copy to. 64413c78e4dSTobias Grosser void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr, 64513c78e4dSTobias Grosser Value *Size); 64613c78e4dSTobias Grosser 64713c78e4dSTobias Grosser /// Create a call to copy data from device to host. 64813c78e4dSTobias Grosser /// 64913c78e4dSTobias Grosser /// @param DevicePtr A pointer to the device data that should be copied. 65013c78e4dSTobias Grosser /// @param HostPtr A host pointer specifying the location to copy to. 65113c78e4dSTobias Grosser void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr, 65213c78e4dSTobias Grosser Value *Size); 65357793596STobias Grosser 654abed4969SSiddharth Bhat /// Create a call to synchronize Host & Device. 655abed4969SSiddharth Bhat /// \note 656abed4969SSiddharth Bhat /// This is to be used only with managed memory. 657abed4969SSiddharth Bhat void createCallSynchronizeDevice(); 658abed4969SSiddharth Bhat 65957793596STobias Grosser /// Create a call to get a kernel from an assembly string. 66057793596STobias Grosser /// 66157793596STobias Grosser /// @param Buffer The string describing the kernel. 66257793596STobias Grosser /// @param Entry The name of the kernel function to call. 66357793596STobias Grosser /// 66457793596STobias Grosser /// @returns A pointer to a kernel object 66557793596STobias Grosser Value *createCallGetKernel(Value *Buffer, Value *Entry); 66657793596STobias Grosser 66757793596STobias Grosser /// Create a call to free a GPU kernel. 66857793596STobias Grosser /// 66957793596STobias Grosser /// @param GPUKernel THe kernel to free. 67057793596STobias Grosser void createCallFreeKernel(Value *GPUKernel); 67179a947c2STobias Grosser 67279a947c2STobias Grosser /// Create a call to launch a GPU kernel. 67379a947c2STobias Grosser /// 67479a947c2STobias Grosser /// @param GPUKernel The kernel to launch. 67579a947c2STobias Grosser /// @param GridDimX The size of the first grid dimension. 67679a947c2STobias Grosser /// @param GridDimY The size of the second grid dimension. 67779a947c2STobias Grosser /// @param GridBlockX The size of the first block dimension. 67879a947c2STobias Grosser /// @param GridBlockY The size of the second block dimension. 67979a947c2STobias Grosser /// @param GridBlockZ The size of the third block dimension. 680a6d48f59SMichael Kruse /// @param Parameters A pointer to an array that contains itself pointers to 68179a947c2STobias Grosser /// the parameter values passed for each kernel argument. 68279a947c2STobias Grosser void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 68379a947c2STobias Grosser Value *GridDimY, Value *BlockDimX, 68479a947c2STobias Grosser Value *BlockDimY, Value *BlockDimZ, 68579a947c2STobias Grosser Value *Parameters); 6861fb9b64dSTobias Grosser }; 6871fb9b64dSTobias Grosser 68879f13b9aSSingapuram Sanjay Srivallabh std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) { 6891abd9ffaSSingapuram Sanjay Srivallabh return "FUNC_" + S.getFunction().getName().str() + "_SCOP_" + 6901abd9ffaSSingapuram Sanjay Srivallabh std::to_string(S.getID()) + "_KERNEL_" + std::to_string(Kernel_id); 69179f13b9aSSingapuram Sanjay Srivallabh } 69279f13b9aSSingapuram Sanjay Srivallabh 693fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() { 694750160e2STobias Grosser BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(), 695750160e2STobias Grosser &*Builder.GetInsertPoint(), &DT, &LI); 696750160e2STobias Grosser NewBB->setName("polly.acc.initialize"); 697750160e2STobias Grosser Builder.SetInsertPoint(&NewBB->front()); 698750160e2STobias Grosser 699fa7b0802STobias Grosser GPUContext = createCallInitContext(); 700abed4969SSiddharth Bhat 701abed4969SSiddharth Bhat if (!ManagedMemory) 702fa7b0802STobias Grosser allocateDeviceArrays(); 703fa7b0802STobias Grosser } 704fa7b0802STobias Grosser 705fa7b0802STobias Grosser void GPUNodeBuilder::finalize() { 706abed4969SSiddharth Bhat if (!ManagedMemory) 7077287aeddSTobias Grosser freeDeviceArrays(); 708abed4969SSiddharth Bhat 709fa7b0802STobias Grosser createCallFreeContext(GPUContext); 710fa7b0802STobias Grosser IslNodeBuilder::finalize(); 711fa7b0802STobias Grosser } 712fa7b0802STobias Grosser 713fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() { 714abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory will directly send host pointers " 715abed4969SSiddharth Bhat "to the kernel. There is no need for device arrays"); 716fa7b0802STobias Grosser isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 717fa7b0802STobias Grosser 718fa7b0802STobias Grosser for (int i = 0; i < Prog->n_array; ++i) { 719fa7b0802STobias Grosser gpu_array_info *Array = &Prog->array[i]; 72013c78e4dSTobias Grosser auto *ScopArray = (ScopArrayInfo *)Array->user; 7217287aeddSTobias Grosser std::string DevArrayName("p_dev_array_"); 7227287aeddSTobias Grosser DevArrayName.append(Array->name); 723fa7b0802STobias Grosser 72413c78e4dSTobias Grosser Value *ArraySize = getArraySize(Array); 725aaabbbf8STobias Grosser Value *Offset = getArrayOffset(Array); 726aaabbbf8STobias Grosser if (Offset) 727aaabbbf8STobias Grosser ArraySize = Builder.CreateSub( 728aaabbbf8STobias Grosser ArraySize, 729aaabbbf8STobias Grosser Builder.CreateMul(Offset, 730aaabbbf8STobias Grosser Builder.getInt64(ScopArray->getElemSizeInBytes()))); 7317287aeddSTobias Grosser Value *DevArray = createCallAllocateMemoryForDevice(ArraySize); 7327287aeddSTobias Grosser DevArray->setName(DevArrayName); 73313c78e4dSTobias Grosser DeviceAllocations[ScopArray] = DevArray; 734fa7b0802STobias Grosser } 735fa7b0802STobias Grosser 736fa7b0802STobias Grosser isl_ast_build_free(Build); 737fa7b0802STobias Grosser } 738fa7b0802STobias Grosser 739c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX, 740c1c6a2a6STobias Grosser Value *BlockDimY, Value *BlockDimZ) { 741c1c6a2a6STobias Grosser auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations"); 742c1c6a2a6STobias Grosser 743c1c6a2a6STobias Grosser for (auto &F : *M) { 744c1c6a2a6STobias Grosser if (F.getCallingConv() != CallingConv::PTX_Kernel) 745c1c6a2a6STobias Grosser continue; 746c1c6a2a6STobias Grosser 747c1c6a2a6STobias Grosser Value *V[] = {BlockDimX, BlockDimY, BlockDimZ}; 748c1c6a2a6STobias Grosser 749c1c6a2a6STobias Grosser Metadata *Elements[] = { 750c1c6a2a6STobias Grosser ValueAsMetadata::get(&F), MDString::get(M->getContext(), "maxntidx"), 751c1c6a2a6STobias Grosser ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"), 752c1c6a2a6STobias Grosser ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"), 753c1c6a2a6STobias Grosser ValueAsMetadata::get(V[2]), 754c1c6a2a6STobias Grosser }; 755c1c6a2a6STobias Grosser MDNode *Node = MDNode::get(M->getContext(), Elements); 756c1c6a2a6STobias Grosser AnnotationNode->addOperand(Node); 757c1c6a2a6STobias Grosser } 758c1c6a2a6STobias Grosser } 759c1c6a2a6STobias Grosser 7607287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() { 761abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not use device arrays"); 76213c78e4dSTobias Grosser for (auto &Array : DeviceAllocations) 76313c78e4dSTobias Grosser createCallFreeDeviceMemory(Array.second); 7647287aeddSTobias Grosser } 7657287aeddSTobias Grosser 76657793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) { 76757793596STobias Grosser const char *Name = "polly_getKernel"; 76857793596STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 76957793596STobias Grosser Function *F = M->getFunction(Name); 77057793596STobias Grosser 77157793596STobias Grosser // If F is not available, declare it. 77257793596STobias Grosser if (!F) { 77357793596STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 77457793596STobias Grosser std::vector<Type *> Args; 77557793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 77657793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 77757793596STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 77857793596STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 77957793596STobias Grosser } 78057793596STobias Grosser 78157793596STobias Grosser return Builder.CreateCall(F, {Buffer, Entry}); 78257793596STobias Grosser } 78357793596STobias Grosser 78479a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) { 78579a947c2STobias Grosser const char *Name = "polly_getDevicePtr"; 78679a947c2STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 78779a947c2STobias Grosser Function *F = M->getFunction(Name); 78879a947c2STobias Grosser 78979a947c2STobias Grosser // If F is not available, declare it. 79079a947c2STobias Grosser if (!F) { 79179a947c2STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 79279a947c2STobias Grosser std::vector<Type *> Args; 79379a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 79479a947c2STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 79579a947c2STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 79679a947c2STobias Grosser } 79779a947c2STobias Grosser 79879a947c2STobias Grosser return Builder.CreateCall(F, {Allocation}); 79979a947c2STobias Grosser } 80079a947c2STobias Grosser 80179a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 80279a947c2STobias Grosser Value *GridDimY, Value *BlockDimX, 80379a947c2STobias Grosser Value *BlockDimY, Value *BlockDimZ, 80479a947c2STobias Grosser Value *Parameters) { 80579a947c2STobias Grosser const char *Name = "polly_launchKernel"; 80679a947c2STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 80779a947c2STobias Grosser Function *F = M->getFunction(Name); 80879a947c2STobias Grosser 80979a947c2STobias Grosser // If F is not available, declare it. 81079a947c2STobias Grosser if (!F) { 81179a947c2STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 81279a947c2STobias Grosser std::vector<Type *> Args; 81379a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 81479a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 81579a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 81679a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 81779a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 81879a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 81979a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 82079a947c2STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 82179a947c2STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 82279a947c2STobias Grosser } 82379a947c2STobias Grosser 824ff40087aSTobias Grosser Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 82579a947c2STobias Grosser BlockDimZ, Parameters}); 82679a947c2STobias Grosser } 82779a947c2STobias Grosser 82857793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) { 82957793596STobias Grosser const char *Name = "polly_freeKernel"; 83057793596STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 83157793596STobias Grosser Function *F = M->getFunction(Name); 83257793596STobias Grosser 83357793596STobias Grosser // If F is not available, declare it. 83457793596STobias Grosser if (!F) { 83557793596STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 83657793596STobias Grosser std::vector<Type *> Args; 83757793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 83857793596STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 83957793596STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 84057793596STobias Grosser } 84157793596STobias Grosser 84257793596STobias Grosser Builder.CreateCall(F, {GPUKernel}); 84357793596STobias Grosser } 84457793596STobias Grosser 8457287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) { 846abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not allocate or free memory " 847abed4969SSiddharth Bhat "for device"); 8487287aeddSTobias Grosser const char *Name = "polly_freeDeviceMemory"; 8497287aeddSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 8507287aeddSTobias Grosser Function *F = M->getFunction(Name); 8517287aeddSTobias Grosser 8527287aeddSTobias Grosser // If F is not available, declare it. 8537287aeddSTobias Grosser if (!F) { 8547287aeddSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 8557287aeddSTobias Grosser std::vector<Type *> Args; 8567287aeddSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 8577287aeddSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 8587287aeddSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 8597287aeddSTobias Grosser } 8607287aeddSTobias Grosser 8617287aeddSTobias Grosser Builder.CreateCall(F, {Array}); 8627287aeddSTobias Grosser } 8637287aeddSTobias Grosser 864fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) { 865abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not allocate or free memory " 866abed4969SSiddharth Bhat "for device"); 867fa7b0802STobias Grosser const char *Name = "polly_allocateMemoryForDevice"; 868fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 869fa7b0802STobias Grosser Function *F = M->getFunction(Name); 870fa7b0802STobias Grosser 871fa7b0802STobias Grosser // If F is not available, declare it. 872fa7b0802STobias Grosser if (!F) { 873fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 874fa7b0802STobias Grosser std::vector<Type *> Args; 875fa7b0802STobias Grosser Args.push_back(Builder.getInt64Ty()); 876fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 877fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 878fa7b0802STobias Grosser } 879fa7b0802STobias Grosser 880fa7b0802STobias Grosser return Builder.CreateCall(F, {Size}); 881fa7b0802STobias Grosser } 882fa7b0802STobias Grosser 88313c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData, 88413c78e4dSTobias Grosser Value *DeviceData, 88513c78e4dSTobias Grosser Value *Size) { 886abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not transfer memory between " 887abed4969SSiddharth Bhat "device and host"); 88813c78e4dSTobias Grosser const char *Name = "polly_copyFromHostToDevice"; 88913c78e4dSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 89013c78e4dSTobias Grosser Function *F = M->getFunction(Name); 89113c78e4dSTobias Grosser 89213c78e4dSTobias Grosser // If F is not available, declare it. 89313c78e4dSTobias Grosser if (!F) { 89413c78e4dSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 89513c78e4dSTobias Grosser std::vector<Type *> Args; 89613c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 89713c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 89813c78e4dSTobias Grosser Args.push_back(Builder.getInt64Ty()); 89913c78e4dSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 90013c78e4dSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 90113c78e4dSTobias Grosser } 90213c78e4dSTobias Grosser 90313c78e4dSTobias Grosser Builder.CreateCall(F, {HostData, DeviceData, Size}); 90413c78e4dSTobias Grosser } 90513c78e4dSTobias Grosser 90613c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData, 90713c78e4dSTobias Grosser Value *HostData, 90813c78e4dSTobias Grosser Value *Size) { 909abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not transfer memory between " 910abed4969SSiddharth Bhat "device and host"); 91113c78e4dSTobias Grosser const char *Name = "polly_copyFromDeviceToHost"; 91213c78e4dSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 91313c78e4dSTobias Grosser Function *F = M->getFunction(Name); 91413c78e4dSTobias Grosser 91513c78e4dSTobias Grosser // If F is not available, declare it. 91613c78e4dSTobias Grosser if (!F) { 91713c78e4dSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 91813c78e4dSTobias Grosser std::vector<Type *> Args; 91913c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 92013c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 92113c78e4dSTobias Grosser Args.push_back(Builder.getInt64Ty()); 92213c78e4dSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 92313c78e4dSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 92413c78e4dSTobias Grosser } 92513c78e4dSTobias Grosser 92613c78e4dSTobias Grosser Builder.CreateCall(F, {DeviceData, HostData, Size}); 92713c78e4dSTobias Grosser } 92813c78e4dSTobias Grosser 929abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() { 930abed4969SSiddharth Bhat assert(ManagedMemory && "explicit synchronization is only necessary for " 931abed4969SSiddharth Bhat "managed memory"); 932abed4969SSiddharth Bhat const char *Name = "polly_synchronizeDevice"; 933abed4969SSiddharth Bhat Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 934abed4969SSiddharth Bhat Function *F = M->getFunction(Name); 935abed4969SSiddharth Bhat 936abed4969SSiddharth Bhat // If F is not available, declare it. 937abed4969SSiddharth Bhat if (!F) { 938abed4969SSiddharth Bhat GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 939abed4969SSiddharth Bhat FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false); 940abed4969SSiddharth Bhat F = Function::Create(Ty, Linkage, Name, M); 941abed4969SSiddharth Bhat } 942abed4969SSiddharth Bhat 943abed4969SSiddharth Bhat Builder.CreateCall(F); 944abed4969SSiddharth Bhat } 945abed4969SSiddharth Bhat 946fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() { 94717f01968SSiddharth Bhat const char *Name; 94817f01968SSiddharth Bhat 94917f01968SSiddharth Bhat switch (Runtime) { 95017f01968SSiddharth Bhat case GPURuntime::CUDA: 95117f01968SSiddharth Bhat Name = "polly_initContextCUDA"; 95217f01968SSiddharth Bhat break; 95317f01968SSiddharth Bhat case GPURuntime::OpenCL: 95417f01968SSiddharth Bhat Name = "polly_initContextCL"; 95517f01968SSiddharth Bhat break; 95617f01968SSiddharth Bhat } 95717f01968SSiddharth Bhat 958fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 959fa7b0802STobias Grosser Function *F = M->getFunction(Name); 960fa7b0802STobias Grosser 961fa7b0802STobias Grosser // If F is not available, declare it. 962fa7b0802STobias Grosser if (!F) { 963fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 964fa7b0802STobias Grosser std::vector<Type *> Args; 965fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 966fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 967fa7b0802STobias Grosser } 968fa7b0802STobias Grosser 969fa7b0802STobias Grosser return Builder.CreateCall(F, {}); 970fa7b0802STobias Grosser } 971fa7b0802STobias Grosser 972fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) { 973fa7b0802STobias Grosser const char *Name = "polly_freeContext"; 974fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 975fa7b0802STobias Grosser Function *F = M->getFunction(Name); 976fa7b0802STobias Grosser 977fa7b0802STobias Grosser // If F is not available, declare it. 978fa7b0802STobias Grosser if (!F) { 979fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 980fa7b0802STobias Grosser std::vector<Type *> Args; 981fa7b0802STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 982fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 983fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 984fa7b0802STobias Grosser } 985fa7b0802STobias Grosser 986fa7b0802STobias Grosser Builder.CreateCall(F, {Context}); 987fa7b0802STobias Grosser } 988fa7b0802STobias Grosser 9895260c041STobias Grosser /// Check if one string is a prefix of another. 9905260c041STobias Grosser /// 9915260c041STobias Grosser /// @param String The string in which to look for the prefix. 9925260c041STobias Grosser /// @param Prefix The prefix to look for. 9935260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) { 9945260c041STobias Grosser return String.find(Prefix) == 0; 9955260c041STobias Grosser } 9965260c041STobias Grosser 99713c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) { 99813c78e4dSTobias Grosser isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 99913c78e4dSTobias Grosser Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size); 100013c78e4dSTobias Grosser 100113c78e4dSTobias Grosser if (!gpu_array_is_scalar(Array)) { 100213c78e4dSTobias Grosser auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]); 100313c78e4dSTobias Grosser isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero); 100413c78e4dSTobias Grosser 100513c78e4dSTobias Grosser for (unsigned int i = 1; i < Array->n_index; i++) { 100613c78e4dSTobias Grosser isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]); 100713c78e4dSTobias Grosser isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I); 100813c78e4dSTobias Grosser Res = isl_ast_expr_mul(Res, Expr); 100913c78e4dSTobias Grosser } 101013c78e4dSTobias Grosser 101113c78e4dSTobias Grosser Value *NumElements = ExprBuilder.create(Res); 1012b79f4d39STobias Grosser if (NumElements->getType() != ArraySize->getType()) 1013b79f4d39STobias Grosser NumElements = Builder.CreateSExt(NumElements, ArraySize->getType()); 101413c78e4dSTobias Grosser ArraySize = Builder.CreateMul(ArraySize, NumElements); 101513c78e4dSTobias Grosser } 101613c78e4dSTobias Grosser isl_ast_build_free(Build); 101713c78e4dSTobias Grosser return ArraySize; 101813c78e4dSTobias Grosser } 101913c78e4dSTobias Grosser 1020aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) { 1021aaabbbf8STobias Grosser if (gpu_array_is_scalar(Array)) 1022aaabbbf8STobias Grosser return nullptr; 1023aaabbbf8STobias Grosser 1024aaabbbf8STobias Grosser isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 1025aaabbbf8STobias Grosser 1026aaabbbf8STobias Grosser isl_set *Min = isl_set_lexmin(isl_set_copy(Array->extent)); 1027aaabbbf8STobias Grosser 1028aaabbbf8STobias Grosser isl_set *ZeroSet = isl_set_universe(isl_set_get_space(Min)); 1029aaabbbf8STobias Grosser 1030aaabbbf8STobias Grosser for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) 1031aaabbbf8STobias Grosser ZeroSet = isl_set_fix_si(ZeroSet, isl_dim_set, i, 0); 1032aaabbbf8STobias Grosser 1033aaabbbf8STobias Grosser if (isl_set_is_subset(Min, ZeroSet)) { 1034aaabbbf8STobias Grosser isl_set_free(Min); 1035aaabbbf8STobias Grosser isl_set_free(ZeroSet); 1036aaabbbf8STobias Grosser isl_ast_build_free(Build); 1037aaabbbf8STobias Grosser return nullptr; 1038aaabbbf8STobias Grosser } 1039aaabbbf8STobias Grosser isl_set_free(ZeroSet); 1040aaabbbf8STobias Grosser 1041aaabbbf8STobias Grosser isl_ast_expr *Result = 1042aaabbbf8STobias Grosser isl_ast_expr_from_val(isl_val_int_from_si(isl_set_get_ctx(Min), 0)); 1043aaabbbf8STobias Grosser 1044aaabbbf8STobias Grosser for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) { 1045aaabbbf8STobias Grosser if (i > 0) { 1046aaabbbf8STobias Grosser isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i - 1]); 1047aaabbbf8STobias Grosser isl_ast_expr *BExpr = isl_ast_build_expr_from_pw_aff(Build, Bound_I); 1048aaabbbf8STobias Grosser Result = isl_ast_expr_mul(Result, BExpr); 1049aaabbbf8STobias Grosser } 1050aaabbbf8STobias Grosser isl_pw_aff *DimMin = isl_set_dim_min(isl_set_copy(Min), i); 1051aaabbbf8STobias Grosser isl_ast_expr *MExpr = isl_ast_build_expr_from_pw_aff(Build, DimMin); 1052aaabbbf8STobias Grosser Result = isl_ast_expr_add(Result, MExpr); 1053aaabbbf8STobias Grosser } 1054aaabbbf8STobias Grosser 1055aaabbbf8STobias Grosser Value *ResultValue = ExprBuilder.create(Result); 1056aaabbbf8STobias Grosser isl_set_free(Min); 1057aaabbbf8STobias Grosser isl_ast_build_free(Build); 1058aaabbbf8STobias Grosser 1059aaabbbf8STobias Grosser return ResultValue; 1060aaabbbf8STobias Grosser } 1061aaabbbf8STobias Grosser 1062abed4969SSiddharth Bhat Value *GPUNodeBuilder::getOrCreateManagedDeviceArray(gpu_array_info *Array, 1063abed4969SSiddharth Bhat ScopArrayInfo *ArrayInfo) { 1064abed4969SSiddharth Bhat 1065abed4969SSiddharth Bhat assert(ManagedMemory && "Only used when you wish to get a host " 1066abed4969SSiddharth Bhat "pointer for sending data to the kernel, " 1067abed4969SSiddharth Bhat "with managed memory"); 1068abed4969SSiddharth Bhat std::map<ScopArrayInfo *, Value *>::iterator it; 1069abed4969SSiddharth Bhat if ((it = DeviceAllocations.find(ArrayInfo)) != DeviceAllocations.end()) { 1070abed4969SSiddharth Bhat return it->second; 1071abed4969SSiddharth Bhat } else { 1072abed4969SSiddharth Bhat Value *HostPtr; 1073abed4969SSiddharth Bhat 1074abed4969SSiddharth Bhat if (gpu_array_is_scalar(Array)) 1075abed4969SSiddharth Bhat HostPtr = BlockGen.getOrCreateAlloca(ArrayInfo); 1076abed4969SSiddharth Bhat else 1077abed4969SSiddharth Bhat HostPtr = ArrayInfo->getBasePtr(); 1078abed4969SSiddharth Bhat 1079abed4969SSiddharth Bhat Value *Offset = getArrayOffset(Array); 1080abed4969SSiddharth Bhat if (Offset) { 1081abed4969SSiddharth Bhat HostPtr = Builder.CreatePointerCast( 1082abed4969SSiddharth Bhat HostPtr, ArrayInfo->getElementType()->getPointerTo()); 1083abed4969SSiddharth Bhat HostPtr = Builder.CreateGEP(HostPtr, Offset); 1084abed4969SSiddharth Bhat } 1085abed4969SSiddharth Bhat 1086abed4969SSiddharth Bhat HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 1087abed4969SSiddharth Bhat DeviceAllocations[ArrayInfo] = HostPtr; 1088abed4969SSiddharth Bhat return HostPtr; 1089abed4969SSiddharth Bhat } 1090abed4969SSiddharth Bhat } 1091abed4969SSiddharth Bhat 109213c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt, 109313c78e4dSTobias Grosser enum DataDirection Direction) { 1094abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory needs no data transfers"); 109513c78e4dSTobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt); 109613c78e4dSTobias Grosser isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0); 109713c78e4dSTobias Grosser isl_id *Id = isl_ast_expr_get_id(Arg); 109813c78e4dSTobias Grosser auto Array = (gpu_array_info *)isl_id_get_user(Id); 109913c78e4dSTobias Grosser auto ScopArray = (ScopArrayInfo *)(Array->user); 110013c78e4dSTobias Grosser 110113c78e4dSTobias Grosser Value *Size = getArraySize(Array); 1102aaabbbf8STobias Grosser Value *Offset = getArrayOffset(Array); 110313c78e4dSTobias Grosser Value *DevPtr = DeviceAllocations[ScopArray]; 110413c78e4dSTobias Grosser 1105b06ff457STobias Grosser Value *HostPtr; 1106b06ff457STobias Grosser 1107b06ff457STobias Grosser if (gpu_array_is_scalar(Array)) 1108b06ff457STobias Grosser HostPtr = BlockGen.getOrCreateAlloca(ScopArray); 1109b06ff457STobias Grosser else 1110b06ff457STobias Grosser HostPtr = ScopArray->getBasePtr(); 111113c78e4dSTobias Grosser 1112aaabbbf8STobias Grosser if (Offset) { 1113aaabbbf8STobias Grosser HostPtr = Builder.CreatePointerCast( 1114aaabbbf8STobias Grosser HostPtr, ScopArray->getElementType()->getPointerTo()); 1115aaabbbf8STobias Grosser HostPtr = Builder.CreateGEP(HostPtr, Offset); 1116aaabbbf8STobias Grosser } 1117aaabbbf8STobias Grosser 111813c78e4dSTobias Grosser HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 111913c78e4dSTobias Grosser 1120aaabbbf8STobias Grosser if (Offset) { 1121aaabbbf8STobias Grosser Size = Builder.CreateSub( 1122ff40087aSTobias Grosser Size, Builder.CreateMul( 1123ff40087aSTobias Grosser Offset, Builder.getInt64(ScopArray->getElemSizeInBytes()))); 1124aaabbbf8STobias Grosser } 1125aaabbbf8STobias Grosser 112613c78e4dSTobias Grosser if (Direction == HOST_TO_DEVICE) 112713c78e4dSTobias Grosser createCallCopyFromHostToDevice(HostPtr, DevPtr, Size); 112813c78e4dSTobias Grosser else 112913c78e4dSTobias Grosser createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size); 113013c78e4dSTobias Grosser 113113c78e4dSTobias Grosser isl_id_free(Id); 113213c78e4dSTobias Grosser isl_ast_expr_free(Arg); 113313c78e4dSTobias Grosser isl_ast_expr_free(Expr); 113413c78e4dSTobias Grosser isl_ast_node_free(TransferStmt); 113513c78e4dSTobias Grosser } 113613c78e4dSTobias Grosser 11371fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) { 113832837fe3STobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt); 113932837fe3STobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 114032837fe3STobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr); 114132837fe3STobias Grosser isl_id_free(Id); 114232837fe3STobias Grosser isl_ast_expr_free(StmtExpr); 114332837fe3STobias Grosser 114432837fe3STobias Grosser const char *Str = isl_id_get_name(Id); 114532837fe3STobias Grosser if (!strcmp(Str, "kernel")) { 114632837fe3STobias Grosser createKernel(UserStmt); 114732837fe3STobias Grosser isl_ast_expr_free(Expr); 114832837fe3STobias Grosser return; 114932837fe3STobias Grosser } 115032837fe3STobias Grosser 115113c78e4dSTobias Grosser if (isPrefix(Str, "to_device")) { 1152abed4969SSiddharth Bhat if (!ManagedMemory) 115313c78e4dSTobias Grosser createDataTransfer(UserStmt, HOST_TO_DEVICE); 1154abed4969SSiddharth Bhat else 1155abed4969SSiddharth Bhat isl_ast_node_free(UserStmt); 1156abed4969SSiddharth Bhat 115732837fe3STobias Grosser isl_ast_expr_free(Expr); 115813c78e4dSTobias Grosser return; 115913c78e4dSTobias Grosser } 116013c78e4dSTobias Grosser 116113c78e4dSTobias Grosser if (isPrefix(Str, "from_device")) { 1162abed4969SSiddharth Bhat if (!ManagedMemory) { 116313c78e4dSTobias Grosser createDataTransfer(UserStmt, DEVICE_TO_HOST); 1164abed4969SSiddharth Bhat } else { 1165abed4969SSiddharth Bhat createCallSynchronizeDevice(); 1166abed4969SSiddharth Bhat isl_ast_node_free(UserStmt); 1167abed4969SSiddharth Bhat } 116813c78e4dSTobias Grosser isl_ast_expr_free(Expr); 116938fc0aedSTobias Grosser return; 117038fc0aedSTobias Grosser } 117138fc0aedSTobias Grosser 11725260c041STobias Grosser isl_id *Anno = isl_ast_node_get_annotation(UserStmt); 11735260c041STobias Grosser struct ppcg_kernel_stmt *KernelStmt = 11745260c041STobias Grosser (struct ppcg_kernel_stmt *)isl_id_get_user(Anno); 11755260c041STobias Grosser isl_id_free(Anno); 11765260c041STobias Grosser 11775260c041STobias Grosser switch (KernelStmt->type) { 11785260c041STobias Grosser case ppcg_kernel_domain: 1179edb885cbSTobias Grosser createScopStmt(Expr, KernelStmt); 11805260c041STobias Grosser isl_ast_node_free(UserStmt); 11815260c041STobias Grosser return; 11825260c041STobias Grosser case ppcg_kernel_copy: 1183b513b491STobias Grosser createKernelCopy(KernelStmt); 11845260c041STobias Grosser isl_ast_expr_free(Expr); 11855260c041STobias Grosser isl_ast_node_free(UserStmt); 11865260c041STobias Grosser return; 11875260c041STobias Grosser case ppcg_kernel_sync: 11885260c041STobias Grosser createKernelSync(); 11895260c041STobias Grosser isl_ast_expr_free(Expr); 11905260c041STobias Grosser isl_ast_node_free(UserStmt); 11915260c041STobias Grosser return; 11925260c041STobias Grosser } 11935260c041STobias Grosser 11945260c041STobias Grosser isl_ast_expr_free(Expr); 11955260c041STobias Grosser isl_ast_node_free(UserStmt); 11965260c041STobias Grosser return; 11975260c041STobias Grosser } 1198b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) { 1199b513b491STobias Grosser isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index); 1200b513b491STobias Grosser LocalIndex = isl_ast_expr_address_of(LocalIndex); 1201b513b491STobias Grosser Value *LocalAddr = ExprBuilder.create(LocalIndex); 1202b513b491STobias Grosser isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index); 1203b513b491STobias Grosser Index = isl_ast_expr_address_of(Index); 1204b513b491STobias Grosser Value *GlobalAddr = ExprBuilder.create(Index); 1205b513b491STobias Grosser 1206b513b491STobias Grosser if (KernelStmt->u.c.read) { 1207b513b491STobias Grosser LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read"); 1208b513b491STobias Grosser Builder.CreateStore(Load, LocalAddr); 1209b513b491STobias Grosser } else { 1210b513b491STobias Grosser LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write"); 1211b513b491STobias Grosser Builder.CreateStore(Load, GlobalAddr); 1212b513b491STobias Grosser } 1213b513b491STobias Grosser } 12145260c041STobias Grosser 1215edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr, 1216edb885cbSTobias Grosser ppcg_kernel_stmt *KernelStmt) { 1217edb885cbSTobias Grosser auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1218edb885cbSTobias Grosser isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr; 1219edb885cbSTobias Grosser 1220edb885cbSTobias Grosser LoopToScevMapT LTS; 1221edb885cbSTobias Grosser LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end()); 1222edb885cbSTobias Grosser 1223edb885cbSTobias Grosser createSubstitutions(Expr, Stmt, LTS); 1224edb885cbSTobias Grosser 1225edb885cbSTobias Grosser if (Stmt->isBlockStmt()) 1226edb885cbSTobias Grosser BlockGen.copyStmt(*Stmt, LTS, Indexes); 1227edb885cbSTobias Grosser else 1228a82c4b5dSTobias Grosser RegionGen.copyStmt(*Stmt, LTS, Indexes); 1229edb885cbSTobias Grosser } 1230edb885cbSTobias Grosser 12315260c041STobias Grosser void GPUNodeBuilder::createKernelSync() { 12325260c041STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 123317f01968SSiddharth Bhat 123417f01968SSiddharth Bhat Function *Sync; 123517f01968SSiddharth Bhat 123617f01968SSiddharth Bhat switch (Arch) { 123717f01968SSiddharth Bhat case GPUArch::NVPTX64: 123817f01968SSiddharth Bhat Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0); 123917f01968SSiddharth Bhat break; 124017f01968SSiddharth Bhat } 124117f01968SSiddharth Bhat 12425260c041STobias Grosser Builder.CreateCall(Sync, {}); 12435260c041STobias Grosser } 12445260c041STobias Grosser 1245edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node 1246edb885cbSTobias Grosser /// 1247edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring 1248edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore. 1249edb885cbSTobias Grosser /// 1250edb885cbSTobias Grosser /// @param Node The node to collect references for. 1251edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected. 1252edb885cbSTobias Grosser /// 1253edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully. 1254edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) { 1255edb885cbSTobias Grosser if (isl_ast_node_get_type(Node) != isl_ast_node_user) 1256edb885cbSTobias Grosser return isl_bool_true; 1257edb885cbSTobias Grosser 1258edb885cbSTobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node); 1259edb885cbSTobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 1260edb885cbSTobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr); 1261edb885cbSTobias Grosser const char *Str = isl_id_get_name(Id); 1262edb885cbSTobias Grosser isl_id_free(Id); 1263edb885cbSTobias Grosser isl_ast_expr_free(StmtExpr); 1264edb885cbSTobias Grosser isl_ast_expr_free(Expr); 1265edb885cbSTobias Grosser 1266edb885cbSTobias Grosser if (!isPrefix(Str, "Stmt")) 1267edb885cbSTobias Grosser return isl_bool_true; 1268edb885cbSTobias Grosser 1269edb885cbSTobias Grosser Id = isl_ast_node_get_annotation(Node); 1270edb885cbSTobias Grosser auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id); 1271edb885cbSTobias Grosser auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1272edb885cbSTobias Grosser isl_id_free(Id); 1273edb885cbSTobias Grosser 127400bb5a99STobias Grosser addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */); 1275edb885cbSTobias Grosser 1276edb885cbSTobias Grosser return isl_bool_true; 1277edb885cbSTobias Grosser } 1278edb885cbSTobias Grosser 1279f291c8d5SSiddharth Bhat /// Check if F is a function that we can code-generate in a GPU kernel. 1280f291c8d5SSiddharth Bhat static bool isValidFunctionInKernel(llvm::Function *F) { 1281f291c8d5SSiddharth Bhat assert(F && "F is an invalid pointer"); 1282f291c8d5SSiddharth Bhat // We string compare against the name of the function to allow 1283f291c8d5SSiddharth Bhat // all variants of the intrinsic "llvm.sqrt.*" 1284f291c8d5SSiddharth Bhat return F->isIntrinsic() && F->getName().startswith("llvm.sqrt"); 1285f291c8d5SSiddharth Bhat } 1286f291c8d5SSiddharth Bhat 1287f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value. 1288f291c8d5SSiddharth Bhat /// 1289f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along 1290f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and 1291f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not 1292f291c8d5SSiddharth Bhat /// `Function`s. 1293f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); } 1294f291c8d5SSiddharth Bhat 1295f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`. 1296f291c8d5SSiddharth Bhat static SetVector<Function *> 1297f291c8d5SSiddharth Bhat getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues) { 1298f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions; 1299f291c8d5SSiddharth Bhat for (Value *It : RawSubtreeValues) { 1300f291c8d5SSiddharth Bhat Function *F = dyn_cast<Function>(It); 1301f291c8d5SSiddharth Bhat if (F) { 1302f291c8d5SSiddharth Bhat assert(isValidFunctionInKernel(F) && "Code should have bailed out by " 1303f291c8d5SSiddharth Bhat "this point if an invalid function " 1304f291c8d5SSiddharth Bhat "were present in a kernel."); 1305f291c8d5SSiddharth Bhat SubtreeFunctions.insert(F); 1306f291c8d5SSiddharth Bhat } 1307f291c8d5SSiddharth Bhat } 1308f291c8d5SSiddharth Bhat return SubtreeFunctions; 1309f291c8d5SSiddharth Bhat } 1310f291c8d5SSiddharth Bhat 1311f291c8d5SSiddharth Bhat std::pair<SetVector<Value *>, SetVector<Function *>> 1312f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) { 1313edb885cbSTobias Grosser SetVector<Value *> SubtreeValues; 1314edb885cbSTobias Grosser SetVector<const SCEV *> SCEVs; 1315edb885cbSTobias Grosser SetVector<const Loop *> Loops; 1316edb885cbSTobias Grosser SubtreeReferences References = { 1317edb885cbSTobias Grosser LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()}; 1318edb885cbSTobias Grosser 1319edb885cbSTobias Grosser for (const auto &I : IDToValue) 1320edb885cbSTobias Grosser SubtreeValues.insert(I.second); 1321edb885cbSTobias Grosser 1322edb885cbSTobias Grosser isl_ast_node_foreach_descendant_top_down( 1323edb885cbSTobias Grosser Kernel->tree, collectReferencesInGPUStmt, &References); 1324edb885cbSTobias Grosser 1325edb885cbSTobias Grosser for (const SCEV *Expr : SCEVs) 1326edb885cbSTobias Grosser findValues(Expr, SE, SubtreeValues); 1327edb885cbSTobias Grosser 1328edb885cbSTobias Grosser for (auto &SAI : S.arrays()) 1329d7754a12SRoman Gareev SubtreeValues.remove(SAI->getBasePtr()); 1330edb885cbSTobias Grosser 1331edb885cbSTobias Grosser isl_space *Space = S.getParamSpace(); 1332edb885cbSTobias Grosser for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) { 1333edb885cbSTobias Grosser isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i); 1334edb885cbSTobias Grosser assert(IDToValue.count(Id)); 1335edb885cbSTobias Grosser Value *Val = IDToValue[Id]; 1336edb885cbSTobias Grosser SubtreeValues.remove(Val); 1337edb885cbSTobias Grosser isl_id_free(Id); 1338edb885cbSTobias Grosser } 1339edb885cbSTobias Grosser isl_space_free(Space); 1340edb885cbSTobias Grosser 1341edb885cbSTobias Grosser for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) { 1342edb885cbSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1343edb885cbSTobias Grosser assert(IDToValue.count(Id)); 1344edb885cbSTobias Grosser Value *Val = IDToValue[Id]; 1345edb885cbSTobias Grosser SubtreeValues.remove(Val); 1346edb885cbSTobias Grosser isl_id_free(Id); 1347edb885cbSTobias Grosser } 1348edb885cbSTobias Grosser 1349f291c8d5SSiddharth Bhat // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions 1350f291c8d5SSiddharth Bhat // SubtreeValues. This is important, because we should not lose any 1351f291c8d5SSiddharth Bhat // SubtreeValues in the process of constructing the 1352f291c8d5SSiddharth Bhat // "ValidSubtree{Values, Functions} sets. Nor should the set 1353f291c8d5SSiddharth Bhat // ValidSubtree{Values, Functions} have any common element. 1354f291c8d5SSiddharth Bhat auto ValidSubtreeValuesIt = 1355f291c8d5SSiddharth Bhat make_filter_range(SubtreeValues, isValidSubtreeValue); 1356f291c8d5SSiddharth Bhat SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(), 1357f291c8d5SSiddharth Bhat ValidSubtreeValuesIt.end()); 1358f291c8d5SSiddharth Bhat SetVector<Function *> ValidSubtreeFunctions( 1359f291c8d5SSiddharth Bhat getFunctionsFromRawSubtreeValues(SubtreeValues)); 1360f291c8d5SSiddharth Bhat 1361a1b2086aSSiddharth Bhat // @see IslNodeBuilder::getReferencesInSubtree 1362a1b2086aSSiddharth Bhat SetVector<Value *> ReplacedValues; 1363a1b2086aSSiddharth Bhat for (Value *V : ValidSubtreeValues) { 1364a1b2086aSSiddharth Bhat auto It = ValueMap.find(V); 1365a1b2086aSSiddharth Bhat if (It == ValueMap.end()) 1366a1b2086aSSiddharth Bhat ReplacedValues.insert(V); 1367a1b2086aSSiddharth Bhat else 1368a1b2086aSSiddharth Bhat ReplacedValues.insert(It->second); 1369a1b2086aSSiddharth Bhat } 1370a1b2086aSSiddharth Bhat return std::make_pair(ReplacedValues, ValidSubtreeFunctions); 1371edb885cbSTobias Grosser } 1372edb885cbSTobias Grosser 137374dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) { 137474dc3cb4STobias Grosser DomTreeNode *N = DT.getNode(&F->getEntryBlock()); 137574dc3cb4STobias Grosser std::vector<BasicBlock *> Nodes; 137674dc3cb4STobias Grosser for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I) 137774dc3cb4STobias Grosser Nodes.push_back(I->getBlock()); 137874dc3cb4STobias Grosser 137974dc3cb4STobias Grosser for (BasicBlock *BB : Nodes) 138074dc3cb4STobias Grosser DT.eraseNode(BB); 138174dc3cb4STobias Grosser } 138274dc3cb4STobias Grosser 138374dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) { 138474dc3cb4STobias Grosser for (BasicBlock &BB : *F) { 138574dc3cb4STobias Grosser Loop *L = LI.getLoopFor(&BB); 138674dc3cb4STobias Grosser if (L) 138774dc3cb4STobias Grosser SE.forgetLoop(L); 138874dc3cb4STobias Grosser } 138974dc3cb4STobias Grosser } 139074dc3cb4STobias Grosser 139174dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) { 139274dc3cb4STobias Grosser for (BasicBlock &BB : *F) { 139374dc3cb4STobias Grosser Loop *L = LI.getLoopFor(&BB); 139474dc3cb4STobias Grosser if (L) 139574dc3cb4STobias Grosser SE.forgetLoop(L); 139674dc3cb4STobias Grosser LI.removeBlock(&BB); 139774dc3cb4STobias Grosser } 139874dc3cb4STobias Grosser } 139974dc3cb4STobias Grosser 140079a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) { 140179a947c2STobias Grosser std::vector<Value *> Sizes; 140279a947c2STobias Grosser isl_ast_build *Context = isl_ast_build_from_context(S.getContext()); 140379a947c2STobias Grosser 140479a947c2STobias Grosser for (long i = 0; i < Kernel->n_grid; i++) { 140579a947c2STobias Grosser isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i); 140679a947c2STobias Grosser isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size); 140779a947c2STobias Grosser Value *Res = ExprBuilder.create(GridSize); 140879a947c2STobias Grosser Res = Builder.CreateTrunc(Res, Builder.getInt32Ty()); 140979a947c2STobias Grosser Sizes.push_back(Res); 141079a947c2STobias Grosser } 141179a947c2STobias Grosser isl_ast_build_free(Context); 141279a947c2STobias Grosser 141379a947c2STobias Grosser for (long i = Kernel->n_grid; i < 3; i++) 141479a947c2STobias Grosser Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 141579a947c2STobias Grosser 141679a947c2STobias Grosser return std::make_tuple(Sizes[0], Sizes[1]); 141779a947c2STobias Grosser } 141879a947c2STobias Grosser 141979a947c2STobias Grosser std::tuple<Value *, Value *, Value *> 142079a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) { 142179a947c2STobias Grosser std::vector<Value *> Sizes; 142279a947c2STobias Grosser 142379a947c2STobias Grosser for (long i = 0; i < Kernel->n_block; i++) { 142479a947c2STobias Grosser Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]); 142579a947c2STobias Grosser Sizes.push_back(Res); 142679a947c2STobias Grosser } 142779a947c2STobias Grosser 142879a947c2STobias Grosser for (long i = Kernel->n_block; i < 3; i++) 142979a947c2STobias Grosser Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 143079a947c2STobias Grosser 143179a947c2STobias Grosser return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]); 143279a947c2STobias Grosser } 143379a947c2STobias Grosser 1434a90be207SSiddharth Bhat void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters, 1435a90be207SSiddharth Bhat Instruction *Param, int Index) { 1436a90be207SSiddharth Bhat Value *Slot = Builder.CreateGEP( 1437a90be207SSiddharth Bhat Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1438a90be207SSiddharth Bhat Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 1439a90be207SSiddharth Bhat Builder.CreateStore(ParamTyped, Slot); 1440a90be207SSiddharth Bhat } 1441a90be207SSiddharth Bhat 144257693272STobias Grosser Value * 144357693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F, 144457693272STobias Grosser SetVector<Value *> SubtreeValues) { 1445a90be207SSiddharth Bhat const int NumArgs = F->arg_size(); 1446a90be207SSiddharth Bhat std::vector<int> ArgSizes(NumArgs); 1447a90be207SSiddharth Bhat 1448a90be207SSiddharth Bhat Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs); 144979a947c2STobias Grosser 145079a947c2STobias Grosser BasicBlock *EntryBlock = 145179a947c2STobias Grosser &Builder.GetInsertBlock()->getParent()->getEntryBlock(); 145267726b32STobias Grosser auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace(); 145379a947c2STobias Grosser std::string Launch = "polly_launch_" + std::to_string(Kernel->id); 145467726b32STobias Grosser Instruction *Parameters = new AllocaInst( 145567726b32STobias Grosser ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator()); 145679a947c2STobias Grosser 145779a947c2STobias Grosser int Index = 0; 145879a947c2STobias Grosser for (long i = 0; i < Prog->n_array; i++) { 145979a947c2STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 146079a947c2STobias Grosser continue; 146179a947c2STobias Grosser 146279a947c2STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 146379a947c2STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id); 146479a947c2STobias Grosser 1465a90be207SSiddharth Bhat ArgSizes[Index] = SAI->getElemSizeInBytes(); 1466a90be207SSiddharth Bhat 1467abed4969SSiddharth Bhat Value *DevArray = nullptr; 1468abed4969SSiddharth Bhat if (ManagedMemory) { 1469abed4969SSiddharth Bhat DevArray = getOrCreateManagedDeviceArray( 1470abed4969SSiddharth Bhat &Prog->array[i], const_cast<ScopArrayInfo *>(SAI)); 1471abed4969SSiddharth Bhat } else { 1472abed4969SSiddharth Bhat DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)]; 147379a947c2STobias Grosser DevArray = createCallGetDevicePtr(DevArray); 1474abed4969SSiddharth Bhat } 1475abed4969SSiddharth Bhat assert(DevArray != nullptr && "Array to be offloaded to device not " 1476abed4969SSiddharth Bhat "initialized"); 1477aaabbbf8STobias Grosser Value *Offset = getArrayOffset(&Prog->array[i]); 1478aaabbbf8STobias Grosser 1479aaabbbf8STobias Grosser if (Offset) { 1480aaabbbf8STobias Grosser DevArray = Builder.CreatePointerCast( 1481aaabbbf8STobias Grosser DevArray, SAI->getElementType()->getPointerTo()); 1482aaabbbf8STobias Grosser DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset)); 1483aaabbbf8STobias Grosser DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy()); 1484aaabbbf8STobias Grosser } 1485fe74a7a1STobias Grosser Value *Slot = Builder.CreateGEP( 1486fe74a7a1STobias Grosser Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1487aaabbbf8STobias Grosser 1488fe74a7a1STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1489abed4969SSiddharth Bhat Value *ValPtr = nullptr; 1490abed4969SSiddharth Bhat if (ManagedMemory) 1491abed4969SSiddharth Bhat ValPtr = DevArray; 1492abed4969SSiddharth Bhat else 1493abed4969SSiddharth Bhat ValPtr = BlockGen.getOrCreateAlloca(SAI); 1494abed4969SSiddharth Bhat 1495abed4969SSiddharth Bhat assert(ValPtr != nullptr && "ValPtr that should point to a valid object" 1496abed4969SSiddharth Bhat " to be stored into Parameters"); 1497fe74a7a1STobias Grosser Value *ValPtrCast = 1498fe74a7a1STobias Grosser Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy()); 1499fe74a7a1STobias Grosser Builder.CreateStore(ValPtrCast, Slot); 1500fe74a7a1STobias Grosser } else { 150167726b32STobias Grosser Instruction *Param = 150267726b32STobias Grosser new AllocaInst(Builder.getInt8PtrTy(), AddressSpace, 150367726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 150479a947c2STobias Grosser EntryBlock->getTerminator()); 150579a947c2STobias Grosser Builder.CreateStore(DevArray, Param); 150679a947c2STobias Grosser Value *ParamTyped = 150779a947c2STobias Grosser Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 150879a947c2STobias Grosser Builder.CreateStore(ParamTyped, Slot); 1509fe74a7a1STobias Grosser } 151079a947c2STobias Grosser Index++; 151179a947c2STobias Grosser } 151279a947c2STobias Grosser 1513a490147cSTobias Grosser int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1514a490147cSTobias Grosser 1515a490147cSTobias Grosser for (long i = 0; i < NumHostIters; i++) { 1516a490147cSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1517a490147cSTobias Grosser Value *Val = IDToValue[Id]; 1518a490147cSTobias Grosser isl_id_free(Id); 1519a90be207SSiddharth Bhat 1520a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1521a90be207SSiddharth Bhat 152267726b32STobias Grosser Instruction *Param = 152367726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 152467726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 1525a490147cSTobias Grosser EntryBlock->getTerminator()); 1526a490147cSTobias Grosser Builder.CreateStore(Val, Param); 1527a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 1528a490147cSTobias Grosser Index++; 1529a490147cSTobias Grosser } 1530a490147cSTobias Grosser 1531d8b94bcaSTobias Grosser int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1532d8b94bcaSTobias Grosser 1533d8b94bcaSTobias Grosser for (long i = 0; i < NumVars; i++) { 1534d8b94bcaSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1535d8b94bcaSTobias Grosser Value *Val = IDToValue[Id]; 1536a1b2086aSSiddharth Bhat if (ValueMap.count(Val)) 1537a1b2086aSSiddharth Bhat Val = ValueMap[Val]; 1538d8b94bcaSTobias Grosser isl_id_free(Id); 1539a90be207SSiddharth Bhat 1540a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1541a90be207SSiddharth Bhat 154267726b32STobias Grosser Instruction *Param = 154367726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 154467726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 1545d8b94bcaSTobias Grosser EntryBlock->getTerminator()); 1546d8b94bcaSTobias Grosser Builder.CreateStore(Val, Param); 1547a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 1548d8b94bcaSTobias Grosser Index++; 1549d8b94bcaSTobias Grosser } 1550d8b94bcaSTobias Grosser 155157693272STobias Grosser for (auto Val : SubtreeValues) { 1552a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1553a90be207SSiddharth Bhat 155467726b32STobias Grosser Instruction *Param = 155567726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 155667726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 155757693272STobias Grosser EntryBlock->getTerminator()); 155857693272STobias Grosser Builder.CreateStore(Val, Param); 1559a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 1560a90be207SSiddharth Bhat Index++; 1561a90be207SSiddharth Bhat } 1562a90be207SSiddharth Bhat 1563a90be207SSiddharth Bhat for (int i = 0; i < NumArgs; i++) { 1564a90be207SSiddharth Bhat Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]); 1565a90be207SSiddharth Bhat Instruction *Param = 1566a90be207SSiddharth Bhat new AllocaInst(Builder.getInt32Ty(), AddressSpace, 1567a90be207SSiddharth Bhat Launch + "_param_size_" + std::to_string(i), 1568a90be207SSiddharth Bhat EntryBlock->getTerminator()); 1569a90be207SSiddharth Bhat Builder.CreateStore(Val, Param); 1570a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 157157693272STobias Grosser Index++; 157257693272STobias Grosser } 157357693272STobias Grosser 157479a947c2STobias Grosser auto Location = EntryBlock->getTerminator(); 157579a947c2STobias Grosser return new BitCastInst(Parameters, Builder.getInt8PtrTy(), 157679a947c2STobias Grosser Launch + "_params_i8ptr", Location); 157779a947c2STobias Grosser } 157879a947c2STobias Grosser 1579f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions( 1580f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions) { 1581f291c8d5SSiddharth Bhat for (auto Fn : SubtreeFunctions) { 1582f291c8d5SSiddharth Bhat const std::string ClonedFnName = Fn->getName(); 1583f291c8d5SSiddharth Bhat Function *Clone = GPUModule->getFunction(ClonedFnName); 1584f291c8d5SSiddharth Bhat if (!Clone) 1585f291c8d5SSiddharth Bhat Clone = 1586f291c8d5SSiddharth Bhat Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage, 1587f291c8d5SSiddharth Bhat ClonedFnName, GPUModule.get()); 1588f291c8d5SSiddharth Bhat assert(Clone && "Expected cloned function to be initialized."); 1589f291c8d5SSiddharth Bhat assert(ValueMap.find(Fn) == ValueMap.end() && 1590f291c8d5SSiddharth Bhat "Fn already present in ValueMap"); 1591f291c8d5SSiddharth Bhat ValueMap[Fn] = Clone; 1592f291c8d5SSiddharth Bhat } 1593f291c8d5SSiddharth Bhat } 159432837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) { 159532837fe3STobias Grosser isl_id *Id = isl_ast_node_get_annotation(KernelStmt); 159632837fe3STobias Grosser ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id); 159732837fe3STobias Grosser isl_id_free(Id); 159832837fe3STobias Grosser isl_ast_node_free(KernelStmt); 159932837fe3STobias Grosser 1600bc653f20STobias Grosser if (Kernel->n_grid > 1) 1601bc653f20STobias Grosser DeepestParallel = 1602bc653f20STobias Grosser std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set)); 1603bc653f20STobias Grosser else 1604bc653f20STobias Grosser DeepestSequential = 1605bc653f20STobias Grosser std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set)); 1606bc653f20STobias Grosser 1607c1c6a2a6STobias Grosser Value *BlockDimX, *BlockDimY, *BlockDimZ; 1608c1c6a2a6STobias Grosser std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel); 1609c1c6a2a6STobias Grosser 1610f291c8d5SSiddharth Bhat SetVector<Value *> SubtreeValues; 1611f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions; 1612f291c8d5SSiddharth Bhat std::tie(SubtreeValues, SubtreeFunctions) = getReferencesInKernel(Kernel); 1613edb885cbSTobias Grosser 161432837fe3STobias Grosser assert(Kernel->tree && "Device AST of kernel node is empty"); 161532837fe3STobias Grosser 161632837fe3STobias Grosser Instruction &HostInsertPoint = *Builder.GetInsertPoint(); 1617472f9654STobias Grosser IslExprBuilder::IDToValueTy HostIDs = IDToValue; 1618edb885cbSTobias Grosser ValueMapT HostValueMap = ValueMap; 1619587f1f57STobias Grosser BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap; 1620b06ff457STobias Grosser ScalarMap.clear(); 162132837fe3STobias Grosser 1622edb885cbSTobias Grosser SetVector<const Loop *> Loops; 1623edb885cbSTobias Grosser 1624edb885cbSTobias Grosser // Create for all loops we depend on values that contain the current loop 1625edb885cbSTobias Grosser // iteration. These values are necessary to generate code for SCEVs that 1626edb885cbSTobias Grosser // depend on such loops. As a result we need to pass them to the subfunction. 1627edb885cbSTobias Grosser for (const Loop *L : Loops) { 1628edb885cbSTobias Grosser const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)), 1629edb885cbSTobias Grosser SE.getUnknown(Builder.getInt64(1)), 1630edb885cbSTobias Grosser L, SCEV::FlagAnyWrap); 1631edb885cbSTobias Grosser Value *V = generateSCEV(OuterLIV); 1632edb885cbSTobias Grosser OutsideLoopIterations[L] = SE.getUnknown(V); 1633edb885cbSTobias Grosser SubtreeValues.insert(V); 1634edb885cbSTobias Grosser } 1635edb885cbSTobias Grosser 1636f291c8d5SSiddharth Bhat createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions); 1637f291c8d5SSiddharth Bhat setupKernelSubtreeFunctions(SubtreeFunctions); 163832837fe3STobias Grosser 163959ab0705STobias Grosser create(isl_ast_node_copy(Kernel->tree)); 164059ab0705STobias Grosser 164151dfc275STobias Grosser finalizeKernelArguments(Kernel); 164274dc3cb4STobias Grosser Function *F = Builder.GetInsertBlock()->getParent(); 1643c1c6a2a6STobias Grosser addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ); 164474dc3cb4STobias Grosser clearDominators(F); 164574dc3cb4STobias Grosser clearScalarEvolution(F); 164674dc3cb4STobias Grosser clearLoops(F); 164774dc3cb4STobias Grosser 1648472f9654STobias Grosser IDToValue = HostIDs; 164932837fe3STobias Grosser 1650b06ff457STobias Grosser ValueMap = std::move(HostValueMap); 1651b06ff457STobias Grosser ScalarMap = std::move(HostScalarMap); 1652edb885cbSTobias Grosser EscapeMap.clear(); 1653edb885cbSTobias Grosser IDToSAI.clear(); 165474dc3cb4STobias Grosser Annotator.resetAlternativeAliasBases(); 165574dc3cb4STobias Grosser for (auto &BasePtr : LocalArrays) 16564d5a9172STobias Grosser S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array); 165774dc3cb4STobias Grosser LocalArrays.clear(); 1658edb885cbSTobias Grosser 165951dfc275STobias Grosser std::string ASMString = finalizeKernelFunction(); 166051dfc275STobias Grosser Builder.SetInsertPoint(&HostInsertPoint); 166157693272STobias Grosser Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues); 166279a947c2STobias Grosser 166379f13b9aSSingapuram Sanjay Srivallabh std::string Name = getKernelFuncName(Kernel->id); 166457793596STobias Grosser Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name); 166557793596STobias Grosser Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name"); 166657793596STobias Grosser Value *GPUKernel = createCallGetKernel(KernelString, NameString); 166779a947c2STobias Grosser 166879a947c2STobias Grosser Value *GridDimX, *GridDimY; 166979a947c2STobias Grosser std::tie(GridDimX, GridDimY) = getGridSizes(Kernel); 167079a947c2STobias Grosser 167179a947c2STobias Grosser createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 167279a947c2STobias Grosser BlockDimZ, Parameters); 167357793596STobias Grosser createCallFreeKernel(GPUKernel); 1674b513b491STobias Grosser 1675b513b491STobias Grosser for (auto Id : KernelIds) 1676b513b491STobias Grosser isl_id_free(Id); 1677b513b491STobias Grosser 1678b513b491STobias Grosser KernelIds.clear(); 167932837fe3STobias Grosser } 168032837fe3STobias Grosser 168132837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend. 168232837fe3STobias Grosser /// 168332837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture? 168432837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) { 1685d277fedaSSiddharth Bhat std::string Ret = ""; 168632837fe3STobias Grosser 1687d277fedaSSiddharth Bhat if (!is64Bit) { 1688d277fedaSSiddharth Bhat Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1689d277fedaSSiddharth Bhat "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1690d277fedaSSiddharth Bhat "64-v128:128:128-n16:32:64"; 1691d277fedaSSiddharth Bhat } else { 1692d277fedaSSiddharth Bhat Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1693d277fedaSSiddharth Bhat "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1694d277fedaSSiddharth Bhat "64-v128:128:128-n16:32:64"; 1695d277fedaSSiddharth Bhat } 169632837fe3STobias Grosser 169732837fe3STobias Grosser return Ret; 169832837fe3STobias Grosser } 169932837fe3STobias Grosser 1700edb885cbSTobias Grosser Function * 1701edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel, 1702edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues) { 170332837fe3STobias Grosser std::vector<Type *> Args; 170479f13b9aSSingapuram Sanjay Srivallabh std::string Identifier = getKernelFuncName(Kernel->id); 170532837fe3STobias Grosser 170632837fe3STobias Grosser for (long i = 0; i < Prog->n_array; i++) { 170732837fe3STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 170832837fe3STobias Grosser continue; 170932837fe3STobias Grosser 1710fe74a7a1STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1711fe74a7a1STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1712fe74a7a1STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id); 1713fe74a7a1STobias Grosser Args.push_back(SAI->getElementType()); 1714fe74a7a1STobias Grosser } else { 1715d277fedaSSiddharth Bhat static const int UseGlobalMemory = 1; 1716d277fedaSSiddharth Bhat Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory)); 171732837fe3STobias Grosser } 1718fe74a7a1STobias Grosser } 171932837fe3STobias Grosser 1720f6044bd0STobias Grosser int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1721f6044bd0STobias Grosser 1722f6044bd0STobias Grosser for (long i = 0; i < NumHostIters; i++) 1723f6044bd0STobias Grosser Args.push_back(Builder.getInt64Ty()); 1724f6044bd0STobias Grosser 1725c84a1995STobias Grosser int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1726c84a1995STobias Grosser 1727cf66ef26STobias Grosser for (long i = 0; i < NumVars; i++) { 1728cf66ef26STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1729cf66ef26STobias Grosser Value *Val = IDToValue[Id]; 1730cf66ef26STobias Grosser isl_id_free(Id); 1731cf66ef26STobias Grosser Args.push_back(Val->getType()); 1732cf66ef26STobias Grosser } 1733c84a1995STobias Grosser 1734edb885cbSTobias Grosser for (auto *V : SubtreeValues) 1735edb885cbSTobias Grosser Args.push_back(V->getType()); 1736edb885cbSTobias Grosser 173732837fe3STobias Grosser auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false); 173832837fe3STobias Grosser auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier, 173932837fe3STobias Grosser GPUModule.get()); 174017f01968SSiddharth Bhat 174117f01968SSiddharth Bhat switch (Arch) { 174217f01968SSiddharth Bhat case GPUArch::NVPTX64: 174332837fe3STobias Grosser FN->setCallingConv(CallingConv::PTX_Kernel); 174417f01968SSiddharth Bhat break; 174517f01968SSiddharth Bhat } 174632837fe3STobias Grosser 174732837fe3STobias Grosser auto Arg = FN->arg_begin(); 174832837fe3STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 174932837fe3STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 175032837fe3STobias Grosser continue; 175132837fe3STobias Grosser 1752edb885cbSTobias Grosser Arg->setName(Kernel->array[i].array->name); 1753edb885cbSTobias Grosser 1754edb885cbSTobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1755edb885cbSTobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 1756edb885cbSTobias Grosser Type *EleTy = SAI->getElementType(); 1757edb885cbSTobias Grosser Value *Val = &*Arg; 1758edb885cbSTobias Grosser SmallVector<const SCEV *, 4> Sizes; 1759edb885cbSTobias Grosser isl_ast_build *Build = 1760edb885cbSTobias Grosser isl_ast_build_from_context(isl_set_copy(Prog->context)); 1761f5aff704SRoman Gareev Sizes.push_back(nullptr); 1762edb885cbSTobias Grosser for (long j = 1; j < Kernel->array[i].array->n_index; j++) { 1763edb885cbSTobias Grosser isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff( 1764edb885cbSTobias Grosser Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j])); 1765edb885cbSTobias Grosser auto V = ExprBuilder.create(DimSize); 1766edb885cbSTobias Grosser Sizes.push_back(SE.getSCEV(V)); 1767edb885cbSTobias Grosser } 1768edb885cbSTobias Grosser const ScopArrayInfo *SAIRep = 17694d5a9172STobias Grosser S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array); 177074dc3cb4STobias Grosser LocalArrays.push_back(Val); 1771edb885cbSTobias Grosser 1772edb885cbSTobias Grosser isl_ast_build_free(Build); 1773b513b491STobias Grosser KernelIds.push_back(Id); 1774edb885cbSTobias Grosser IDToSAI[Id] = SAIRep; 177532837fe3STobias Grosser Arg++; 177632837fe3STobias Grosser } 177732837fe3STobias Grosser 1778f6044bd0STobias Grosser for (long i = 0; i < NumHostIters; i++) { 1779f6044bd0STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1780f6044bd0STobias Grosser Arg->setName(isl_id_get_name(Id)); 1781f6044bd0STobias Grosser IDToValue[Id] = &*Arg; 1782f6044bd0STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1783f6044bd0STobias Grosser Arg++; 1784f6044bd0STobias Grosser } 1785f6044bd0STobias Grosser 1786c84a1995STobias Grosser for (long i = 0; i < NumVars; i++) { 1787c84a1995STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1788c84a1995STobias Grosser Arg->setName(isl_id_get_name(Id)); 178912453403STobias Grosser Value *Val = IDToValue[Id]; 179012453403STobias Grosser ValueMap[Val] = &*Arg; 1791c84a1995STobias Grosser IDToValue[Id] = &*Arg; 1792c84a1995STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1793c84a1995STobias Grosser Arg++; 1794c84a1995STobias Grosser } 1795c84a1995STobias Grosser 1796edb885cbSTobias Grosser for (auto *V : SubtreeValues) { 1797edb885cbSTobias Grosser Arg->setName(V->getName()); 1798edb885cbSTobias Grosser ValueMap[V] = &*Arg; 1799edb885cbSTobias Grosser Arg++; 1800edb885cbSTobias Grosser } 1801edb885cbSTobias Grosser 180232837fe3STobias Grosser return FN; 180332837fe3STobias Grosser } 180432837fe3STobias Grosser 1805472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) { 180617f01968SSiddharth Bhat Intrinsic::ID IntrinsicsBID[2]; 180717f01968SSiddharth Bhat Intrinsic::ID IntrinsicsTID[3]; 1808472f9654STobias Grosser 180917f01968SSiddharth Bhat switch (Arch) { 181017f01968SSiddharth Bhat case GPUArch::NVPTX64: 181117f01968SSiddharth Bhat IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x; 181217f01968SSiddharth Bhat IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y; 181317f01968SSiddharth Bhat 181417f01968SSiddharth Bhat IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x; 181517f01968SSiddharth Bhat IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y; 181617f01968SSiddharth Bhat IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z; 181717f01968SSiddharth Bhat break; 181817f01968SSiddharth Bhat } 1819472f9654STobias Grosser 1820472f9654STobias Grosser auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable { 1821472f9654STobias Grosser std::string Name = isl_id_get_name(Id); 1822472f9654STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1823472f9654STobias Grosser Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr); 1824472f9654STobias Grosser Value *Val = Builder.CreateCall(IntrinsicFn, {}); 1825472f9654STobias Grosser Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 1826472f9654STobias Grosser IDToValue[Id] = Val; 1827472f9654STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1828472f9654STobias Grosser }; 1829472f9654STobias Grosser 1830472f9654STobias Grosser for (int i = 0; i < Kernel->n_grid; ++i) { 1831472f9654STobias Grosser isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i); 1832472f9654STobias Grosser addId(Id, IntrinsicsBID[i]); 1833472f9654STobias Grosser } 1834472f9654STobias Grosser 1835472f9654STobias Grosser for (int i = 0; i < Kernel->n_block; ++i) { 1836472f9654STobias Grosser isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i); 1837472f9654STobias Grosser addId(Id, IntrinsicsTID[i]); 1838472f9654STobias Grosser } 1839472f9654STobias Grosser } 1840472f9654STobias Grosser 184100bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) { 184200bb5a99STobias Grosser auto Arg = FN->arg_begin(); 184300bb5a99STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 184400bb5a99STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 184500bb5a99STobias Grosser continue; 184600bb5a99STobias Grosser 184700bb5a99STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 184800bb5a99STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 184900bb5a99STobias Grosser isl_id_free(Id); 185000bb5a99STobias Grosser 185100bb5a99STobias Grosser if (SAI->getNumberOfDimensions() > 0) { 185200bb5a99STobias Grosser Arg++; 185300bb5a99STobias Grosser continue; 185400bb5a99STobias Grosser } 185500bb5a99STobias Grosser 1856fe74a7a1STobias Grosser Value *Val = &*Arg; 1857fe74a7a1STobias Grosser 1858fe74a7a1STobias Grosser if (!gpu_array_is_read_only_scalar(&Prog->array[i])) { 185900bb5a99STobias Grosser Type *TypePtr = SAI->getElementType()->getPointerTo(); 1860fe74a7a1STobias Grosser Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr); 1861fe74a7a1STobias Grosser Val = Builder.CreateLoad(TypedArgPtr); 1862fe74a7a1STobias Grosser } 1863fe74a7a1STobias Grosser 1864fe74a7a1STobias Grosser Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 186500bb5a99STobias Grosser Builder.CreateStore(Val, Alloca); 186600bb5a99STobias Grosser 186700bb5a99STobias Grosser Arg++; 186800bb5a99STobias Grosser } 186900bb5a99STobias Grosser } 187000bb5a99STobias Grosser 187151dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) { 187251dfc275STobias Grosser auto *FN = Builder.GetInsertBlock()->getParent(); 187351dfc275STobias Grosser auto Arg = FN->arg_begin(); 187451dfc275STobias Grosser 187551dfc275STobias Grosser bool StoredScalar = false; 187651dfc275STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 187751dfc275STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 187851dfc275STobias Grosser continue; 187951dfc275STobias Grosser 188051dfc275STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 188151dfc275STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 188251dfc275STobias Grosser isl_id_free(Id); 188351dfc275STobias Grosser 188451dfc275STobias Grosser if (SAI->getNumberOfDimensions() > 0) { 188551dfc275STobias Grosser Arg++; 188651dfc275STobias Grosser continue; 188751dfc275STobias Grosser } 188851dfc275STobias Grosser 188951dfc275STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 189051dfc275STobias Grosser Arg++; 189151dfc275STobias Grosser continue; 189251dfc275STobias Grosser } 189351dfc275STobias Grosser 189451dfc275STobias Grosser Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 189551dfc275STobias Grosser Value *ArgPtr = &*Arg; 189651dfc275STobias Grosser Type *TypePtr = SAI->getElementType()->getPointerTo(); 189751dfc275STobias Grosser Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr); 189851dfc275STobias Grosser Value *Val = Builder.CreateLoad(Alloca); 189951dfc275STobias Grosser Builder.CreateStore(Val, TypedArgPtr); 190051dfc275STobias Grosser StoredScalar = true; 190151dfc275STobias Grosser 190251dfc275STobias Grosser Arg++; 190351dfc275STobias Grosser } 190451dfc275STobias Grosser 190551dfc275STobias Grosser if (StoredScalar) 190651dfc275STobias Grosser /// In case more than one thread contains scalar stores, the generated 190751dfc275STobias Grosser /// code might be incorrect, if we only store at the end of the kernel. 190851dfc275STobias Grosser /// To support this case we need to store these scalars back at each 190951dfc275STobias Grosser /// memory store or at least before each kernel barrier. 191051dfc275STobias Grosser if (Kernel->n_block != 0 || Kernel->n_grid != 0) 191151dfc275STobias Grosser BuildSuccessful = 0; 191251dfc275STobias Grosser } 191351dfc275STobias Grosser 1914b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) { 1915b513b491STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1916b513b491STobias Grosser 1917b513b491STobias Grosser for (int i = 0; i < Kernel->n_var; ++i) { 1918b513b491STobias Grosser struct ppcg_kernel_var &Var = Kernel->var[i]; 1919b513b491STobias Grosser isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set); 1920b513b491STobias Grosser Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType(); 1921b513b491STobias Grosser 1922f919d8b3STobias Grosser Type *ArrayTy = EleTy; 1923b513b491STobias Grosser SmallVector<const SCEV *, 4> Sizes; 1924b513b491STobias Grosser 1925f5aff704SRoman Gareev Sizes.push_back(nullptr); 1926928d7573STobias Grosser for (unsigned int j = 1; j < Var.array->n_index; ++j) { 1927b513b491STobias Grosser isl_val *Val = isl_vec_get_element_val(Var.size, j); 1928f919d8b3STobias Grosser long Bound = isl_val_get_num_si(Val); 1929b513b491STobias Grosser isl_val_free(Val); 1930b513b491STobias Grosser Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound)); 1931928d7573STobias Grosser } 1932928d7573STobias Grosser 1933928d7573STobias Grosser for (int j = Var.array->n_index - 1; j >= 0; --j) { 1934928d7573STobias Grosser isl_val *Val = isl_vec_get_element_val(Var.size, j); 1935928d7573STobias Grosser long Bound = isl_val_get_num_si(Val); 1936928d7573STobias Grosser isl_val_free(Val); 1937b513b491STobias Grosser ArrayTy = ArrayType::get(ArrayTy, Bound); 1938b513b491STobias Grosser } 1939b513b491STobias Grosser 1940130ca30fSTobias Grosser const ScopArrayInfo *SAI; 1941130ca30fSTobias Grosser Value *Allocation; 1942130ca30fSTobias Grosser if (Var.type == ppcg_access_shared) { 1943130ca30fSTobias Grosser auto GlobalVar = new GlobalVariable( 1944130ca30fSTobias Grosser *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name, 1945130ca30fSTobias Grosser nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3); 1946130ca30fSTobias Grosser GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8); 1947f919d8b3STobias Grosser GlobalVar->setInitializer(Constant::getNullValue(ArrayTy)); 1948f919d8b3STobias Grosser 1949130ca30fSTobias Grosser Allocation = GlobalVar; 1950130ca30fSTobias Grosser } else if (Var.type == ppcg_access_private) { 1951130ca30fSTobias Grosser Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array"); 1952130ca30fSTobias Grosser } else { 1953130ca30fSTobias Grosser llvm_unreachable("unknown variable type"); 1954130ca30fSTobias Grosser } 19554d5a9172STobias Grosser SAI = 19564d5a9172STobias Grosser S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array); 1957b513b491STobias Grosser Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr); 1958130ca30fSTobias Grosser IDToValue[Id] = Allocation; 1959130ca30fSTobias Grosser LocalArrays.push_back(Allocation); 1960b513b491STobias Grosser KernelIds.push_back(Id); 1961b513b491STobias Grosser IDToSAI[Id] = SAI; 1962b513b491STobias Grosser } 1963b513b491STobias Grosser } 1964b513b491STobias Grosser 1965f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction( 1966f291c8d5SSiddharth Bhat ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues, 1967f291c8d5SSiddharth Bhat SetVector<Function *> &SubtreeFunctions) { 196879f13b9aSSingapuram Sanjay Srivallabh std::string Identifier = getKernelFuncName(Kernel->id); 196932837fe3STobias Grosser GPUModule.reset(new Module(Identifier, Builder.getContext())); 197017f01968SSiddharth Bhat 197117f01968SSiddharth Bhat switch (Arch) { 197217f01968SSiddharth Bhat case GPUArch::NVPTX64: 197317f01968SSiddharth Bhat if (Runtime == GPURuntime::CUDA) 197432837fe3STobias Grosser GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda")); 197517f01968SSiddharth Bhat else if (Runtime == GPURuntime::OpenCL) 197617f01968SSiddharth Bhat GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl")); 197732837fe3STobias Grosser GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */)); 197817f01968SSiddharth Bhat break; 197917f01968SSiddharth Bhat } 198032837fe3STobias Grosser 1981edb885cbSTobias Grosser Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues); 198232837fe3STobias Grosser 198359ab0705STobias Grosser BasicBlock *PrevBlock = Builder.GetInsertBlock(); 198432837fe3STobias Grosser auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN); 198532837fe3STobias Grosser 198659ab0705STobias Grosser DT.addNewBlock(EntryBlock, PrevBlock); 198759ab0705STobias Grosser 198832837fe3STobias Grosser Builder.SetInsertPoint(EntryBlock); 198932837fe3STobias Grosser Builder.CreateRetVoid(); 199032837fe3STobias Grosser Builder.SetInsertPoint(EntryBlock, EntryBlock->begin()); 1991472f9654STobias Grosser 1992629109b6STobias Grosser ScopDetection::markFunctionAsInvalid(FN); 1993629109b6STobias Grosser 199400bb5a99STobias Grosser prepareKernelArguments(Kernel, FN); 1995b513b491STobias Grosser createKernelVariables(Kernel, FN); 1996472f9654STobias Grosser insertKernelIntrinsics(Kernel); 199732837fe3STobias Grosser } 199832837fe3STobias Grosser 199974dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() { 200017f01968SSiddharth Bhat llvm::Triple GPUTriple; 200117f01968SSiddharth Bhat 200217f01968SSiddharth Bhat switch (Arch) { 200317f01968SSiddharth Bhat case GPUArch::NVPTX64: 200417f01968SSiddharth Bhat switch (Runtime) { 200517f01968SSiddharth Bhat case GPURuntime::CUDA: 200617f01968SSiddharth Bhat GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda")); 200717f01968SSiddharth Bhat break; 200817f01968SSiddharth Bhat case GPURuntime::OpenCL: 200917f01968SSiddharth Bhat GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl")); 201017f01968SSiddharth Bhat break; 201117f01968SSiddharth Bhat } 201217f01968SSiddharth Bhat break; 201317f01968SSiddharth Bhat } 201417f01968SSiddharth Bhat 201574dc3cb4STobias Grosser std::string ErrMsg; 201674dc3cb4STobias Grosser auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg); 201774dc3cb4STobias Grosser 201874dc3cb4STobias Grosser if (!GPUTarget) { 201974dc3cb4STobias Grosser errs() << ErrMsg << "\n"; 202074dc3cb4STobias Grosser return ""; 202174dc3cb4STobias Grosser } 202274dc3cb4STobias Grosser 202374dc3cb4STobias Grosser TargetOptions Options; 202474dc3cb4STobias Grosser Options.UnsafeFPMath = FastMath; 202517f01968SSiddharth Bhat 202617f01968SSiddharth Bhat std::string subtarget; 202717f01968SSiddharth Bhat 202817f01968SSiddharth Bhat switch (Arch) { 202917f01968SSiddharth Bhat case GPUArch::NVPTX64: 203017f01968SSiddharth Bhat subtarget = CudaVersion; 203117f01968SSiddharth Bhat break; 203217f01968SSiddharth Bhat } 203317f01968SSiddharth Bhat 203417f01968SSiddharth Bhat std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine( 203517f01968SSiddharth Bhat GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>())); 203674dc3cb4STobias Grosser 203774dc3cb4STobias Grosser SmallString<0> ASMString; 203874dc3cb4STobias Grosser raw_svector_ostream ASMStream(ASMString); 203974dc3cb4STobias Grosser llvm::legacy::PassManager PM; 204074dc3cb4STobias Grosser 204174dc3cb4STobias Grosser PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis())); 204274dc3cb4STobias Grosser 204374dc3cb4STobias Grosser if (TargetM->addPassesToEmitFile( 204474dc3cb4STobias Grosser PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) { 204574dc3cb4STobias Grosser errs() << "The target does not support generation of this file type!\n"; 204674dc3cb4STobias Grosser return ""; 204774dc3cb4STobias Grosser } 204874dc3cb4STobias Grosser 204974dc3cb4STobias Grosser PM.run(*GPUModule); 205074dc3cb4STobias Grosser 205174dc3cb4STobias Grosser return ASMStream.str(); 205274dc3cb4STobias Grosser } 205374dc3cb4STobias Grosser 205457793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() { 205565d7f72fSSiddharth Bhat 20565857b701STobias Grosser if (verifyModule(*GPUModule)) { 205765d7f72fSSiddharth Bhat DEBUG(dbgs() << "verifyModule failed on module:\n"; 205865d7f72fSSiddharth Bhat GPUModule->print(dbgs(), nullptr); dbgs() << "\n";); 205965d7f72fSSiddharth Bhat 206065d7f72fSSiddharth Bhat if (FailOnVerifyModuleFailure) 206165d7f72fSSiddharth Bhat llvm_unreachable("VerifyModule failed."); 206265d7f72fSSiddharth Bhat 20635857b701STobias Grosser BuildSuccessful = false; 20645857b701STobias Grosser return ""; 20655857b701STobias Grosser } 206632837fe3STobias Grosser 206732837fe3STobias Grosser if (DumpKernelIR) 206832837fe3STobias Grosser outs() << *GPUModule << "\n"; 206932837fe3STobias Grosser 20709a18d559STobias Grosser // Optimize module. 20719a18d559STobias Grosser llvm::legacy::PassManager OptPasses; 20729a18d559STobias Grosser PassManagerBuilder PassBuilder; 20739a18d559STobias Grosser PassBuilder.OptLevel = 3; 20749a18d559STobias Grosser PassBuilder.SizeLevel = 0; 20759a18d559STobias Grosser PassBuilder.populateModulePassManager(OptPasses); 20769a18d559STobias Grosser OptPasses.run(*GPUModule); 20779a18d559STobias Grosser 207874dc3cb4STobias Grosser std::string Assembly = createKernelASM(); 207974dc3cb4STobias Grosser 208074dc3cb4STobias Grosser if (DumpKernelASM) 208174dc3cb4STobias Grosser outs() << Assembly << "\n"; 208274dc3cb4STobias Grosser 208332837fe3STobias Grosser GPUModule.release(); 2084472f9654STobias Grosser KernelIDs.clear(); 208557793596STobias Grosser 208657793596STobias Grosser return Assembly; 208732837fe3STobias Grosser } 208832837fe3STobias Grosser 20899dfe4e7cSTobias Grosser namespace { 20909dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass { 20919dfe4e7cSTobias Grosser public: 20929dfe4e7cSTobias Grosser static char ID; 20939dfe4e7cSTobias Grosser 209417f01968SSiddharth Bhat GPURuntime Runtime = GPURuntime::CUDA; 209517f01968SSiddharth Bhat 209617f01968SSiddharth Bhat GPUArch Architecture = GPUArch::NVPTX64; 209717f01968SSiddharth Bhat 2098e938517eSTobias Grosser /// The scop that is currently processed. 2099e938517eSTobias Grosser Scop *S; 2100e938517eSTobias Grosser 210138fc0aedSTobias Grosser LoopInfo *LI; 210238fc0aedSTobias Grosser DominatorTree *DT; 210338fc0aedSTobias Grosser ScalarEvolution *SE; 210438fc0aedSTobias Grosser const DataLayout *DL; 210538fc0aedSTobias Grosser RegionInfo *RI; 210638fc0aedSTobias Grosser 21079dfe4e7cSTobias Grosser PPCGCodeGeneration() : ScopPass(ID) {} 21089dfe4e7cSTobias Grosser 2109e938517eSTobias Grosser /// Construct compilation options for PPCG. 2110e938517eSTobias Grosser /// 2111e938517eSTobias Grosser /// @returns The compilation options. 2112e938517eSTobias Grosser ppcg_options *createPPCGOptions() { 2113e938517eSTobias Grosser auto DebugOptions = 2114e938517eSTobias Grosser (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options)); 2115e938517eSTobias Grosser auto Options = (ppcg_options *)malloc(sizeof(ppcg_options)); 2116e938517eSTobias Grosser 2117e938517eSTobias Grosser DebugOptions->dump_schedule_constraints = false; 2118e938517eSTobias Grosser DebugOptions->dump_schedule = false; 2119e938517eSTobias Grosser DebugOptions->dump_final_schedule = false; 2120e938517eSTobias Grosser DebugOptions->dump_sizes = false; 21218950ceadSTobias Grosser DebugOptions->verbose = false; 2122e938517eSTobias Grosser 2123e938517eSTobias Grosser Options->debug = DebugOptions; 2124e938517eSTobias Grosser 2125e938517eSTobias Grosser Options->reschedule = true; 2126e938517eSTobias Grosser Options->scale_tile_loops = false; 2127e938517eSTobias Grosser Options->wrap = false; 2128e938517eSTobias Grosser 2129e938517eSTobias Grosser Options->non_negative_parameters = false; 2130e938517eSTobias Grosser Options->ctx = nullptr; 2131e938517eSTobias Grosser Options->sizes = nullptr; 2132e938517eSTobias Grosser 21334eaedde5STobias Grosser Options->tile_size = 32; 21344eaedde5STobias Grosser 2135130ca30fSTobias Grosser Options->use_private_memory = PrivateMemory; 2136b513b491STobias Grosser Options->use_shared_memory = SharedMemory; 2137b513b491STobias Grosser Options->max_shared_memory = 48 * 1024; 2138e938517eSTobias Grosser 2139e938517eSTobias Grosser Options->target = PPCG_TARGET_CUDA; 2140e938517eSTobias Grosser Options->openmp = false; 2141e938517eSTobias Grosser Options->linearize_device_arrays = true; 2142e938517eSTobias Grosser Options->live_range_reordering = false; 2143e938517eSTobias Grosser 2144e938517eSTobias Grosser Options->opencl_compiler_options = nullptr; 2145e938517eSTobias Grosser Options->opencl_use_gpu = false; 2146e938517eSTobias Grosser Options->opencl_n_include_file = 0; 2147e938517eSTobias Grosser Options->opencl_include_files = nullptr; 2148e938517eSTobias Grosser Options->opencl_print_kernel_types = false; 2149e938517eSTobias Grosser Options->opencl_embed_kernel_code = false; 2150e938517eSTobias Grosser 2151e938517eSTobias Grosser Options->save_schedule_file = nullptr; 2152e938517eSTobias Grosser Options->load_schedule_file = nullptr; 2153e938517eSTobias Grosser 2154e938517eSTobias Grosser return Options; 2155e938517eSTobias Grosser } 2156e938517eSTobias Grosser 2157f384594dSTobias Grosser /// Get a tagged access relation containing all accesses of type @p AccessTy. 2158f384594dSTobias Grosser /// 2159f384594dSTobias Grosser /// Instead of a normal access of the form: 2160f384594dSTobias Grosser /// 2161f384594dSTobias Grosser /// Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)] 2162f384594dSTobias Grosser /// 2163f384594dSTobias Grosser /// a tagged access has the form 2164f384594dSTobias Grosser /// 2165f384594dSTobias Grosser /// [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)] 2166f384594dSTobias Grosser /// 2167f384594dSTobias Grosser /// where 'id' is an additional space that references the memory access that 2168f384594dSTobias Grosser /// triggered the access. 2169f384594dSTobias Grosser /// 2170f384594dSTobias Grosser /// @param AccessTy The type of the memory accesses to collect. 2171f384594dSTobias Grosser /// 2172f384594dSTobias Grosser /// @return The relation describing all tagged memory accesses. 2173f384594dSTobias Grosser isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) { 2174f384594dSTobias Grosser isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace()); 2175f384594dSTobias Grosser 2176f384594dSTobias Grosser for (auto &Stmt : *S) 2177f384594dSTobias Grosser for (auto &Acc : Stmt) 2178f384594dSTobias Grosser if (Acc->getType() == AccessTy) { 2179f384594dSTobias Grosser isl_map *Relation = Acc->getAccessRelation(); 2180f384594dSTobias Grosser Relation = isl_map_intersect_domain(Relation, Stmt.getDomain()); 2181f384594dSTobias Grosser 2182f384594dSTobias Grosser isl_space *Space = isl_map_get_space(Relation); 2183f384594dSTobias Grosser Space = isl_space_range(Space); 2184f384594dSTobias Grosser Space = isl_space_from_range(Space); 21856293ba69STobias Grosser Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId()); 2186f384594dSTobias Grosser isl_map *Universe = isl_map_universe(Space); 2187f384594dSTobias Grosser Relation = isl_map_domain_product(Relation, Universe); 2188f384594dSTobias Grosser Accesses = isl_union_map_add_map(Accesses, Relation); 2189f384594dSTobias Grosser } 2190f384594dSTobias Grosser 2191f384594dSTobias Grosser return Accesses; 2192f384594dSTobias Grosser } 2193f384594dSTobias Grosser 2194f384594dSTobias Grosser /// Get the set of all read accesses, tagged with the access id. 2195f384594dSTobias Grosser /// 2196f384594dSTobias Grosser /// @see getTaggedAccesses 2197f384594dSTobias Grosser isl_union_map *getTaggedReads() { 2198f384594dSTobias Grosser return getTaggedAccesses(MemoryAccess::READ); 2199f384594dSTobias Grosser } 2200f384594dSTobias Grosser 2201f384594dSTobias Grosser /// Get the set of all may (and must) accesses, tagged with the access id. 2202f384594dSTobias Grosser /// 2203f384594dSTobias Grosser /// @see getTaggedAccesses 2204f384594dSTobias Grosser isl_union_map *getTaggedMayWrites() { 2205f384594dSTobias Grosser return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE), 2206f384594dSTobias Grosser getTaggedAccesses(MemoryAccess::MUST_WRITE)); 2207f384594dSTobias Grosser } 2208f384594dSTobias Grosser 2209f384594dSTobias Grosser /// Get the set of all must accesses, tagged with the access id. 2210f384594dSTobias Grosser /// 2211f384594dSTobias Grosser /// @see getTaggedAccesses 2212f384594dSTobias Grosser isl_union_map *getTaggedMustWrites() { 2213f384594dSTobias Grosser return getTaggedAccesses(MemoryAccess::MUST_WRITE); 2214f384594dSTobias Grosser } 2215f384594dSTobias Grosser 2216aef5196fSTobias Grosser /// Collect parameter and array names as isl_ids. 2217aef5196fSTobias Grosser /// 2218aef5196fSTobias Grosser /// To reason about the different parameters and arrays used, ppcg requires 2219aef5196fSTobias Grosser /// a list of all isl_ids in use. As PPCG traditionally performs 2220aef5196fSTobias Grosser /// source-to-source compilation each of these isl_ids is mapped to the 2221aef5196fSTobias Grosser /// expression that represents it. As we do not have a corresponding 2222aef5196fSTobias Grosser /// expression in Polly, we just map each id to a 'zero' expression to match 2223aef5196fSTobias Grosser /// the data format that ppcg expects. 2224aef5196fSTobias Grosser /// 2225aef5196fSTobias Grosser /// @returns Retun a map from collected ids to 'zero' ast expressions. 2226aef5196fSTobias Grosser __isl_give isl_id_to_ast_expr *getNames() { 2227aef5196fSTobias Grosser auto *Names = isl_id_to_ast_expr_alloc( 2228bd81a7eeSTobias Grosser S->getIslCtx(), 2229bd81a7eeSTobias Grosser S->getNumParams() + std::distance(S->array_begin(), S->array_end())); 2230aef5196fSTobias Grosser auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx())); 2231aef5196fSTobias Grosser auto *Space = S->getParamSpace(); 2232aef5196fSTobias Grosser 2233aef5196fSTobias Grosser for (int I = 0, E = S->getNumParams(); I < E; ++I) { 2234aef5196fSTobias Grosser isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I); 2235aef5196fSTobias Grosser Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2236aef5196fSTobias Grosser } 2237aef5196fSTobias Grosser 2238aef5196fSTobias Grosser for (auto &Array : S->arrays()) { 2239d7754a12SRoman Gareev auto Id = Array->getBasePtrId(); 2240aef5196fSTobias Grosser Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2241aef5196fSTobias Grosser } 2242aef5196fSTobias Grosser 2243aef5196fSTobias Grosser isl_space_free(Space); 2244aef5196fSTobias Grosser isl_ast_expr_free(Zero); 2245aef5196fSTobias Grosser 2246aef5196fSTobias Grosser return Names; 2247aef5196fSTobias Grosser } 2248aef5196fSTobias Grosser 2249e938517eSTobias Grosser /// Create a new PPCG scop from the current scop. 2250e938517eSTobias Grosser /// 2251f384594dSTobias Grosser /// The PPCG scop is initialized with data from the current polly::Scop. From 2252f384594dSTobias Grosser /// this initial data, the data-dependences in the PPCG scop are initialized. 2253f384594dSTobias Grosser /// We do not use Polly's dependence analysis for now, to ensure we match 2254f384594dSTobias Grosser /// the PPCG default behaviour more closely. 2255e938517eSTobias Grosser /// 2256e938517eSTobias Grosser /// @returns A new ppcg scop. 2257e938517eSTobias Grosser ppcg_scop *createPPCGScop() { 2258e938517eSTobias Grosser auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop)); 2259e938517eSTobias Grosser 2260e938517eSTobias Grosser PPCGScop->options = createPPCGOptions(); 2261a82f2d26SSiddharth Bhat // enable live range reordering 2262a82f2d26SSiddharth Bhat PPCGScop->options->live_range_reordering = 1; 2263e938517eSTobias Grosser 2264e938517eSTobias Grosser PPCGScop->start = 0; 2265e938517eSTobias Grosser PPCGScop->end = 0; 2266e938517eSTobias Grosser 2267f384594dSTobias Grosser PPCGScop->context = S->getContext(); 2268f384594dSTobias Grosser PPCGScop->domain = S->getDomains(); 2269e938517eSTobias Grosser PPCGScop->call = nullptr; 2270f384594dSTobias Grosser PPCGScop->tagged_reads = getTaggedReads(); 2271f384594dSTobias Grosser PPCGScop->reads = S->getReads(); 2272e938517eSTobias Grosser PPCGScop->live_in = nullptr; 2273f384594dSTobias Grosser PPCGScop->tagged_may_writes = getTaggedMayWrites(); 2274f384594dSTobias Grosser PPCGScop->may_writes = S->getWrites(); 2275f384594dSTobias Grosser PPCGScop->tagged_must_writes = getTaggedMustWrites(); 2276f384594dSTobias Grosser PPCGScop->must_writes = S->getMustWrites(); 2277e938517eSTobias Grosser PPCGScop->live_out = nullptr; 2278e938517eSTobias Grosser PPCGScop->tagger = nullptr; 2279a82f2d26SSiddharth Bhat PPCGScop->independence = 2280a82f2d26SSiddharth Bhat isl_union_map_empty(isl_set_get_space(PPCGScop->context)); 2281e938517eSTobias Grosser PPCGScop->dep_flow = nullptr; 2282e938517eSTobias Grosser PPCGScop->tagged_dep_flow = nullptr; 2283e938517eSTobias Grosser PPCGScop->dep_false = nullptr; 2284e938517eSTobias Grosser PPCGScop->dep_forced = nullptr; 2285e938517eSTobias Grosser PPCGScop->dep_order = nullptr; 2286e938517eSTobias Grosser PPCGScop->tagged_dep_order = nullptr; 2287e938517eSTobias Grosser 2288f384594dSTobias Grosser PPCGScop->schedule = S->getScheduleTree(); 2289e938517eSTobias Grosser 2290a82f2d26SSiddharth Bhat MustKillsInfo KillsInfo = computeMustKillsInfo(*S); 2291a82f2d26SSiddharth Bhat // If we have something non-trivial to kill, add it to the schedule 2292a82f2d26SSiddharth Bhat if (KillsInfo.KillsSchedule.get()) 2293a82f2d26SSiddharth Bhat PPCGScop->schedule = isl_schedule_sequence( 2294a82f2d26SSiddharth Bhat PPCGScop->schedule, KillsInfo.KillsSchedule.take()); 2295a82f2d26SSiddharth Bhat PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.take(); 2296a82f2d26SSiddharth Bhat 2297a82f2d26SSiddharth Bhat PPCGScop->names = getNames(); 2298e938517eSTobias Grosser PPCGScop->pet = nullptr; 2299e938517eSTobias Grosser 2300f384594dSTobias Grosser compute_tagger(PPCGScop); 2301f384594dSTobias Grosser compute_dependences(PPCGScop); 2302f384594dSTobias Grosser 2303e938517eSTobias Grosser return PPCGScop; 2304e938517eSTobias Grosser } 2305e938517eSTobias Grosser 2306a6d48f59SMichael Kruse /// Collect the array accesses in a statement. 230760f63b49STobias Grosser /// 230860f63b49STobias Grosser /// @param Stmt The statement for which to collect the accesses. 230960f63b49STobias Grosser /// 231060f63b49STobias Grosser /// @returns A list of array accesses. 231160f63b49STobias Grosser gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) { 231260f63b49STobias Grosser gpu_stmt_access *Accesses = nullptr; 231360f63b49STobias Grosser 231460f63b49STobias Grosser for (MemoryAccess *Acc : Stmt) { 231560f63b49STobias Grosser auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access); 231660f63b49STobias Grosser Access->read = Acc->isRead(); 231760f63b49STobias Grosser Access->write = Acc->isWrite(); 231860f63b49STobias Grosser Access->access = Acc->getAccessRelation(); 231960f63b49STobias Grosser isl_space *Space = isl_map_get_space(Access->access); 232060f63b49STobias Grosser Space = isl_space_range(Space); 232160f63b49STobias Grosser Space = isl_space_from_range(Space); 23226293ba69STobias Grosser Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId()); 232360f63b49STobias Grosser isl_map *Universe = isl_map_universe(Space); 232460f63b49STobias Grosser Access->tagged_access = 232560f63b49STobias Grosser isl_map_domain_product(Acc->getAccessRelation(), Universe); 2326b513b491STobias Grosser Access->exact_write = !Acc->isMayWrite(); 232760f63b49STobias Grosser Access->ref_id = Acc->getId(); 232860f63b49STobias Grosser Access->next = Accesses; 2329b513b491STobias Grosser Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions(); 233060f63b49STobias Grosser Accesses = Access; 233160f63b49STobias Grosser } 233260f63b49STobias Grosser 233360f63b49STobias Grosser return Accesses; 233460f63b49STobias Grosser } 233560f63b49STobias Grosser 233669b46751STobias Grosser /// Collect the list of GPU statements. 233769b46751STobias Grosser /// 233869b46751STobias Grosser /// Each statement has an id, a pointer to the underlying data structure, 233969b46751STobias Grosser /// as well as a list with all memory accesses. 234069b46751STobias Grosser /// 234169b46751STobias Grosser /// TODO: Initialize the list of memory accesses. 234269b46751STobias Grosser /// 234369b46751STobias Grosser /// @returns A linked-list of statements. 234469b46751STobias Grosser gpu_stmt *getStatements() { 234569b46751STobias Grosser gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt, 234669b46751STobias Grosser std::distance(S->begin(), S->end())); 234769b46751STobias Grosser 234869b46751STobias Grosser int i = 0; 234969b46751STobias Grosser for (auto &Stmt : *S) { 235069b46751STobias Grosser gpu_stmt *GPUStmt = &Stmts[i]; 235169b46751STobias Grosser 235269b46751STobias Grosser GPUStmt->id = Stmt.getDomainId(); 235369b46751STobias Grosser 235469b46751STobias Grosser // We use the pet stmt pointer to keep track of the Polly statements. 235569b46751STobias Grosser GPUStmt->stmt = (pet_stmt *)&Stmt; 235660f63b49STobias Grosser GPUStmt->accesses = getStmtAccesses(Stmt); 235769b46751STobias Grosser i++; 235869b46751STobias Grosser } 235969b46751STobias Grosser 236069b46751STobias Grosser return Stmts; 236169b46751STobias Grosser } 236269b46751STobias Grosser 236360f63b49STobias Grosser /// Derive the extent of an array. 236460f63b49STobias Grosser /// 2365d58acf86STobias Grosser /// The extent of an array is the set of elements that are within the 2366d58acf86STobias Grosser /// accessed array. For the inner dimensions, the extent constraints are 2367d58acf86STobias Grosser /// 0 and the size of the corresponding array dimension. For the first 2368d58acf86STobias Grosser /// (outermost) dimension, the extent constraints are the minimal and maximal 2369d58acf86STobias Grosser /// subscript value for the first dimension. 237060f63b49STobias Grosser /// 237160f63b49STobias Grosser /// @param Array The array to derive the extent for. 237260f63b49STobias Grosser /// 237360f63b49STobias Grosser /// @returns An isl_set describing the extent of the array. 237460f63b49STobias Grosser __isl_give isl_set *getExtent(ScopArrayInfo *Array) { 2375d58acf86STobias Grosser unsigned NumDims = Array->getNumberOfDimensions(); 237660f63b49STobias Grosser isl_union_map *Accesses = S->getAccesses(); 237760f63b49STobias Grosser Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains()); 2378d58acf86STobias Grosser Accesses = isl_union_map_detect_equalities(Accesses); 237960f63b49STobias Grosser isl_union_set *AccessUSet = isl_union_map_range(Accesses); 2380d58acf86STobias Grosser AccessUSet = isl_union_set_coalesce(AccessUSet); 2381d58acf86STobias Grosser AccessUSet = isl_union_set_detect_equalities(AccessUSet); 2382d58acf86STobias Grosser AccessUSet = isl_union_set_coalesce(AccessUSet); 2383d58acf86STobias Grosser 2384d58acf86STobias Grosser if (isl_union_set_is_empty(AccessUSet)) { 2385d58acf86STobias Grosser isl_union_set_free(AccessUSet); 2386d58acf86STobias Grosser return isl_set_empty(Array->getSpace()); 2387d58acf86STobias Grosser } 2388d58acf86STobias Grosser 2389d58acf86STobias Grosser if (Array->getNumberOfDimensions() == 0) { 2390d58acf86STobias Grosser isl_union_set_free(AccessUSet); 2391d58acf86STobias Grosser return isl_set_universe(Array->getSpace()); 2392d58acf86STobias Grosser } 2393d58acf86STobias Grosser 239460f63b49STobias Grosser isl_set *AccessSet = 239560f63b49STobias Grosser isl_union_set_extract_set(AccessUSet, Array->getSpace()); 239660f63b49STobias Grosser 2397d58acf86STobias Grosser isl_union_set_free(AccessUSet); 2398d58acf86STobias Grosser isl_local_space *LS = isl_local_space_from_space(Array->getSpace()); 2399d58acf86STobias Grosser 2400d58acf86STobias Grosser isl_pw_aff *Val = 2401d58acf86STobias Grosser isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0)); 2402d58acf86STobias Grosser 2403d58acf86STobias Grosser isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0); 2404d58acf86STobias Grosser isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0); 2405d58acf86STobias Grosser OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in, 2406d58acf86STobias Grosser isl_pw_aff_dim(Val, isl_dim_in)); 2407d58acf86STobias Grosser OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in, 2408d58acf86STobias Grosser isl_pw_aff_dim(Val, isl_dim_in)); 2409d58acf86STobias Grosser OuterMin = 2410d58acf86STobias Grosser isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, Array->getBasePtrId()); 2411d58acf86STobias Grosser OuterMax = 2412d58acf86STobias Grosser isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, Array->getBasePtrId()); 2413d58acf86STobias Grosser 2414d58acf86STobias Grosser isl_set *Extent = isl_set_universe(Array->getSpace()); 2415d58acf86STobias Grosser 2416d58acf86STobias Grosser Extent = isl_set_intersect( 2417d58acf86STobias Grosser Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val))); 2418d58acf86STobias Grosser Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val)); 2419d58acf86STobias Grosser 2420d58acf86STobias Grosser for (unsigned i = 1; i < NumDims; ++i) 2421d58acf86STobias Grosser Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0); 2422d58acf86STobias Grosser 2423b7f68b8cSSiddharth Bhat for (unsigned i = 0; i < NumDims; ++i) { 2424d58acf86STobias Grosser isl_pw_aff *PwAff = 2425d58acf86STobias Grosser const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i)); 2426b7f68b8cSSiddharth Bhat 2427b7f68b8cSSiddharth Bhat // isl_pw_aff can be NULL for zero dimension. Only in the case of a 2428b7f68b8cSSiddharth Bhat // Fortran array will we have a legitimate dimension. 2429b7f68b8cSSiddharth Bhat if (!PwAff) { 2430b7f68b8cSSiddharth Bhat assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension"); 2431b7f68b8cSSiddharth Bhat continue; 2432b7f68b8cSSiddharth Bhat } 2433b7f68b8cSSiddharth Bhat 2434d58acf86STobias Grosser isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain( 2435d58acf86STobias Grosser isl_local_space_from_space(Array->getSpace()), isl_dim_set, i)); 2436d58acf86STobias Grosser PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in, 2437d58acf86STobias Grosser isl_pw_aff_dim(Val, isl_dim_in)); 2438d58acf86STobias Grosser PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in, 2439d58acf86STobias Grosser isl_pw_aff_get_tuple_id(Val, isl_dim_in)); 2440d58acf86STobias Grosser auto *Set = isl_pw_aff_gt_set(PwAff, Val); 2441d58acf86STobias Grosser Extent = isl_set_intersect(Set, Extent); 2442d58acf86STobias Grosser } 2443d58acf86STobias Grosser 2444d58acf86STobias Grosser return Extent; 244560f63b49STobias Grosser } 244660f63b49STobias Grosser 244760f63b49STobias Grosser /// Derive the bounds of an array. 244860f63b49STobias Grosser /// 244960f63b49STobias Grosser /// For the first dimension we derive the bound of the array from the extent 245060f63b49STobias Grosser /// of this dimension. For inner dimensions we obtain their size directly from 245160f63b49STobias Grosser /// ScopArrayInfo. 245260f63b49STobias Grosser /// 245360f63b49STobias Grosser /// @param PPCGArray The array to compute bounds for. 245460f63b49STobias Grosser /// @param Array The polly array from which to take the information. 245560f63b49STobias Grosser void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) { 245660f63b49STobias Grosser if (PPCGArray.n_index > 0) { 245702293ed7STobias Grosser if (isl_set_is_empty(PPCGArray.extent)) { 245802293ed7STobias Grosser isl_set *Dom = isl_set_copy(PPCGArray.extent); 245902293ed7STobias Grosser isl_local_space *LS = isl_local_space_from_space( 246002293ed7STobias Grosser isl_space_params(isl_set_get_space(Dom))); 246102293ed7STobias Grosser isl_set_free(Dom); 246202293ed7STobias Grosser isl_aff *Zero = isl_aff_zero_on_domain(LS); 246302293ed7STobias Grosser PPCGArray.bound[0] = isl_pw_aff_from_aff(Zero); 246402293ed7STobias Grosser } else { 246560f63b49STobias Grosser isl_set *Dom = isl_set_copy(PPCGArray.extent); 246660f63b49STobias Grosser Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1); 246760f63b49STobias Grosser isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0); 246860f63b49STobias Grosser isl_set_free(Dom); 246960f63b49STobias Grosser Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound)); 247002293ed7STobias Grosser isl_local_space *LS = 247102293ed7STobias Grosser isl_local_space_from_space(isl_set_get_space(Dom)); 247260f63b49STobias Grosser isl_aff *One = isl_aff_zero_on_domain(LS); 247360f63b49STobias Grosser One = isl_aff_add_constant_si(One, 1); 247460f63b49STobias Grosser Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One)); 247560f63b49STobias Grosser Bound = isl_pw_aff_gist(Bound, S->getContext()); 247660f63b49STobias Grosser PPCGArray.bound[0] = Bound; 247760f63b49STobias Grosser } 247802293ed7STobias Grosser } 247960f63b49STobias Grosser 248060f63b49STobias Grosser for (unsigned i = 1; i < PPCGArray.n_index; ++i) { 248160f63b49STobias Grosser isl_pw_aff *Bound = Array->getDimensionSizePw(i); 248260f63b49STobias Grosser auto LS = isl_pw_aff_get_domain_space(Bound); 248360f63b49STobias Grosser auto Aff = isl_multi_aff_zero(LS); 248460f63b49STobias Grosser Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff); 248560f63b49STobias Grosser PPCGArray.bound[i] = Bound; 248660f63b49STobias Grosser } 248760f63b49STobias Grosser } 248860f63b49STobias Grosser 248960f63b49STobias Grosser /// Create the arrays for @p PPCGProg. 249060f63b49STobias Grosser /// 249160f63b49STobias Grosser /// @param PPCGProg The program to compute the arrays for. 249260f63b49STobias Grosser void createArrays(gpu_prog *PPCGProg) { 249360f63b49STobias Grosser int i = 0; 2494d7754a12SRoman Gareev for (auto &Array : S->arrays()) { 249560f63b49STobias Grosser std::string TypeName; 249660f63b49STobias Grosser raw_string_ostream OS(TypeName); 249760f63b49STobias Grosser 249860f63b49STobias Grosser OS << *Array->getElementType(); 249960f63b49STobias Grosser TypeName = OS.str(); 250060f63b49STobias Grosser 250160f63b49STobias Grosser gpu_array_info &PPCGArray = PPCGProg->array[i]; 250260f63b49STobias Grosser 250360f63b49STobias Grosser PPCGArray.space = Array->getSpace(); 250460f63b49STobias Grosser PPCGArray.type = strdup(TypeName.c_str()); 250560f63b49STobias Grosser PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8; 250660f63b49STobias Grosser PPCGArray.name = strdup(Array->getName().c_str()); 250760f63b49STobias Grosser PPCGArray.extent = nullptr; 250860f63b49STobias Grosser PPCGArray.n_index = Array->getNumberOfDimensions(); 250960f63b49STobias Grosser PPCGArray.bound = 251060f63b49STobias Grosser isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index); 251160f63b49STobias Grosser PPCGArray.extent = getExtent(Array); 251260f63b49STobias Grosser PPCGArray.n_ref = 0; 251360f63b49STobias Grosser PPCGArray.refs = nullptr; 251460f63b49STobias Grosser PPCGArray.accessed = true; 2515fe74a7a1STobias Grosser PPCGArray.read_only_scalar = 2516fe74a7a1STobias Grosser Array->isReadOnly() && Array->getNumberOfDimensions() == 0; 251760f63b49STobias Grosser PPCGArray.has_compound_element = false; 251860f63b49STobias Grosser PPCGArray.local = false; 251960f63b49STobias Grosser PPCGArray.declare_local = false; 252060f63b49STobias Grosser PPCGArray.global = false; 252160f63b49STobias Grosser PPCGArray.linearize = false; 252260f63b49STobias Grosser PPCGArray.dep_order = nullptr; 252313c78e4dSTobias Grosser PPCGArray.user = Array; 252460f63b49STobias Grosser 252560f63b49STobias Grosser setArrayBounds(PPCGArray, Array); 25262d010dafSTobias Grosser i++; 2527b9fc860aSTobias Grosser 2528b9fc860aSTobias Grosser collect_references(PPCGProg, &PPCGArray); 252960f63b49STobias Grosser } 253060f63b49STobias Grosser } 253160f63b49STobias Grosser 253260f63b49STobias Grosser /// Create an identity map between the arrays in the scop. 253360f63b49STobias Grosser /// 253460f63b49STobias Grosser /// @returns An identity map between the arrays in the scop. 253560f63b49STobias Grosser isl_union_map *getArrayIdentity() { 253660f63b49STobias Grosser isl_union_map *Maps = isl_union_map_empty(S->getParamSpace()); 253760f63b49STobias Grosser 2538d7754a12SRoman Gareev for (auto &Array : S->arrays()) { 253960f63b49STobias Grosser isl_space *Space = Array->getSpace(); 254060f63b49STobias Grosser Space = isl_space_map_from_set(Space); 254160f63b49STobias Grosser isl_map *Identity = isl_map_identity(Space); 254260f63b49STobias Grosser Maps = isl_union_map_add_map(Maps, Identity); 254360f63b49STobias Grosser } 254460f63b49STobias Grosser 254560f63b49STobias Grosser return Maps; 254660f63b49STobias Grosser } 254760f63b49STobias Grosser 2548e938517eSTobias Grosser /// Create a default-initialized PPCG GPU program. 2549e938517eSTobias Grosser /// 2550a6d48f59SMichael Kruse /// @returns A new gpu program description. 2551e938517eSTobias Grosser gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) { 2552e938517eSTobias Grosser 2553e938517eSTobias Grosser if (!PPCGScop) 2554e938517eSTobias Grosser return nullptr; 2555e938517eSTobias Grosser 2556e938517eSTobias Grosser auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog); 2557e938517eSTobias Grosser 2558e938517eSTobias Grosser PPCGProg->ctx = S->getIslCtx(); 2559e938517eSTobias Grosser PPCGProg->scop = PPCGScop; 2560aef5196fSTobias Grosser PPCGProg->context = isl_set_copy(PPCGScop->context); 256160f63b49STobias Grosser PPCGProg->read = isl_union_map_copy(PPCGScop->reads); 256260f63b49STobias Grosser PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes); 256360f63b49STobias Grosser PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes); 256460f63b49STobias Grosser PPCGProg->tagged_must_kill = 256560f63b49STobias Grosser isl_union_map_copy(PPCGScop->tagged_must_kills); 256660f63b49STobias Grosser PPCGProg->to_inner = getArrayIdentity(); 256760f63b49STobias Grosser PPCGProg->to_outer = getArrayIdentity(); 2568e938517eSTobias Grosser PPCGProg->any_to_outer = nullptr; 2569a82f2d26SSiddharth Bhat 2570a82f2d26SSiddharth Bhat // this needs to be set when live range reordering is enabled. 2571a82f2d26SSiddharth Bhat // NOTE: I believe that is conservatively correct. I'm not sure 2572a82f2d26SSiddharth Bhat // what the semantics of this is. 2573a82f2d26SSiddharth Bhat // Quoting PPCG/gpu.h: "Order dependences on non-scalars." 2574a82f2d26SSiddharth Bhat PPCGProg->array_order = 2575a82f2d26SSiddharth Bhat isl_union_map_empty(isl_set_get_space(PPCGScop->context)); 257669b46751STobias Grosser PPCGProg->n_stmts = std::distance(S->begin(), S->end()); 257769b46751STobias Grosser PPCGProg->stmts = getStatements(); 257860f63b49STobias Grosser PPCGProg->n_array = std::distance(S->array_begin(), S->array_end()); 257960f63b49STobias Grosser PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info, 258060f63b49STobias Grosser PPCGProg->n_array); 258160f63b49STobias Grosser 258260f63b49STobias Grosser createArrays(PPCGProg); 2583e938517eSTobias Grosser 2584d58acf86STobias Grosser PPCGProg->may_persist = compute_may_persist(PPCGProg); 2585e938517eSTobias Grosser return PPCGProg; 2586e938517eSTobias Grosser } 2587e938517eSTobias Grosser 258869b46751STobias Grosser struct PrintGPUUserData { 258969b46751STobias Grosser struct cuda_info *CudaInfo; 259069b46751STobias Grosser struct gpu_prog *PPCGProg; 259169b46751STobias Grosser std::vector<ppcg_kernel *> Kernels; 259269b46751STobias Grosser }; 259369b46751STobias Grosser 259469b46751STobias Grosser /// Print a user statement node in the host code. 259569b46751STobias Grosser /// 259669b46751STobias Grosser /// We use ppcg's printing facilities to print the actual statement and 259769b46751STobias Grosser /// additionally build up a list of all kernels that are encountered in the 259869b46751STobias Grosser /// host ast. 259969b46751STobias Grosser /// 260069b46751STobias Grosser /// @param P The printer to print to 260169b46751STobias Grosser /// @param Options The printing options to use 260269b46751STobias Grosser /// @param Node The node to print 260369b46751STobias Grosser /// @param User A user pointer to carry additional data. This pointer is 260469b46751STobias Grosser /// expected to be of type PrintGPUUserData. 260569b46751STobias Grosser /// 260669b46751STobias Grosser /// @returns A printer to which the output has been printed. 260769b46751STobias Grosser static __isl_give isl_printer * 260869b46751STobias Grosser printHostUser(__isl_take isl_printer *P, 260969b46751STobias Grosser __isl_take isl_ast_print_options *Options, 261069b46751STobias Grosser __isl_take isl_ast_node *Node, void *User) { 261169b46751STobias Grosser auto Data = (struct PrintGPUUserData *)User; 261269b46751STobias Grosser auto Id = isl_ast_node_get_annotation(Node); 261369b46751STobias Grosser 261469b46751STobias Grosser if (Id) { 261520251734STobias Grosser bool IsUser = !strcmp(isl_id_get_name(Id), "user"); 261620251734STobias Grosser 261720251734STobias Grosser // If this is a user statement, format it ourselves as ppcg would 261820251734STobias Grosser // otherwise try to call pet functionality that is not available in 261920251734STobias Grosser // Polly. 262020251734STobias Grosser if (IsUser) { 262120251734STobias Grosser P = isl_printer_start_line(P); 262220251734STobias Grosser P = isl_printer_print_ast_node(P, Node); 262320251734STobias Grosser P = isl_printer_end_line(P); 262420251734STobias Grosser isl_id_free(Id); 262520251734STobias Grosser isl_ast_print_options_free(Options); 262620251734STobias Grosser return P; 262720251734STobias Grosser } 262820251734STobias Grosser 262969b46751STobias Grosser auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id); 263069b46751STobias Grosser isl_id_free(Id); 263169b46751STobias Grosser Data->Kernels.push_back(Kernel); 263269b46751STobias Grosser } 263369b46751STobias Grosser 263469b46751STobias Grosser return print_host_user(P, Options, Node, User); 263569b46751STobias Grosser } 263669b46751STobias Grosser 263769b46751STobias Grosser /// Print C code corresponding to the control flow in @p Kernel. 263869b46751STobias Grosser /// 263969b46751STobias Grosser /// @param Kernel The kernel to print 264069b46751STobias Grosser void printKernel(ppcg_kernel *Kernel) { 264169b46751STobias Grosser auto *P = isl_printer_to_str(S->getIslCtx()); 264269b46751STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C); 264369b46751STobias Grosser auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 264469b46751STobias Grosser P = isl_ast_node_print(Kernel->tree, P, Options); 264569b46751STobias Grosser char *String = isl_printer_get_str(P); 264669b46751STobias Grosser printf("%s\n", String); 264769b46751STobias Grosser free(String); 264869b46751STobias Grosser isl_printer_free(P); 264969b46751STobias Grosser } 265069b46751STobias Grosser 265169b46751STobias Grosser /// Print C code corresponding to the GPU code described by @p Tree. 265269b46751STobias Grosser /// 265369b46751STobias Grosser /// @param Tree An AST describing GPU code 265469b46751STobias Grosser /// @param PPCGProg The PPCG program from which @Tree has been constructed. 265569b46751STobias Grosser void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) { 265669b46751STobias Grosser auto *P = isl_printer_to_str(S->getIslCtx()); 265769b46751STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C); 265869b46751STobias Grosser 265969b46751STobias Grosser PrintGPUUserData Data; 266069b46751STobias Grosser Data.PPCGProg = PPCGProg; 266169b46751STobias Grosser 266269b46751STobias Grosser auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 266369b46751STobias Grosser Options = 266469b46751STobias Grosser isl_ast_print_options_set_print_user(Options, printHostUser, &Data); 266569b46751STobias Grosser P = isl_ast_node_print(Tree, P, Options); 266669b46751STobias Grosser char *String = isl_printer_get_str(P); 266769b46751STobias Grosser printf("# host\n"); 266869b46751STobias Grosser printf("%s\n", String); 266969b46751STobias Grosser free(String); 267069b46751STobias Grosser isl_printer_free(P); 267169b46751STobias Grosser 267269b46751STobias Grosser for (auto Kernel : Data.Kernels) { 267369b46751STobias Grosser printf("# kernel%d\n", Kernel->id); 267469b46751STobias Grosser printKernel(Kernel); 267569b46751STobias Grosser } 267669b46751STobias Grosser } 267769b46751STobias Grosser 2678f384594dSTobias Grosser // Generate a GPU program using PPCG. 2679f384594dSTobias Grosser // 2680f384594dSTobias Grosser // GPU mapping consists of multiple steps: 2681f384594dSTobias Grosser // 2682f384594dSTobias Grosser // 1) Compute new schedule for the program. 2683f384594dSTobias Grosser // 2) Map schedule to GPU (TODO) 2684f384594dSTobias Grosser // 3) Generate code for new schedule (TODO) 2685f384594dSTobias Grosser // 2686f384594dSTobias Grosser // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer 2687f384594dSTobias Grosser // is mostly CPU specific. Instead, we use PPCG's GPU code generation 2688f384594dSTobias Grosser // strategy directly from this pass. 2689f384594dSTobias Grosser gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) { 2690f384594dSTobias Grosser 2691f384594dSTobias Grosser auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen); 2692f384594dSTobias Grosser 2693f384594dSTobias Grosser PPCGGen->ctx = S->getIslCtx(); 2694f384594dSTobias Grosser PPCGGen->options = PPCGScop->options; 2695f384594dSTobias Grosser PPCGGen->print = nullptr; 2696f384594dSTobias Grosser PPCGGen->print_user = nullptr; 269760c60025STobias Grosser PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt; 2698f384594dSTobias Grosser PPCGGen->prog = PPCGProg; 2699f384594dSTobias Grosser PPCGGen->tree = nullptr; 2700f384594dSTobias Grosser PPCGGen->types.n = 0; 2701f384594dSTobias Grosser PPCGGen->types.name = nullptr; 2702f384594dSTobias Grosser PPCGGen->sizes = nullptr; 2703f384594dSTobias Grosser PPCGGen->used_sizes = nullptr; 2704f384594dSTobias Grosser PPCGGen->kernel_id = 0; 2705f384594dSTobias Grosser 2706f384594dSTobias Grosser // Set scheduling strategy to same strategy PPCG is using. 2707f384594dSTobias Grosser isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true); 2708f384594dSTobias Grosser isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true); 27092341fe9eSTobias Grosser isl_options_set_schedule_whole_component(PPCGGen->ctx, false); 2710f384594dSTobias Grosser 2711f384594dSTobias Grosser isl_schedule *Schedule = get_schedule(PPCGGen); 2712f384594dSTobias Grosser 2713aef5196fSTobias Grosser int has_permutable = has_any_permutable_node(Schedule); 2714aef5196fSTobias Grosser 271569b46751STobias Grosser if (!has_permutable || has_permutable < 0) { 2716aef5196fSTobias Grosser Schedule = isl_schedule_free(Schedule); 271769b46751STobias Grosser } else { 2718aef5196fSTobias Grosser Schedule = map_to_device(PPCGGen, Schedule); 271969b46751STobias Grosser PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule)); 272069b46751STobias Grosser } 2721aef5196fSTobias Grosser 2722f384594dSTobias Grosser if (DumpSchedule) { 2723f384594dSTobias Grosser isl_printer *P = isl_printer_to_str(S->getIslCtx()); 2724f384594dSTobias Grosser P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK); 2725f384594dSTobias Grosser P = isl_printer_print_str(P, "Schedule\n"); 2726f384594dSTobias Grosser P = isl_printer_print_str(P, "========\n"); 2727f384594dSTobias Grosser if (Schedule) 2728f384594dSTobias Grosser P = isl_printer_print_schedule(P, Schedule); 2729f384594dSTobias Grosser else 2730f384594dSTobias Grosser P = isl_printer_print_str(P, "No schedule found\n"); 2731f384594dSTobias Grosser 2732f384594dSTobias Grosser printf("%s\n", isl_printer_get_str(P)); 2733f384594dSTobias Grosser isl_printer_free(P); 2734f384594dSTobias Grosser } 2735f384594dSTobias Grosser 273669b46751STobias Grosser if (DumpCode) { 273769b46751STobias Grosser printf("Code\n"); 273869b46751STobias Grosser printf("====\n"); 273969b46751STobias Grosser if (PPCGGen->tree) 274069b46751STobias Grosser printGPUTree(PPCGGen->tree, PPCGProg); 274169b46751STobias Grosser else 274269b46751STobias Grosser printf("No code generated\n"); 274369b46751STobias Grosser } 274469b46751STobias Grosser 2745f384594dSTobias Grosser isl_schedule_free(Schedule); 2746f384594dSTobias Grosser 2747f384594dSTobias Grosser return PPCGGen; 2748f384594dSTobias Grosser } 2749f384594dSTobias Grosser 2750f384594dSTobias Grosser /// Free gpu_gen structure. 2751f384594dSTobias Grosser /// 2752f384594dSTobias Grosser /// @param PPCGGen The ppcg_gen object to free. 2753f384594dSTobias Grosser void freePPCGGen(gpu_gen *PPCGGen) { 2754f384594dSTobias Grosser isl_ast_node_free(PPCGGen->tree); 2755f384594dSTobias Grosser isl_union_map_free(PPCGGen->sizes); 2756f384594dSTobias Grosser isl_union_map_free(PPCGGen->used_sizes); 2757f384594dSTobias Grosser free(PPCGGen); 2758f384594dSTobias Grosser } 2759f384594dSTobias Grosser 2760b307ed4dSTobias Grosser /// Free the options in the ppcg scop structure. 2761b307ed4dSTobias Grosser /// 2762b307ed4dSTobias Grosser /// ppcg is not freeing these options for us. To avoid leaks we do this 2763b307ed4dSTobias Grosser /// ourselves. 2764b307ed4dSTobias Grosser /// 2765b307ed4dSTobias Grosser /// @param PPCGScop The scop referencing the options to free. 2766b307ed4dSTobias Grosser void freeOptions(ppcg_scop *PPCGScop) { 2767b307ed4dSTobias Grosser free(PPCGScop->options->debug); 2768b307ed4dSTobias Grosser PPCGScop->options->debug = nullptr; 2769b307ed4dSTobias Grosser free(PPCGScop->options); 2770b307ed4dSTobias Grosser PPCGScop->options = nullptr; 2771b307ed4dSTobias Grosser } 2772b307ed4dSTobias Grosser 277382f2af35STobias Grosser /// Approximate the number of points in the set. 277482f2af35STobias Grosser /// 277582f2af35STobias Grosser /// This function returns an ast expression that overapproximates the number 277682f2af35STobias Grosser /// of points in an isl set through the rectangular hull surrounding this set. 277782f2af35STobias Grosser /// 277882f2af35STobias Grosser /// @param Set The set to count. 277982f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 278082f2af35STobias Grosser /// expression. 278182f2af35STobias Grosser /// 278282f2af35STobias Grosser /// @returns An approximation of the number of points in the set. 278382f2af35STobias Grosser __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set, 278482f2af35STobias Grosser __isl_keep isl_ast_build *Build) { 278582f2af35STobias Grosser 278682f2af35STobias Grosser isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1); 278782f2af35STobias Grosser auto *Expr = isl_ast_expr_from_val(isl_val_copy(One)); 278882f2af35STobias Grosser 278982f2af35STobias Grosser isl_space *Space = isl_set_get_space(Set); 279082f2af35STobias Grosser Space = isl_space_params(Space); 279182f2af35STobias Grosser auto *Univ = isl_set_universe(Space); 279282f2af35STobias Grosser isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One); 279382f2af35STobias Grosser 279482f2af35STobias Grosser for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) { 279582f2af35STobias Grosser isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i); 279682f2af35STobias Grosser isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i); 279782f2af35STobias Grosser isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min); 279882f2af35STobias Grosser DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff)); 279982f2af35STobias Grosser auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize); 280082f2af35STobias Grosser Expr = isl_ast_expr_mul(Expr, DimSizeExpr); 280182f2af35STobias Grosser } 280282f2af35STobias Grosser 280382f2af35STobias Grosser isl_set_free(Set); 280482f2af35STobias Grosser isl_pw_aff_free(OneAff); 280582f2af35STobias Grosser 280682f2af35STobias Grosser return Expr; 280782f2af35STobias Grosser } 280882f2af35STobias Grosser 280982f2af35STobias Grosser /// Approximate a number of dynamic instructions executed by a given 281082f2af35STobias Grosser /// statement. 281182f2af35STobias Grosser /// 281282f2af35STobias Grosser /// @param Stmt The statement for which to compute the number of dynamic 281382f2af35STobias Grosser /// instructions. 281482f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 281582f2af35STobias Grosser /// expression. 281682f2af35STobias Grosser /// @returns An approximation of the number of dynamic instructions executed 281782f2af35STobias Grosser /// by @p Stmt. 281882f2af35STobias Grosser __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt, 281982f2af35STobias Grosser __isl_keep isl_ast_build *Build) { 282082f2af35STobias Grosser auto Iterations = approxPointsInSet(Stmt.getDomain(), Build); 282182f2af35STobias Grosser 282282f2af35STobias Grosser long InstCount = 0; 282382f2af35STobias Grosser 282482f2af35STobias Grosser if (Stmt.isBlockStmt()) { 282582f2af35STobias Grosser auto *BB = Stmt.getBasicBlock(); 282682f2af35STobias Grosser InstCount = std::distance(BB->begin(), BB->end()); 282782f2af35STobias Grosser } else { 282882f2af35STobias Grosser auto *R = Stmt.getRegion(); 282982f2af35STobias Grosser 283082f2af35STobias Grosser for (auto *BB : R->blocks()) { 283182f2af35STobias Grosser InstCount += std::distance(BB->begin(), BB->end()); 283282f2af35STobias Grosser } 283382f2af35STobias Grosser } 283482f2af35STobias Grosser 283582f2af35STobias Grosser isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount); 283682f2af35STobias Grosser auto *InstExpr = isl_ast_expr_from_val(InstVal); 283782f2af35STobias Grosser return isl_ast_expr_mul(InstExpr, Iterations); 283882f2af35STobias Grosser } 283982f2af35STobias Grosser 284082f2af35STobias Grosser /// Approximate dynamic instructions executed in scop. 284182f2af35STobias Grosser /// 284282f2af35STobias Grosser /// @param S The scop for which to approximate dynamic instructions. 284382f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 284482f2af35STobias Grosser /// expression. 284582f2af35STobias Grosser /// @returns An approximation of the number of dynamic instructions executed 284682f2af35STobias Grosser /// in @p S. 284782f2af35STobias Grosser __isl_give isl_ast_expr * 284882f2af35STobias Grosser getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) { 284982f2af35STobias Grosser isl_ast_expr *Instructions; 285082f2af35STobias Grosser 285182f2af35STobias Grosser isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0); 285282f2af35STobias Grosser Instructions = isl_ast_expr_from_val(Zero); 285382f2af35STobias Grosser 285482f2af35STobias Grosser for (ScopStmt &Stmt : S) { 285582f2af35STobias Grosser isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build); 285682f2af35STobias Grosser Instructions = isl_ast_expr_add(Instructions, StmtInstructions); 285782f2af35STobias Grosser } 285882f2af35STobias Grosser return Instructions; 285982f2af35STobias Grosser } 286082f2af35STobias Grosser 286182f2af35STobias Grosser /// Create a check that ensures sufficient compute in scop. 286282f2af35STobias Grosser /// 286382f2af35STobias Grosser /// @param S The scop for which to ensure sufficient compute. 286482f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 286582f2af35STobias Grosser /// expression. 286682f2af35STobias Grosser /// @returns An expression that evaluates to TRUE in case of sufficient 286782f2af35STobias Grosser /// compute and to FALSE, otherwise. 286882f2af35STobias Grosser __isl_give isl_ast_expr * 286982f2af35STobias Grosser createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) { 287082f2af35STobias Grosser auto Iterations = getNumberOfIterations(S, Build); 287182f2af35STobias Grosser auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute); 287282f2af35STobias Grosser auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal); 287382f2af35STobias Grosser return isl_ast_expr_ge(Iterations, MinComputeExpr); 287482f2af35STobias Grosser } 287582f2af35STobias Grosser 2876f291c8d5SSiddharth Bhat /// Check if the basic block contains a function we cannot codegen for GPU 2877f291c8d5SSiddharth Bhat /// kernels. 2878f291c8d5SSiddharth Bhat /// 2879f291c8d5SSiddharth Bhat /// If this basic block does something with a `Function` other than calling 2880f291c8d5SSiddharth Bhat /// a function that we support in a kernel, return true. 2881f291c8d5SSiddharth Bhat bool containsInvalidKernelFunctionInBllock(const BasicBlock *BB) { 2882f291c8d5SSiddharth Bhat for (const Instruction &Inst : *BB) { 2883f291c8d5SSiddharth Bhat const CallInst *Call = dyn_cast<CallInst>(&Inst); 2884f291c8d5SSiddharth Bhat if (Call && isValidFunctionInKernel(Call->getCalledFunction())) { 2885f291c8d5SSiddharth Bhat continue; 2886f291c8d5SSiddharth Bhat } 2887f291c8d5SSiddharth Bhat 2888bccaea57SSiddharth Bhat for (Value *SrcVal : Inst.operands()) { 2889bccaea57SSiddharth Bhat PointerType *p = dyn_cast<PointerType>(SrcVal->getType()); 2890bccaea57SSiddharth Bhat if (!p) 2891bccaea57SSiddharth Bhat continue; 2892bccaea57SSiddharth Bhat if (isa<FunctionType>(p->getElementType())) 2893bccaea57SSiddharth Bhat return true; 2894bccaea57SSiddharth Bhat } 2895f291c8d5SSiddharth Bhat } 2896bccaea57SSiddharth Bhat return false; 2897bccaea57SSiddharth Bhat } 2898bccaea57SSiddharth Bhat 2899f291c8d5SSiddharth Bhat /// Return whether the Scop S uses functions in a way that we do not support. 2900f291c8d5SSiddharth Bhat bool containsInvalidKernelFunction(const Scop &S) { 2901bccaea57SSiddharth Bhat for (auto &Stmt : S) { 2902bccaea57SSiddharth Bhat if (Stmt.isBlockStmt()) { 2903f291c8d5SSiddharth Bhat if (containsInvalidKernelFunctionInBllock(Stmt.getBasicBlock())) 2904bccaea57SSiddharth Bhat return true; 2905bccaea57SSiddharth Bhat } else { 2906bccaea57SSiddharth Bhat assert(Stmt.isRegionStmt() && 2907bccaea57SSiddharth Bhat "Stmt was neither block nor region statement"); 2908bccaea57SSiddharth Bhat for (const BasicBlock *BB : Stmt.getRegion()->blocks()) 2909f291c8d5SSiddharth Bhat if (containsInvalidKernelFunctionInBllock(BB)) 2910bccaea57SSiddharth Bhat return true; 2911bccaea57SSiddharth Bhat } 2912bccaea57SSiddharth Bhat } 2913bccaea57SSiddharth Bhat return false; 2914bccaea57SSiddharth Bhat } 2915bccaea57SSiddharth Bhat 291638fc0aedSTobias Grosser /// Generate code for a given GPU AST described by @p Root. 291738fc0aedSTobias Grosser /// 291832837fe3STobias Grosser /// @param Root An isl_ast_node pointing to the root of the GPU AST. 291932837fe3STobias Grosser /// @param Prog The GPU Program to generate code for. 292032837fe3STobias Grosser void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) { 292138fc0aedSTobias Grosser ScopAnnotator Annotator; 292238fc0aedSTobias Grosser Annotator.buildAliasScopes(*S); 292338fc0aedSTobias Grosser 292438fc0aedSTobias Grosser Region *R = &S->getRegion(); 292538fc0aedSTobias Grosser 292638fc0aedSTobias Grosser simplifyRegion(R, DT, LI, RI); 292738fc0aedSTobias Grosser 292838fc0aedSTobias Grosser BasicBlock *EnteringBB = R->getEnteringBlock(); 292938fc0aedSTobias Grosser 293038fc0aedSTobias Grosser PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator); 293138fc0aedSTobias Grosser 293238fc0aedSTobias Grosser // Only build the run-time condition and parameters _after_ having 293338fc0aedSTobias Grosser // introduced the conditional branch. This is important as the conditional 293438fc0aedSTobias Grosser // branch will guard the original scop from new induction variables that 293538fc0aedSTobias Grosser // the SCEVExpander may introduce while code generating the parameters and 293638fc0aedSTobias Grosser // which may introduce scalar dependences that prevent us from correctly 293738fc0aedSTobias Grosser // code generating this scop. 293803346c27SSiddharth Bhat BBPair StartExitBlocks; 293903346c27SSiddharth Bhat BranchInst *CondBr = nullptr; 294003346c27SSiddharth Bhat std::tie(StartExitBlocks, CondBr) = 29412d950f36SPhilip Pfaffe executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI); 2942256070d8SAndreas Simbuerger BasicBlock *StartBlock = std::get<0>(StartExitBlocks); 294338fc0aedSTobias Grosser 294403346c27SSiddharth Bhat assert(CondBr && "CondBr not initialized by executeScopConditionally"); 294503346c27SSiddharth Bhat 29462d950f36SPhilip Pfaffe GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S, 294717f01968SSiddharth Bhat StartBlock, Prog, Runtime, Architecture); 2948acf80064SEli Friedman 294938fc0aedSTobias Grosser // TODO: Handle LICM 295038fc0aedSTobias Grosser auto SplitBlock = StartBlock->getSinglePredecessor(); 295138fc0aedSTobias Grosser Builder.SetInsertPoint(SplitBlock->getTerminator()); 295238fc0aedSTobias Grosser NodeBuilder.addParameters(S->getContext()); 2953cb1aef8dSTobias Grosser 2954cb1aef8dSTobias Grosser isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx()); 29552b852e2eSPhilip Pfaffe isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build); 295682f2af35STobias Grosser isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build); 295782f2af35STobias Grosser Condition = isl_ast_expr_and(Condition, SufficientCompute); 2958cb1aef8dSTobias Grosser isl_ast_build_free(Build); 2959cb1aef8dSTobias Grosser 2960cb1aef8dSTobias Grosser Value *RTC = NodeBuilder.createRTC(Condition); 2961cb1aef8dSTobias Grosser Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC); 2962cb1aef8dSTobias Grosser 296338fc0aedSTobias Grosser Builder.SetInsertPoint(&*StartBlock->begin()); 2964fa7b0802STobias Grosser 2965fa7b0802STobias Grosser NodeBuilder.initializeAfterRTH(); 2966*233d717eSSiddharth Bhat NodeBuilder.preloadInvariantLoads(); 296738fc0aedSTobias Grosser NodeBuilder.create(Root); 29688ed5e599STobias Grosser NodeBuilder.finalize(); 29695857b701STobias Grosser 2970bc653f20STobias Grosser /// In case a sequential kernel has more surrounding loops as any parallel 2971bc653f20STobias Grosser /// kernel, the SCoP is probably mostly sequential. Hence, there is no 2972de244eb4STobias Grosser /// point in running it on a GPU. 2973bc653f20STobias Grosser if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel) 297403346c27SSiddharth Bhat CondBr->setOperand(0, Builder.getFalse()); 2975bc653f20STobias Grosser 29765857b701STobias Grosser if (!NodeBuilder.BuildSuccessful) 297703346c27SSiddharth Bhat CondBr->setOperand(0, Builder.getFalse()); 297838fc0aedSTobias Grosser } 297938fc0aedSTobias Grosser 2980e938517eSTobias Grosser bool runOnScop(Scop &CurrentScop) override { 2981e938517eSTobias Grosser S = &CurrentScop; 298238fc0aedSTobias Grosser LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 298338fc0aedSTobias Grosser DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 298438fc0aedSTobias Grosser SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 29857b5a4dfdSTobias Grosser DL = &S->getRegion().getEntry()->getModule()->getDataLayout(); 298638fc0aedSTobias Grosser RI = &getAnalysis<RegionInfoPass>().getRegionInfo(); 2987e938517eSTobias Grosser 2988f291c8d5SSiddharth Bhat // We currently do not support functions other than intrinsics inside 2989f291c8d5SSiddharth Bhat // kernels, as code generation will need to offload function calls to the 2990f291c8d5SSiddharth Bhat // kernel. This may lead to a kernel trying to call a function on the host. 2991bccaea57SSiddharth Bhat // This also allows us to prevent codegen from trying to take the 2992bccaea57SSiddharth Bhat // address of an intrinsic function to send to the kernel. 2993f291c8d5SSiddharth Bhat if (containsInvalidKernelFunction(CurrentScop)) { 2994f291c8d5SSiddharth Bhat DEBUG( 2995f291c8d5SSiddharth Bhat dbgs() 2996f291c8d5SSiddharth Bhat << "Scop contains function which cannot be materialised in a GPU " 2997f291c8d5SSiddharth Bhat "kernel. Bailing out.\n";); 2998bccaea57SSiddharth Bhat return false; 2999f291c8d5SSiddharth Bhat } 3000bccaea57SSiddharth Bhat 3001e938517eSTobias Grosser auto PPCGScop = createPPCGScop(); 3002e938517eSTobias Grosser auto PPCGProg = createPPCGProg(PPCGScop); 3003f384594dSTobias Grosser auto PPCGGen = generateGPU(PPCGScop, PPCGProg); 300438fc0aedSTobias Grosser 300502ca346eSSingapuram Sanjay Srivallabh if (PPCGGen->tree) { 300632837fe3STobias Grosser generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg); 300702ca346eSSingapuram Sanjay Srivallabh CurrentScop.markAsToBeSkipped(); 300802ca346eSSingapuram Sanjay Srivallabh } 300938fc0aedSTobias Grosser 3010b307ed4dSTobias Grosser freeOptions(PPCGScop); 3011f384594dSTobias Grosser freePPCGGen(PPCGGen); 3012e938517eSTobias Grosser gpu_prog_free(PPCGProg); 3013e938517eSTobias Grosser ppcg_scop_free(PPCGScop); 3014e938517eSTobias Grosser 3015e938517eSTobias Grosser return true; 3016e938517eSTobias Grosser } 30179dfe4e7cSTobias Grosser 30189dfe4e7cSTobias Grosser void printScop(raw_ostream &, Scop &) const override {} 30199dfe4e7cSTobias Grosser 30209dfe4e7cSTobias Grosser void getAnalysisUsage(AnalysisUsage &AU) const override { 30219dfe4e7cSTobias Grosser AU.addRequired<DominatorTreeWrapperPass>(); 30229dfe4e7cSTobias Grosser AU.addRequired<RegionInfoPass>(); 30239dfe4e7cSTobias Grosser AU.addRequired<ScalarEvolutionWrapperPass>(); 30245cc87e3aSPhilip Pfaffe AU.addRequired<ScopDetectionWrapperPass>(); 30259dfe4e7cSTobias Grosser AU.addRequired<ScopInfoRegionPass>(); 30269dfe4e7cSTobias Grosser AU.addRequired<LoopInfoWrapperPass>(); 30279dfe4e7cSTobias Grosser 30289dfe4e7cSTobias Grosser AU.addPreserved<AAResultsWrapperPass>(); 30299dfe4e7cSTobias Grosser AU.addPreserved<BasicAAWrapperPass>(); 30309dfe4e7cSTobias Grosser AU.addPreserved<LoopInfoWrapperPass>(); 30319dfe4e7cSTobias Grosser AU.addPreserved<DominatorTreeWrapperPass>(); 30329dfe4e7cSTobias Grosser AU.addPreserved<GlobalsAAWrapperPass>(); 30335cc87e3aSPhilip Pfaffe AU.addPreserved<ScopDetectionWrapperPass>(); 30349dfe4e7cSTobias Grosser AU.addPreserved<ScalarEvolutionWrapperPass>(); 30359dfe4e7cSTobias Grosser AU.addPreserved<SCEVAAWrapperPass>(); 30369dfe4e7cSTobias Grosser 30379dfe4e7cSTobias Grosser // FIXME: We do not yet add regions for the newly generated code to the 30389dfe4e7cSTobias Grosser // region tree. 30399dfe4e7cSTobias Grosser AU.addPreserved<RegionInfoPass>(); 30409dfe4e7cSTobias Grosser AU.addPreserved<ScopInfoRegionPass>(); 30419dfe4e7cSTobias Grosser } 30429dfe4e7cSTobias Grosser }; 304324222c73STobias Grosser } // namespace 30449dfe4e7cSTobias Grosser 30459dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1; 30469dfe4e7cSTobias Grosser 304717f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) { 304817f01968SSiddharth Bhat PPCGCodeGeneration *generator = new PPCGCodeGeneration(); 304917f01968SSiddharth Bhat generator->Runtime = Runtime; 305017f01968SSiddharth Bhat generator->Architecture = Arch; 305117f01968SSiddharth Bhat return generator; 305217f01968SSiddharth Bhat } 30539dfe4e7cSTobias Grosser 30549dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg", 30559dfe4e7cSTobias Grosser "Polly - Apply PPCG translation to SCOP", false, false) 30569dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo); 30579dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 30589dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 30599dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 30609dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 30615cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass); 30629dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg", 30639dfe4e7cSTobias Grosser "Polly - Apply PPCG translation to SCOP", false, false) 3064