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 /// 132*edfef5aeSSiddharth Bhat /// We currently derive kill information for: 133*edfef5aeSSiddharth Bhat /// 1. phi nodes. PHI nodes are not alive outside the scop and can 134*edfef5aeSSiddharth Bhat /// consequently all be killed. 135*edfef5aeSSiddharth Bhat /// 2. Scalar arrays that are not used outside the Scop. This is 136*edfef5aeSSiddharth Bhat /// checked by `isScalarUsesContainedInScop`. 137*edfef5aeSSiddharth Bhat /// [params] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] } 138a82f2d26SSiddharth Bhat isl::union_map TaggedMustKills; 139a82f2d26SSiddharth Bhat 140a82f2d26SSiddharth Bhat MustKillsInfo() : KillsSchedule(nullptr), TaggedMustKills(nullptr){}; 141a82f2d26SSiddharth Bhat }; 142a82f2d26SSiddharth Bhat 143761e5b93SSiddharth Bhat /// Check if SAI's uses are entirely contained within Scop S. 144761e5b93SSiddharth Bhat /// If a scalar is used only with a Scop, we are free to kill it, as no data 145761e5b93SSiddharth Bhat /// can flow in/out of the value any more. 146761e5b93SSiddharth Bhat /// @see computeMustKillsInfo 147761e5b93SSiddharth Bhat static bool isScalarUsesContainedInScop(const Scop &S, 148761e5b93SSiddharth Bhat const ScopArrayInfo *SAI) { 149761e5b93SSiddharth Bhat assert(SAI->isValueKind() && "this function only deals with scalars." 150761e5b93SSiddharth Bhat " Dealing with arrays required alias analysis"); 151761e5b93SSiddharth Bhat 152761e5b93SSiddharth Bhat const Region &R = S.getRegion(); 153761e5b93SSiddharth Bhat for (User *U : SAI->getBasePtr()->users()) { 154761e5b93SSiddharth Bhat Instruction *I = dyn_cast<Instruction>(U); 155761e5b93SSiddharth Bhat assert(I && "invalid user of scop array info"); 156761e5b93SSiddharth Bhat if (!R.contains(I)) 157761e5b93SSiddharth Bhat return false; 158761e5b93SSiddharth Bhat } 159761e5b93SSiddharth Bhat return true; 160761e5b93SSiddharth Bhat } 161761e5b93SSiddharth Bhat 162a82f2d26SSiddharth Bhat /// Compute must-kills needed to enable live range reordering with PPCG. 163a82f2d26SSiddharth Bhat /// 164a82f2d26SSiddharth Bhat /// @params S The Scop to compute live range reordering information 165a82f2d26SSiddharth Bhat /// @returns live range reordering information that can be used to setup 166a82f2d26SSiddharth Bhat /// PPCG. 167a82f2d26SSiddharth Bhat static MustKillsInfo computeMustKillsInfo(const Scop &S) { 168a82f2d26SSiddharth Bhat const isl::space ParamSpace(isl::manage(S.getParamSpace())); 169a82f2d26SSiddharth Bhat MustKillsInfo Info; 170a82f2d26SSiddharth Bhat 171761e5b93SSiddharth Bhat // 1. Collect all ScopArrayInfo that satisfy *any* of the criteria: 172761e5b93SSiddharth Bhat // 1.1 phi nodes in scop. 173761e5b93SSiddharth Bhat // 1.2 scalars that are only used within the scop 174a82f2d26SSiddharth Bhat SmallVector<isl::id, 4> KillMemIds; 175a82f2d26SSiddharth Bhat for (ScopArrayInfo *SAI : S.arrays()) { 176761e5b93SSiddharth Bhat if (SAI->isPHIKind() || 177761e5b93SSiddharth Bhat (SAI->isValueKind() && isScalarUsesContainedInScop(S, SAI))) 178a82f2d26SSiddharth Bhat KillMemIds.push_back(isl::manage(SAI->getBasePtrId())); 179a82f2d26SSiddharth Bhat } 180a82f2d26SSiddharth Bhat 181a82f2d26SSiddharth Bhat Info.TaggedMustKills = isl::union_map::empty(isl::space(ParamSpace)); 182a82f2d26SSiddharth Bhat 183a82f2d26SSiddharth Bhat // Initialising KillsSchedule to `isl_set_empty` creates an empty node in the 184a82f2d26SSiddharth Bhat // schedule: 185a82f2d26SSiddharth Bhat // - filter: "[control] -> { }" 186a82f2d26SSiddharth Bhat // So, we choose to not create this to keep the output a little nicer, 187a82f2d26SSiddharth Bhat // at the cost of some code complexity. 188a82f2d26SSiddharth Bhat Info.KillsSchedule = nullptr; 189a82f2d26SSiddharth Bhat 190*edfef5aeSSiddharth Bhat for (isl::id &ToKillId : KillMemIds) { 191a82f2d26SSiddharth Bhat isl::id KillStmtId = isl::id::alloc( 192*edfef5aeSSiddharth Bhat S.getIslCtx(), 193*edfef5aeSSiddharth Bhat std::string("SKill_phantom_").append(ToKillId.get_name()), nullptr); 194a82f2d26SSiddharth Bhat 195a82f2d26SSiddharth Bhat // NOTE: construction of tagged_must_kill: 196a82f2d26SSiddharth Bhat // 2. We need to construct a map: 197*edfef5aeSSiddharth Bhat // [param] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] } 198a82f2d26SSiddharth Bhat // To construct this, we use `isl_map_domain_product` on 2 maps`: 199*edfef5aeSSiddharth Bhat // 2a. StmtToScalar: 200*edfef5aeSSiddharth Bhat // [param] -> { Stmt_phantom[] -> scalar_to_kill[] } 201*edfef5aeSSiddharth Bhat // 2b. PhantomRefToScalar: 202*edfef5aeSSiddharth Bhat // [param] -> { ref_phantom[] -> scalar_to_kill[] } 203a82f2d26SSiddharth Bhat // 204a82f2d26SSiddharth Bhat // Combining these with `isl_map_domain_product` gives us 205a82f2d26SSiddharth Bhat // TaggedMustKill: 206*edfef5aeSSiddharth Bhat // [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] } 207a82f2d26SSiddharth Bhat 208*edfef5aeSSiddharth Bhat // 2a. [param] -> { Stmt[] -> scalar_to_kill[] } 209*edfef5aeSSiddharth Bhat isl::map StmtToScalar = isl::map::universe(isl::space(ParamSpace)); 210*edfef5aeSSiddharth Bhat StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::in, isl::id(KillStmtId)); 211*edfef5aeSSiddharth Bhat StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::out, isl::id(ToKillId)); 212a82f2d26SSiddharth Bhat 213a82f2d26SSiddharth Bhat isl::id PhantomRefId = isl::id::alloc( 214*edfef5aeSSiddharth Bhat S.getIslCtx(), std::string("ref_phantom") + ToKillId.get_name(), 215*edfef5aeSSiddharth Bhat nullptr); 216a82f2d26SSiddharth Bhat 217*edfef5aeSSiddharth Bhat // 2b. [param] -> { phantom_ref[] -> scalar_to_kill[] } 218*edfef5aeSSiddharth Bhat isl::map PhantomRefToScalar = isl::map::universe(isl::space(ParamSpace)); 219*edfef5aeSSiddharth Bhat PhantomRefToScalar = 220*edfef5aeSSiddharth Bhat PhantomRefToScalar.set_tuple_id(isl::dim::in, PhantomRefId); 221*edfef5aeSSiddharth Bhat PhantomRefToScalar = 222*edfef5aeSSiddharth Bhat PhantomRefToScalar.set_tuple_id(isl::dim::out, ToKillId); 223a82f2d26SSiddharth Bhat 224*edfef5aeSSiddharth Bhat // 2. [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] } 225*edfef5aeSSiddharth Bhat isl::map TaggedMustKill = StmtToScalar.domain_product(PhantomRefToScalar); 226a82f2d26SSiddharth Bhat Info.TaggedMustKills = Info.TaggedMustKills.unite(TaggedMustKill); 227a82f2d26SSiddharth Bhat 228a82f2d26SSiddharth Bhat // 3. Create the kill schedule of the form: 229a82f2d26SSiddharth Bhat // "[param] -> { Stmt_phantom[] }" 230a82f2d26SSiddharth Bhat // Then add this to Info.KillsSchedule. 231a82f2d26SSiddharth Bhat isl::space KillStmtSpace = ParamSpace; 232a82f2d26SSiddharth Bhat KillStmtSpace = KillStmtSpace.set_tuple_id(isl::dim::set, KillStmtId); 233a82f2d26SSiddharth Bhat isl::union_set KillStmtDomain = isl::set::universe(KillStmtSpace); 234a82f2d26SSiddharth Bhat 235a82f2d26SSiddharth Bhat isl::schedule KillSchedule = isl::schedule::from_domain(KillStmtDomain); 236a82f2d26SSiddharth Bhat if (Info.KillsSchedule) 237a82f2d26SSiddharth Bhat Info.KillsSchedule = Info.KillsSchedule.set(KillSchedule); 238a82f2d26SSiddharth Bhat else 239a82f2d26SSiddharth Bhat Info.KillsSchedule = KillSchedule; 240a82f2d26SSiddharth Bhat } 241a82f2d26SSiddharth Bhat 242a82f2d26SSiddharth Bhat return Info; 243a82f2d26SSiddharth Bhat } 244a82f2d26SSiddharth Bhat 24560c60025STobias Grosser /// Create the ast expressions for a ScopStmt. 24660c60025STobias Grosser /// 24760c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each 24860c60025STobias Grosser /// of the scheduled ScopStmts. 24960c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt( 250edb885cbSTobias Grosser void *StmtT, isl_ast_build *Build, 25160c60025STobias Grosser isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA, 25260c60025STobias Grosser isl_id *Id, void *User), 25360c60025STobias Grosser void *UserIndex, 25460c60025STobias Grosser isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User), 255edb885cbSTobias Grosser void *UserExpr) { 25660c60025STobias Grosser 257edb885cbSTobias Grosser ScopStmt *Stmt = (ScopStmt *)StmtT; 25860c60025STobias Grosser 259edb885cbSTobias Grosser isl_ctx *Ctx; 260edb885cbSTobias Grosser 261edb885cbSTobias Grosser if (!Stmt || !Build) 262edb885cbSTobias Grosser return NULL; 263edb885cbSTobias Grosser 264edb885cbSTobias Grosser Ctx = isl_ast_build_get_ctx(Build); 265edb885cbSTobias Grosser isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0); 266edb885cbSTobias Grosser 267edb885cbSTobias Grosser for (MemoryAccess *Acc : *Stmt) { 268edb885cbSTobias Grosser isl_map *AddrFunc = Acc->getAddressFunction(); 269edb885cbSTobias Grosser AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain()); 270edb885cbSTobias Grosser isl_id *RefId = Acc->getId(); 271edb885cbSTobias Grosser isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc); 272edb885cbSTobias Grosser isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA); 273edb885cbSTobias Grosser MPA = isl_multi_pw_aff_coalesce(MPA); 274edb885cbSTobias Grosser MPA = FunctionIndex(MPA, RefId, UserIndex); 275edb885cbSTobias Grosser isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA); 276edb885cbSTobias Grosser Access = FunctionExpr(Access, RefId, UserExpr); 277edb885cbSTobias Grosser RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access); 278edb885cbSTobias Grosser } 279edb885cbSTobias Grosser 280edb885cbSTobias Grosser return RefToExpr; 28160c60025STobias Grosser } 282f384594dSTobias Grosser 283a90be207SSiddharth Bhat /// Given a LLVM Type, compute its size in bytes, 284a90be207SSiddharth Bhat static int computeSizeInBytes(const Type *T) { 285a90be207SSiddharth Bhat int bytes = T->getPrimitiveSizeInBits() / 8; 286a90be207SSiddharth Bhat if (bytes == 0) 287a90be207SSiddharth Bhat bytes = T->getScalarSizeInBits() / 8; 288a90be207SSiddharth Bhat return bytes; 289a90be207SSiddharth Bhat } 290a90be207SSiddharth Bhat 29138fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST. 29238fc0aedSTobias Grosser /// 29338fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which 294a6d48f59SMichael Kruse /// generates code for general-purpose AST nodes, with special functionality 29538fc0aedSTobias Grosser /// for generating GPU specific user nodes. 29638fc0aedSTobias Grosser /// 29738fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser 29838fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder { 29938fc0aedSTobias Grosser public: 3002d950f36SPhilip Pfaffe GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, 30138fc0aedSTobias Grosser const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE, 302acf80064SEli Friedman DominatorTree &DT, Scop &S, BasicBlock *StartBlock, 30317f01968SSiddharth Bhat gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch) 3042d950f36SPhilip Pfaffe : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock), 30517f01968SSiddharth Bhat Prog(Prog), Runtime(Runtime), Arch(Arch) { 306edb885cbSTobias Grosser getExprBuilder().setIDToSAI(&IDToSAI); 307edb885cbSTobias Grosser } 30838fc0aedSTobias Grosser 309fa7b0802STobias Grosser /// Create after-run-time-check initialization code. 310fa7b0802STobias Grosser void initializeAfterRTH(); 311fa7b0802STobias Grosser 312fa7b0802STobias Grosser /// Finalize the generated scop. 313fa7b0802STobias Grosser virtual void finalize(); 314fa7b0802STobias Grosser 3155857b701STobias Grosser /// Track if the full build process was successful. 3165857b701STobias Grosser /// 3175857b701STobias Grosser /// This value is set to false, if throughout the build process an error 3185857b701STobias Grosser /// occurred which prevents us from generating valid GPU code. 3195857b701STobias Grosser bool BuildSuccessful = true; 3205857b701STobias Grosser 321bc653f20STobias Grosser /// The maximal number of loops surrounding a sequential kernel. 322bc653f20STobias Grosser unsigned DeepestSequential = 0; 323bc653f20STobias Grosser 324bc653f20STobias Grosser /// The maximal number of loops surrounding a parallel kernel. 325bc653f20STobias Grosser unsigned DeepestParallel = 0; 326bc653f20STobias Grosser 32779f13b9aSSingapuram Sanjay Srivallabh /// Return the name to set for the ptx_kernel. 32879f13b9aSSingapuram Sanjay Srivallabh std::string getKernelFuncName(int Kernel_id); 32979f13b9aSSingapuram Sanjay Srivallabh 33038fc0aedSTobias Grosser private: 33174dc3cb4STobias Grosser /// A vector of array base pointers for which a new ScopArrayInfo was created. 33274dc3cb4STobias Grosser /// 33374dc3cb4STobias Grosser /// This vector is used to delete the ScopArrayInfo when it is not needed any 33474dc3cb4STobias Grosser /// more. 33574dc3cb4STobias Grosser std::vector<Value *> LocalArrays; 33674dc3cb4STobias Grosser 33713c78e4dSTobias Grosser /// A map from ScopArrays to their corresponding device allocations. 33813c78e4dSTobias Grosser std::map<ScopArrayInfo *, Value *> DeviceAllocations; 3397287aeddSTobias Grosser 340fa7b0802STobias Grosser /// The current GPU context. 341fa7b0802STobias Grosser Value *GPUContext; 342fa7b0802STobias Grosser 343b513b491STobias Grosser /// The set of isl_ids allocated in the kernel 344b513b491STobias Grosser std::vector<isl_id *> KernelIds; 345b513b491STobias Grosser 34632837fe3STobias Grosser /// A module containing GPU code. 34732837fe3STobias Grosser /// 34832837fe3STobias Grosser /// This pointer is only set in case we are currently generating GPU code. 34932837fe3STobias Grosser std::unique_ptr<Module> GPUModule; 35032837fe3STobias Grosser 35132837fe3STobias Grosser /// The GPU program we generate code for. 35232837fe3STobias Grosser gpu_prog *Prog; 35332837fe3STobias Grosser 35417f01968SSiddharth Bhat /// The GPU Runtime implementation to use (OpenCL or CUDA). 35517f01968SSiddharth Bhat GPURuntime Runtime; 35617f01968SSiddharth Bhat 35717f01968SSiddharth Bhat /// The GPU Architecture to target. 35817f01968SSiddharth Bhat GPUArch Arch; 35917f01968SSiddharth Bhat 360472f9654STobias Grosser /// Class to free isl_ids. 361472f9654STobias Grosser class IslIdDeleter { 362472f9654STobias Grosser public: 363472f9654STobias Grosser void operator()(__isl_take isl_id *Id) { isl_id_free(Id); }; 364472f9654STobias Grosser }; 365472f9654STobias Grosser 366472f9654STobias Grosser /// A set containing all isl_ids allocated in a GPU kernel. 367472f9654STobias Grosser /// 368472f9654STobias Grosser /// By releasing this set all isl_ids will be freed. 369472f9654STobias Grosser std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs; 370472f9654STobias Grosser 371edb885cbSTobias Grosser IslExprBuilder::IDToScopArrayInfoTy IDToSAI; 372edb885cbSTobias Grosser 37338fc0aedSTobias Grosser /// Create code for user-defined AST nodes. 37438fc0aedSTobias Grosser /// 37538fc0aedSTobias Grosser /// These AST nodes can be of type: 37638fc0aedSTobias Grosser /// 37738fc0aedSTobias Grosser /// - ScopStmt: A computational statement (TODO) 37838fc0aedSTobias Grosser /// - Kernel: A GPU kernel call (TODO) 37913c78e4dSTobias Grosser /// - Data-Transfer: A GPU <-> CPU data-transfer 3805260c041STobias Grosser /// - In-kernel synchronization 3815260c041STobias Grosser /// - In-kernel memory copy statement 38238fc0aedSTobias Grosser /// 3831fb9b64dSTobias Grosser /// @param UserStmt The ast node to generate code for. 3841fb9b64dSTobias Grosser virtual void createUser(__isl_take isl_ast_node *UserStmt); 38532837fe3STobias Grosser 38613c78e4dSTobias Grosser enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST }; 38713c78e4dSTobias Grosser 38813c78e4dSTobias Grosser /// Create code for a data transfer statement 38913c78e4dSTobias Grosser /// 39013c78e4dSTobias Grosser /// @param TransferStmt The data transfer statement. 39113c78e4dSTobias Grosser /// @param Direction The direction in which to transfer data. 39213c78e4dSTobias Grosser void createDataTransfer(__isl_take isl_ast_node *TransferStmt, 39313c78e4dSTobias Grosser enum DataDirection Direction); 39413c78e4dSTobias Grosser 395edb885cbSTobias Grosser /// Find llvm::Values referenced in GPU kernel. 396edb885cbSTobias Grosser /// 397edb885cbSTobias Grosser /// @param Kernel The kernel to scan for llvm::Values 398edb885cbSTobias Grosser /// 399f291c8d5SSiddharth Bhat /// @returns A pair, whose first element contains the set of values 400f291c8d5SSiddharth Bhat /// referenced by the kernel, and whose second element contains the 401f291c8d5SSiddharth Bhat /// set of functions referenced by the kernel. All functions in the 402f291c8d5SSiddharth Bhat /// second set satisfy isValidFunctionInKernel. 403f291c8d5SSiddharth Bhat std::pair<SetVector<Value *>, SetVector<Function *>> 404f291c8d5SSiddharth Bhat getReferencesInKernel(ppcg_kernel *Kernel); 405edb885cbSTobias Grosser 40679a947c2STobias Grosser /// Compute the sizes of the execution grid for a given kernel. 40779a947c2STobias Grosser /// 40879a947c2STobias Grosser /// @param Kernel The kernel to compute grid sizes for. 40979a947c2STobias Grosser /// 41079a947c2STobias Grosser /// @returns A tuple with grid sizes for X and Y dimension 41179a947c2STobias Grosser std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel); 41279a947c2STobias Grosser 413abed4969SSiddharth Bhat /// Creates a array that can be sent to the kernel on the device using a 414abed4969SSiddharth Bhat /// host pointer. This is required for managed memory, when we directly send 415abed4969SSiddharth Bhat /// host pointers to the device. 416abed4969SSiddharth Bhat /// \note 417abed4969SSiddharth Bhat /// This is to be used only with managed memory 418abed4969SSiddharth Bhat Value *getOrCreateManagedDeviceArray(gpu_array_info *Array, 419abed4969SSiddharth Bhat ScopArrayInfo *ArrayInfo); 420abed4969SSiddharth Bhat 42179a947c2STobias Grosser /// Compute the sizes of the thread blocks for a given kernel. 42279a947c2STobias Grosser /// 42379a947c2STobias Grosser /// @param Kernel The kernel to compute thread block sizes for. 42479a947c2STobias Grosser /// 42579a947c2STobias Grosser /// @returns A tuple with thread block sizes for X, Y, and Z dimensions. 42679a947c2STobias Grosser std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel); 42779a947c2STobias Grosser 428a90be207SSiddharth Bhat /// Store a specific kernel launch parameter in the array of kernel launch 429a90be207SSiddharth Bhat /// parameters. 430a90be207SSiddharth Bhat /// 431a90be207SSiddharth Bhat /// @param Parameters The list of parameters in which to store. 432a90be207SSiddharth Bhat /// @param Param The kernel launch parameter to store. 433a90be207SSiddharth Bhat /// @param Index The index in the parameter list, at which to store the 434a90be207SSiddharth Bhat /// parameter. 435a90be207SSiddharth Bhat void insertStoreParameter(Instruction *Parameters, Instruction *Param, 436a90be207SSiddharth Bhat int Index); 437a90be207SSiddharth Bhat 43879a947c2STobias Grosser /// Create kernel launch parameters. 43979a947c2STobias Grosser /// 44079a947c2STobias Grosser /// @param Kernel The kernel to create parameters for. 44179a947c2STobias Grosser /// @param F The kernel function that has been created. 44257693272STobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 44379a947c2STobias Grosser /// 44479a947c2STobias Grosser /// @returns A stack allocated array with pointers to the parameter 44579a947c2STobias Grosser /// values that are passed to the kernel. 44657693272STobias Grosser Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F, 44757693272STobias Grosser SetVector<Value *> SubtreeValues); 44879a947c2STobias Grosser 449b513b491STobias Grosser /// Create declarations for kernel variable. 450b513b491STobias Grosser /// 451b513b491STobias Grosser /// This includes shared memory declarations. 452b513b491STobias Grosser /// 453b513b491STobias Grosser /// @param Kernel The kernel definition to create variables for. 454b513b491STobias Grosser /// @param FN The function into which to generate the variables. 455b513b491STobias Grosser void createKernelVariables(ppcg_kernel *Kernel, Function *FN); 456b513b491STobias Grosser 457c1c6a2a6STobias Grosser /// Add CUDA annotations to module. 458c1c6a2a6STobias Grosser /// 459c1c6a2a6STobias Grosser /// Add a set of CUDA annotations that declares the maximal block dimensions 460c1c6a2a6STobias Grosser /// that will be used to execute the CUDA kernel. This allows the NVIDIA 461c1c6a2a6STobias Grosser /// PTX compiler to bound the number of allocated registers to ensure the 462c1c6a2a6STobias Grosser /// resulting kernel is known to run with up to as many block dimensions 463c1c6a2a6STobias Grosser /// as specified here. 464c1c6a2a6STobias Grosser /// 465c1c6a2a6STobias Grosser /// @param M The module to add the annotations to. 466c1c6a2a6STobias Grosser /// @param BlockDimX The size of block dimension X. 467c1c6a2a6STobias Grosser /// @param BlockDimY The size of block dimension Y. 468c1c6a2a6STobias Grosser /// @param BlockDimZ The size of block dimension Z. 469c1c6a2a6STobias Grosser void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY, 470c1c6a2a6STobias Grosser Value *BlockDimZ); 471c1c6a2a6STobias Grosser 47232837fe3STobias Grosser /// Create GPU kernel. 47332837fe3STobias Grosser /// 47432837fe3STobias Grosser /// Code generate the kernel described by @p KernelStmt. 47532837fe3STobias Grosser /// 47632837fe3STobias Grosser /// @param KernelStmt The ast node to generate kernel code for. 47732837fe3STobias Grosser void createKernel(__isl_take isl_ast_node *KernelStmt); 47832837fe3STobias Grosser 47913c78e4dSTobias Grosser /// Generate code that computes the size of an array. 48013c78e4dSTobias Grosser /// 48113c78e4dSTobias Grosser /// @param Array The array for which to compute a size. 48213c78e4dSTobias Grosser Value *getArraySize(gpu_array_info *Array); 48313c78e4dSTobias Grosser 484aaabbbf8STobias Grosser /// Generate code to compute the minimal offset at which an array is accessed. 485aaabbbf8STobias Grosser /// 486aaabbbf8STobias Grosser /// The offset of an array is the minimal array location accessed in a scop. 487aaabbbf8STobias Grosser /// 488aaabbbf8STobias Grosser /// Example: 489aaabbbf8STobias Grosser /// 490aaabbbf8STobias Grosser /// for (long i = 0; i < 100; i++) 491aaabbbf8STobias Grosser /// A[i + 42] += ... 492aaabbbf8STobias Grosser /// 493aaabbbf8STobias Grosser /// getArrayOffset(A) results in 42. 494aaabbbf8STobias Grosser /// 495aaabbbf8STobias Grosser /// @param Array The array for which to compute the offset. 496aaabbbf8STobias Grosser /// @returns An llvm::Value that contains the offset of the array. 497aaabbbf8STobias Grosser Value *getArrayOffset(gpu_array_info *Array); 498aaabbbf8STobias Grosser 49900bb5a99STobias Grosser /// Prepare the kernel arguments for kernel code generation 50000bb5a99STobias Grosser /// 50100bb5a99STobias Grosser /// @param Kernel The kernel to generate code for. 50200bb5a99STobias Grosser /// @param FN The function created for the kernel. 50300bb5a99STobias Grosser void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN); 50400bb5a99STobias Grosser 50532837fe3STobias Grosser /// Create kernel function. 50632837fe3STobias Grosser /// 50732837fe3STobias Grosser /// Create a kernel function located in a newly created module that can serve 50832837fe3STobias Grosser /// as target for device code generation. Set the Builder to point to the 50932837fe3STobias Grosser /// start block of this newly created function. 51032837fe3STobias Grosser /// 51132837fe3STobias Grosser /// @param Kernel The kernel to generate code for. 512edb885cbSTobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 513f291c8d5SSiddharth Bhat /// @param SubtreeFunctions The set of llvm::Functions referenced by this 514f291c8d5SSiddharth Bhat /// kernel. 515edb885cbSTobias Grosser void createKernelFunction(ppcg_kernel *Kernel, 516f291c8d5SSiddharth Bhat SetVector<Value *> &SubtreeValues, 517f291c8d5SSiddharth Bhat SetVector<Function *> &SubtreeFunctions); 51832837fe3STobias Grosser 51932837fe3STobias Grosser /// Create the declaration of a kernel function. 52032837fe3STobias Grosser /// 52132837fe3STobias Grosser /// The kernel function takes as arguments: 52232837fe3STobias Grosser /// 52332837fe3STobias Grosser /// - One i8 pointer for each external array reference used in the kernel. 524f6044bd0STobias Grosser /// - Host iterators 525c84a1995STobias Grosser /// - Parameters 52632837fe3STobias Grosser /// - Other LLVM Value references (TODO) 52732837fe3STobias Grosser /// 52832837fe3STobias Grosser /// @param Kernel The kernel to generate the function declaration for. 529edb885cbSTobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 530edb885cbSTobias Grosser /// 53132837fe3STobias Grosser /// @returns The newly declared function. 532edb885cbSTobias Grosser Function *createKernelFunctionDecl(ppcg_kernel *Kernel, 533edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues); 53432837fe3STobias Grosser 535472f9654STobias Grosser /// Insert intrinsic functions to obtain thread and block ids. 536472f9654STobias Grosser /// 537472f9654STobias Grosser /// @param The kernel to generate the intrinsic functions for. 538472f9654STobias Grosser void insertKernelIntrinsics(ppcg_kernel *Kernel); 539472f9654STobias Grosser 540f291c8d5SSiddharth Bhat /// Setup the creation of functions referenced by the GPU kernel. 541f291c8d5SSiddharth Bhat /// 542f291c8d5SSiddharth Bhat /// 1. Create new function declarations in GPUModule which are the same as 543f291c8d5SSiddharth Bhat /// SubtreeFunctions. 544f291c8d5SSiddharth Bhat /// 545f291c8d5SSiddharth Bhat /// 2. Populate IslNodeBuilder::ValueMap with mappings from 546f291c8d5SSiddharth Bhat /// old functions (that come from the original module) to new functions 547f291c8d5SSiddharth Bhat /// (that are created within GPUModule). That way, we generate references 548f291c8d5SSiddharth Bhat /// to the correct function (in GPUModule) in BlockGenerator. 549f291c8d5SSiddharth Bhat /// 550f291c8d5SSiddharth Bhat /// @see IslNodeBuilder::ValueMap 551f291c8d5SSiddharth Bhat /// @see BlockGenerator::GlobalMap 552f291c8d5SSiddharth Bhat /// @see BlockGenerator::getNewValue 553f291c8d5SSiddharth Bhat /// @see GPUNodeBuilder::getReferencesInKernel. 554f291c8d5SSiddharth Bhat /// 555f291c8d5SSiddharth Bhat /// @param SubtreeFunctions The set of llvm::Functions referenced by 556f291c8d5SSiddharth Bhat /// this kernel. 557f291c8d5SSiddharth Bhat void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions); 558f291c8d5SSiddharth Bhat 559b513b491STobias Grosser /// Create a global-to-shared or shared-to-global copy statement. 560b513b491STobias Grosser /// 561b513b491STobias Grosser /// @param CopyStmt The copy statement to generate code for 562b513b491STobias Grosser void createKernelCopy(ppcg_kernel_stmt *CopyStmt); 563b513b491STobias Grosser 564edb885cbSTobias Grosser /// Create code for a ScopStmt called in @p Expr. 565edb885cbSTobias Grosser /// 566edb885cbSTobias Grosser /// @param Expr The expression containing the call. 567edb885cbSTobias Grosser /// @param KernelStmt The kernel statement referenced in the call. 568edb885cbSTobias Grosser void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt); 569edb885cbSTobias Grosser 5705260c041STobias Grosser /// Create an in-kernel synchronization call. 5715260c041STobias Grosser void createKernelSync(); 5725260c041STobias Grosser 57374dc3cb4STobias Grosser /// Create a PTX assembly string for the current GPU kernel. 57474dc3cb4STobias Grosser /// 57574dc3cb4STobias Grosser /// @returns A string containing the corresponding PTX assembly code. 57674dc3cb4STobias Grosser std::string createKernelASM(); 57774dc3cb4STobias Grosser 57874dc3cb4STobias Grosser /// Remove references from the dominator tree to the kernel function @p F. 57974dc3cb4STobias Grosser /// 58074dc3cb4STobias Grosser /// @param F The function to remove references to. 58174dc3cb4STobias Grosser void clearDominators(Function *F); 58274dc3cb4STobias Grosser 58374dc3cb4STobias Grosser /// Remove references from scalar evolution to the kernel function @p F. 58474dc3cb4STobias Grosser /// 58574dc3cb4STobias Grosser /// @param F The function to remove references to. 58674dc3cb4STobias Grosser void clearScalarEvolution(Function *F); 58774dc3cb4STobias Grosser 58874dc3cb4STobias Grosser /// Remove references from loop info to the kernel function @p F. 58974dc3cb4STobias Grosser /// 59074dc3cb4STobias Grosser /// @param F The function to remove references to. 59174dc3cb4STobias Grosser void clearLoops(Function *F); 59274dc3cb4STobias Grosser 59332837fe3STobias Grosser /// Finalize the generation of the kernel function. 59432837fe3STobias Grosser /// 59532837fe3STobias Grosser /// Free the LLVM-IR module corresponding to the kernel and -- if requested -- 59632837fe3STobias Grosser /// dump its IR to stderr. 59757793596STobias Grosser /// 59857793596STobias Grosser /// @returns The Assembly string of the kernel. 59957793596STobias Grosser std::string finalizeKernelFunction(); 600fa7b0802STobias Grosser 60151dfc275STobias Grosser /// Finalize the generation of the kernel arguments. 60251dfc275STobias Grosser /// 60351dfc275STobias Grosser /// This function ensures that not-read-only scalars used in a kernel are 604a6d48f59SMichael Kruse /// stored back to the global memory location they are backed with before 60551dfc275STobias Grosser /// the kernel terminates. 60651dfc275STobias Grosser /// 60751dfc275STobias Grosser /// @params Kernel The kernel to finalize kernel arguments for. 60851dfc275STobias Grosser void finalizeKernelArguments(ppcg_kernel *Kernel); 60951dfc275STobias Grosser 6107287aeddSTobias Grosser /// Create code that allocates memory to store arrays on device. 611fa7b0802STobias Grosser void allocateDeviceArrays(); 612fa7b0802STobias Grosser 6137287aeddSTobias Grosser /// Free all allocated device arrays. 6147287aeddSTobias Grosser void freeDeviceArrays(); 6157287aeddSTobias Grosser 616fa7b0802STobias Grosser /// Create a call to initialize the GPU context. 617fa7b0802STobias Grosser /// 618fa7b0802STobias Grosser /// @returns A pointer to the newly initialized context. 619fa7b0802STobias Grosser Value *createCallInitContext(); 620fa7b0802STobias Grosser 62179a947c2STobias Grosser /// Create a call to get the device pointer for a kernel allocation. 62279a947c2STobias Grosser /// 62379a947c2STobias Grosser /// @param Allocation The Polly GPU allocation 62479a947c2STobias Grosser /// 62579a947c2STobias Grosser /// @returns The device parameter corresponding to this allocation. 62679a947c2STobias Grosser Value *createCallGetDevicePtr(Value *Allocation); 62779a947c2STobias Grosser 628fa7b0802STobias Grosser /// Create a call to free the GPU context. 629fa7b0802STobias Grosser /// 630fa7b0802STobias Grosser /// @param Context A pointer to an initialized GPU context. 631fa7b0802STobias Grosser void createCallFreeContext(Value *Context); 632fa7b0802STobias Grosser 6337287aeddSTobias Grosser /// Create a call to allocate memory on the device. 6347287aeddSTobias Grosser /// 6357287aeddSTobias Grosser /// @param Size The size of memory to allocate 6367287aeddSTobias Grosser /// 6377287aeddSTobias Grosser /// @returns A pointer that identifies this allocation. 638fa7b0802STobias Grosser Value *createCallAllocateMemoryForDevice(Value *Size); 6397287aeddSTobias Grosser 6407287aeddSTobias Grosser /// Create a call to free a device array. 6417287aeddSTobias Grosser /// 6427287aeddSTobias Grosser /// @param Array The device array to free. 6437287aeddSTobias Grosser void createCallFreeDeviceMemory(Value *Array); 64413c78e4dSTobias Grosser 64513c78e4dSTobias Grosser /// Create a call to copy data from host to device. 64613c78e4dSTobias Grosser /// 64713c78e4dSTobias Grosser /// @param HostPtr A pointer to the host data that should be copied. 64813c78e4dSTobias Grosser /// @param DevicePtr A device pointer specifying the location to copy to. 64913c78e4dSTobias Grosser void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr, 65013c78e4dSTobias Grosser Value *Size); 65113c78e4dSTobias Grosser 65213c78e4dSTobias Grosser /// Create a call to copy data from device to host. 65313c78e4dSTobias Grosser /// 65413c78e4dSTobias Grosser /// @param DevicePtr A pointer to the device data that should be copied. 65513c78e4dSTobias Grosser /// @param HostPtr A host pointer specifying the location to copy to. 65613c78e4dSTobias Grosser void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr, 65713c78e4dSTobias Grosser Value *Size); 65857793596STobias Grosser 659abed4969SSiddharth Bhat /// Create a call to synchronize Host & Device. 660abed4969SSiddharth Bhat /// \note 661abed4969SSiddharth Bhat /// This is to be used only with managed memory. 662abed4969SSiddharth Bhat void createCallSynchronizeDevice(); 663abed4969SSiddharth Bhat 66457793596STobias Grosser /// Create a call to get a kernel from an assembly string. 66557793596STobias Grosser /// 66657793596STobias Grosser /// @param Buffer The string describing the kernel. 66757793596STobias Grosser /// @param Entry The name of the kernel function to call. 66857793596STobias Grosser /// 66957793596STobias Grosser /// @returns A pointer to a kernel object 67057793596STobias Grosser Value *createCallGetKernel(Value *Buffer, Value *Entry); 67157793596STobias Grosser 67257793596STobias Grosser /// Create a call to free a GPU kernel. 67357793596STobias Grosser /// 67457793596STobias Grosser /// @param GPUKernel THe kernel to free. 67557793596STobias Grosser void createCallFreeKernel(Value *GPUKernel); 67679a947c2STobias Grosser 67779a947c2STobias Grosser /// Create a call to launch a GPU kernel. 67879a947c2STobias Grosser /// 67979a947c2STobias Grosser /// @param GPUKernel The kernel to launch. 68079a947c2STobias Grosser /// @param GridDimX The size of the first grid dimension. 68179a947c2STobias Grosser /// @param GridDimY The size of the second grid dimension. 68279a947c2STobias Grosser /// @param GridBlockX The size of the first block dimension. 68379a947c2STobias Grosser /// @param GridBlockY The size of the second block dimension. 68479a947c2STobias Grosser /// @param GridBlockZ The size of the third block dimension. 685a6d48f59SMichael Kruse /// @param Parameters A pointer to an array that contains itself pointers to 68679a947c2STobias Grosser /// the parameter values passed for each kernel argument. 68779a947c2STobias Grosser void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 68879a947c2STobias Grosser Value *GridDimY, Value *BlockDimX, 68979a947c2STobias Grosser Value *BlockDimY, Value *BlockDimZ, 69079a947c2STobias Grosser Value *Parameters); 6911fb9b64dSTobias Grosser }; 6921fb9b64dSTobias Grosser 69379f13b9aSSingapuram Sanjay Srivallabh std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) { 6941abd9ffaSSingapuram Sanjay Srivallabh return "FUNC_" + S.getFunction().getName().str() + "_SCOP_" + 6951abd9ffaSSingapuram Sanjay Srivallabh std::to_string(S.getID()) + "_KERNEL_" + std::to_string(Kernel_id); 69679f13b9aSSingapuram Sanjay Srivallabh } 69779f13b9aSSingapuram Sanjay Srivallabh 698fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() { 699750160e2STobias Grosser BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(), 700750160e2STobias Grosser &*Builder.GetInsertPoint(), &DT, &LI); 701750160e2STobias Grosser NewBB->setName("polly.acc.initialize"); 702750160e2STobias Grosser Builder.SetInsertPoint(&NewBB->front()); 703750160e2STobias Grosser 704fa7b0802STobias Grosser GPUContext = createCallInitContext(); 705abed4969SSiddharth Bhat 706abed4969SSiddharth Bhat if (!ManagedMemory) 707fa7b0802STobias Grosser allocateDeviceArrays(); 708fa7b0802STobias Grosser } 709fa7b0802STobias Grosser 710fa7b0802STobias Grosser void GPUNodeBuilder::finalize() { 711abed4969SSiddharth Bhat if (!ManagedMemory) 7127287aeddSTobias Grosser freeDeviceArrays(); 713abed4969SSiddharth Bhat 714fa7b0802STobias Grosser createCallFreeContext(GPUContext); 715fa7b0802STobias Grosser IslNodeBuilder::finalize(); 716fa7b0802STobias Grosser } 717fa7b0802STobias Grosser 718fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() { 719abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory will directly send host pointers " 720abed4969SSiddharth Bhat "to the kernel. There is no need for device arrays"); 721fa7b0802STobias Grosser isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 722fa7b0802STobias Grosser 723fa7b0802STobias Grosser for (int i = 0; i < Prog->n_array; ++i) { 724fa7b0802STobias Grosser gpu_array_info *Array = &Prog->array[i]; 72513c78e4dSTobias Grosser auto *ScopArray = (ScopArrayInfo *)Array->user; 7267287aeddSTobias Grosser std::string DevArrayName("p_dev_array_"); 7277287aeddSTobias Grosser DevArrayName.append(Array->name); 728fa7b0802STobias Grosser 72913c78e4dSTobias Grosser Value *ArraySize = getArraySize(Array); 730aaabbbf8STobias Grosser Value *Offset = getArrayOffset(Array); 731aaabbbf8STobias Grosser if (Offset) 732aaabbbf8STobias Grosser ArraySize = Builder.CreateSub( 733aaabbbf8STobias Grosser ArraySize, 734aaabbbf8STobias Grosser Builder.CreateMul(Offset, 735aaabbbf8STobias Grosser Builder.getInt64(ScopArray->getElemSizeInBytes()))); 7367287aeddSTobias Grosser Value *DevArray = createCallAllocateMemoryForDevice(ArraySize); 7377287aeddSTobias Grosser DevArray->setName(DevArrayName); 73813c78e4dSTobias Grosser DeviceAllocations[ScopArray] = DevArray; 739fa7b0802STobias Grosser } 740fa7b0802STobias Grosser 741fa7b0802STobias Grosser isl_ast_build_free(Build); 742fa7b0802STobias Grosser } 743fa7b0802STobias Grosser 744c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX, 745c1c6a2a6STobias Grosser Value *BlockDimY, Value *BlockDimZ) { 746c1c6a2a6STobias Grosser auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations"); 747c1c6a2a6STobias Grosser 748c1c6a2a6STobias Grosser for (auto &F : *M) { 749c1c6a2a6STobias Grosser if (F.getCallingConv() != CallingConv::PTX_Kernel) 750c1c6a2a6STobias Grosser continue; 751c1c6a2a6STobias Grosser 752c1c6a2a6STobias Grosser Value *V[] = {BlockDimX, BlockDimY, BlockDimZ}; 753c1c6a2a6STobias Grosser 754c1c6a2a6STobias Grosser Metadata *Elements[] = { 755c1c6a2a6STobias Grosser ValueAsMetadata::get(&F), MDString::get(M->getContext(), "maxntidx"), 756c1c6a2a6STobias Grosser ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"), 757c1c6a2a6STobias Grosser ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"), 758c1c6a2a6STobias Grosser ValueAsMetadata::get(V[2]), 759c1c6a2a6STobias Grosser }; 760c1c6a2a6STobias Grosser MDNode *Node = MDNode::get(M->getContext(), Elements); 761c1c6a2a6STobias Grosser AnnotationNode->addOperand(Node); 762c1c6a2a6STobias Grosser } 763c1c6a2a6STobias Grosser } 764c1c6a2a6STobias Grosser 7657287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() { 766abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not use device arrays"); 76713c78e4dSTobias Grosser for (auto &Array : DeviceAllocations) 76813c78e4dSTobias Grosser createCallFreeDeviceMemory(Array.second); 7697287aeddSTobias Grosser } 7707287aeddSTobias Grosser 77157793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) { 77257793596STobias Grosser const char *Name = "polly_getKernel"; 77357793596STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 77457793596STobias Grosser Function *F = M->getFunction(Name); 77557793596STobias Grosser 77657793596STobias Grosser // If F is not available, declare it. 77757793596STobias Grosser if (!F) { 77857793596STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 77957793596STobias Grosser std::vector<Type *> Args; 78057793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 78157793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 78257793596STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 78357793596STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 78457793596STobias Grosser } 78557793596STobias Grosser 78657793596STobias Grosser return Builder.CreateCall(F, {Buffer, Entry}); 78757793596STobias Grosser } 78857793596STobias Grosser 78979a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) { 79079a947c2STobias Grosser const char *Name = "polly_getDevicePtr"; 79179a947c2STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 79279a947c2STobias Grosser Function *F = M->getFunction(Name); 79379a947c2STobias Grosser 79479a947c2STobias Grosser // If F is not available, declare it. 79579a947c2STobias Grosser if (!F) { 79679a947c2STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 79779a947c2STobias Grosser std::vector<Type *> Args; 79879a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 79979a947c2STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 80079a947c2STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 80179a947c2STobias Grosser } 80279a947c2STobias Grosser 80379a947c2STobias Grosser return Builder.CreateCall(F, {Allocation}); 80479a947c2STobias Grosser } 80579a947c2STobias Grosser 80679a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 80779a947c2STobias Grosser Value *GridDimY, Value *BlockDimX, 80879a947c2STobias Grosser Value *BlockDimY, Value *BlockDimZ, 80979a947c2STobias Grosser Value *Parameters) { 81079a947c2STobias Grosser const char *Name = "polly_launchKernel"; 81179a947c2STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 81279a947c2STobias Grosser Function *F = M->getFunction(Name); 81379a947c2STobias Grosser 81479a947c2STobias Grosser // If F is not available, declare it. 81579a947c2STobias Grosser if (!F) { 81679a947c2STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 81779a947c2STobias Grosser std::vector<Type *> Args; 81879a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 81979a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 82079a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 82179a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 82279a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 82379a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 82479a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 82579a947c2STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 82679a947c2STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 82779a947c2STobias Grosser } 82879a947c2STobias Grosser 829ff40087aSTobias Grosser Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 83079a947c2STobias Grosser BlockDimZ, Parameters}); 83179a947c2STobias Grosser } 83279a947c2STobias Grosser 83357793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) { 83457793596STobias Grosser const char *Name = "polly_freeKernel"; 83557793596STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 83657793596STobias Grosser Function *F = M->getFunction(Name); 83757793596STobias Grosser 83857793596STobias Grosser // If F is not available, declare it. 83957793596STobias Grosser if (!F) { 84057793596STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 84157793596STobias Grosser std::vector<Type *> Args; 84257793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 84357793596STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 84457793596STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 84557793596STobias Grosser } 84657793596STobias Grosser 84757793596STobias Grosser Builder.CreateCall(F, {GPUKernel}); 84857793596STobias Grosser } 84957793596STobias Grosser 8507287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) { 851abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not allocate or free memory " 852abed4969SSiddharth Bhat "for device"); 8537287aeddSTobias Grosser const char *Name = "polly_freeDeviceMemory"; 8547287aeddSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 8557287aeddSTobias Grosser Function *F = M->getFunction(Name); 8567287aeddSTobias Grosser 8577287aeddSTobias Grosser // If F is not available, declare it. 8587287aeddSTobias Grosser if (!F) { 8597287aeddSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 8607287aeddSTobias Grosser std::vector<Type *> Args; 8617287aeddSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 8627287aeddSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 8637287aeddSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 8647287aeddSTobias Grosser } 8657287aeddSTobias Grosser 8667287aeddSTobias Grosser Builder.CreateCall(F, {Array}); 8677287aeddSTobias Grosser } 8687287aeddSTobias Grosser 869fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) { 870abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not allocate or free memory " 871abed4969SSiddharth Bhat "for device"); 872fa7b0802STobias Grosser const char *Name = "polly_allocateMemoryForDevice"; 873fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 874fa7b0802STobias Grosser Function *F = M->getFunction(Name); 875fa7b0802STobias Grosser 876fa7b0802STobias Grosser // If F is not available, declare it. 877fa7b0802STobias Grosser if (!F) { 878fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 879fa7b0802STobias Grosser std::vector<Type *> Args; 880fa7b0802STobias Grosser Args.push_back(Builder.getInt64Ty()); 881fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 882fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 883fa7b0802STobias Grosser } 884fa7b0802STobias Grosser 885fa7b0802STobias Grosser return Builder.CreateCall(F, {Size}); 886fa7b0802STobias Grosser } 887fa7b0802STobias Grosser 88813c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData, 88913c78e4dSTobias Grosser Value *DeviceData, 89013c78e4dSTobias Grosser Value *Size) { 891abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not transfer memory between " 892abed4969SSiddharth Bhat "device and host"); 89313c78e4dSTobias Grosser const char *Name = "polly_copyFromHostToDevice"; 89413c78e4dSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 89513c78e4dSTobias Grosser Function *F = M->getFunction(Name); 89613c78e4dSTobias Grosser 89713c78e4dSTobias Grosser // If F is not available, declare it. 89813c78e4dSTobias Grosser if (!F) { 89913c78e4dSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 90013c78e4dSTobias Grosser std::vector<Type *> Args; 90113c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 90213c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 90313c78e4dSTobias Grosser Args.push_back(Builder.getInt64Ty()); 90413c78e4dSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 90513c78e4dSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 90613c78e4dSTobias Grosser } 90713c78e4dSTobias Grosser 90813c78e4dSTobias Grosser Builder.CreateCall(F, {HostData, DeviceData, Size}); 90913c78e4dSTobias Grosser } 91013c78e4dSTobias Grosser 91113c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData, 91213c78e4dSTobias Grosser Value *HostData, 91313c78e4dSTobias Grosser Value *Size) { 914abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not transfer memory between " 915abed4969SSiddharth Bhat "device and host"); 91613c78e4dSTobias Grosser const char *Name = "polly_copyFromDeviceToHost"; 91713c78e4dSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 91813c78e4dSTobias Grosser Function *F = M->getFunction(Name); 91913c78e4dSTobias Grosser 92013c78e4dSTobias Grosser // If F is not available, declare it. 92113c78e4dSTobias Grosser if (!F) { 92213c78e4dSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 92313c78e4dSTobias Grosser std::vector<Type *> Args; 92413c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 92513c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 92613c78e4dSTobias Grosser Args.push_back(Builder.getInt64Ty()); 92713c78e4dSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 92813c78e4dSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 92913c78e4dSTobias Grosser } 93013c78e4dSTobias Grosser 93113c78e4dSTobias Grosser Builder.CreateCall(F, {DeviceData, HostData, Size}); 93213c78e4dSTobias Grosser } 93313c78e4dSTobias Grosser 934abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() { 935abed4969SSiddharth Bhat assert(ManagedMemory && "explicit synchronization is only necessary for " 936abed4969SSiddharth Bhat "managed memory"); 937abed4969SSiddharth Bhat const char *Name = "polly_synchronizeDevice"; 938abed4969SSiddharth Bhat Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 939abed4969SSiddharth Bhat Function *F = M->getFunction(Name); 940abed4969SSiddharth Bhat 941abed4969SSiddharth Bhat // If F is not available, declare it. 942abed4969SSiddharth Bhat if (!F) { 943abed4969SSiddharth Bhat GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 944abed4969SSiddharth Bhat FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false); 945abed4969SSiddharth Bhat F = Function::Create(Ty, Linkage, Name, M); 946abed4969SSiddharth Bhat } 947abed4969SSiddharth Bhat 948abed4969SSiddharth Bhat Builder.CreateCall(F); 949abed4969SSiddharth Bhat } 950abed4969SSiddharth Bhat 951fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() { 95217f01968SSiddharth Bhat const char *Name; 95317f01968SSiddharth Bhat 95417f01968SSiddharth Bhat switch (Runtime) { 95517f01968SSiddharth Bhat case GPURuntime::CUDA: 95617f01968SSiddharth Bhat Name = "polly_initContextCUDA"; 95717f01968SSiddharth Bhat break; 95817f01968SSiddharth Bhat case GPURuntime::OpenCL: 95917f01968SSiddharth Bhat Name = "polly_initContextCL"; 96017f01968SSiddharth Bhat break; 96117f01968SSiddharth Bhat } 96217f01968SSiddharth Bhat 963fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 964fa7b0802STobias Grosser Function *F = M->getFunction(Name); 965fa7b0802STobias Grosser 966fa7b0802STobias Grosser // If F is not available, declare it. 967fa7b0802STobias Grosser if (!F) { 968fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 969fa7b0802STobias Grosser std::vector<Type *> Args; 970fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 971fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 972fa7b0802STobias Grosser } 973fa7b0802STobias Grosser 974fa7b0802STobias Grosser return Builder.CreateCall(F, {}); 975fa7b0802STobias Grosser } 976fa7b0802STobias Grosser 977fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) { 978fa7b0802STobias Grosser const char *Name = "polly_freeContext"; 979fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 980fa7b0802STobias Grosser Function *F = M->getFunction(Name); 981fa7b0802STobias Grosser 982fa7b0802STobias Grosser // If F is not available, declare it. 983fa7b0802STobias Grosser if (!F) { 984fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 985fa7b0802STobias Grosser std::vector<Type *> Args; 986fa7b0802STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 987fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 988fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 989fa7b0802STobias Grosser } 990fa7b0802STobias Grosser 991fa7b0802STobias Grosser Builder.CreateCall(F, {Context}); 992fa7b0802STobias Grosser } 993fa7b0802STobias Grosser 9945260c041STobias Grosser /// Check if one string is a prefix of another. 9955260c041STobias Grosser /// 9965260c041STobias Grosser /// @param String The string in which to look for the prefix. 9975260c041STobias Grosser /// @param Prefix The prefix to look for. 9985260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) { 9995260c041STobias Grosser return String.find(Prefix) == 0; 10005260c041STobias Grosser } 10015260c041STobias Grosser 100213c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) { 100313c78e4dSTobias Grosser isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 100413c78e4dSTobias Grosser Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size); 100513c78e4dSTobias Grosser 100613c78e4dSTobias Grosser if (!gpu_array_is_scalar(Array)) { 100713c78e4dSTobias Grosser auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]); 100813c78e4dSTobias Grosser isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero); 100913c78e4dSTobias Grosser 101013c78e4dSTobias Grosser for (unsigned int i = 1; i < Array->n_index; i++) { 101113c78e4dSTobias Grosser isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]); 101213c78e4dSTobias Grosser isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I); 101313c78e4dSTobias Grosser Res = isl_ast_expr_mul(Res, Expr); 101413c78e4dSTobias Grosser } 101513c78e4dSTobias Grosser 101613c78e4dSTobias Grosser Value *NumElements = ExprBuilder.create(Res); 1017b79f4d39STobias Grosser if (NumElements->getType() != ArraySize->getType()) 1018b79f4d39STobias Grosser NumElements = Builder.CreateSExt(NumElements, ArraySize->getType()); 101913c78e4dSTobias Grosser ArraySize = Builder.CreateMul(ArraySize, NumElements); 102013c78e4dSTobias Grosser } 102113c78e4dSTobias Grosser isl_ast_build_free(Build); 102213c78e4dSTobias Grosser return ArraySize; 102313c78e4dSTobias Grosser } 102413c78e4dSTobias Grosser 1025aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) { 1026aaabbbf8STobias Grosser if (gpu_array_is_scalar(Array)) 1027aaabbbf8STobias Grosser return nullptr; 1028aaabbbf8STobias Grosser 1029aaabbbf8STobias Grosser isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 1030aaabbbf8STobias Grosser 1031aaabbbf8STobias Grosser isl_set *Min = isl_set_lexmin(isl_set_copy(Array->extent)); 1032aaabbbf8STobias Grosser 1033aaabbbf8STobias Grosser isl_set *ZeroSet = isl_set_universe(isl_set_get_space(Min)); 1034aaabbbf8STobias Grosser 1035aaabbbf8STobias Grosser for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) 1036aaabbbf8STobias Grosser ZeroSet = isl_set_fix_si(ZeroSet, isl_dim_set, i, 0); 1037aaabbbf8STobias Grosser 1038aaabbbf8STobias Grosser if (isl_set_is_subset(Min, ZeroSet)) { 1039aaabbbf8STobias Grosser isl_set_free(Min); 1040aaabbbf8STobias Grosser isl_set_free(ZeroSet); 1041aaabbbf8STobias Grosser isl_ast_build_free(Build); 1042aaabbbf8STobias Grosser return nullptr; 1043aaabbbf8STobias Grosser } 1044aaabbbf8STobias Grosser isl_set_free(ZeroSet); 1045aaabbbf8STobias Grosser 1046aaabbbf8STobias Grosser isl_ast_expr *Result = 1047aaabbbf8STobias Grosser isl_ast_expr_from_val(isl_val_int_from_si(isl_set_get_ctx(Min), 0)); 1048aaabbbf8STobias Grosser 1049aaabbbf8STobias Grosser for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) { 1050aaabbbf8STobias Grosser if (i > 0) { 1051aaabbbf8STobias Grosser isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i - 1]); 1052aaabbbf8STobias Grosser isl_ast_expr *BExpr = isl_ast_build_expr_from_pw_aff(Build, Bound_I); 1053aaabbbf8STobias Grosser Result = isl_ast_expr_mul(Result, BExpr); 1054aaabbbf8STobias Grosser } 1055aaabbbf8STobias Grosser isl_pw_aff *DimMin = isl_set_dim_min(isl_set_copy(Min), i); 1056aaabbbf8STobias Grosser isl_ast_expr *MExpr = isl_ast_build_expr_from_pw_aff(Build, DimMin); 1057aaabbbf8STobias Grosser Result = isl_ast_expr_add(Result, MExpr); 1058aaabbbf8STobias Grosser } 1059aaabbbf8STobias Grosser 1060aaabbbf8STobias Grosser Value *ResultValue = ExprBuilder.create(Result); 1061aaabbbf8STobias Grosser isl_set_free(Min); 1062aaabbbf8STobias Grosser isl_ast_build_free(Build); 1063aaabbbf8STobias Grosser 1064aaabbbf8STobias Grosser return ResultValue; 1065aaabbbf8STobias Grosser } 1066aaabbbf8STobias Grosser 1067abed4969SSiddharth Bhat Value *GPUNodeBuilder::getOrCreateManagedDeviceArray(gpu_array_info *Array, 1068abed4969SSiddharth Bhat ScopArrayInfo *ArrayInfo) { 1069abed4969SSiddharth Bhat 1070abed4969SSiddharth Bhat assert(ManagedMemory && "Only used when you wish to get a host " 1071abed4969SSiddharth Bhat "pointer for sending data to the kernel, " 1072abed4969SSiddharth Bhat "with managed memory"); 1073abed4969SSiddharth Bhat std::map<ScopArrayInfo *, Value *>::iterator it; 1074abed4969SSiddharth Bhat if ((it = DeviceAllocations.find(ArrayInfo)) != DeviceAllocations.end()) { 1075abed4969SSiddharth Bhat return it->second; 1076abed4969SSiddharth Bhat } else { 1077abed4969SSiddharth Bhat Value *HostPtr; 1078abed4969SSiddharth Bhat 1079abed4969SSiddharth Bhat if (gpu_array_is_scalar(Array)) 1080abed4969SSiddharth Bhat HostPtr = BlockGen.getOrCreateAlloca(ArrayInfo); 1081abed4969SSiddharth Bhat else 1082abed4969SSiddharth Bhat HostPtr = ArrayInfo->getBasePtr(); 1083abed4969SSiddharth Bhat 1084abed4969SSiddharth Bhat Value *Offset = getArrayOffset(Array); 1085abed4969SSiddharth Bhat if (Offset) { 1086abed4969SSiddharth Bhat HostPtr = Builder.CreatePointerCast( 1087abed4969SSiddharth Bhat HostPtr, ArrayInfo->getElementType()->getPointerTo()); 1088abed4969SSiddharth Bhat HostPtr = Builder.CreateGEP(HostPtr, Offset); 1089abed4969SSiddharth Bhat } 1090abed4969SSiddharth Bhat 1091abed4969SSiddharth Bhat HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 1092abed4969SSiddharth Bhat DeviceAllocations[ArrayInfo] = HostPtr; 1093abed4969SSiddharth Bhat return HostPtr; 1094abed4969SSiddharth Bhat } 1095abed4969SSiddharth Bhat } 1096abed4969SSiddharth Bhat 109713c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt, 109813c78e4dSTobias Grosser enum DataDirection Direction) { 1099abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory needs no data transfers"); 110013c78e4dSTobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt); 110113c78e4dSTobias Grosser isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0); 110213c78e4dSTobias Grosser isl_id *Id = isl_ast_expr_get_id(Arg); 110313c78e4dSTobias Grosser auto Array = (gpu_array_info *)isl_id_get_user(Id); 110413c78e4dSTobias Grosser auto ScopArray = (ScopArrayInfo *)(Array->user); 110513c78e4dSTobias Grosser 110613c78e4dSTobias Grosser Value *Size = getArraySize(Array); 1107aaabbbf8STobias Grosser Value *Offset = getArrayOffset(Array); 110813c78e4dSTobias Grosser Value *DevPtr = DeviceAllocations[ScopArray]; 110913c78e4dSTobias Grosser 1110b06ff457STobias Grosser Value *HostPtr; 1111b06ff457STobias Grosser 1112b06ff457STobias Grosser if (gpu_array_is_scalar(Array)) 1113b06ff457STobias Grosser HostPtr = BlockGen.getOrCreateAlloca(ScopArray); 1114b06ff457STobias Grosser else 1115b06ff457STobias Grosser HostPtr = ScopArray->getBasePtr(); 111613c78e4dSTobias Grosser 1117aaabbbf8STobias Grosser if (Offset) { 1118aaabbbf8STobias Grosser HostPtr = Builder.CreatePointerCast( 1119aaabbbf8STobias Grosser HostPtr, ScopArray->getElementType()->getPointerTo()); 1120aaabbbf8STobias Grosser HostPtr = Builder.CreateGEP(HostPtr, Offset); 1121aaabbbf8STobias Grosser } 1122aaabbbf8STobias Grosser 112313c78e4dSTobias Grosser HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 112413c78e4dSTobias Grosser 1125aaabbbf8STobias Grosser if (Offset) { 1126aaabbbf8STobias Grosser Size = Builder.CreateSub( 1127ff40087aSTobias Grosser Size, Builder.CreateMul( 1128ff40087aSTobias Grosser Offset, Builder.getInt64(ScopArray->getElemSizeInBytes()))); 1129aaabbbf8STobias Grosser } 1130aaabbbf8STobias Grosser 113113c78e4dSTobias Grosser if (Direction == HOST_TO_DEVICE) 113213c78e4dSTobias Grosser createCallCopyFromHostToDevice(HostPtr, DevPtr, Size); 113313c78e4dSTobias Grosser else 113413c78e4dSTobias Grosser createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size); 113513c78e4dSTobias Grosser 113613c78e4dSTobias Grosser isl_id_free(Id); 113713c78e4dSTobias Grosser isl_ast_expr_free(Arg); 113813c78e4dSTobias Grosser isl_ast_expr_free(Expr); 113913c78e4dSTobias Grosser isl_ast_node_free(TransferStmt); 114013c78e4dSTobias Grosser } 114113c78e4dSTobias Grosser 11421fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) { 114332837fe3STobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt); 114432837fe3STobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 114532837fe3STobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr); 114632837fe3STobias Grosser isl_id_free(Id); 114732837fe3STobias Grosser isl_ast_expr_free(StmtExpr); 114832837fe3STobias Grosser 114932837fe3STobias Grosser const char *Str = isl_id_get_name(Id); 115032837fe3STobias Grosser if (!strcmp(Str, "kernel")) { 115132837fe3STobias Grosser createKernel(UserStmt); 115232837fe3STobias Grosser isl_ast_expr_free(Expr); 115332837fe3STobias Grosser return; 115432837fe3STobias Grosser } 115532837fe3STobias Grosser 115613c78e4dSTobias Grosser if (isPrefix(Str, "to_device")) { 1157abed4969SSiddharth Bhat if (!ManagedMemory) 115813c78e4dSTobias Grosser createDataTransfer(UserStmt, HOST_TO_DEVICE); 1159abed4969SSiddharth Bhat else 1160abed4969SSiddharth Bhat isl_ast_node_free(UserStmt); 1161abed4969SSiddharth Bhat 116232837fe3STobias Grosser isl_ast_expr_free(Expr); 116313c78e4dSTobias Grosser return; 116413c78e4dSTobias Grosser } 116513c78e4dSTobias Grosser 116613c78e4dSTobias Grosser if (isPrefix(Str, "from_device")) { 1167abed4969SSiddharth Bhat if (!ManagedMemory) { 116813c78e4dSTobias Grosser createDataTransfer(UserStmt, DEVICE_TO_HOST); 1169abed4969SSiddharth Bhat } else { 1170abed4969SSiddharth Bhat createCallSynchronizeDevice(); 1171abed4969SSiddharth Bhat isl_ast_node_free(UserStmt); 1172abed4969SSiddharth Bhat } 117313c78e4dSTobias Grosser isl_ast_expr_free(Expr); 117438fc0aedSTobias Grosser return; 117538fc0aedSTobias Grosser } 117638fc0aedSTobias Grosser 11775260c041STobias Grosser isl_id *Anno = isl_ast_node_get_annotation(UserStmt); 11785260c041STobias Grosser struct ppcg_kernel_stmt *KernelStmt = 11795260c041STobias Grosser (struct ppcg_kernel_stmt *)isl_id_get_user(Anno); 11805260c041STobias Grosser isl_id_free(Anno); 11815260c041STobias Grosser 11825260c041STobias Grosser switch (KernelStmt->type) { 11835260c041STobias Grosser case ppcg_kernel_domain: 1184edb885cbSTobias Grosser createScopStmt(Expr, KernelStmt); 11855260c041STobias Grosser isl_ast_node_free(UserStmt); 11865260c041STobias Grosser return; 11875260c041STobias Grosser case ppcg_kernel_copy: 1188b513b491STobias Grosser createKernelCopy(KernelStmt); 11895260c041STobias Grosser isl_ast_expr_free(Expr); 11905260c041STobias Grosser isl_ast_node_free(UserStmt); 11915260c041STobias Grosser return; 11925260c041STobias Grosser case ppcg_kernel_sync: 11935260c041STobias Grosser createKernelSync(); 11945260c041STobias Grosser isl_ast_expr_free(Expr); 11955260c041STobias Grosser isl_ast_node_free(UserStmt); 11965260c041STobias Grosser return; 11975260c041STobias Grosser } 11985260c041STobias Grosser 11995260c041STobias Grosser isl_ast_expr_free(Expr); 12005260c041STobias Grosser isl_ast_node_free(UserStmt); 12015260c041STobias Grosser return; 12025260c041STobias Grosser } 1203b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) { 1204b513b491STobias Grosser isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index); 1205b513b491STobias Grosser LocalIndex = isl_ast_expr_address_of(LocalIndex); 1206b513b491STobias Grosser Value *LocalAddr = ExprBuilder.create(LocalIndex); 1207b513b491STobias Grosser isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index); 1208b513b491STobias Grosser Index = isl_ast_expr_address_of(Index); 1209b513b491STobias Grosser Value *GlobalAddr = ExprBuilder.create(Index); 1210b513b491STobias Grosser 1211b513b491STobias Grosser if (KernelStmt->u.c.read) { 1212b513b491STobias Grosser LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read"); 1213b513b491STobias Grosser Builder.CreateStore(Load, LocalAddr); 1214b513b491STobias Grosser } else { 1215b513b491STobias Grosser LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write"); 1216b513b491STobias Grosser Builder.CreateStore(Load, GlobalAddr); 1217b513b491STobias Grosser } 1218b513b491STobias Grosser } 12195260c041STobias Grosser 1220edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr, 1221edb885cbSTobias Grosser ppcg_kernel_stmt *KernelStmt) { 1222edb885cbSTobias Grosser auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1223edb885cbSTobias Grosser isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr; 1224edb885cbSTobias Grosser 1225edb885cbSTobias Grosser LoopToScevMapT LTS; 1226edb885cbSTobias Grosser LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end()); 1227edb885cbSTobias Grosser 1228edb885cbSTobias Grosser createSubstitutions(Expr, Stmt, LTS); 1229edb885cbSTobias Grosser 1230edb885cbSTobias Grosser if (Stmt->isBlockStmt()) 1231edb885cbSTobias Grosser BlockGen.copyStmt(*Stmt, LTS, Indexes); 1232edb885cbSTobias Grosser else 1233a82c4b5dSTobias Grosser RegionGen.copyStmt(*Stmt, LTS, Indexes); 1234edb885cbSTobias Grosser } 1235edb885cbSTobias Grosser 12365260c041STobias Grosser void GPUNodeBuilder::createKernelSync() { 12375260c041STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 123817f01968SSiddharth Bhat 123917f01968SSiddharth Bhat Function *Sync; 124017f01968SSiddharth Bhat 124117f01968SSiddharth Bhat switch (Arch) { 124217f01968SSiddharth Bhat case GPUArch::NVPTX64: 124317f01968SSiddharth Bhat Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0); 124417f01968SSiddharth Bhat break; 124517f01968SSiddharth Bhat } 124617f01968SSiddharth Bhat 12475260c041STobias Grosser Builder.CreateCall(Sync, {}); 12485260c041STobias Grosser } 12495260c041STobias Grosser 1250edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node 1251edb885cbSTobias Grosser /// 1252edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring 1253edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore. 1254edb885cbSTobias Grosser /// 1255edb885cbSTobias Grosser /// @param Node The node to collect references for. 1256edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected. 1257edb885cbSTobias Grosser /// 1258edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully. 1259edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) { 1260edb885cbSTobias Grosser if (isl_ast_node_get_type(Node) != isl_ast_node_user) 1261edb885cbSTobias Grosser return isl_bool_true; 1262edb885cbSTobias Grosser 1263edb885cbSTobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node); 1264edb885cbSTobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 1265edb885cbSTobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr); 1266edb885cbSTobias Grosser const char *Str = isl_id_get_name(Id); 1267edb885cbSTobias Grosser isl_id_free(Id); 1268edb885cbSTobias Grosser isl_ast_expr_free(StmtExpr); 1269edb885cbSTobias Grosser isl_ast_expr_free(Expr); 1270edb885cbSTobias Grosser 1271edb885cbSTobias Grosser if (!isPrefix(Str, "Stmt")) 1272edb885cbSTobias Grosser return isl_bool_true; 1273edb885cbSTobias Grosser 1274edb885cbSTobias Grosser Id = isl_ast_node_get_annotation(Node); 1275edb885cbSTobias Grosser auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id); 1276edb885cbSTobias Grosser auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1277edb885cbSTobias Grosser isl_id_free(Id); 1278edb885cbSTobias Grosser 127900bb5a99STobias Grosser addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */); 1280edb885cbSTobias Grosser 1281edb885cbSTobias Grosser return isl_bool_true; 1282edb885cbSTobias Grosser } 1283edb885cbSTobias Grosser 1284f291c8d5SSiddharth Bhat /// Check if F is a function that we can code-generate in a GPU kernel. 1285f291c8d5SSiddharth Bhat static bool isValidFunctionInKernel(llvm::Function *F) { 1286f291c8d5SSiddharth Bhat assert(F && "F is an invalid pointer"); 1287f291c8d5SSiddharth Bhat // We string compare against the name of the function to allow 1288f291c8d5SSiddharth Bhat // all variants of the intrinsic "llvm.sqrt.*" 1289f291c8d5SSiddharth Bhat return F->isIntrinsic() && F->getName().startswith("llvm.sqrt"); 1290f291c8d5SSiddharth Bhat } 1291f291c8d5SSiddharth Bhat 1292f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value. 1293f291c8d5SSiddharth Bhat /// 1294f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along 1295f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and 1296f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not 1297f291c8d5SSiddharth Bhat /// `Function`s. 1298f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); } 1299f291c8d5SSiddharth Bhat 1300f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`. 1301f291c8d5SSiddharth Bhat static SetVector<Function *> 1302f291c8d5SSiddharth Bhat getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues) { 1303f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions; 1304f291c8d5SSiddharth Bhat for (Value *It : RawSubtreeValues) { 1305f291c8d5SSiddharth Bhat Function *F = dyn_cast<Function>(It); 1306f291c8d5SSiddharth Bhat if (F) { 1307f291c8d5SSiddharth Bhat assert(isValidFunctionInKernel(F) && "Code should have bailed out by " 1308f291c8d5SSiddharth Bhat "this point if an invalid function " 1309f291c8d5SSiddharth Bhat "were present in a kernel."); 1310f291c8d5SSiddharth Bhat SubtreeFunctions.insert(F); 1311f291c8d5SSiddharth Bhat } 1312f291c8d5SSiddharth Bhat } 1313f291c8d5SSiddharth Bhat return SubtreeFunctions; 1314f291c8d5SSiddharth Bhat } 1315f291c8d5SSiddharth Bhat 1316f291c8d5SSiddharth Bhat std::pair<SetVector<Value *>, SetVector<Function *>> 1317f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) { 1318edb885cbSTobias Grosser SetVector<Value *> SubtreeValues; 1319edb885cbSTobias Grosser SetVector<const SCEV *> SCEVs; 1320edb885cbSTobias Grosser SetVector<const Loop *> Loops; 1321edb885cbSTobias Grosser SubtreeReferences References = { 1322edb885cbSTobias Grosser LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()}; 1323edb885cbSTobias Grosser 1324edb885cbSTobias Grosser for (const auto &I : IDToValue) 1325edb885cbSTobias Grosser SubtreeValues.insert(I.second); 1326edb885cbSTobias Grosser 1327edb885cbSTobias Grosser isl_ast_node_foreach_descendant_top_down( 1328edb885cbSTobias Grosser Kernel->tree, collectReferencesInGPUStmt, &References); 1329edb885cbSTobias Grosser 1330edb885cbSTobias Grosser for (const SCEV *Expr : SCEVs) 1331edb885cbSTobias Grosser findValues(Expr, SE, SubtreeValues); 1332edb885cbSTobias Grosser 1333edb885cbSTobias Grosser for (auto &SAI : S.arrays()) 1334d7754a12SRoman Gareev SubtreeValues.remove(SAI->getBasePtr()); 1335edb885cbSTobias Grosser 1336edb885cbSTobias Grosser isl_space *Space = S.getParamSpace(); 1337edb885cbSTobias Grosser for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) { 1338edb885cbSTobias Grosser isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i); 1339edb885cbSTobias Grosser assert(IDToValue.count(Id)); 1340edb885cbSTobias Grosser Value *Val = IDToValue[Id]; 1341edb885cbSTobias Grosser SubtreeValues.remove(Val); 1342edb885cbSTobias Grosser isl_id_free(Id); 1343edb885cbSTobias Grosser } 1344edb885cbSTobias Grosser isl_space_free(Space); 1345edb885cbSTobias Grosser 1346edb885cbSTobias Grosser for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) { 1347edb885cbSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1348edb885cbSTobias Grosser assert(IDToValue.count(Id)); 1349edb885cbSTobias Grosser Value *Val = IDToValue[Id]; 1350edb885cbSTobias Grosser SubtreeValues.remove(Val); 1351edb885cbSTobias Grosser isl_id_free(Id); 1352edb885cbSTobias Grosser } 1353edb885cbSTobias Grosser 1354f291c8d5SSiddharth Bhat // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions 1355f291c8d5SSiddharth Bhat // SubtreeValues. This is important, because we should not lose any 1356f291c8d5SSiddharth Bhat // SubtreeValues in the process of constructing the 1357f291c8d5SSiddharth Bhat // "ValidSubtree{Values, Functions} sets. Nor should the set 1358f291c8d5SSiddharth Bhat // ValidSubtree{Values, Functions} have any common element. 1359f291c8d5SSiddharth Bhat auto ValidSubtreeValuesIt = 1360f291c8d5SSiddharth Bhat make_filter_range(SubtreeValues, isValidSubtreeValue); 1361f291c8d5SSiddharth Bhat SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(), 1362f291c8d5SSiddharth Bhat ValidSubtreeValuesIt.end()); 1363f291c8d5SSiddharth Bhat SetVector<Function *> ValidSubtreeFunctions( 1364f291c8d5SSiddharth Bhat getFunctionsFromRawSubtreeValues(SubtreeValues)); 1365f291c8d5SSiddharth Bhat 1366a1b2086aSSiddharth Bhat // @see IslNodeBuilder::getReferencesInSubtree 1367a1b2086aSSiddharth Bhat SetVector<Value *> ReplacedValues; 1368a1b2086aSSiddharth Bhat for (Value *V : ValidSubtreeValues) { 1369a1b2086aSSiddharth Bhat auto It = ValueMap.find(V); 1370a1b2086aSSiddharth Bhat if (It == ValueMap.end()) 1371a1b2086aSSiddharth Bhat ReplacedValues.insert(V); 1372a1b2086aSSiddharth Bhat else 1373a1b2086aSSiddharth Bhat ReplacedValues.insert(It->second); 1374a1b2086aSSiddharth Bhat } 1375a1b2086aSSiddharth Bhat return std::make_pair(ReplacedValues, ValidSubtreeFunctions); 1376edb885cbSTobias Grosser } 1377edb885cbSTobias Grosser 137874dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) { 137974dc3cb4STobias Grosser DomTreeNode *N = DT.getNode(&F->getEntryBlock()); 138074dc3cb4STobias Grosser std::vector<BasicBlock *> Nodes; 138174dc3cb4STobias Grosser for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I) 138274dc3cb4STobias Grosser Nodes.push_back(I->getBlock()); 138374dc3cb4STobias Grosser 138474dc3cb4STobias Grosser for (BasicBlock *BB : Nodes) 138574dc3cb4STobias Grosser DT.eraseNode(BB); 138674dc3cb4STobias Grosser } 138774dc3cb4STobias Grosser 138874dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) { 138974dc3cb4STobias Grosser for (BasicBlock &BB : *F) { 139074dc3cb4STobias Grosser Loop *L = LI.getLoopFor(&BB); 139174dc3cb4STobias Grosser if (L) 139274dc3cb4STobias Grosser SE.forgetLoop(L); 139374dc3cb4STobias Grosser } 139474dc3cb4STobias Grosser } 139574dc3cb4STobias Grosser 139674dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) { 139774dc3cb4STobias Grosser for (BasicBlock &BB : *F) { 139874dc3cb4STobias Grosser Loop *L = LI.getLoopFor(&BB); 139974dc3cb4STobias Grosser if (L) 140074dc3cb4STobias Grosser SE.forgetLoop(L); 140174dc3cb4STobias Grosser LI.removeBlock(&BB); 140274dc3cb4STobias Grosser } 140374dc3cb4STobias Grosser } 140474dc3cb4STobias Grosser 140579a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) { 140679a947c2STobias Grosser std::vector<Value *> Sizes; 140779a947c2STobias Grosser isl_ast_build *Context = isl_ast_build_from_context(S.getContext()); 140879a947c2STobias Grosser 140979a947c2STobias Grosser for (long i = 0; i < Kernel->n_grid; i++) { 141079a947c2STobias Grosser isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i); 141179a947c2STobias Grosser isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size); 141279a947c2STobias Grosser Value *Res = ExprBuilder.create(GridSize); 141379a947c2STobias Grosser Res = Builder.CreateTrunc(Res, Builder.getInt32Ty()); 141479a947c2STobias Grosser Sizes.push_back(Res); 141579a947c2STobias Grosser } 141679a947c2STobias Grosser isl_ast_build_free(Context); 141779a947c2STobias Grosser 141879a947c2STobias Grosser for (long i = Kernel->n_grid; i < 3; i++) 141979a947c2STobias Grosser Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 142079a947c2STobias Grosser 142179a947c2STobias Grosser return std::make_tuple(Sizes[0], Sizes[1]); 142279a947c2STobias Grosser } 142379a947c2STobias Grosser 142479a947c2STobias Grosser std::tuple<Value *, Value *, Value *> 142579a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) { 142679a947c2STobias Grosser std::vector<Value *> Sizes; 142779a947c2STobias Grosser 142879a947c2STobias Grosser for (long i = 0; i < Kernel->n_block; i++) { 142979a947c2STobias Grosser Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]); 143079a947c2STobias Grosser Sizes.push_back(Res); 143179a947c2STobias Grosser } 143279a947c2STobias Grosser 143379a947c2STobias Grosser for (long i = Kernel->n_block; i < 3; i++) 143479a947c2STobias Grosser Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 143579a947c2STobias Grosser 143679a947c2STobias Grosser return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]); 143779a947c2STobias Grosser } 143879a947c2STobias Grosser 1439a90be207SSiddharth Bhat void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters, 1440a90be207SSiddharth Bhat Instruction *Param, int Index) { 1441a90be207SSiddharth Bhat Value *Slot = Builder.CreateGEP( 1442a90be207SSiddharth Bhat Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1443a90be207SSiddharth Bhat Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 1444a90be207SSiddharth Bhat Builder.CreateStore(ParamTyped, Slot); 1445a90be207SSiddharth Bhat } 1446a90be207SSiddharth Bhat 144757693272STobias Grosser Value * 144857693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F, 144957693272STobias Grosser SetVector<Value *> SubtreeValues) { 1450a90be207SSiddharth Bhat const int NumArgs = F->arg_size(); 1451a90be207SSiddharth Bhat std::vector<int> ArgSizes(NumArgs); 1452a90be207SSiddharth Bhat 1453a90be207SSiddharth Bhat Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs); 145479a947c2STobias Grosser 145579a947c2STobias Grosser BasicBlock *EntryBlock = 145679a947c2STobias Grosser &Builder.GetInsertBlock()->getParent()->getEntryBlock(); 145767726b32STobias Grosser auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace(); 145879a947c2STobias Grosser std::string Launch = "polly_launch_" + std::to_string(Kernel->id); 145967726b32STobias Grosser Instruction *Parameters = new AllocaInst( 146067726b32STobias Grosser ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator()); 146179a947c2STobias Grosser 146279a947c2STobias Grosser int Index = 0; 146379a947c2STobias Grosser for (long i = 0; i < Prog->n_array; i++) { 146479a947c2STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 146579a947c2STobias Grosser continue; 146679a947c2STobias Grosser 146779a947c2STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 146879a947c2STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id); 146979a947c2STobias Grosser 1470a90be207SSiddharth Bhat ArgSizes[Index] = SAI->getElemSizeInBytes(); 1471a90be207SSiddharth Bhat 1472abed4969SSiddharth Bhat Value *DevArray = nullptr; 1473abed4969SSiddharth Bhat if (ManagedMemory) { 1474abed4969SSiddharth Bhat DevArray = getOrCreateManagedDeviceArray( 1475abed4969SSiddharth Bhat &Prog->array[i], const_cast<ScopArrayInfo *>(SAI)); 1476abed4969SSiddharth Bhat } else { 1477abed4969SSiddharth Bhat DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)]; 147879a947c2STobias Grosser DevArray = createCallGetDevicePtr(DevArray); 1479abed4969SSiddharth Bhat } 1480abed4969SSiddharth Bhat assert(DevArray != nullptr && "Array to be offloaded to device not " 1481abed4969SSiddharth Bhat "initialized"); 1482aaabbbf8STobias Grosser Value *Offset = getArrayOffset(&Prog->array[i]); 1483aaabbbf8STobias Grosser 1484aaabbbf8STobias Grosser if (Offset) { 1485aaabbbf8STobias Grosser DevArray = Builder.CreatePointerCast( 1486aaabbbf8STobias Grosser DevArray, SAI->getElementType()->getPointerTo()); 1487aaabbbf8STobias Grosser DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset)); 1488aaabbbf8STobias Grosser DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy()); 1489aaabbbf8STobias Grosser } 1490fe74a7a1STobias Grosser Value *Slot = Builder.CreateGEP( 1491fe74a7a1STobias Grosser Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1492aaabbbf8STobias Grosser 1493fe74a7a1STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1494abed4969SSiddharth Bhat Value *ValPtr = nullptr; 1495abed4969SSiddharth Bhat if (ManagedMemory) 1496abed4969SSiddharth Bhat ValPtr = DevArray; 1497abed4969SSiddharth Bhat else 1498abed4969SSiddharth Bhat ValPtr = BlockGen.getOrCreateAlloca(SAI); 1499abed4969SSiddharth Bhat 1500abed4969SSiddharth Bhat assert(ValPtr != nullptr && "ValPtr that should point to a valid object" 1501abed4969SSiddharth Bhat " to be stored into Parameters"); 1502fe74a7a1STobias Grosser Value *ValPtrCast = 1503fe74a7a1STobias Grosser Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy()); 1504fe74a7a1STobias Grosser Builder.CreateStore(ValPtrCast, Slot); 1505fe74a7a1STobias Grosser } else { 150667726b32STobias Grosser Instruction *Param = 150767726b32STobias Grosser new AllocaInst(Builder.getInt8PtrTy(), AddressSpace, 150867726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 150979a947c2STobias Grosser EntryBlock->getTerminator()); 151079a947c2STobias Grosser Builder.CreateStore(DevArray, Param); 151179a947c2STobias Grosser Value *ParamTyped = 151279a947c2STobias Grosser Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 151379a947c2STobias Grosser Builder.CreateStore(ParamTyped, Slot); 1514fe74a7a1STobias Grosser } 151579a947c2STobias Grosser Index++; 151679a947c2STobias Grosser } 151779a947c2STobias Grosser 1518a490147cSTobias Grosser int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1519a490147cSTobias Grosser 1520a490147cSTobias Grosser for (long i = 0; i < NumHostIters; i++) { 1521a490147cSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1522a490147cSTobias Grosser Value *Val = IDToValue[Id]; 1523a490147cSTobias Grosser isl_id_free(Id); 1524a90be207SSiddharth Bhat 1525a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1526a90be207SSiddharth Bhat 152767726b32STobias Grosser Instruction *Param = 152867726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 152967726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 1530a490147cSTobias Grosser EntryBlock->getTerminator()); 1531a490147cSTobias Grosser Builder.CreateStore(Val, Param); 1532a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 1533a490147cSTobias Grosser Index++; 1534a490147cSTobias Grosser } 1535a490147cSTobias Grosser 1536d8b94bcaSTobias Grosser int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1537d8b94bcaSTobias Grosser 1538d8b94bcaSTobias Grosser for (long i = 0; i < NumVars; i++) { 1539d8b94bcaSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1540d8b94bcaSTobias Grosser Value *Val = IDToValue[Id]; 1541a1b2086aSSiddharth Bhat if (ValueMap.count(Val)) 1542a1b2086aSSiddharth Bhat Val = ValueMap[Val]; 1543d8b94bcaSTobias Grosser isl_id_free(Id); 1544a90be207SSiddharth Bhat 1545a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1546a90be207SSiddharth Bhat 154767726b32STobias Grosser Instruction *Param = 154867726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 154967726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 1550d8b94bcaSTobias Grosser EntryBlock->getTerminator()); 1551d8b94bcaSTobias Grosser Builder.CreateStore(Val, Param); 1552a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 1553d8b94bcaSTobias Grosser Index++; 1554d8b94bcaSTobias Grosser } 1555d8b94bcaSTobias Grosser 155657693272STobias Grosser for (auto Val : SubtreeValues) { 1557a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1558a90be207SSiddharth Bhat 155967726b32STobias Grosser Instruction *Param = 156067726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 156167726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 156257693272STobias Grosser EntryBlock->getTerminator()); 156357693272STobias Grosser Builder.CreateStore(Val, Param); 1564a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 1565a90be207SSiddharth Bhat Index++; 1566a90be207SSiddharth Bhat } 1567a90be207SSiddharth Bhat 1568a90be207SSiddharth Bhat for (int i = 0; i < NumArgs; i++) { 1569a90be207SSiddharth Bhat Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]); 1570a90be207SSiddharth Bhat Instruction *Param = 1571a90be207SSiddharth Bhat new AllocaInst(Builder.getInt32Ty(), AddressSpace, 1572a90be207SSiddharth Bhat Launch + "_param_size_" + std::to_string(i), 1573a90be207SSiddharth Bhat EntryBlock->getTerminator()); 1574a90be207SSiddharth Bhat Builder.CreateStore(Val, Param); 1575a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 157657693272STobias Grosser Index++; 157757693272STobias Grosser } 157857693272STobias Grosser 157979a947c2STobias Grosser auto Location = EntryBlock->getTerminator(); 158079a947c2STobias Grosser return new BitCastInst(Parameters, Builder.getInt8PtrTy(), 158179a947c2STobias Grosser Launch + "_params_i8ptr", Location); 158279a947c2STobias Grosser } 158379a947c2STobias Grosser 1584f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions( 1585f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions) { 1586f291c8d5SSiddharth Bhat for (auto Fn : SubtreeFunctions) { 1587f291c8d5SSiddharth Bhat const std::string ClonedFnName = Fn->getName(); 1588f291c8d5SSiddharth Bhat Function *Clone = GPUModule->getFunction(ClonedFnName); 1589f291c8d5SSiddharth Bhat if (!Clone) 1590f291c8d5SSiddharth Bhat Clone = 1591f291c8d5SSiddharth Bhat Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage, 1592f291c8d5SSiddharth Bhat ClonedFnName, GPUModule.get()); 1593f291c8d5SSiddharth Bhat assert(Clone && "Expected cloned function to be initialized."); 1594f291c8d5SSiddharth Bhat assert(ValueMap.find(Fn) == ValueMap.end() && 1595f291c8d5SSiddharth Bhat "Fn already present in ValueMap"); 1596f291c8d5SSiddharth Bhat ValueMap[Fn] = Clone; 1597f291c8d5SSiddharth Bhat } 1598f291c8d5SSiddharth Bhat } 159932837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) { 160032837fe3STobias Grosser isl_id *Id = isl_ast_node_get_annotation(KernelStmt); 160132837fe3STobias Grosser ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id); 160232837fe3STobias Grosser isl_id_free(Id); 160332837fe3STobias Grosser isl_ast_node_free(KernelStmt); 160432837fe3STobias Grosser 1605bc653f20STobias Grosser if (Kernel->n_grid > 1) 1606bc653f20STobias Grosser DeepestParallel = 1607bc653f20STobias Grosser std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set)); 1608bc653f20STobias Grosser else 1609bc653f20STobias Grosser DeepestSequential = 1610bc653f20STobias Grosser std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set)); 1611bc653f20STobias Grosser 1612c1c6a2a6STobias Grosser Value *BlockDimX, *BlockDimY, *BlockDimZ; 1613c1c6a2a6STobias Grosser std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel); 1614c1c6a2a6STobias Grosser 1615f291c8d5SSiddharth Bhat SetVector<Value *> SubtreeValues; 1616f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions; 1617f291c8d5SSiddharth Bhat std::tie(SubtreeValues, SubtreeFunctions) = getReferencesInKernel(Kernel); 1618edb885cbSTobias Grosser 161932837fe3STobias Grosser assert(Kernel->tree && "Device AST of kernel node is empty"); 162032837fe3STobias Grosser 162132837fe3STobias Grosser Instruction &HostInsertPoint = *Builder.GetInsertPoint(); 1622472f9654STobias Grosser IslExprBuilder::IDToValueTy HostIDs = IDToValue; 1623edb885cbSTobias Grosser ValueMapT HostValueMap = ValueMap; 1624587f1f57STobias Grosser BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap; 1625b06ff457STobias Grosser ScalarMap.clear(); 162632837fe3STobias Grosser 1627edb885cbSTobias Grosser SetVector<const Loop *> Loops; 1628edb885cbSTobias Grosser 1629edb885cbSTobias Grosser // Create for all loops we depend on values that contain the current loop 1630edb885cbSTobias Grosser // iteration. These values are necessary to generate code for SCEVs that 1631edb885cbSTobias Grosser // depend on such loops. As a result we need to pass them to the subfunction. 1632edb885cbSTobias Grosser for (const Loop *L : Loops) { 1633edb885cbSTobias Grosser const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)), 1634edb885cbSTobias Grosser SE.getUnknown(Builder.getInt64(1)), 1635edb885cbSTobias Grosser L, SCEV::FlagAnyWrap); 1636edb885cbSTobias Grosser Value *V = generateSCEV(OuterLIV); 1637edb885cbSTobias Grosser OutsideLoopIterations[L] = SE.getUnknown(V); 1638edb885cbSTobias Grosser SubtreeValues.insert(V); 1639edb885cbSTobias Grosser } 1640edb885cbSTobias Grosser 1641f291c8d5SSiddharth Bhat createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions); 1642f291c8d5SSiddharth Bhat setupKernelSubtreeFunctions(SubtreeFunctions); 164332837fe3STobias Grosser 164459ab0705STobias Grosser create(isl_ast_node_copy(Kernel->tree)); 164559ab0705STobias Grosser 164651dfc275STobias Grosser finalizeKernelArguments(Kernel); 164774dc3cb4STobias Grosser Function *F = Builder.GetInsertBlock()->getParent(); 1648c1c6a2a6STobias Grosser addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ); 164974dc3cb4STobias Grosser clearDominators(F); 165074dc3cb4STobias Grosser clearScalarEvolution(F); 165174dc3cb4STobias Grosser clearLoops(F); 165274dc3cb4STobias Grosser 1653472f9654STobias Grosser IDToValue = HostIDs; 165432837fe3STobias Grosser 1655b06ff457STobias Grosser ValueMap = std::move(HostValueMap); 1656b06ff457STobias Grosser ScalarMap = std::move(HostScalarMap); 1657edb885cbSTobias Grosser EscapeMap.clear(); 1658edb885cbSTobias Grosser IDToSAI.clear(); 165974dc3cb4STobias Grosser Annotator.resetAlternativeAliasBases(); 166074dc3cb4STobias Grosser for (auto &BasePtr : LocalArrays) 16614d5a9172STobias Grosser S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array); 166274dc3cb4STobias Grosser LocalArrays.clear(); 1663edb885cbSTobias Grosser 166451dfc275STobias Grosser std::string ASMString = finalizeKernelFunction(); 166551dfc275STobias Grosser Builder.SetInsertPoint(&HostInsertPoint); 166657693272STobias Grosser Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues); 166779a947c2STobias Grosser 166879f13b9aSSingapuram Sanjay Srivallabh std::string Name = getKernelFuncName(Kernel->id); 166957793596STobias Grosser Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name); 167057793596STobias Grosser Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name"); 167157793596STobias Grosser Value *GPUKernel = createCallGetKernel(KernelString, NameString); 167279a947c2STobias Grosser 167379a947c2STobias Grosser Value *GridDimX, *GridDimY; 167479a947c2STobias Grosser std::tie(GridDimX, GridDimY) = getGridSizes(Kernel); 167579a947c2STobias Grosser 167679a947c2STobias Grosser createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 167779a947c2STobias Grosser BlockDimZ, Parameters); 167857793596STobias Grosser createCallFreeKernel(GPUKernel); 1679b513b491STobias Grosser 1680b513b491STobias Grosser for (auto Id : KernelIds) 1681b513b491STobias Grosser isl_id_free(Id); 1682b513b491STobias Grosser 1683b513b491STobias Grosser KernelIds.clear(); 168432837fe3STobias Grosser } 168532837fe3STobias Grosser 168632837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend. 168732837fe3STobias Grosser /// 168832837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture? 168932837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) { 1690d277fedaSSiddharth Bhat std::string Ret = ""; 169132837fe3STobias Grosser 1692d277fedaSSiddharth Bhat if (!is64Bit) { 1693d277fedaSSiddharth Bhat Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1694d277fedaSSiddharth Bhat "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1695d277fedaSSiddharth Bhat "64-v128:128:128-n16:32:64"; 1696d277fedaSSiddharth Bhat } else { 1697d277fedaSSiddharth Bhat Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1698d277fedaSSiddharth Bhat "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1699d277fedaSSiddharth Bhat "64-v128:128:128-n16:32:64"; 1700d277fedaSSiddharth Bhat } 170132837fe3STobias Grosser 170232837fe3STobias Grosser return Ret; 170332837fe3STobias Grosser } 170432837fe3STobias Grosser 1705edb885cbSTobias Grosser Function * 1706edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel, 1707edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues) { 170832837fe3STobias Grosser std::vector<Type *> Args; 170979f13b9aSSingapuram Sanjay Srivallabh std::string Identifier = getKernelFuncName(Kernel->id); 171032837fe3STobias Grosser 171132837fe3STobias Grosser for (long i = 0; i < Prog->n_array; i++) { 171232837fe3STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 171332837fe3STobias Grosser continue; 171432837fe3STobias Grosser 1715fe74a7a1STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1716fe74a7a1STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1717fe74a7a1STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id); 1718fe74a7a1STobias Grosser Args.push_back(SAI->getElementType()); 1719fe74a7a1STobias Grosser } else { 1720d277fedaSSiddharth Bhat static const int UseGlobalMemory = 1; 1721d277fedaSSiddharth Bhat Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory)); 172232837fe3STobias Grosser } 1723fe74a7a1STobias Grosser } 172432837fe3STobias Grosser 1725f6044bd0STobias Grosser int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1726f6044bd0STobias Grosser 1727f6044bd0STobias Grosser for (long i = 0; i < NumHostIters; i++) 1728f6044bd0STobias Grosser Args.push_back(Builder.getInt64Ty()); 1729f6044bd0STobias Grosser 1730c84a1995STobias Grosser int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1731c84a1995STobias Grosser 1732cf66ef26STobias Grosser for (long i = 0; i < NumVars; i++) { 1733cf66ef26STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1734cf66ef26STobias Grosser Value *Val = IDToValue[Id]; 1735cf66ef26STobias Grosser isl_id_free(Id); 1736cf66ef26STobias Grosser Args.push_back(Val->getType()); 1737cf66ef26STobias Grosser } 1738c84a1995STobias Grosser 1739edb885cbSTobias Grosser for (auto *V : SubtreeValues) 1740edb885cbSTobias Grosser Args.push_back(V->getType()); 1741edb885cbSTobias Grosser 174232837fe3STobias Grosser auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false); 174332837fe3STobias Grosser auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier, 174432837fe3STobias Grosser GPUModule.get()); 174517f01968SSiddharth Bhat 174617f01968SSiddharth Bhat switch (Arch) { 174717f01968SSiddharth Bhat case GPUArch::NVPTX64: 174832837fe3STobias Grosser FN->setCallingConv(CallingConv::PTX_Kernel); 174917f01968SSiddharth Bhat break; 175017f01968SSiddharth Bhat } 175132837fe3STobias Grosser 175232837fe3STobias Grosser auto Arg = FN->arg_begin(); 175332837fe3STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 175432837fe3STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 175532837fe3STobias Grosser continue; 175632837fe3STobias Grosser 1757edb885cbSTobias Grosser Arg->setName(Kernel->array[i].array->name); 1758edb885cbSTobias Grosser 1759edb885cbSTobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1760edb885cbSTobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 1761edb885cbSTobias Grosser Type *EleTy = SAI->getElementType(); 1762edb885cbSTobias Grosser Value *Val = &*Arg; 1763edb885cbSTobias Grosser SmallVector<const SCEV *, 4> Sizes; 1764edb885cbSTobias Grosser isl_ast_build *Build = 1765edb885cbSTobias Grosser isl_ast_build_from_context(isl_set_copy(Prog->context)); 1766f5aff704SRoman Gareev Sizes.push_back(nullptr); 1767edb885cbSTobias Grosser for (long j = 1; j < Kernel->array[i].array->n_index; j++) { 1768edb885cbSTobias Grosser isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff( 1769edb885cbSTobias Grosser Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j])); 1770edb885cbSTobias Grosser auto V = ExprBuilder.create(DimSize); 1771edb885cbSTobias Grosser Sizes.push_back(SE.getSCEV(V)); 1772edb885cbSTobias Grosser } 1773edb885cbSTobias Grosser const ScopArrayInfo *SAIRep = 17744d5a9172STobias Grosser S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array); 177574dc3cb4STobias Grosser LocalArrays.push_back(Val); 1776edb885cbSTobias Grosser 1777edb885cbSTobias Grosser isl_ast_build_free(Build); 1778b513b491STobias Grosser KernelIds.push_back(Id); 1779edb885cbSTobias Grosser IDToSAI[Id] = SAIRep; 178032837fe3STobias Grosser Arg++; 178132837fe3STobias Grosser } 178232837fe3STobias Grosser 1783f6044bd0STobias Grosser for (long i = 0; i < NumHostIters; i++) { 1784f6044bd0STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1785f6044bd0STobias Grosser Arg->setName(isl_id_get_name(Id)); 1786f6044bd0STobias Grosser IDToValue[Id] = &*Arg; 1787f6044bd0STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1788f6044bd0STobias Grosser Arg++; 1789f6044bd0STobias Grosser } 1790f6044bd0STobias Grosser 1791c84a1995STobias Grosser for (long i = 0; i < NumVars; i++) { 1792c84a1995STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1793c84a1995STobias Grosser Arg->setName(isl_id_get_name(Id)); 179412453403STobias Grosser Value *Val = IDToValue[Id]; 179512453403STobias Grosser ValueMap[Val] = &*Arg; 1796c84a1995STobias Grosser IDToValue[Id] = &*Arg; 1797c84a1995STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1798c84a1995STobias Grosser Arg++; 1799c84a1995STobias Grosser } 1800c84a1995STobias Grosser 1801edb885cbSTobias Grosser for (auto *V : SubtreeValues) { 1802edb885cbSTobias Grosser Arg->setName(V->getName()); 1803edb885cbSTobias Grosser ValueMap[V] = &*Arg; 1804edb885cbSTobias Grosser Arg++; 1805edb885cbSTobias Grosser } 1806edb885cbSTobias Grosser 180732837fe3STobias Grosser return FN; 180832837fe3STobias Grosser } 180932837fe3STobias Grosser 1810472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) { 181117f01968SSiddharth Bhat Intrinsic::ID IntrinsicsBID[2]; 181217f01968SSiddharth Bhat Intrinsic::ID IntrinsicsTID[3]; 1813472f9654STobias Grosser 181417f01968SSiddharth Bhat switch (Arch) { 181517f01968SSiddharth Bhat case GPUArch::NVPTX64: 181617f01968SSiddharth Bhat IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x; 181717f01968SSiddharth Bhat IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y; 181817f01968SSiddharth Bhat 181917f01968SSiddharth Bhat IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x; 182017f01968SSiddharth Bhat IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y; 182117f01968SSiddharth Bhat IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z; 182217f01968SSiddharth Bhat break; 182317f01968SSiddharth Bhat } 1824472f9654STobias Grosser 1825472f9654STobias Grosser auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable { 1826472f9654STobias Grosser std::string Name = isl_id_get_name(Id); 1827472f9654STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1828472f9654STobias Grosser Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr); 1829472f9654STobias Grosser Value *Val = Builder.CreateCall(IntrinsicFn, {}); 1830472f9654STobias Grosser Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 1831472f9654STobias Grosser IDToValue[Id] = Val; 1832472f9654STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1833472f9654STobias Grosser }; 1834472f9654STobias Grosser 1835472f9654STobias Grosser for (int i = 0; i < Kernel->n_grid; ++i) { 1836472f9654STobias Grosser isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i); 1837472f9654STobias Grosser addId(Id, IntrinsicsBID[i]); 1838472f9654STobias Grosser } 1839472f9654STobias Grosser 1840472f9654STobias Grosser for (int i = 0; i < Kernel->n_block; ++i) { 1841472f9654STobias Grosser isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i); 1842472f9654STobias Grosser addId(Id, IntrinsicsTID[i]); 1843472f9654STobias Grosser } 1844472f9654STobias Grosser } 1845472f9654STobias Grosser 184600bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) { 184700bb5a99STobias Grosser auto Arg = FN->arg_begin(); 184800bb5a99STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 184900bb5a99STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 185000bb5a99STobias Grosser continue; 185100bb5a99STobias Grosser 185200bb5a99STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 185300bb5a99STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 185400bb5a99STobias Grosser isl_id_free(Id); 185500bb5a99STobias Grosser 185600bb5a99STobias Grosser if (SAI->getNumberOfDimensions() > 0) { 185700bb5a99STobias Grosser Arg++; 185800bb5a99STobias Grosser continue; 185900bb5a99STobias Grosser } 186000bb5a99STobias Grosser 1861fe74a7a1STobias Grosser Value *Val = &*Arg; 1862fe74a7a1STobias Grosser 1863fe74a7a1STobias Grosser if (!gpu_array_is_read_only_scalar(&Prog->array[i])) { 186400bb5a99STobias Grosser Type *TypePtr = SAI->getElementType()->getPointerTo(); 1865fe74a7a1STobias Grosser Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr); 1866fe74a7a1STobias Grosser Val = Builder.CreateLoad(TypedArgPtr); 1867fe74a7a1STobias Grosser } 1868fe74a7a1STobias Grosser 1869fe74a7a1STobias Grosser Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 187000bb5a99STobias Grosser Builder.CreateStore(Val, Alloca); 187100bb5a99STobias Grosser 187200bb5a99STobias Grosser Arg++; 187300bb5a99STobias Grosser } 187400bb5a99STobias Grosser } 187500bb5a99STobias Grosser 187651dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) { 187751dfc275STobias Grosser auto *FN = Builder.GetInsertBlock()->getParent(); 187851dfc275STobias Grosser auto Arg = FN->arg_begin(); 187951dfc275STobias Grosser 188051dfc275STobias Grosser bool StoredScalar = false; 188151dfc275STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 188251dfc275STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 188351dfc275STobias Grosser continue; 188451dfc275STobias Grosser 188551dfc275STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 188651dfc275STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 188751dfc275STobias Grosser isl_id_free(Id); 188851dfc275STobias Grosser 188951dfc275STobias Grosser if (SAI->getNumberOfDimensions() > 0) { 189051dfc275STobias Grosser Arg++; 189151dfc275STobias Grosser continue; 189251dfc275STobias Grosser } 189351dfc275STobias Grosser 189451dfc275STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 189551dfc275STobias Grosser Arg++; 189651dfc275STobias Grosser continue; 189751dfc275STobias Grosser } 189851dfc275STobias Grosser 189951dfc275STobias Grosser Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 190051dfc275STobias Grosser Value *ArgPtr = &*Arg; 190151dfc275STobias Grosser Type *TypePtr = SAI->getElementType()->getPointerTo(); 190251dfc275STobias Grosser Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr); 190351dfc275STobias Grosser Value *Val = Builder.CreateLoad(Alloca); 190451dfc275STobias Grosser Builder.CreateStore(Val, TypedArgPtr); 190551dfc275STobias Grosser StoredScalar = true; 190651dfc275STobias Grosser 190751dfc275STobias Grosser Arg++; 190851dfc275STobias Grosser } 190951dfc275STobias Grosser 191051dfc275STobias Grosser if (StoredScalar) 191151dfc275STobias Grosser /// In case more than one thread contains scalar stores, the generated 191251dfc275STobias Grosser /// code might be incorrect, if we only store at the end of the kernel. 191351dfc275STobias Grosser /// To support this case we need to store these scalars back at each 191451dfc275STobias Grosser /// memory store or at least before each kernel barrier. 191551dfc275STobias Grosser if (Kernel->n_block != 0 || Kernel->n_grid != 0) 191651dfc275STobias Grosser BuildSuccessful = 0; 191751dfc275STobias Grosser } 191851dfc275STobias Grosser 1919b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) { 1920b513b491STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1921b513b491STobias Grosser 1922b513b491STobias Grosser for (int i = 0; i < Kernel->n_var; ++i) { 1923b513b491STobias Grosser struct ppcg_kernel_var &Var = Kernel->var[i]; 1924b513b491STobias Grosser isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set); 1925b513b491STobias Grosser Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType(); 1926b513b491STobias Grosser 1927f919d8b3STobias Grosser Type *ArrayTy = EleTy; 1928b513b491STobias Grosser SmallVector<const SCEV *, 4> Sizes; 1929b513b491STobias Grosser 1930f5aff704SRoman Gareev Sizes.push_back(nullptr); 1931928d7573STobias Grosser for (unsigned int j = 1; j < Var.array->n_index; ++j) { 1932b513b491STobias Grosser isl_val *Val = isl_vec_get_element_val(Var.size, j); 1933f919d8b3STobias Grosser long Bound = isl_val_get_num_si(Val); 1934b513b491STobias Grosser isl_val_free(Val); 1935b513b491STobias Grosser Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound)); 1936928d7573STobias Grosser } 1937928d7573STobias Grosser 1938928d7573STobias Grosser for (int j = Var.array->n_index - 1; j >= 0; --j) { 1939928d7573STobias Grosser isl_val *Val = isl_vec_get_element_val(Var.size, j); 1940928d7573STobias Grosser long Bound = isl_val_get_num_si(Val); 1941928d7573STobias Grosser isl_val_free(Val); 1942b513b491STobias Grosser ArrayTy = ArrayType::get(ArrayTy, Bound); 1943b513b491STobias Grosser } 1944b513b491STobias Grosser 1945130ca30fSTobias Grosser const ScopArrayInfo *SAI; 1946130ca30fSTobias Grosser Value *Allocation; 1947130ca30fSTobias Grosser if (Var.type == ppcg_access_shared) { 1948130ca30fSTobias Grosser auto GlobalVar = new GlobalVariable( 1949130ca30fSTobias Grosser *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name, 1950130ca30fSTobias Grosser nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3); 1951130ca30fSTobias Grosser GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8); 1952f919d8b3STobias Grosser GlobalVar->setInitializer(Constant::getNullValue(ArrayTy)); 1953f919d8b3STobias Grosser 1954130ca30fSTobias Grosser Allocation = GlobalVar; 1955130ca30fSTobias Grosser } else if (Var.type == ppcg_access_private) { 1956130ca30fSTobias Grosser Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array"); 1957130ca30fSTobias Grosser } else { 1958130ca30fSTobias Grosser llvm_unreachable("unknown variable type"); 1959130ca30fSTobias Grosser } 19604d5a9172STobias Grosser SAI = 19614d5a9172STobias Grosser S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array); 1962b513b491STobias Grosser Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr); 1963130ca30fSTobias Grosser IDToValue[Id] = Allocation; 1964130ca30fSTobias Grosser LocalArrays.push_back(Allocation); 1965b513b491STobias Grosser KernelIds.push_back(Id); 1966b513b491STobias Grosser IDToSAI[Id] = SAI; 1967b513b491STobias Grosser } 1968b513b491STobias Grosser } 1969b513b491STobias Grosser 1970f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction( 1971f291c8d5SSiddharth Bhat ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues, 1972f291c8d5SSiddharth Bhat SetVector<Function *> &SubtreeFunctions) { 197379f13b9aSSingapuram Sanjay Srivallabh std::string Identifier = getKernelFuncName(Kernel->id); 197432837fe3STobias Grosser GPUModule.reset(new Module(Identifier, Builder.getContext())); 197517f01968SSiddharth Bhat 197617f01968SSiddharth Bhat switch (Arch) { 197717f01968SSiddharth Bhat case GPUArch::NVPTX64: 197817f01968SSiddharth Bhat if (Runtime == GPURuntime::CUDA) 197932837fe3STobias Grosser GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda")); 198017f01968SSiddharth Bhat else if (Runtime == GPURuntime::OpenCL) 198117f01968SSiddharth Bhat GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl")); 198232837fe3STobias Grosser GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */)); 198317f01968SSiddharth Bhat break; 198417f01968SSiddharth Bhat } 198532837fe3STobias Grosser 1986edb885cbSTobias Grosser Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues); 198732837fe3STobias Grosser 198859ab0705STobias Grosser BasicBlock *PrevBlock = Builder.GetInsertBlock(); 198932837fe3STobias Grosser auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN); 199032837fe3STobias Grosser 199159ab0705STobias Grosser DT.addNewBlock(EntryBlock, PrevBlock); 199259ab0705STobias Grosser 199332837fe3STobias Grosser Builder.SetInsertPoint(EntryBlock); 199432837fe3STobias Grosser Builder.CreateRetVoid(); 199532837fe3STobias Grosser Builder.SetInsertPoint(EntryBlock, EntryBlock->begin()); 1996472f9654STobias Grosser 1997629109b6STobias Grosser ScopDetection::markFunctionAsInvalid(FN); 1998629109b6STobias Grosser 199900bb5a99STobias Grosser prepareKernelArguments(Kernel, FN); 2000b513b491STobias Grosser createKernelVariables(Kernel, FN); 2001472f9654STobias Grosser insertKernelIntrinsics(Kernel); 200232837fe3STobias Grosser } 200332837fe3STobias Grosser 200474dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() { 200517f01968SSiddharth Bhat llvm::Triple GPUTriple; 200617f01968SSiddharth Bhat 200717f01968SSiddharth Bhat switch (Arch) { 200817f01968SSiddharth Bhat case GPUArch::NVPTX64: 200917f01968SSiddharth Bhat switch (Runtime) { 201017f01968SSiddharth Bhat case GPURuntime::CUDA: 201117f01968SSiddharth Bhat GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda")); 201217f01968SSiddharth Bhat break; 201317f01968SSiddharth Bhat case GPURuntime::OpenCL: 201417f01968SSiddharth Bhat GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl")); 201517f01968SSiddharth Bhat break; 201617f01968SSiddharth Bhat } 201717f01968SSiddharth Bhat break; 201817f01968SSiddharth Bhat } 201917f01968SSiddharth Bhat 202074dc3cb4STobias Grosser std::string ErrMsg; 202174dc3cb4STobias Grosser auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg); 202274dc3cb4STobias Grosser 202374dc3cb4STobias Grosser if (!GPUTarget) { 202474dc3cb4STobias Grosser errs() << ErrMsg << "\n"; 202574dc3cb4STobias Grosser return ""; 202674dc3cb4STobias Grosser } 202774dc3cb4STobias Grosser 202874dc3cb4STobias Grosser TargetOptions Options; 202974dc3cb4STobias Grosser Options.UnsafeFPMath = FastMath; 203017f01968SSiddharth Bhat 203117f01968SSiddharth Bhat std::string subtarget; 203217f01968SSiddharth Bhat 203317f01968SSiddharth Bhat switch (Arch) { 203417f01968SSiddharth Bhat case GPUArch::NVPTX64: 203517f01968SSiddharth Bhat subtarget = CudaVersion; 203617f01968SSiddharth Bhat break; 203717f01968SSiddharth Bhat } 203817f01968SSiddharth Bhat 203917f01968SSiddharth Bhat std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine( 204017f01968SSiddharth Bhat GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>())); 204174dc3cb4STobias Grosser 204274dc3cb4STobias Grosser SmallString<0> ASMString; 204374dc3cb4STobias Grosser raw_svector_ostream ASMStream(ASMString); 204474dc3cb4STobias Grosser llvm::legacy::PassManager PM; 204574dc3cb4STobias Grosser 204674dc3cb4STobias Grosser PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis())); 204774dc3cb4STobias Grosser 204874dc3cb4STobias Grosser if (TargetM->addPassesToEmitFile( 204974dc3cb4STobias Grosser PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) { 205074dc3cb4STobias Grosser errs() << "The target does not support generation of this file type!\n"; 205174dc3cb4STobias Grosser return ""; 205274dc3cb4STobias Grosser } 205374dc3cb4STobias Grosser 205474dc3cb4STobias Grosser PM.run(*GPUModule); 205574dc3cb4STobias Grosser 205674dc3cb4STobias Grosser return ASMStream.str(); 205774dc3cb4STobias Grosser } 205874dc3cb4STobias Grosser 205957793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() { 206065d7f72fSSiddharth Bhat 20615857b701STobias Grosser if (verifyModule(*GPUModule)) { 206265d7f72fSSiddharth Bhat DEBUG(dbgs() << "verifyModule failed on module:\n"; 206365d7f72fSSiddharth Bhat GPUModule->print(dbgs(), nullptr); dbgs() << "\n";); 206465d7f72fSSiddharth Bhat 206565d7f72fSSiddharth Bhat if (FailOnVerifyModuleFailure) 206665d7f72fSSiddharth Bhat llvm_unreachable("VerifyModule failed."); 206765d7f72fSSiddharth Bhat 20685857b701STobias Grosser BuildSuccessful = false; 20695857b701STobias Grosser return ""; 20705857b701STobias Grosser } 207132837fe3STobias Grosser 207232837fe3STobias Grosser if (DumpKernelIR) 207332837fe3STobias Grosser outs() << *GPUModule << "\n"; 207432837fe3STobias Grosser 20759a18d559STobias Grosser // Optimize module. 20769a18d559STobias Grosser llvm::legacy::PassManager OptPasses; 20779a18d559STobias Grosser PassManagerBuilder PassBuilder; 20789a18d559STobias Grosser PassBuilder.OptLevel = 3; 20799a18d559STobias Grosser PassBuilder.SizeLevel = 0; 20809a18d559STobias Grosser PassBuilder.populateModulePassManager(OptPasses); 20819a18d559STobias Grosser OptPasses.run(*GPUModule); 20829a18d559STobias Grosser 208374dc3cb4STobias Grosser std::string Assembly = createKernelASM(); 208474dc3cb4STobias Grosser 208574dc3cb4STobias Grosser if (DumpKernelASM) 208674dc3cb4STobias Grosser outs() << Assembly << "\n"; 208774dc3cb4STobias Grosser 208832837fe3STobias Grosser GPUModule.release(); 2089472f9654STobias Grosser KernelIDs.clear(); 209057793596STobias Grosser 209157793596STobias Grosser return Assembly; 209232837fe3STobias Grosser } 209332837fe3STobias Grosser 20949dfe4e7cSTobias Grosser namespace { 20959dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass { 20969dfe4e7cSTobias Grosser public: 20979dfe4e7cSTobias Grosser static char ID; 20989dfe4e7cSTobias Grosser 209917f01968SSiddharth Bhat GPURuntime Runtime = GPURuntime::CUDA; 210017f01968SSiddharth Bhat 210117f01968SSiddharth Bhat GPUArch Architecture = GPUArch::NVPTX64; 210217f01968SSiddharth Bhat 2103e938517eSTobias Grosser /// The scop that is currently processed. 2104e938517eSTobias Grosser Scop *S; 2105e938517eSTobias Grosser 210638fc0aedSTobias Grosser LoopInfo *LI; 210738fc0aedSTobias Grosser DominatorTree *DT; 210838fc0aedSTobias Grosser ScalarEvolution *SE; 210938fc0aedSTobias Grosser const DataLayout *DL; 211038fc0aedSTobias Grosser RegionInfo *RI; 211138fc0aedSTobias Grosser 21129dfe4e7cSTobias Grosser PPCGCodeGeneration() : ScopPass(ID) {} 21139dfe4e7cSTobias Grosser 2114e938517eSTobias Grosser /// Construct compilation options for PPCG. 2115e938517eSTobias Grosser /// 2116e938517eSTobias Grosser /// @returns The compilation options. 2117e938517eSTobias Grosser ppcg_options *createPPCGOptions() { 2118e938517eSTobias Grosser auto DebugOptions = 2119e938517eSTobias Grosser (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options)); 2120e938517eSTobias Grosser auto Options = (ppcg_options *)malloc(sizeof(ppcg_options)); 2121e938517eSTobias Grosser 2122e938517eSTobias Grosser DebugOptions->dump_schedule_constraints = false; 2123e938517eSTobias Grosser DebugOptions->dump_schedule = false; 2124e938517eSTobias Grosser DebugOptions->dump_final_schedule = false; 2125e938517eSTobias Grosser DebugOptions->dump_sizes = false; 21268950ceadSTobias Grosser DebugOptions->verbose = false; 2127e938517eSTobias Grosser 2128e938517eSTobias Grosser Options->debug = DebugOptions; 2129e938517eSTobias Grosser 2130e938517eSTobias Grosser Options->reschedule = true; 2131e938517eSTobias Grosser Options->scale_tile_loops = false; 2132e938517eSTobias Grosser Options->wrap = false; 2133e938517eSTobias Grosser 2134e938517eSTobias Grosser Options->non_negative_parameters = false; 2135e938517eSTobias Grosser Options->ctx = nullptr; 2136e938517eSTobias Grosser Options->sizes = nullptr; 2137e938517eSTobias Grosser 21384eaedde5STobias Grosser Options->tile_size = 32; 21394eaedde5STobias Grosser 2140130ca30fSTobias Grosser Options->use_private_memory = PrivateMemory; 2141b513b491STobias Grosser Options->use_shared_memory = SharedMemory; 2142b513b491STobias Grosser Options->max_shared_memory = 48 * 1024; 2143e938517eSTobias Grosser 2144e938517eSTobias Grosser Options->target = PPCG_TARGET_CUDA; 2145e938517eSTobias Grosser Options->openmp = false; 2146e938517eSTobias Grosser Options->linearize_device_arrays = true; 2147e938517eSTobias Grosser Options->live_range_reordering = false; 2148e938517eSTobias Grosser 2149e938517eSTobias Grosser Options->opencl_compiler_options = nullptr; 2150e938517eSTobias Grosser Options->opencl_use_gpu = false; 2151e938517eSTobias Grosser Options->opencl_n_include_file = 0; 2152e938517eSTobias Grosser Options->opencl_include_files = nullptr; 2153e938517eSTobias Grosser Options->opencl_print_kernel_types = false; 2154e938517eSTobias Grosser Options->opencl_embed_kernel_code = false; 2155e938517eSTobias Grosser 2156e938517eSTobias Grosser Options->save_schedule_file = nullptr; 2157e938517eSTobias Grosser Options->load_schedule_file = nullptr; 2158e938517eSTobias Grosser 2159e938517eSTobias Grosser return Options; 2160e938517eSTobias Grosser } 2161e938517eSTobias Grosser 2162f384594dSTobias Grosser /// Get a tagged access relation containing all accesses of type @p AccessTy. 2163f384594dSTobias Grosser /// 2164f384594dSTobias Grosser /// Instead of a normal access of the form: 2165f384594dSTobias Grosser /// 2166f384594dSTobias Grosser /// Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)] 2167f384594dSTobias Grosser /// 2168f384594dSTobias Grosser /// a tagged access has the form 2169f384594dSTobias Grosser /// 2170f384594dSTobias Grosser /// [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)] 2171f384594dSTobias Grosser /// 2172f384594dSTobias Grosser /// where 'id' is an additional space that references the memory access that 2173f384594dSTobias Grosser /// triggered the access. 2174f384594dSTobias Grosser /// 2175f384594dSTobias Grosser /// @param AccessTy The type of the memory accesses to collect. 2176f384594dSTobias Grosser /// 2177f384594dSTobias Grosser /// @return The relation describing all tagged memory accesses. 2178f384594dSTobias Grosser isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) { 2179f384594dSTobias Grosser isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace()); 2180f384594dSTobias Grosser 2181f384594dSTobias Grosser for (auto &Stmt : *S) 2182f384594dSTobias Grosser for (auto &Acc : Stmt) 2183f384594dSTobias Grosser if (Acc->getType() == AccessTy) { 2184f384594dSTobias Grosser isl_map *Relation = Acc->getAccessRelation(); 2185f384594dSTobias Grosser Relation = isl_map_intersect_domain(Relation, Stmt.getDomain()); 2186f384594dSTobias Grosser 2187f384594dSTobias Grosser isl_space *Space = isl_map_get_space(Relation); 2188f384594dSTobias Grosser Space = isl_space_range(Space); 2189f384594dSTobias Grosser Space = isl_space_from_range(Space); 21906293ba69STobias Grosser Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId()); 2191f384594dSTobias Grosser isl_map *Universe = isl_map_universe(Space); 2192f384594dSTobias Grosser Relation = isl_map_domain_product(Relation, Universe); 2193f384594dSTobias Grosser Accesses = isl_union_map_add_map(Accesses, Relation); 2194f384594dSTobias Grosser } 2195f384594dSTobias Grosser 2196f384594dSTobias Grosser return Accesses; 2197f384594dSTobias Grosser } 2198f384594dSTobias Grosser 2199f384594dSTobias Grosser /// Get the set of all read accesses, tagged with the access id. 2200f384594dSTobias Grosser /// 2201f384594dSTobias Grosser /// @see getTaggedAccesses 2202f384594dSTobias Grosser isl_union_map *getTaggedReads() { 2203f384594dSTobias Grosser return getTaggedAccesses(MemoryAccess::READ); 2204f384594dSTobias Grosser } 2205f384594dSTobias Grosser 2206f384594dSTobias Grosser /// Get the set of all may (and must) accesses, tagged with the access id. 2207f384594dSTobias Grosser /// 2208f384594dSTobias Grosser /// @see getTaggedAccesses 2209f384594dSTobias Grosser isl_union_map *getTaggedMayWrites() { 2210f384594dSTobias Grosser return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE), 2211f384594dSTobias Grosser getTaggedAccesses(MemoryAccess::MUST_WRITE)); 2212f384594dSTobias Grosser } 2213f384594dSTobias Grosser 2214f384594dSTobias Grosser /// Get the set of all must accesses, tagged with the access id. 2215f384594dSTobias Grosser /// 2216f384594dSTobias Grosser /// @see getTaggedAccesses 2217f384594dSTobias Grosser isl_union_map *getTaggedMustWrites() { 2218f384594dSTobias Grosser return getTaggedAccesses(MemoryAccess::MUST_WRITE); 2219f384594dSTobias Grosser } 2220f384594dSTobias Grosser 2221aef5196fSTobias Grosser /// Collect parameter and array names as isl_ids. 2222aef5196fSTobias Grosser /// 2223aef5196fSTobias Grosser /// To reason about the different parameters and arrays used, ppcg requires 2224aef5196fSTobias Grosser /// a list of all isl_ids in use. As PPCG traditionally performs 2225aef5196fSTobias Grosser /// source-to-source compilation each of these isl_ids is mapped to the 2226aef5196fSTobias Grosser /// expression that represents it. As we do not have a corresponding 2227aef5196fSTobias Grosser /// expression in Polly, we just map each id to a 'zero' expression to match 2228aef5196fSTobias Grosser /// the data format that ppcg expects. 2229aef5196fSTobias Grosser /// 2230aef5196fSTobias Grosser /// @returns Retun a map from collected ids to 'zero' ast expressions. 2231aef5196fSTobias Grosser __isl_give isl_id_to_ast_expr *getNames() { 2232aef5196fSTobias Grosser auto *Names = isl_id_to_ast_expr_alloc( 2233bd81a7eeSTobias Grosser S->getIslCtx(), 2234bd81a7eeSTobias Grosser S->getNumParams() + std::distance(S->array_begin(), S->array_end())); 2235aef5196fSTobias Grosser auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx())); 2236aef5196fSTobias Grosser auto *Space = S->getParamSpace(); 2237aef5196fSTobias Grosser 2238aef5196fSTobias Grosser for (int I = 0, E = S->getNumParams(); I < E; ++I) { 2239aef5196fSTobias Grosser isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I); 2240aef5196fSTobias Grosser Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2241aef5196fSTobias Grosser } 2242aef5196fSTobias Grosser 2243aef5196fSTobias Grosser for (auto &Array : S->arrays()) { 2244d7754a12SRoman Gareev auto Id = Array->getBasePtrId(); 2245aef5196fSTobias Grosser Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2246aef5196fSTobias Grosser } 2247aef5196fSTobias Grosser 2248aef5196fSTobias Grosser isl_space_free(Space); 2249aef5196fSTobias Grosser isl_ast_expr_free(Zero); 2250aef5196fSTobias Grosser 2251aef5196fSTobias Grosser return Names; 2252aef5196fSTobias Grosser } 2253aef5196fSTobias Grosser 2254e938517eSTobias Grosser /// Create a new PPCG scop from the current scop. 2255e938517eSTobias Grosser /// 2256f384594dSTobias Grosser /// The PPCG scop is initialized with data from the current polly::Scop. From 2257f384594dSTobias Grosser /// this initial data, the data-dependences in the PPCG scop are initialized. 2258f384594dSTobias Grosser /// We do not use Polly's dependence analysis for now, to ensure we match 2259f384594dSTobias Grosser /// the PPCG default behaviour more closely. 2260e938517eSTobias Grosser /// 2261e938517eSTobias Grosser /// @returns A new ppcg scop. 2262e938517eSTobias Grosser ppcg_scop *createPPCGScop() { 2263e938517eSTobias Grosser auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop)); 2264e938517eSTobias Grosser 2265e938517eSTobias Grosser PPCGScop->options = createPPCGOptions(); 2266a82f2d26SSiddharth Bhat // enable live range reordering 2267a82f2d26SSiddharth Bhat PPCGScop->options->live_range_reordering = 1; 2268e938517eSTobias Grosser 2269e938517eSTobias Grosser PPCGScop->start = 0; 2270e938517eSTobias Grosser PPCGScop->end = 0; 2271e938517eSTobias Grosser 2272f384594dSTobias Grosser PPCGScop->context = S->getContext(); 2273f384594dSTobias Grosser PPCGScop->domain = S->getDomains(); 2274e938517eSTobias Grosser PPCGScop->call = nullptr; 2275f384594dSTobias Grosser PPCGScop->tagged_reads = getTaggedReads(); 2276f384594dSTobias Grosser PPCGScop->reads = S->getReads(); 2277e938517eSTobias Grosser PPCGScop->live_in = nullptr; 2278f384594dSTobias Grosser PPCGScop->tagged_may_writes = getTaggedMayWrites(); 2279f384594dSTobias Grosser PPCGScop->may_writes = S->getWrites(); 2280f384594dSTobias Grosser PPCGScop->tagged_must_writes = getTaggedMustWrites(); 2281f384594dSTobias Grosser PPCGScop->must_writes = S->getMustWrites(); 2282e938517eSTobias Grosser PPCGScop->live_out = nullptr; 2283e938517eSTobias Grosser PPCGScop->tagger = nullptr; 2284a82f2d26SSiddharth Bhat PPCGScop->independence = 2285a82f2d26SSiddharth Bhat isl_union_map_empty(isl_set_get_space(PPCGScop->context)); 2286e938517eSTobias Grosser PPCGScop->dep_flow = nullptr; 2287e938517eSTobias Grosser PPCGScop->tagged_dep_flow = nullptr; 2288e938517eSTobias Grosser PPCGScop->dep_false = nullptr; 2289e938517eSTobias Grosser PPCGScop->dep_forced = nullptr; 2290e938517eSTobias Grosser PPCGScop->dep_order = nullptr; 2291e938517eSTobias Grosser PPCGScop->tagged_dep_order = nullptr; 2292e938517eSTobias Grosser 2293f384594dSTobias Grosser PPCGScop->schedule = S->getScheduleTree(); 2294e938517eSTobias Grosser 2295a82f2d26SSiddharth Bhat MustKillsInfo KillsInfo = computeMustKillsInfo(*S); 2296a82f2d26SSiddharth Bhat // If we have something non-trivial to kill, add it to the schedule 2297a82f2d26SSiddharth Bhat if (KillsInfo.KillsSchedule.get()) 2298a82f2d26SSiddharth Bhat PPCGScop->schedule = isl_schedule_sequence( 2299a82f2d26SSiddharth Bhat PPCGScop->schedule, KillsInfo.KillsSchedule.take()); 2300a82f2d26SSiddharth Bhat PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.take(); 2301a82f2d26SSiddharth Bhat 2302a82f2d26SSiddharth Bhat PPCGScop->names = getNames(); 2303e938517eSTobias Grosser PPCGScop->pet = nullptr; 2304e938517eSTobias Grosser 2305f384594dSTobias Grosser compute_tagger(PPCGScop); 2306f384594dSTobias Grosser compute_dependences(PPCGScop); 2307f384594dSTobias Grosser 2308e938517eSTobias Grosser return PPCGScop; 2309e938517eSTobias Grosser } 2310e938517eSTobias Grosser 2311a6d48f59SMichael Kruse /// Collect the array accesses in a statement. 231260f63b49STobias Grosser /// 231360f63b49STobias Grosser /// @param Stmt The statement for which to collect the accesses. 231460f63b49STobias Grosser /// 231560f63b49STobias Grosser /// @returns A list of array accesses. 231660f63b49STobias Grosser gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) { 231760f63b49STobias Grosser gpu_stmt_access *Accesses = nullptr; 231860f63b49STobias Grosser 231960f63b49STobias Grosser for (MemoryAccess *Acc : Stmt) { 232060f63b49STobias Grosser auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access); 232160f63b49STobias Grosser Access->read = Acc->isRead(); 232260f63b49STobias Grosser Access->write = Acc->isWrite(); 232360f63b49STobias Grosser Access->access = Acc->getAccessRelation(); 232460f63b49STobias Grosser isl_space *Space = isl_map_get_space(Access->access); 232560f63b49STobias Grosser Space = isl_space_range(Space); 232660f63b49STobias Grosser Space = isl_space_from_range(Space); 23276293ba69STobias Grosser Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId()); 232860f63b49STobias Grosser isl_map *Universe = isl_map_universe(Space); 232960f63b49STobias Grosser Access->tagged_access = 233060f63b49STobias Grosser isl_map_domain_product(Acc->getAccessRelation(), Universe); 2331b513b491STobias Grosser Access->exact_write = !Acc->isMayWrite(); 233260f63b49STobias Grosser Access->ref_id = Acc->getId(); 233360f63b49STobias Grosser Access->next = Accesses; 2334b513b491STobias Grosser Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions(); 233560f63b49STobias Grosser Accesses = Access; 233660f63b49STobias Grosser } 233760f63b49STobias Grosser 233860f63b49STobias Grosser return Accesses; 233960f63b49STobias Grosser } 234060f63b49STobias Grosser 234169b46751STobias Grosser /// Collect the list of GPU statements. 234269b46751STobias Grosser /// 234369b46751STobias Grosser /// Each statement has an id, a pointer to the underlying data structure, 234469b46751STobias Grosser /// as well as a list with all memory accesses. 234569b46751STobias Grosser /// 234669b46751STobias Grosser /// TODO: Initialize the list of memory accesses. 234769b46751STobias Grosser /// 234869b46751STobias Grosser /// @returns A linked-list of statements. 234969b46751STobias Grosser gpu_stmt *getStatements() { 235069b46751STobias Grosser gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt, 235169b46751STobias Grosser std::distance(S->begin(), S->end())); 235269b46751STobias Grosser 235369b46751STobias Grosser int i = 0; 235469b46751STobias Grosser for (auto &Stmt : *S) { 235569b46751STobias Grosser gpu_stmt *GPUStmt = &Stmts[i]; 235669b46751STobias Grosser 235769b46751STobias Grosser GPUStmt->id = Stmt.getDomainId(); 235869b46751STobias Grosser 235969b46751STobias Grosser // We use the pet stmt pointer to keep track of the Polly statements. 236069b46751STobias Grosser GPUStmt->stmt = (pet_stmt *)&Stmt; 236160f63b49STobias Grosser GPUStmt->accesses = getStmtAccesses(Stmt); 236269b46751STobias Grosser i++; 236369b46751STobias Grosser } 236469b46751STobias Grosser 236569b46751STobias Grosser return Stmts; 236669b46751STobias Grosser } 236769b46751STobias Grosser 236860f63b49STobias Grosser /// Derive the extent of an array. 236960f63b49STobias Grosser /// 2370d58acf86STobias Grosser /// The extent of an array is the set of elements that are within the 2371d58acf86STobias Grosser /// accessed array. For the inner dimensions, the extent constraints are 2372d58acf86STobias Grosser /// 0 and the size of the corresponding array dimension. For the first 2373d58acf86STobias Grosser /// (outermost) dimension, the extent constraints are the minimal and maximal 2374d58acf86STobias Grosser /// subscript value for the first dimension. 237560f63b49STobias Grosser /// 237660f63b49STobias Grosser /// @param Array The array to derive the extent for. 237760f63b49STobias Grosser /// 237860f63b49STobias Grosser /// @returns An isl_set describing the extent of the array. 237960f63b49STobias Grosser __isl_give isl_set *getExtent(ScopArrayInfo *Array) { 2380d58acf86STobias Grosser unsigned NumDims = Array->getNumberOfDimensions(); 238160f63b49STobias Grosser isl_union_map *Accesses = S->getAccesses(); 238260f63b49STobias Grosser Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains()); 2383d58acf86STobias Grosser Accesses = isl_union_map_detect_equalities(Accesses); 238460f63b49STobias Grosser isl_union_set *AccessUSet = isl_union_map_range(Accesses); 2385d58acf86STobias Grosser AccessUSet = isl_union_set_coalesce(AccessUSet); 2386d58acf86STobias Grosser AccessUSet = isl_union_set_detect_equalities(AccessUSet); 2387d58acf86STobias Grosser AccessUSet = isl_union_set_coalesce(AccessUSet); 2388d58acf86STobias Grosser 2389d58acf86STobias Grosser if (isl_union_set_is_empty(AccessUSet)) { 2390d58acf86STobias Grosser isl_union_set_free(AccessUSet); 2391d58acf86STobias Grosser return isl_set_empty(Array->getSpace()); 2392d58acf86STobias Grosser } 2393d58acf86STobias Grosser 2394d58acf86STobias Grosser if (Array->getNumberOfDimensions() == 0) { 2395d58acf86STobias Grosser isl_union_set_free(AccessUSet); 2396d58acf86STobias Grosser return isl_set_universe(Array->getSpace()); 2397d58acf86STobias Grosser } 2398d58acf86STobias Grosser 239960f63b49STobias Grosser isl_set *AccessSet = 240060f63b49STobias Grosser isl_union_set_extract_set(AccessUSet, Array->getSpace()); 240160f63b49STobias Grosser 2402d58acf86STobias Grosser isl_union_set_free(AccessUSet); 2403d58acf86STobias Grosser isl_local_space *LS = isl_local_space_from_space(Array->getSpace()); 2404d58acf86STobias Grosser 2405d58acf86STobias Grosser isl_pw_aff *Val = 2406d58acf86STobias Grosser isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0)); 2407d58acf86STobias Grosser 2408d58acf86STobias Grosser isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0); 2409d58acf86STobias Grosser isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0); 2410d58acf86STobias Grosser OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in, 2411d58acf86STobias Grosser isl_pw_aff_dim(Val, isl_dim_in)); 2412d58acf86STobias Grosser OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in, 2413d58acf86STobias Grosser isl_pw_aff_dim(Val, isl_dim_in)); 2414d58acf86STobias Grosser OuterMin = 2415d58acf86STobias Grosser isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, Array->getBasePtrId()); 2416d58acf86STobias Grosser OuterMax = 2417d58acf86STobias Grosser isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, Array->getBasePtrId()); 2418d58acf86STobias Grosser 2419d58acf86STobias Grosser isl_set *Extent = isl_set_universe(Array->getSpace()); 2420d58acf86STobias Grosser 2421d58acf86STobias Grosser Extent = isl_set_intersect( 2422d58acf86STobias Grosser Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val))); 2423d58acf86STobias Grosser Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val)); 2424d58acf86STobias Grosser 2425d58acf86STobias Grosser for (unsigned i = 1; i < NumDims; ++i) 2426d58acf86STobias Grosser Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0); 2427d58acf86STobias Grosser 2428b7f68b8cSSiddharth Bhat for (unsigned i = 0; i < NumDims; ++i) { 2429d58acf86STobias Grosser isl_pw_aff *PwAff = 2430d58acf86STobias Grosser const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i)); 2431b7f68b8cSSiddharth Bhat 2432b7f68b8cSSiddharth Bhat // isl_pw_aff can be NULL for zero dimension. Only in the case of a 2433b7f68b8cSSiddharth Bhat // Fortran array will we have a legitimate dimension. 2434b7f68b8cSSiddharth Bhat if (!PwAff) { 2435b7f68b8cSSiddharth Bhat assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension"); 2436b7f68b8cSSiddharth Bhat continue; 2437b7f68b8cSSiddharth Bhat } 2438b7f68b8cSSiddharth Bhat 2439d58acf86STobias Grosser isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain( 2440d58acf86STobias Grosser isl_local_space_from_space(Array->getSpace()), isl_dim_set, i)); 2441d58acf86STobias Grosser PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in, 2442d58acf86STobias Grosser isl_pw_aff_dim(Val, isl_dim_in)); 2443d58acf86STobias Grosser PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in, 2444d58acf86STobias Grosser isl_pw_aff_get_tuple_id(Val, isl_dim_in)); 2445d58acf86STobias Grosser auto *Set = isl_pw_aff_gt_set(PwAff, Val); 2446d58acf86STobias Grosser Extent = isl_set_intersect(Set, Extent); 2447d58acf86STobias Grosser } 2448d58acf86STobias Grosser 2449d58acf86STobias Grosser return Extent; 245060f63b49STobias Grosser } 245160f63b49STobias Grosser 245260f63b49STobias Grosser /// Derive the bounds of an array. 245360f63b49STobias Grosser /// 245460f63b49STobias Grosser /// For the first dimension we derive the bound of the array from the extent 245560f63b49STobias Grosser /// of this dimension. For inner dimensions we obtain their size directly from 245660f63b49STobias Grosser /// ScopArrayInfo. 245760f63b49STobias Grosser /// 245860f63b49STobias Grosser /// @param PPCGArray The array to compute bounds for. 245960f63b49STobias Grosser /// @param Array The polly array from which to take the information. 246060f63b49STobias Grosser void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) { 246160f63b49STobias Grosser if (PPCGArray.n_index > 0) { 246202293ed7STobias Grosser if (isl_set_is_empty(PPCGArray.extent)) { 246302293ed7STobias Grosser isl_set *Dom = isl_set_copy(PPCGArray.extent); 246402293ed7STobias Grosser isl_local_space *LS = isl_local_space_from_space( 246502293ed7STobias Grosser isl_space_params(isl_set_get_space(Dom))); 246602293ed7STobias Grosser isl_set_free(Dom); 246702293ed7STobias Grosser isl_aff *Zero = isl_aff_zero_on_domain(LS); 246802293ed7STobias Grosser PPCGArray.bound[0] = isl_pw_aff_from_aff(Zero); 246902293ed7STobias Grosser } else { 247060f63b49STobias Grosser isl_set *Dom = isl_set_copy(PPCGArray.extent); 247160f63b49STobias Grosser Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1); 247260f63b49STobias Grosser isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0); 247360f63b49STobias Grosser isl_set_free(Dom); 247460f63b49STobias Grosser Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound)); 247502293ed7STobias Grosser isl_local_space *LS = 247602293ed7STobias Grosser isl_local_space_from_space(isl_set_get_space(Dom)); 247760f63b49STobias Grosser isl_aff *One = isl_aff_zero_on_domain(LS); 247860f63b49STobias Grosser One = isl_aff_add_constant_si(One, 1); 247960f63b49STobias Grosser Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One)); 248060f63b49STobias Grosser Bound = isl_pw_aff_gist(Bound, S->getContext()); 248160f63b49STobias Grosser PPCGArray.bound[0] = Bound; 248260f63b49STobias Grosser } 248302293ed7STobias Grosser } 248460f63b49STobias Grosser 248560f63b49STobias Grosser for (unsigned i = 1; i < PPCGArray.n_index; ++i) { 248660f63b49STobias Grosser isl_pw_aff *Bound = Array->getDimensionSizePw(i); 248760f63b49STobias Grosser auto LS = isl_pw_aff_get_domain_space(Bound); 248860f63b49STobias Grosser auto Aff = isl_multi_aff_zero(LS); 248960f63b49STobias Grosser Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff); 249060f63b49STobias Grosser PPCGArray.bound[i] = Bound; 249160f63b49STobias Grosser } 249260f63b49STobias Grosser } 249360f63b49STobias Grosser 249460f63b49STobias Grosser /// Create the arrays for @p PPCGProg. 249560f63b49STobias Grosser /// 249660f63b49STobias Grosser /// @param PPCGProg The program to compute the arrays for. 249760f63b49STobias Grosser void createArrays(gpu_prog *PPCGProg) { 249860f63b49STobias Grosser int i = 0; 2499d7754a12SRoman Gareev for (auto &Array : S->arrays()) { 250060f63b49STobias Grosser std::string TypeName; 250160f63b49STobias Grosser raw_string_ostream OS(TypeName); 250260f63b49STobias Grosser 250360f63b49STobias Grosser OS << *Array->getElementType(); 250460f63b49STobias Grosser TypeName = OS.str(); 250560f63b49STobias Grosser 250660f63b49STobias Grosser gpu_array_info &PPCGArray = PPCGProg->array[i]; 250760f63b49STobias Grosser 250860f63b49STobias Grosser PPCGArray.space = Array->getSpace(); 250960f63b49STobias Grosser PPCGArray.type = strdup(TypeName.c_str()); 251060f63b49STobias Grosser PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8; 251160f63b49STobias Grosser PPCGArray.name = strdup(Array->getName().c_str()); 251260f63b49STobias Grosser PPCGArray.extent = nullptr; 251360f63b49STobias Grosser PPCGArray.n_index = Array->getNumberOfDimensions(); 251460f63b49STobias Grosser PPCGArray.bound = 251560f63b49STobias Grosser isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index); 251660f63b49STobias Grosser PPCGArray.extent = getExtent(Array); 251760f63b49STobias Grosser PPCGArray.n_ref = 0; 251860f63b49STobias Grosser PPCGArray.refs = nullptr; 251960f63b49STobias Grosser PPCGArray.accessed = true; 2520fe74a7a1STobias Grosser PPCGArray.read_only_scalar = 2521fe74a7a1STobias Grosser Array->isReadOnly() && Array->getNumberOfDimensions() == 0; 252260f63b49STobias Grosser PPCGArray.has_compound_element = false; 252360f63b49STobias Grosser PPCGArray.local = false; 252460f63b49STobias Grosser PPCGArray.declare_local = false; 252560f63b49STobias Grosser PPCGArray.global = false; 252660f63b49STobias Grosser PPCGArray.linearize = false; 252760f63b49STobias Grosser PPCGArray.dep_order = nullptr; 252813c78e4dSTobias Grosser PPCGArray.user = Array; 252960f63b49STobias Grosser 253060f63b49STobias Grosser setArrayBounds(PPCGArray, Array); 25312d010dafSTobias Grosser i++; 2532b9fc860aSTobias Grosser 2533b9fc860aSTobias Grosser collect_references(PPCGProg, &PPCGArray); 253460f63b49STobias Grosser } 253560f63b49STobias Grosser } 253660f63b49STobias Grosser 253760f63b49STobias Grosser /// Create an identity map between the arrays in the scop. 253860f63b49STobias Grosser /// 253960f63b49STobias Grosser /// @returns An identity map between the arrays in the scop. 254060f63b49STobias Grosser isl_union_map *getArrayIdentity() { 254160f63b49STobias Grosser isl_union_map *Maps = isl_union_map_empty(S->getParamSpace()); 254260f63b49STobias Grosser 2543d7754a12SRoman Gareev for (auto &Array : S->arrays()) { 254460f63b49STobias Grosser isl_space *Space = Array->getSpace(); 254560f63b49STobias Grosser Space = isl_space_map_from_set(Space); 254660f63b49STobias Grosser isl_map *Identity = isl_map_identity(Space); 254760f63b49STobias Grosser Maps = isl_union_map_add_map(Maps, Identity); 254860f63b49STobias Grosser } 254960f63b49STobias Grosser 255060f63b49STobias Grosser return Maps; 255160f63b49STobias Grosser } 255260f63b49STobias Grosser 2553e938517eSTobias Grosser /// Create a default-initialized PPCG GPU program. 2554e938517eSTobias Grosser /// 2555a6d48f59SMichael Kruse /// @returns A new gpu program description. 2556e938517eSTobias Grosser gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) { 2557e938517eSTobias Grosser 2558e938517eSTobias Grosser if (!PPCGScop) 2559e938517eSTobias Grosser return nullptr; 2560e938517eSTobias Grosser 2561e938517eSTobias Grosser auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog); 2562e938517eSTobias Grosser 2563e938517eSTobias Grosser PPCGProg->ctx = S->getIslCtx(); 2564e938517eSTobias Grosser PPCGProg->scop = PPCGScop; 2565aef5196fSTobias Grosser PPCGProg->context = isl_set_copy(PPCGScop->context); 256660f63b49STobias Grosser PPCGProg->read = isl_union_map_copy(PPCGScop->reads); 256760f63b49STobias Grosser PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes); 256860f63b49STobias Grosser PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes); 256960f63b49STobias Grosser PPCGProg->tagged_must_kill = 257060f63b49STobias Grosser isl_union_map_copy(PPCGScop->tagged_must_kills); 257160f63b49STobias Grosser PPCGProg->to_inner = getArrayIdentity(); 257260f63b49STobias Grosser PPCGProg->to_outer = getArrayIdentity(); 2573e938517eSTobias Grosser PPCGProg->any_to_outer = nullptr; 2574a82f2d26SSiddharth Bhat 2575a82f2d26SSiddharth Bhat // this needs to be set when live range reordering is enabled. 2576a82f2d26SSiddharth Bhat // NOTE: I believe that is conservatively correct. I'm not sure 2577a82f2d26SSiddharth Bhat // what the semantics of this is. 2578a82f2d26SSiddharth Bhat // Quoting PPCG/gpu.h: "Order dependences on non-scalars." 2579a82f2d26SSiddharth Bhat PPCGProg->array_order = 2580a82f2d26SSiddharth Bhat isl_union_map_empty(isl_set_get_space(PPCGScop->context)); 258169b46751STobias Grosser PPCGProg->n_stmts = std::distance(S->begin(), S->end()); 258269b46751STobias Grosser PPCGProg->stmts = getStatements(); 258360f63b49STobias Grosser PPCGProg->n_array = std::distance(S->array_begin(), S->array_end()); 258460f63b49STobias Grosser PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info, 258560f63b49STobias Grosser PPCGProg->n_array); 258660f63b49STobias Grosser 258760f63b49STobias Grosser createArrays(PPCGProg); 2588e938517eSTobias Grosser 2589d58acf86STobias Grosser PPCGProg->may_persist = compute_may_persist(PPCGProg); 2590e938517eSTobias Grosser return PPCGProg; 2591e938517eSTobias Grosser } 2592e938517eSTobias Grosser 259369b46751STobias Grosser struct PrintGPUUserData { 259469b46751STobias Grosser struct cuda_info *CudaInfo; 259569b46751STobias Grosser struct gpu_prog *PPCGProg; 259669b46751STobias Grosser std::vector<ppcg_kernel *> Kernels; 259769b46751STobias Grosser }; 259869b46751STobias Grosser 259969b46751STobias Grosser /// Print a user statement node in the host code. 260069b46751STobias Grosser /// 260169b46751STobias Grosser /// We use ppcg's printing facilities to print the actual statement and 260269b46751STobias Grosser /// additionally build up a list of all kernels that are encountered in the 260369b46751STobias Grosser /// host ast. 260469b46751STobias Grosser /// 260569b46751STobias Grosser /// @param P The printer to print to 260669b46751STobias Grosser /// @param Options The printing options to use 260769b46751STobias Grosser /// @param Node The node to print 260869b46751STobias Grosser /// @param User A user pointer to carry additional data. This pointer is 260969b46751STobias Grosser /// expected to be of type PrintGPUUserData. 261069b46751STobias Grosser /// 261169b46751STobias Grosser /// @returns A printer to which the output has been printed. 261269b46751STobias Grosser static __isl_give isl_printer * 261369b46751STobias Grosser printHostUser(__isl_take isl_printer *P, 261469b46751STobias Grosser __isl_take isl_ast_print_options *Options, 261569b46751STobias Grosser __isl_take isl_ast_node *Node, void *User) { 261669b46751STobias Grosser auto Data = (struct PrintGPUUserData *)User; 261769b46751STobias Grosser auto Id = isl_ast_node_get_annotation(Node); 261869b46751STobias Grosser 261969b46751STobias Grosser if (Id) { 262020251734STobias Grosser bool IsUser = !strcmp(isl_id_get_name(Id), "user"); 262120251734STobias Grosser 262220251734STobias Grosser // If this is a user statement, format it ourselves as ppcg would 262320251734STobias Grosser // otherwise try to call pet functionality that is not available in 262420251734STobias Grosser // Polly. 262520251734STobias Grosser if (IsUser) { 262620251734STobias Grosser P = isl_printer_start_line(P); 262720251734STobias Grosser P = isl_printer_print_ast_node(P, Node); 262820251734STobias Grosser P = isl_printer_end_line(P); 262920251734STobias Grosser isl_id_free(Id); 263020251734STobias Grosser isl_ast_print_options_free(Options); 263120251734STobias Grosser return P; 263220251734STobias Grosser } 263320251734STobias Grosser 263469b46751STobias Grosser auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id); 263569b46751STobias Grosser isl_id_free(Id); 263669b46751STobias Grosser Data->Kernels.push_back(Kernel); 263769b46751STobias Grosser } 263869b46751STobias Grosser 263969b46751STobias Grosser return print_host_user(P, Options, Node, User); 264069b46751STobias Grosser } 264169b46751STobias Grosser 264269b46751STobias Grosser /// Print C code corresponding to the control flow in @p Kernel. 264369b46751STobias Grosser /// 264469b46751STobias Grosser /// @param Kernel The kernel to print 264569b46751STobias Grosser void printKernel(ppcg_kernel *Kernel) { 264669b46751STobias Grosser auto *P = isl_printer_to_str(S->getIslCtx()); 264769b46751STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C); 264869b46751STobias Grosser auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 264969b46751STobias Grosser P = isl_ast_node_print(Kernel->tree, P, Options); 265069b46751STobias Grosser char *String = isl_printer_get_str(P); 265169b46751STobias Grosser printf("%s\n", String); 265269b46751STobias Grosser free(String); 265369b46751STobias Grosser isl_printer_free(P); 265469b46751STobias Grosser } 265569b46751STobias Grosser 265669b46751STobias Grosser /// Print C code corresponding to the GPU code described by @p Tree. 265769b46751STobias Grosser /// 265869b46751STobias Grosser /// @param Tree An AST describing GPU code 265969b46751STobias Grosser /// @param PPCGProg The PPCG program from which @Tree has been constructed. 266069b46751STobias Grosser void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) { 266169b46751STobias Grosser auto *P = isl_printer_to_str(S->getIslCtx()); 266269b46751STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C); 266369b46751STobias Grosser 266469b46751STobias Grosser PrintGPUUserData Data; 266569b46751STobias Grosser Data.PPCGProg = PPCGProg; 266669b46751STobias Grosser 266769b46751STobias Grosser auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 266869b46751STobias Grosser Options = 266969b46751STobias Grosser isl_ast_print_options_set_print_user(Options, printHostUser, &Data); 267069b46751STobias Grosser P = isl_ast_node_print(Tree, P, Options); 267169b46751STobias Grosser char *String = isl_printer_get_str(P); 267269b46751STobias Grosser printf("# host\n"); 267369b46751STobias Grosser printf("%s\n", String); 267469b46751STobias Grosser free(String); 267569b46751STobias Grosser isl_printer_free(P); 267669b46751STobias Grosser 267769b46751STobias Grosser for (auto Kernel : Data.Kernels) { 267869b46751STobias Grosser printf("# kernel%d\n", Kernel->id); 267969b46751STobias Grosser printKernel(Kernel); 268069b46751STobias Grosser } 268169b46751STobias Grosser } 268269b46751STobias Grosser 2683f384594dSTobias Grosser // Generate a GPU program using PPCG. 2684f384594dSTobias Grosser // 2685f384594dSTobias Grosser // GPU mapping consists of multiple steps: 2686f384594dSTobias Grosser // 2687f384594dSTobias Grosser // 1) Compute new schedule for the program. 2688f384594dSTobias Grosser // 2) Map schedule to GPU (TODO) 2689f384594dSTobias Grosser // 3) Generate code for new schedule (TODO) 2690f384594dSTobias Grosser // 2691f384594dSTobias Grosser // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer 2692f384594dSTobias Grosser // is mostly CPU specific. Instead, we use PPCG's GPU code generation 2693f384594dSTobias Grosser // strategy directly from this pass. 2694f384594dSTobias Grosser gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) { 2695f384594dSTobias Grosser 2696f384594dSTobias Grosser auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen); 2697f384594dSTobias Grosser 2698f384594dSTobias Grosser PPCGGen->ctx = S->getIslCtx(); 2699f384594dSTobias Grosser PPCGGen->options = PPCGScop->options; 2700f384594dSTobias Grosser PPCGGen->print = nullptr; 2701f384594dSTobias Grosser PPCGGen->print_user = nullptr; 270260c60025STobias Grosser PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt; 2703f384594dSTobias Grosser PPCGGen->prog = PPCGProg; 2704f384594dSTobias Grosser PPCGGen->tree = nullptr; 2705f384594dSTobias Grosser PPCGGen->types.n = 0; 2706f384594dSTobias Grosser PPCGGen->types.name = nullptr; 2707f384594dSTobias Grosser PPCGGen->sizes = nullptr; 2708f384594dSTobias Grosser PPCGGen->used_sizes = nullptr; 2709f384594dSTobias Grosser PPCGGen->kernel_id = 0; 2710f384594dSTobias Grosser 2711f384594dSTobias Grosser // Set scheduling strategy to same strategy PPCG is using. 2712f384594dSTobias Grosser isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true); 2713f384594dSTobias Grosser isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true); 27142341fe9eSTobias Grosser isl_options_set_schedule_whole_component(PPCGGen->ctx, false); 2715f384594dSTobias Grosser 2716f384594dSTobias Grosser isl_schedule *Schedule = get_schedule(PPCGGen); 2717f384594dSTobias Grosser 2718aef5196fSTobias Grosser int has_permutable = has_any_permutable_node(Schedule); 2719aef5196fSTobias Grosser 272069b46751STobias Grosser if (!has_permutable || has_permutable < 0) { 2721aef5196fSTobias Grosser Schedule = isl_schedule_free(Schedule); 272269b46751STobias Grosser } else { 2723aef5196fSTobias Grosser Schedule = map_to_device(PPCGGen, Schedule); 272469b46751STobias Grosser PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule)); 272569b46751STobias Grosser } 2726aef5196fSTobias Grosser 2727f384594dSTobias Grosser if (DumpSchedule) { 2728f384594dSTobias Grosser isl_printer *P = isl_printer_to_str(S->getIslCtx()); 2729f384594dSTobias Grosser P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK); 2730f384594dSTobias Grosser P = isl_printer_print_str(P, "Schedule\n"); 2731f384594dSTobias Grosser P = isl_printer_print_str(P, "========\n"); 2732f384594dSTobias Grosser if (Schedule) 2733f384594dSTobias Grosser P = isl_printer_print_schedule(P, Schedule); 2734f384594dSTobias Grosser else 2735f384594dSTobias Grosser P = isl_printer_print_str(P, "No schedule found\n"); 2736f384594dSTobias Grosser 2737f384594dSTobias Grosser printf("%s\n", isl_printer_get_str(P)); 2738f384594dSTobias Grosser isl_printer_free(P); 2739f384594dSTobias Grosser } 2740f384594dSTobias Grosser 274169b46751STobias Grosser if (DumpCode) { 274269b46751STobias Grosser printf("Code\n"); 274369b46751STobias Grosser printf("====\n"); 274469b46751STobias Grosser if (PPCGGen->tree) 274569b46751STobias Grosser printGPUTree(PPCGGen->tree, PPCGProg); 274669b46751STobias Grosser else 274769b46751STobias Grosser printf("No code generated\n"); 274869b46751STobias Grosser } 274969b46751STobias Grosser 2750f384594dSTobias Grosser isl_schedule_free(Schedule); 2751f384594dSTobias Grosser 2752f384594dSTobias Grosser return PPCGGen; 2753f384594dSTobias Grosser } 2754f384594dSTobias Grosser 2755f384594dSTobias Grosser /// Free gpu_gen structure. 2756f384594dSTobias Grosser /// 2757f384594dSTobias Grosser /// @param PPCGGen The ppcg_gen object to free. 2758f384594dSTobias Grosser void freePPCGGen(gpu_gen *PPCGGen) { 2759f384594dSTobias Grosser isl_ast_node_free(PPCGGen->tree); 2760f384594dSTobias Grosser isl_union_map_free(PPCGGen->sizes); 2761f384594dSTobias Grosser isl_union_map_free(PPCGGen->used_sizes); 2762f384594dSTobias Grosser free(PPCGGen); 2763f384594dSTobias Grosser } 2764f384594dSTobias Grosser 2765b307ed4dSTobias Grosser /// Free the options in the ppcg scop structure. 2766b307ed4dSTobias Grosser /// 2767b307ed4dSTobias Grosser /// ppcg is not freeing these options for us. To avoid leaks we do this 2768b307ed4dSTobias Grosser /// ourselves. 2769b307ed4dSTobias Grosser /// 2770b307ed4dSTobias Grosser /// @param PPCGScop The scop referencing the options to free. 2771b307ed4dSTobias Grosser void freeOptions(ppcg_scop *PPCGScop) { 2772b307ed4dSTobias Grosser free(PPCGScop->options->debug); 2773b307ed4dSTobias Grosser PPCGScop->options->debug = nullptr; 2774b307ed4dSTobias Grosser free(PPCGScop->options); 2775b307ed4dSTobias Grosser PPCGScop->options = nullptr; 2776b307ed4dSTobias Grosser } 2777b307ed4dSTobias Grosser 277882f2af35STobias Grosser /// Approximate the number of points in the set. 277982f2af35STobias Grosser /// 278082f2af35STobias Grosser /// This function returns an ast expression that overapproximates the number 278182f2af35STobias Grosser /// of points in an isl set through the rectangular hull surrounding this set. 278282f2af35STobias Grosser /// 278382f2af35STobias Grosser /// @param Set The set to count. 278482f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 278582f2af35STobias Grosser /// expression. 278682f2af35STobias Grosser /// 278782f2af35STobias Grosser /// @returns An approximation of the number of points in the set. 278882f2af35STobias Grosser __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set, 278982f2af35STobias Grosser __isl_keep isl_ast_build *Build) { 279082f2af35STobias Grosser 279182f2af35STobias Grosser isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1); 279282f2af35STobias Grosser auto *Expr = isl_ast_expr_from_val(isl_val_copy(One)); 279382f2af35STobias Grosser 279482f2af35STobias Grosser isl_space *Space = isl_set_get_space(Set); 279582f2af35STobias Grosser Space = isl_space_params(Space); 279682f2af35STobias Grosser auto *Univ = isl_set_universe(Space); 279782f2af35STobias Grosser isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One); 279882f2af35STobias Grosser 279982f2af35STobias Grosser for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) { 280082f2af35STobias Grosser isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i); 280182f2af35STobias Grosser isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i); 280282f2af35STobias Grosser isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min); 280382f2af35STobias Grosser DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff)); 280482f2af35STobias Grosser auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize); 280582f2af35STobias Grosser Expr = isl_ast_expr_mul(Expr, DimSizeExpr); 280682f2af35STobias Grosser } 280782f2af35STobias Grosser 280882f2af35STobias Grosser isl_set_free(Set); 280982f2af35STobias Grosser isl_pw_aff_free(OneAff); 281082f2af35STobias Grosser 281182f2af35STobias Grosser return Expr; 281282f2af35STobias Grosser } 281382f2af35STobias Grosser 281482f2af35STobias Grosser /// Approximate a number of dynamic instructions executed by a given 281582f2af35STobias Grosser /// statement. 281682f2af35STobias Grosser /// 281782f2af35STobias Grosser /// @param Stmt The statement for which to compute the number of dynamic 281882f2af35STobias Grosser /// instructions. 281982f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 282082f2af35STobias Grosser /// expression. 282182f2af35STobias Grosser /// @returns An approximation of the number of dynamic instructions executed 282282f2af35STobias Grosser /// by @p Stmt. 282382f2af35STobias Grosser __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt, 282482f2af35STobias Grosser __isl_keep isl_ast_build *Build) { 282582f2af35STobias Grosser auto Iterations = approxPointsInSet(Stmt.getDomain(), Build); 282682f2af35STobias Grosser 282782f2af35STobias Grosser long InstCount = 0; 282882f2af35STobias Grosser 282982f2af35STobias Grosser if (Stmt.isBlockStmt()) { 283082f2af35STobias Grosser auto *BB = Stmt.getBasicBlock(); 283182f2af35STobias Grosser InstCount = std::distance(BB->begin(), BB->end()); 283282f2af35STobias Grosser } else { 283382f2af35STobias Grosser auto *R = Stmt.getRegion(); 283482f2af35STobias Grosser 283582f2af35STobias Grosser for (auto *BB : R->blocks()) { 283682f2af35STobias Grosser InstCount += std::distance(BB->begin(), BB->end()); 283782f2af35STobias Grosser } 283882f2af35STobias Grosser } 283982f2af35STobias Grosser 284082f2af35STobias Grosser isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount); 284182f2af35STobias Grosser auto *InstExpr = isl_ast_expr_from_val(InstVal); 284282f2af35STobias Grosser return isl_ast_expr_mul(InstExpr, Iterations); 284382f2af35STobias Grosser } 284482f2af35STobias Grosser 284582f2af35STobias Grosser /// Approximate dynamic instructions executed in scop. 284682f2af35STobias Grosser /// 284782f2af35STobias Grosser /// @param S The scop for which to approximate dynamic instructions. 284882f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 284982f2af35STobias Grosser /// expression. 285082f2af35STobias Grosser /// @returns An approximation of the number of dynamic instructions executed 285182f2af35STobias Grosser /// in @p S. 285282f2af35STobias Grosser __isl_give isl_ast_expr * 285382f2af35STobias Grosser getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) { 285482f2af35STobias Grosser isl_ast_expr *Instructions; 285582f2af35STobias Grosser 285682f2af35STobias Grosser isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0); 285782f2af35STobias Grosser Instructions = isl_ast_expr_from_val(Zero); 285882f2af35STobias Grosser 285982f2af35STobias Grosser for (ScopStmt &Stmt : S) { 286082f2af35STobias Grosser isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build); 286182f2af35STobias Grosser Instructions = isl_ast_expr_add(Instructions, StmtInstructions); 286282f2af35STobias Grosser } 286382f2af35STobias Grosser return Instructions; 286482f2af35STobias Grosser } 286582f2af35STobias Grosser 286682f2af35STobias Grosser /// Create a check that ensures sufficient compute in scop. 286782f2af35STobias Grosser /// 286882f2af35STobias Grosser /// @param S The scop for which to ensure sufficient compute. 286982f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 287082f2af35STobias Grosser /// expression. 287182f2af35STobias Grosser /// @returns An expression that evaluates to TRUE in case of sufficient 287282f2af35STobias Grosser /// compute and to FALSE, otherwise. 287382f2af35STobias Grosser __isl_give isl_ast_expr * 287482f2af35STobias Grosser createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) { 287582f2af35STobias Grosser auto Iterations = getNumberOfIterations(S, Build); 287682f2af35STobias Grosser auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute); 287782f2af35STobias Grosser auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal); 287882f2af35STobias Grosser return isl_ast_expr_ge(Iterations, MinComputeExpr); 287982f2af35STobias Grosser } 288082f2af35STobias Grosser 2881f291c8d5SSiddharth Bhat /// Check if the basic block contains a function we cannot codegen for GPU 2882f291c8d5SSiddharth Bhat /// kernels. 2883f291c8d5SSiddharth Bhat /// 2884f291c8d5SSiddharth Bhat /// If this basic block does something with a `Function` other than calling 2885f291c8d5SSiddharth Bhat /// a function that we support in a kernel, return true. 2886f291c8d5SSiddharth Bhat bool containsInvalidKernelFunctionInBllock(const BasicBlock *BB) { 2887f291c8d5SSiddharth Bhat for (const Instruction &Inst : *BB) { 2888f291c8d5SSiddharth Bhat const CallInst *Call = dyn_cast<CallInst>(&Inst); 2889f291c8d5SSiddharth Bhat if (Call && isValidFunctionInKernel(Call->getCalledFunction())) { 2890f291c8d5SSiddharth Bhat continue; 2891f291c8d5SSiddharth Bhat } 2892f291c8d5SSiddharth Bhat 2893bccaea57SSiddharth Bhat for (Value *SrcVal : Inst.operands()) { 2894bccaea57SSiddharth Bhat PointerType *p = dyn_cast<PointerType>(SrcVal->getType()); 2895bccaea57SSiddharth Bhat if (!p) 2896bccaea57SSiddharth Bhat continue; 2897bccaea57SSiddharth Bhat if (isa<FunctionType>(p->getElementType())) 2898bccaea57SSiddharth Bhat return true; 2899bccaea57SSiddharth Bhat } 2900f291c8d5SSiddharth Bhat } 2901bccaea57SSiddharth Bhat return false; 2902bccaea57SSiddharth Bhat } 2903bccaea57SSiddharth Bhat 2904f291c8d5SSiddharth Bhat /// Return whether the Scop S uses functions in a way that we do not support. 2905f291c8d5SSiddharth Bhat bool containsInvalidKernelFunction(const Scop &S) { 2906bccaea57SSiddharth Bhat for (auto &Stmt : S) { 2907bccaea57SSiddharth Bhat if (Stmt.isBlockStmt()) { 2908f291c8d5SSiddharth Bhat if (containsInvalidKernelFunctionInBllock(Stmt.getBasicBlock())) 2909bccaea57SSiddharth Bhat return true; 2910bccaea57SSiddharth Bhat } else { 2911bccaea57SSiddharth Bhat assert(Stmt.isRegionStmt() && 2912bccaea57SSiddharth Bhat "Stmt was neither block nor region statement"); 2913bccaea57SSiddharth Bhat for (const BasicBlock *BB : Stmt.getRegion()->blocks()) 2914f291c8d5SSiddharth Bhat if (containsInvalidKernelFunctionInBllock(BB)) 2915bccaea57SSiddharth Bhat return true; 2916bccaea57SSiddharth Bhat } 2917bccaea57SSiddharth Bhat } 2918bccaea57SSiddharth Bhat return false; 2919bccaea57SSiddharth Bhat } 2920bccaea57SSiddharth Bhat 292138fc0aedSTobias Grosser /// Generate code for a given GPU AST described by @p Root. 292238fc0aedSTobias Grosser /// 292332837fe3STobias Grosser /// @param Root An isl_ast_node pointing to the root of the GPU AST. 292432837fe3STobias Grosser /// @param Prog The GPU Program to generate code for. 292532837fe3STobias Grosser void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) { 292638fc0aedSTobias Grosser ScopAnnotator Annotator; 292738fc0aedSTobias Grosser Annotator.buildAliasScopes(*S); 292838fc0aedSTobias Grosser 292938fc0aedSTobias Grosser Region *R = &S->getRegion(); 293038fc0aedSTobias Grosser 293138fc0aedSTobias Grosser simplifyRegion(R, DT, LI, RI); 293238fc0aedSTobias Grosser 293338fc0aedSTobias Grosser BasicBlock *EnteringBB = R->getEnteringBlock(); 293438fc0aedSTobias Grosser 293538fc0aedSTobias Grosser PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator); 293638fc0aedSTobias Grosser 293738fc0aedSTobias Grosser // Only build the run-time condition and parameters _after_ having 293838fc0aedSTobias Grosser // introduced the conditional branch. This is important as the conditional 293938fc0aedSTobias Grosser // branch will guard the original scop from new induction variables that 294038fc0aedSTobias Grosser // the SCEVExpander may introduce while code generating the parameters and 294138fc0aedSTobias Grosser // which may introduce scalar dependences that prevent us from correctly 294238fc0aedSTobias Grosser // code generating this scop. 294303346c27SSiddharth Bhat BBPair StartExitBlocks; 294403346c27SSiddharth Bhat BranchInst *CondBr = nullptr; 294503346c27SSiddharth Bhat std::tie(StartExitBlocks, CondBr) = 29462d950f36SPhilip Pfaffe executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI); 2947256070d8SAndreas Simbuerger BasicBlock *StartBlock = std::get<0>(StartExitBlocks); 294838fc0aedSTobias Grosser 294903346c27SSiddharth Bhat assert(CondBr && "CondBr not initialized by executeScopConditionally"); 295003346c27SSiddharth Bhat 29512d950f36SPhilip Pfaffe GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S, 295217f01968SSiddharth Bhat StartBlock, Prog, Runtime, Architecture); 2953acf80064SEli Friedman 295438fc0aedSTobias Grosser // TODO: Handle LICM 295538fc0aedSTobias Grosser auto SplitBlock = StartBlock->getSinglePredecessor(); 295638fc0aedSTobias Grosser Builder.SetInsertPoint(SplitBlock->getTerminator()); 295738fc0aedSTobias Grosser NodeBuilder.addParameters(S->getContext()); 2958cb1aef8dSTobias Grosser 2959cb1aef8dSTobias Grosser isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx()); 29602b852e2eSPhilip Pfaffe isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build); 296182f2af35STobias Grosser isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build); 296282f2af35STobias Grosser Condition = isl_ast_expr_and(Condition, SufficientCompute); 2963cb1aef8dSTobias Grosser isl_ast_build_free(Build); 2964cb1aef8dSTobias Grosser 2965cb1aef8dSTobias Grosser Value *RTC = NodeBuilder.createRTC(Condition); 2966cb1aef8dSTobias Grosser Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC); 2967cb1aef8dSTobias Grosser 296838fc0aedSTobias Grosser Builder.SetInsertPoint(&*StartBlock->begin()); 2969fa7b0802STobias Grosser 2970fa7b0802STobias Grosser NodeBuilder.initializeAfterRTH(); 2971233d717eSSiddharth Bhat NodeBuilder.preloadInvariantLoads(); 297238fc0aedSTobias Grosser NodeBuilder.create(Root); 29738ed5e599STobias Grosser NodeBuilder.finalize(); 29745857b701STobias Grosser 2975bc653f20STobias Grosser /// In case a sequential kernel has more surrounding loops as any parallel 2976bc653f20STobias Grosser /// kernel, the SCoP is probably mostly sequential. Hence, there is no 2977de244eb4STobias Grosser /// point in running it on a GPU. 2978bc653f20STobias Grosser if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel) 297903346c27SSiddharth Bhat CondBr->setOperand(0, Builder.getFalse()); 2980bc653f20STobias Grosser 29815857b701STobias Grosser if (!NodeBuilder.BuildSuccessful) 298203346c27SSiddharth Bhat CondBr->setOperand(0, Builder.getFalse()); 298338fc0aedSTobias Grosser } 298438fc0aedSTobias Grosser 2985e938517eSTobias Grosser bool runOnScop(Scop &CurrentScop) override { 2986e938517eSTobias Grosser S = &CurrentScop; 298738fc0aedSTobias Grosser LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 298838fc0aedSTobias Grosser DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 298938fc0aedSTobias Grosser SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 29907b5a4dfdSTobias Grosser DL = &S->getRegion().getEntry()->getModule()->getDataLayout(); 299138fc0aedSTobias Grosser RI = &getAnalysis<RegionInfoPass>().getRegionInfo(); 2992e938517eSTobias Grosser 2993f291c8d5SSiddharth Bhat // We currently do not support functions other than intrinsics inside 2994f291c8d5SSiddharth Bhat // kernels, as code generation will need to offload function calls to the 2995f291c8d5SSiddharth Bhat // kernel. This may lead to a kernel trying to call a function on the host. 2996bccaea57SSiddharth Bhat // This also allows us to prevent codegen from trying to take the 2997bccaea57SSiddharth Bhat // address of an intrinsic function to send to the kernel. 2998f291c8d5SSiddharth Bhat if (containsInvalidKernelFunction(CurrentScop)) { 2999f291c8d5SSiddharth Bhat DEBUG( 3000f291c8d5SSiddharth Bhat dbgs() 3001f291c8d5SSiddharth Bhat << "Scop contains function which cannot be materialised in a GPU " 3002f291c8d5SSiddharth Bhat "kernel. Bailing out.\n";); 3003bccaea57SSiddharth Bhat return false; 3004f291c8d5SSiddharth Bhat } 3005bccaea57SSiddharth Bhat 3006e938517eSTobias Grosser auto PPCGScop = createPPCGScop(); 3007e938517eSTobias Grosser auto PPCGProg = createPPCGProg(PPCGScop); 3008f384594dSTobias Grosser auto PPCGGen = generateGPU(PPCGScop, PPCGProg); 300938fc0aedSTobias Grosser 301002ca346eSSingapuram Sanjay Srivallabh if (PPCGGen->tree) { 301132837fe3STobias Grosser generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg); 301202ca346eSSingapuram Sanjay Srivallabh CurrentScop.markAsToBeSkipped(); 301302ca346eSSingapuram Sanjay Srivallabh } 301438fc0aedSTobias Grosser 3015b307ed4dSTobias Grosser freeOptions(PPCGScop); 3016f384594dSTobias Grosser freePPCGGen(PPCGGen); 3017e938517eSTobias Grosser gpu_prog_free(PPCGProg); 3018e938517eSTobias Grosser ppcg_scop_free(PPCGScop); 3019e938517eSTobias Grosser 3020e938517eSTobias Grosser return true; 3021e938517eSTobias Grosser } 30229dfe4e7cSTobias Grosser 30239dfe4e7cSTobias Grosser void printScop(raw_ostream &, Scop &) const override {} 30249dfe4e7cSTobias Grosser 30259dfe4e7cSTobias Grosser void getAnalysisUsage(AnalysisUsage &AU) const override { 30269dfe4e7cSTobias Grosser AU.addRequired<DominatorTreeWrapperPass>(); 30279dfe4e7cSTobias Grosser AU.addRequired<RegionInfoPass>(); 30289dfe4e7cSTobias Grosser AU.addRequired<ScalarEvolutionWrapperPass>(); 30295cc87e3aSPhilip Pfaffe AU.addRequired<ScopDetectionWrapperPass>(); 30309dfe4e7cSTobias Grosser AU.addRequired<ScopInfoRegionPass>(); 30319dfe4e7cSTobias Grosser AU.addRequired<LoopInfoWrapperPass>(); 30329dfe4e7cSTobias Grosser 30339dfe4e7cSTobias Grosser AU.addPreserved<AAResultsWrapperPass>(); 30349dfe4e7cSTobias Grosser AU.addPreserved<BasicAAWrapperPass>(); 30359dfe4e7cSTobias Grosser AU.addPreserved<LoopInfoWrapperPass>(); 30369dfe4e7cSTobias Grosser AU.addPreserved<DominatorTreeWrapperPass>(); 30379dfe4e7cSTobias Grosser AU.addPreserved<GlobalsAAWrapperPass>(); 30385cc87e3aSPhilip Pfaffe AU.addPreserved<ScopDetectionWrapperPass>(); 30399dfe4e7cSTobias Grosser AU.addPreserved<ScalarEvolutionWrapperPass>(); 30409dfe4e7cSTobias Grosser AU.addPreserved<SCEVAAWrapperPass>(); 30419dfe4e7cSTobias Grosser 30429dfe4e7cSTobias Grosser // FIXME: We do not yet add regions for the newly generated code to the 30439dfe4e7cSTobias Grosser // region tree. 30449dfe4e7cSTobias Grosser AU.addPreserved<RegionInfoPass>(); 30459dfe4e7cSTobias Grosser AU.addPreserved<ScopInfoRegionPass>(); 30469dfe4e7cSTobias Grosser } 30479dfe4e7cSTobias Grosser }; 304824222c73STobias Grosser } // namespace 30499dfe4e7cSTobias Grosser 30509dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1; 30519dfe4e7cSTobias Grosser 305217f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) { 305317f01968SSiddharth Bhat PPCGCodeGeneration *generator = new PPCGCodeGeneration(); 305417f01968SSiddharth Bhat generator->Runtime = Runtime; 305517f01968SSiddharth Bhat generator->Architecture = Arch; 305617f01968SSiddharth Bhat return generator; 305717f01968SSiddharth Bhat } 30589dfe4e7cSTobias Grosser 30599dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg", 30609dfe4e7cSTobias Grosser "Polly - Apply PPCG translation to SCOP", false, false) 30619dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo); 30629dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 30639dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 30649dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 30659dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 30665cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass); 30679dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg", 30689dfe4e7cSTobias Grosser "Polly - Apply PPCG translation to SCOP", false, false) 3069