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 159dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h" 1638fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h" 179dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h" 189dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h" 19f384594dSTobias Grosser #include "polly/Options.h" 209dfe4e7cSTobias Grosser #include "polly/ScopInfo.h" 21edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h" 2274dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h" 239dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h" 249dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h" 259dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h" 269dfe4e7cSTobias Grosser #include "llvm/Analysis/PostDominators.h" 279dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 2874dc3cb4STobias Grosser #include "llvm/Analysis/TargetLibraryInfo.h" 2974dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h" 3074dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h" 31e1a98343STobias Grosser #include "llvm/IR/Verifier.h" 3274dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h" 3374dc3cb4STobias Grosser #include "llvm/Support/TargetSelect.h" 3474dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h" 359a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h" 369dfe4e7cSTobias Grosser 37f384594dSTobias Grosser #include "isl/union_map.h" 38f384594dSTobias Grosser 39e938517eSTobias Grosser extern "C" { 40a56f8f8eSTobias Grosser #include "ppcg/cuda.h" 41a56f8f8eSTobias Grosser #include "ppcg/gpu.h" 42a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h" 43a56f8f8eSTobias Grosser #include "ppcg/ppcg.h" 44a56f8f8eSTobias Grosser #include "ppcg/schedule.h" 45e938517eSTobias Grosser } 46e938517eSTobias Grosser 479dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h" 489dfe4e7cSTobias Grosser 499dfe4e7cSTobias Grosser using namespace polly; 509dfe4e7cSTobias Grosser using namespace llvm; 519dfe4e7cSTobias Grosser 529dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg" 539dfe4e7cSTobias Grosser 54f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule", 55f384594dSTobias Grosser cl::desc("Dump the computed GPU Schedule"), 56681bd568STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 57f384594dSTobias Grosser cl::cat(PollyCategory)); 5869b46751STobias Grosser 5969b46751STobias Grosser static cl::opt<bool> 6069b46751STobias Grosser DumpCode("polly-acc-dump-code", 6169b46751STobias Grosser cl::desc("Dump C code describing the GPU mapping"), cl::Hidden, 6269b46751STobias Grosser cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory)); 6369b46751STobias Grosser 6432837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir", 6532837fe3STobias Grosser cl::desc("Dump the kernel LLVM-IR"), 6632837fe3STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 6732837fe3STobias Grosser cl::cat(PollyCategory)); 6832837fe3STobias Grosser 6974dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm", 7074dc3cb4STobias Grosser cl::desc("Dump the kernel assembly code"), 7174dc3cb4STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 7274dc3cb4STobias Grosser cl::cat(PollyCategory)); 7374dc3cb4STobias Grosser 7474dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath", 7574dc3cb4STobias Grosser cl::desc("Allow unsafe math optimizations"), 7674dc3cb4STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 7774dc3cb4STobias Grosser cl::cat(PollyCategory)); 7874dc3cb4STobias Grosser 7974dc3cb4STobias Grosser static cl::opt<std::string> 8074dc3cb4STobias Grosser CudaVersion("polly-acc-cuda-version", 8174dc3cb4STobias Grosser cl::desc("The CUDA version to compile for"), cl::Hidden, 8274dc3cb4STobias Grosser cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory)); 8374dc3cb4STobias Grosser 8460c60025STobias Grosser /// Create the ast expressions for a ScopStmt. 8560c60025STobias Grosser /// 8660c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each 8760c60025STobias Grosser /// of the scheduled ScopStmts. 8860c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt( 89edb885cbSTobias Grosser void *StmtT, isl_ast_build *Build, 9060c60025STobias Grosser isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA, 9160c60025STobias Grosser isl_id *Id, void *User), 9260c60025STobias Grosser void *UserIndex, 9360c60025STobias Grosser isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User), 94edb885cbSTobias Grosser void *UserExpr) { 9560c60025STobias Grosser 96edb885cbSTobias Grosser ScopStmt *Stmt = (ScopStmt *)StmtT; 9760c60025STobias Grosser 98edb885cbSTobias Grosser isl_ctx *Ctx; 99edb885cbSTobias Grosser 100edb885cbSTobias Grosser if (!Stmt || !Build) 101edb885cbSTobias Grosser return NULL; 102edb885cbSTobias Grosser 103edb885cbSTobias Grosser Ctx = isl_ast_build_get_ctx(Build); 104edb885cbSTobias Grosser isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0); 105edb885cbSTobias Grosser 106edb885cbSTobias Grosser for (MemoryAccess *Acc : *Stmt) { 107edb885cbSTobias Grosser isl_map *AddrFunc = Acc->getAddressFunction(); 108edb885cbSTobias Grosser AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain()); 109edb885cbSTobias Grosser isl_id *RefId = Acc->getId(); 110edb885cbSTobias Grosser isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc); 111edb885cbSTobias Grosser isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA); 112edb885cbSTobias Grosser MPA = isl_multi_pw_aff_coalesce(MPA); 113edb885cbSTobias Grosser MPA = FunctionIndex(MPA, RefId, UserIndex); 114edb885cbSTobias Grosser isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA); 115edb885cbSTobias Grosser Access = FunctionExpr(Access, RefId, UserExpr); 116edb885cbSTobias Grosser RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access); 117edb885cbSTobias Grosser } 118edb885cbSTobias Grosser 119edb885cbSTobias Grosser return RefToExpr; 12060c60025STobias Grosser } 121f384594dSTobias Grosser 12238fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST. 12338fc0aedSTobias Grosser /// 12438fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which 12538fc0aedSTobias Grosser /// generates code for general-prupose AST nodes, with special functionality 12638fc0aedSTobias Grosser /// for generating GPU specific user nodes. 12738fc0aedSTobias Grosser /// 12838fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser 12938fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder { 13038fc0aedSTobias Grosser public: 13138fc0aedSTobias Grosser GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P, 13238fc0aedSTobias Grosser const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE, 13332837fe3STobias Grosser DominatorTree &DT, Scop &S, gpu_prog *Prog) 134edb885cbSTobias Grosser : IslNodeBuilder(Builder, Annotator, P, DL, LI, SE, DT, S), Prog(Prog) { 135edb885cbSTobias Grosser getExprBuilder().setIDToSAI(&IDToSAI); 136edb885cbSTobias Grosser } 13738fc0aedSTobias Grosser 13838fc0aedSTobias Grosser private: 13974dc3cb4STobias Grosser /// A vector of array base pointers for which a new ScopArrayInfo was created. 14074dc3cb4STobias Grosser /// 14174dc3cb4STobias Grosser /// This vector is used to delete the ScopArrayInfo when it is not needed any 14274dc3cb4STobias Grosser /// more. 14374dc3cb4STobias Grosser std::vector<Value *> LocalArrays; 14474dc3cb4STobias Grosser 14532837fe3STobias Grosser /// A module containing GPU code. 14632837fe3STobias Grosser /// 14732837fe3STobias Grosser /// This pointer is only set in case we are currently generating GPU code. 14832837fe3STobias Grosser std::unique_ptr<Module> GPUModule; 14932837fe3STobias Grosser 15032837fe3STobias Grosser /// The GPU program we generate code for. 15132837fe3STobias Grosser gpu_prog *Prog; 15232837fe3STobias Grosser 153472f9654STobias Grosser /// Class to free isl_ids. 154472f9654STobias Grosser class IslIdDeleter { 155472f9654STobias Grosser public: 156472f9654STobias Grosser void operator()(__isl_take isl_id *Id) { isl_id_free(Id); }; 157472f9654STobias Grosser }; 158472f9654STobias Grosser 159472f9654STobias Grosser /// A set containing all isl_ids allocated in a GPU kernel. 160472f9654STobias Grosser /// 161472f9654STobias Grosser /// By releasing this set all isl_ids will be freed. 162472f9654STobias Grosser std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs; 163472f9654STobias Grosser 164edb885cbSTobias Grosser IslExprBuilder::IDToScopArrayInfoTy IDToSAI; 165edb885cbSTobias Grosser 16638fc0aedSTobias Grosser /// Create code for user-defined AST nodes. 16738fc0aedSTobias Grosser /// 16838fc0aedSTobias Grosser /// These AST nodes can be of type: 16938fc0aedSTobias Grosser /// 17038fc0aedSTobias Grosser /// - ScopStmt: A computational statement (TODO) 17138fc0aedSTobias Grosser /// - Kernel: A GPU kernel call (TODO) 17238fc0aedSTobias Grosser /// - Data-Transfer: A GPU <-> CPU data-transfer (TODO) 1735260c041STobias Grosser /// - In-kernel synchronization 1745260c041STobias Grosser /// - In-kernel memory copy statement 17538fc0aedSTobias Grosser /// 1761fb9b64dSTobias Grosser /// @param UserStmt The ast node to generate code for. 1771fb9b64dSTobias Grosser virtual void createUser(__isl_take isl_ast_node *UserStmt); 17832837fe3STobias Grosser 179edb885cbSTobias Grosser /// Find llvm::Values referenced in GPU kernel. 180edb885cbSTobias Grosser /// 181edb885cbSTobias Grosser /// @param Kernel The kernel to scan for llvm::Values 182edb885cbSTobias Grosser /// 183edb885cbSTobias Grosser /// @returns A set of values referenced by the kernel. 184edb885cbSTobias Grosser SetVector<Value *> getReferencesInKernel(ppcg_kernel *Kernel); 185edb885cbSTobias Grosser 18632837fe3STobias Grosser /// Create GPU kernel. 18732837fe3STobias Grosser /// 18832837fe3STobias Grosser /// Code generate the kernel described by @p KernelStmt. 18932837fe3STobias Grosser /// 19032837fe3STobias Grosser /// @param KernelStmt The ast node to generate kernel code for. 19132837fe3STobias Grosser void createKernel(__isl_take isl_ast_node *KernelStmt); 19232837fe3STobias Grosser 19332837fe3STobias Grosser /// Create kernel function. 19432837fe3STobias Grosser /// 19532837fe3STobias Grosser /// Create a kernel function located in a newly created module that can serve 19632837fe3STobias Grosser /// as target for device code generation. Set the Builder to point to the 19732837fe3STobias Grosser /// start block of this newly created function. 19832837fe3STobias Grosser /// 19932837fe3STobias Grosser /// @param Kernel The kernel to generate code for. 200edb885cbSTobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 201edb885cbSTobias Grosser void createKernelFunction(ppcg_kernel *Kernel, 202edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues); 20332837fe3STobias Grosser 20432837fe3STobias Grosser /// Create the declaration of a kernel function. 20532837fe3STobias Grosser /// 20632837fe3STobias Grosser /// The kernel function takes as arguments: 20732837fe3STobias Grosser /// 20832837fe3STobias Grosser /// - One i8 pointer for each external array reference used in the kernel. 209f6044bd0STobias Grosser /// - Host iterators 210c84a1995STobias Grosser /// - Parameters 21132837fe3STobias Grosser /// - Other LLVM Value references (TODO) 21232837fe3STobias Grosser /// 21332837fe3STobias Grosser /// @param Kernel The kernel to generate the function declaration for. 214edb885cbSTobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 215edb885cbSTobias Grosser /// 21632837fe3STobias Grosser /// @returns The newly declared function. 217edb885cbSTobias Grosser Function *createKernelFunctionDecl(ppcg_kernel *Kernel, 218edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues); 21932837fe3STobias Grosser 220472f9654STobias Grosser /// Insert intrinsic functions to obtain thread and block ids. 221472f9654STobias Grosser /// 222472f9654STobias Grosser /// @param The kernel to generate the intrinsic functions for. 223472f9654STobias Grosser void insertKernelIntrinsics(ppcg_kernel *Kernel); 224472f9654STobias Grosser 225edb885cbSTobias Grosser /// Create code for a ScopStmt called in @p Expr. 226edb885cbSTobias Grosser /// 227edb885cbSTobias Grosser /// @param Expr The expression containing the call. 228edb885cbSTobias Grosser /// @param KernelStmt The kernel statement referenced in the call. 229edb885cbSTobias Grosser void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt); 230edb885cbSTobias Grosser 2315260c041STobias Grosser /// Create an in-kernel synchronization call. 2325260c041STobias Grosser void createKernelSync(); 2335260c041STobias Grosser 23474dc3cb4STobias Grosser /// Create a PTX assembly string for the current GPU kernel. 23574dc3cb4STobias Grosser /// 23674dc3cb4STobias Grosser /// @returns A string containing the corresponding PTX assembly code. 23774dc3cb4STobias Grosser std::string createKernelASM(); 23874dc3cb4STobias Grosser 23974dc3cb4STobias Grosser /// Remove references from the dominator tree to the kernel function @p F. 24074dc3cb4STobias Grosser /// 24174dc3cb4STobias Grosser /// @param F The function to remove references to. 24274dc3cb4STobias Grosser void clearDominators(Function *F); 24374dc3cb4STobias Grosser 24474dc3cb4STobias Grosser /// Remove references from scalar evolution to the kernel function @p F. 24574dc3cb4STobias Grosser /// 24674dc3cb4STobias Grosser /// @param F The function to remove references to. 24774dc3cb4STobias Grosser void clearScalarEvolution(Function *F); 24874dc3cb4STobias Grosser 24974dc3cb4STobias Grosser /// Remove references from loop info to the kernel function @p F. 25074dc3cb4STobias Grosser /// 25174dc3cb4STobias Grosser /// @param F The function to remove references to. 25274dc3cb4STobias Grosser void clearLoops(Function *F); 25374dc3cb4STobias Grosser 25432837fe3STobias Grosser /// Finalize the generation of the kernel function. 25532837fe3STobias Grosser /// 25632837fe3STobias Grosser /// Free the LLVM-IR module corresponding to the kernel and -- if requested -- 25732837fe3STobias Grosser /// dump its IR to stderr. 25832837fe3STobias Grosser void finalizeKernelFunction(); 2591fb9b64dSTobias Grosser }; 2601fb9b64dSTobias Grosser 2615260c041STobias Grosser /// Check if one string is a prefix of another. 2625260c041STobias Grosser /// 2635260c041STobias Grosser /// @param String The string in which to look for the prefix. 2645260c041STobias Grosser /// @param Prefix The prefix to look for. 2655260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) { 2665260c041STobias Grosser return String.find(Prefix) == 0; 2675260c041STobias Grosser } 2685260c041STobias Grosser 2691fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) { 27032837fe3STobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt); 27132837fe3STobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 27232837fe3STobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr); 27332837fe3STobias Grosser isl_id_free(Id); 27432837fe3STobias Grosser isl_ast_expr_free(StmtExpr); 27532837fe3STobias Grosser 27632837fe3STobias Grosser const char *Str = isl_id_get_name(Id); 27732837fe3STobias Grosser if (!strcmp(Str, "kernel")) { 27832837fe3STobias Grosser createKernel(UserStmt); 27932837fe3STobias Grosser isl_ast_expr_free(Expr); 28032837fe3STobias Grosser return; 28132837fe3STobias Grosser } 28232837fe3STobias Grosser 2835260c041STobias Grosser if (isPrefix(Str, "to_device") || isPrefix(Str, "from_device")) { 2845260c041STobias Grosser // TODO: Insert memory copies 28532837fe3STobias Grosser isl_ast_expr_free(Expr); 2861fb9b64dSTobias Grosser isl_ast_node_free(UserStmt); 28738fc0aedSTobias Grosser return; 28838fc0aedSTobias Grosser } 28938fc0aedSTobias Grosser 2905260c041STobias Grosser isl_id *Anno = isl_ast_node_get_annotation(UserStmt); 2915260c041STobias Grosser struct ppcg_kernel_stmt *KernelStmt = 2925260c041STobias Grosser (struct ppcg_kernel_stmt *)isl_id_get_user(Anno); 2935260c041STobias Grosser isl_id_free(Anno); 2945260c041STobias Grosser 2955260c041STobias Grosser switch (KernelStmt->type) { 2965260c041STobias Grosser case ppcg_kernel_domain: 297edb885cbSTobias Grosser createScopStmt(Expr, KernelStmt); 2985260c041STobias Grosser isl_ast_node_free(UserStmt); 2995260c041STobias Grosser return; 3005260c041STobias Grosser case ppcg_kernel_copy: 3015260c041STobias Grosser // TODO: Create kernel copy stmt 3025260c041STobias Grosser isl_ast_expr_free(Expr); 3035260c041STobias Grosser isl_ast_node_free(UserStmt); 3045260c041STobias Grosser return; 3055260c041STobias Grosser case ppcg_kernel_sync: 3065260c041STobias Grosser createKernelSync(); 3075260c041STobias Grosser isl_ast_expr_free(Expr); 3085260c041STobias Grosser isl_ast_node_free(UserStmt); 3095260c041STobias Grosser return; 3105260c041STobias Grosser } 3115260c041STobias Grosser 3125260c041STobias Grosser isl_ast_expr_free(Expr); 3135260c041STobias Grosser isl_ast_node_free(UserStmt); 3145260c041STobias Grosser return; 3155260c041STobias Grosser } 3165260c041STobias Grosser 317edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr, 318edb885cbSTobias Grosser ppcg_kernel_stmt *KernelStmt) { 319edb885cbSTobias Grosser auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 320edb885cbSTobias Grosser isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr; 321edb885cbSTobias Grosser 322edb885cbSTobias Grosser LoopToScevMapT LTS; 323edb885cbSTobias Grosser LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end()); 324edb885cbSTobias Grosser 325edb885cbSTobias Grosser createSubstitutions(Expr, Stmt, LTS); 326edb885cbSTobias Grosser 327edb885cbSTobias Grosser if (Stmt->isBlockStmt()) 328edb885cbSTobias Grosser BlockGen.copyStmt(*Stmt, LTS, Indexes); 329edb885cbSTobias Grosser else 330edb885cbSTobias Grosser assert(0 && "Region statement not supported\n"); 331edb885cbSTobias Grosser } 332edb885cbSTobias Grosser 3335260c041STobias Grosser void GPUNodeBuilder::createKernelSync() { 3345260c041STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 3355260c041STobias Grosser auto *Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0); 3365260c041STobias Grosser Builder.CreateCall(Sync, {}); 3375260c041STobias Grosser } 3385260c041STobias Grosser 339edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node 340edb885cbSTobias Grosser /// 341edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring 342edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore. 343edb885cbSTobias Grosser /// 344edb885cbSTobias Grosser /// @param Node The node to collect references for. 345edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected. 346edb885cbSTobias Grosser /// 347edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully. 348edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) { 349edb885cbSTobias Grosser if (isl_ast_node_get_type(Node) != isl_ast_node_user) 350edb885cbSTobias Grosser return isl_bool_true; 351edb885cbSTobias Grosser 352edb885cbSTobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node); 353edb885cbSTobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 354edb885cbSTobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr); 355edb885cbSTobias Grosser const char *Str = isl_id_get_name(Id); 356edb885cbSTobias Grosser isl_id_free(Id); 357edb885cbSTobias Grosser isl_ast_expr_free(StmtExpr); 358edb885cbSTobias Grosser isl_ast_expr_free(Expr); 359edb885cbSTobias Grosser 360edb885cbSTobias Grosser if (!isPrefix(Str, "Stmt")) 361edb885cbSTobias Grosser return isl_bool_true; 362edb885cbSTobias Grosser 363edb885cbSTobias Grosser Id = isl_ast_node_get_annotation(Node); 364edb885cbSTobias Grosser auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id); 365edb885cbSTobias Grosser auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 366edb885cbSTobias Grosser isl_id_free(Id); 367edb885cbSTobias Grosser 368edb885cbSTobias Grosser addReferencesFromStmt(Stmt, User); 369edb885cbSTobias Grosser 370edb885cbSTobias Grosser return isl_bool_true; 371edb885cbSTobias Grosser } 372edb885cbSTobias Grosser 373edb885cbSTobias Grosser SetVector<Value *> GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) { 374edb885cbSTobias Grosser SetVector<Value *> SubtreeValues; 375edb885cbSTobias Grosser SetVector<const SCEV *> SCEVs; 376edb885cbSTobias Grosser SetVector<const Loop *> Loops; 377edb885cbSTobias Grosser SubtreeReferences References = { 378edb885cbSTobias Grosser LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()}; 379edb885cbSTobias Grosser 380edb885cbSTobias Grosser for (const auto &I : IDToValue) 381edb885cbSTobias Grosser SubtreeValues.insert(I.second); 382edb885cbSTobias Grosser 383edb885cbSTobias Grosser isl_ast_node_foreach_descendant_top_down( 384edb885cbSTobias Grosser Kernel->tree, collectReferencesInGPUStmt, &References); 385edb885cbSTobias Grosser 386edb885cbSTobias Grosser for (const SCEV *Expr : SCEVs) 387edb885cbSTobias Grosser findValues(Expr, SE, SubtreeValues); 388edb885cbSTobias Grosser 389edb885cbSTobias Grosser for (auto &SAI : S.arrays()) 390edb885cbSTobias Grosser SubtreeValues.remove(SAI.second->getBasePtr()); 391edb885cbSTobias Grosser 392edb885cbSTobias Grosser isl_space *Space = S.getParamSpace(); 393edb885cbSTobias Grosser for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) { 394edb885cbSTobias Grosser isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i); 395edb885cbSTobias Grosser assert(IDToValue.count(Id)); 396edb885cbSTobias Grosser Value *Val = IDToValue[Id]; 397edb885cbSTobias Grosser SubtreeValues.remove(Val); 398edb885cbSTobias Grosser isl_id_free(Id); 399edb885cbSTobias Grosser } 400edb885cbSTobias Grosser isl_space_free(Space); 401edb885cbSTobias Grosser 402edb885cbSTobias Grosser for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) { 403edb885cbSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 404edb885cbSTobias Grosser assert(IDToValue.count(Id)); 405edb885cbSTobias Grosser Value *Val = IDToValue[Id]; 406edb885cbSTobias Grosser SubtreeValues.remove(Val); 407edb885cbSTobias Grosser isl_id_free(Id); 408edb885cbSTobias Grosser } 409edb885cbSTobias Grosser 410edb885cbSTobias Grosser return SubtreeValues; 411edb885cbSTobias Grosser } 412edb885cbSTobias Grosser 41374dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) { 41474dc3cb4STobias Grosser DomTreeNode *N = DT.getNode(&F->getEntryBlock()); 41574dc3cb4STobias Grosser std::vector<BasicBlock *> Nodes; 41674dc3cb4STobias Grosser for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I) 41774dc3cb4STobias Grosser Nodes.push_back(I->getBlock()); 41874dc3cb4STobias Grosser 41974dc3cb4STobias Grosser for (BasicBlock *BB : Nodes) 42074dc3cb4STobias Grosser DT.eraseNode(BB); 42174dc3cb4STobias Grosser } 42274dc3cb4STobias Grosser 42374dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) { 42474dc3cb4STobias Grosser for (BasicBlock &BB : *F) { 42574dc3cb4STobias Grosser Loop *L = LI.getLoopFor(&BB); 42674dc3cb4STobias Grosser if (L) 42774dc3cb4STobias Grosser SE.forgetLoop(L); 42874dc3cb4STobias Grosser } 42974dc3cb4STobias Grosser } 43074dc3cb4STobias Grosser 43174dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) { 43274dc3cb4STobias Grosser for (BasicBlock &BB : *F) { 43374dc3cb4STobias Grosser Loop *L = LI.getLoopFor(&BB); 43474dc3cb4STobias Grosser if (L) 43574dc3cb4STobias Grosser SE.forgetLoop(L); 43674dc3cb4STobias Grosser LI.removeBlock(&BB); 43774dc3cb4STobias Grosser } 43874dc3cb4STobias Grosser } 43974dc3cb4STobias Grosser 44032837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) { 44132837fe3STobias Grosser isl_id *Id = isl_ast_node_get_annotation(KernelStmt); 44232837fe3STobias Grosser ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id); 44332837fe3STobias Grosser isl_id_free(Id); 44432837fe3STobias Grosser isl_ast_node_free(KernelStmt); 44532837fe3STobias Grosser 446edb885cbSTobias Grosser SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel); 447edb885cbSTobias Grosser 44832837fe3STobias Grosser assert(Kernel->tree && "Device AST of kernel node is empty"); 44932837fe3STobias Grosser 45032837fe3STobias Grosser Instruction &HostInsertPoint = *Builder.GetInsertPoint(); 451472f9654STobias Grosser IslExprBuilder::IDToValueTy HostIDs = IDToValue; 452edb885cbSTobias Grosser ValueMapT HostValueMap = ValueMap; 45332837fe3STobias Grosser 454edb885cbSTobias Grosser SetVector<const Loop *> Loops; 455edb885cbSTobias Grosser 456edb885cbSTobias Grosser // Create for all loops we depend on values that contain the current loop 457edb885cbSTobias Grosser // iteration. These values are necessary to generate code for SCEVs that 458edb885cbSTobias Grosser // depend on such loops. As a result we need to pass them to the subfunction. 459edb885cbSTobias Grosser for (const Loop *L : Loops) { 460edb885cbSTobias Grosser const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)), 461edb885cbSTobias Grosser SE.getUnknown(Builder.getInt64(1)), 462edb885cbSTobias Grosser L, SCEV::FlagAnyWrap); 463edb885cbSTobias Grosser Value *V = generateSCEV(OuterLIV); 464edb885cbSTobias Grosser OutsideLoopIterations[L] = SE.getUnknown(V); 465edb885cbSTobias Grosser SubtreeValues.insert(V); 466edb885cbSTobias Grosser } 467edb885cbSTobias Grosser 468edb885cbSTobias Grosser createKernelFunction(Kernel, SubtreeValues); 46932837fe3STobias Grosser 47059ab0705STobias Grosser create(isl_ast_node_copy(Kernel->tree)); 47159ab0705STobias Grosser 47274dc3cb4STobias Grosser Function *F = Builder.GetInsertBlock()->getParent(); 47374dc3cb4STobias Grosser clearDominators(F); 47474dc3cb4STobias Grosser clearScalarEvolution(F); 47574dc3cb4STobias Grosser clearLoops(F); 47674dc3cb4STobias Grosser 47732837fe3STobias Grosser Builder.SetInsertPoint(&HostInsertPoint); 478472f9654STobias Grosser IDToValue = HostIDs; 47932837fe3STobias Grosser 480edb885cbSTobias Grosser ValueMap = HostValueMap; 481edb885cbSTobias Grosser ScalarMap.clear(); 482edb885cbSTobias Grosser PHIOpMap.clear(); 483edb885cbSTobias Grosser EscapeMap.clear(); 484edb885cbSTobias Grosser IDToSAI.clear(); 48574dc3cb4STobias Grosser Annotator.resetAlternativeAliasBases(); 48674dc3cb4STobias Grosser for (auto &BasePtr : LocalArrays) 48774dc3cb4STobias Grosser S.invalidateScopArrayInfo(BasePtr, ScopArrayInfo::MK_Array); 48874dc3cb4STobias Grosser LocalArrays.clear(); 489edb885cbSTobias Grosser 49032837fe3STobias Grosser finalizeKernelFunction(); 49132837fe3STobias Grosser } 49232837fe3STobias Grosser 49332837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend. 49432837fe3STobias Grosser /// 49532837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture? 49632837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) { 49732837fe3STobias Grosser std::string Ret = "e"; 49832837fe3STobias Grosser 49932837fe3STobias Grosser if (!is64Bit) 50032837fe3STobias Grosser Ret += "-p:32:32"; 50132837fe3STobias Grosser 50232837fe3STobias Grosser Ret += "-i64:64-v16:16-v32:32-n16:32:64"; 50332837fe3STobias Grosser 50432837fe3STobias Grosser return Ret; 50532837fe3STobias Grosser } 50632837fe3STobias Grosser 507edb885cbSTobias Grosser Function * 508edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel, 509edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues) { 51032837fe3STobias Grosser std::vector<Type *> Args; 51132837fe3STobias Grosser std::string Identifier = "kernel_" + std::to_string(Kernel->id); 51232837fe3STobias Grosser 51332837fe3STobias Grosser for (long i = 0; i < Prog->n_array; i++) { 51432837fe3STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 51532837fe3STobias Grosser continue; 51632837fe3STobias Grosser 51732837fe3STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 51832837fe3STobias Grosser } 51932837fe3STobias Grosser 520f6044bd0STobias Grosser int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 521f6044bd0STobias Grosser 522f6044bd0STobias Grosser for (long i = 0; i < NumHostIters; i++) 523f6044bd0STobias Grosser Args.push_back(Builder.getInt64Ty()); 524f6044bd0STobias Grosser 525c84a1995STobias Grosser int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 526c84a1995STobias Grosser 527c84a1995STobias Grosser for (long i = 0; i < NumVars; i++) 528c84a1995STobias Grosser Args.push_back(Builder.getInt64Ty()); 529c84a1995STobias Grosser 530edb885cbSTobias Grosser for (auto *V : SubtreeValues) 531edb885cbSTobias Grosser Args.push_back(V->getType()); 532edb885cbSTobias Grosser 53332837fe3STobias Grosser auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false); 53432837fe3STobias Grosser auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier, 53532837fe3STobias Grosser GPUModule.get()); 53632837fe3STobias Grosser FN->setCallingConv(CallingConv::PTX_Kernel); 53732837fe3STobias Grosser 53832837fe3STobias Grosser auto Arg = FN->arg_begin(); 53932837fe3STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 54032837fe3STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 54132837fe3STobias Grosser continue; 54232837fe3STobias Grosser 543edb885cbSTobias Grosser Arg->setName(Kernel->array[i].array->name); 544edb885cbSTobias Grosser 545edb885cbSTobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 546edb885cbSTobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 547edb885cbSTobias Grosser Type *EleTy = SAI->getElementType(); 548edb885cbSTobias Grosser Value *Val = &*Arg; 549edb885cbSTobias Grosser SmallVector<const SCEV *, 4> Sizes; 550edb885cbSTobias Grosser isl_ast_build *Build = 551edb885cbSTobias Grosser isl_ast_build_from_context(isl_set_copy(Prog->context)); 552edb885cbSTobias Grosser for (long j = 1; j < Kernel->array[i].array->n_index; j++) { 553edb885cbSTobias Grosser isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff( 554edb885cbSTobias Grosser Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j])); 555edb885cbSTobias Grosser auto V = ExprBuilder.create(DimSize); 556edb885cbSTobias Grosser Sizes.push_back(SE.getSCEV(V)); 557edb885cbSTobias Grosser } 558edb885cbSTobias Grosser const ScopArrayInfo *SAIRep = 559edb885cbSTobias Grosser S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, ScopArrayInfo::MK_Array); 56074dc3cb4STobias Grosser LocalArrays.push_back(Val); 561edb885cbSTobias Grosser 562edb885cbSTobias Grosser isl_ast_build_free(Build); 563edb885cbSTobias Grosser isl_id_free(Id); 564edb885cbSTobias Grosser IDToSAI[Id] = SAIRep; 56532837fe3STobias Grosser Arg++; 56632837fe3STobias Grosser } 56732837fe3STobias Grosser 568f6044bd0STobias Grosser for (long i = 0; i < NumHostIters; i++) { 569f6044bd0STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 570f6044bd0STobias Grosser Arg->setName(isl_id_get_name(Id)); 571f6044bd0STobias Grosser IDToValue[Id] = &*Arg; 572f6044bd0STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 573f6044bd0STobias Grosser Arg++; 574f6044bd0STobias Grosser } 575f6044bd0STobias Grosser 576c84a1995STobias Grosser for (long i = 0; i < NumVars; i++) { 577c84a1995STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 578c84a1995STobias Grosser Arg->setName(isl_id_get_name(Id)); 579c84a1995STobias Grosser IDToValue[Id] = &*Arg; 580c84a1995STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 581c84a1995STobias Grosser Arg++; 582c84a1995STobias Grosser } 583c84a1995STobias Grosser 584edb885cbSTobias Grosser for (auto *V : SubtreeValues) { 585edb885cbSTobias Grosser Arg->setName(V->getName()); 586edb885cbSTobias Grosser ValueMap[V] = &*Arg; 587edb885cbSTobias Grosser Arg++; 588edb885cbSTobias Grosser } 589edb885cbSTobias Grosser 59032837fe3STobias Grosser return FN; 59132837fe3STobias Grosser } 59232837fe3STobias Grosser 593472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) { 594472f9654STobias Grosser Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x, 595472f9654STobias Grosser Intrinsic::nvvm_read_ptx_sreg_ctaid_y}; 596472f9654STobias Grosser 597472f9654STobias Grosser Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x, 598472f9654STobias Grosser Intrinsic::nvvm_read_ptx_sreg_tid_y, 599472f9654STobias Grosser Intrinsic::nvvm_read_ptx_sreg_tid_z}; 600472f9654STobias Grosser 601472f9654STobias Grosser auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable { 602472f9654STobias Grosser std::string Name = isl_id_get_name(Id); 603472f9654STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 604472f9654STobias Grosser Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr); 605472f9654STobias Grosser Value *Val = Builder.CreateCall(IntrinsicFn, {}); 606472f9654STobias Grosser Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 607472f9654STobias Grosser IDToValue[Id] = Val; 608472f9654STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 609472f9654STobias Grosser }; 610472f9654STobias Grosser 611472f9654STobias Grosser for (int i = 0; i < Kernel->n_grid; ++i) { 612472f9654STobias Grosser isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i); 613472f9654STobias Grosser addId(Id, IntrinsicsBID[i]); 614472f9654STobias Grosser } 615472f9654STobias Grosser 616472f9654STobias Grosser for (int i = 0; i < Kernel->n_block; ++i) { 617472f9654STobias Grosser isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i); 618472f9654STobias Grosser addId(Id, IntrinsicsTID[i]); 619472f9654STobias Grosser } 620472f9654STobias Grosser } 621472f9654STobias Grosser 622edb885cbSTobias Grosser void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel, 623edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues) { 62432837fe3STobias Grosser 62532837fe3STobias Grosser std::string Identifier = "kernel_" + std::to_string(Kernel->id); 62632837fe3STobias Grosser GPUModule.reset(new Module(Identifier, Builder.getContext())); 62732837fe3STobias Grosser GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda")); 62832837fe3STobias Grosser GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */)); 62932837fe3STobias Grosser 630edb885cbSTobias Grosser Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues); 63132837fe3STobias Grosser 63259ab0705STobias Grosser BasicBlock *PrevBlock = Builder.GetInsertBlock(); 63332837fe3STobias Grosser auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN); 63432837fe3STobias Grosser 63559ab0705STobias Grosser DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 63659ab0705STobias Grosser DT.addNewBlock(EntryBlock, PrevBlock); 63759ab0705STobias Grosser 63832837fe3STobias Grosser Builder.SetInsertPoint(EntryBlock); 63932837fe3STobias Grosser Builder.CreateRetVoid(); 64032837fe3STobias Grosser Builder.SetInsertPoint(EntryBlock, EntryBlock->begin()); 641472f9654STobias Grosser 642472f9654STobias Grosser insertKernelIntrinsics(Kernel); 64332837fe3STobias Grosser } 64432837fe3STobias Grosser 64574dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() { 64674dc3cb4STobias Grosser llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda")); 64774dc3cb4STobias Grosser std::string ErrMsg; 64874dc3cb4STobias Grosser auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg); 64974dc3cb4STobias Grosser 65074dc3cb4STobias Grosser if (!GPUTarget) { 65174dc3cb4STobias Grosser errs() << ErrMsg << "\n"; 65274dc3cb4STobias Grosser return ""; 65374dc3cb4STobias Grosser } 65474dc3cb4STobias Grosser 65574dc3cb4STobias Grosser TargetOptions Options; 65674dc3cb4STobias Grosser Options.UnsafeFPMath = FastMath; 65774dc3cb4STobias Grosser std::unique_ptr<TargetMachine> TargetM( 65874dc3cb4STobias Grosser GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "", 65974dc3cb4STobias Grosser Options, Optional<Reloc::Model>())); 66074dc3cb4STobias Grosser 66174dc3cb4STobias Grosser SmallString<0> ASMString; 66274dc3cb4STobias Grosser raw_svector_ostream ASMStream(ASMString); 66374dc3cb4STobias Grosser llvm::legacy::PassManager PM; 66474dc3cb4STobias Grosser 66574dc3cb4STobias Grosser PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis())); 66674dc3cb4STobias Grosser 66774dc3cb4STobias Grosser if (TargetM->addPassesToEmitFile( 66874dc3cb4STobias Grosser PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) { 66974dc3cb4STobias Grosser errs() << "The target does not support generation of this file type!\n"; 67074dc3cb4STobias Grosser return ""; 67174dc3cb4STobias Grosser } 67274dc3cb4STobias Grosser 67374dc3cb4STobias Grosser PM.run(*GPUModule); 67474dc3cb4STobias Grosser 67574dc3cb4STobias Grosser return ASMStream.str(); 67674dc3cb4STobias Grosser } 67774dc3cb4STobias Grosser 67832837fe3STobias Grosser void GPUNodeBuilder::finalizeKernelFunction() { 679e1a98343STobias Grosser // Verify module. 680e1a98343STobias Grosser llvm::legacy::PassManager Passes; 681e1a98343STobias Grosser Passes.add(createVerifierPass()); 682e1a98343STobias Grosser Passes.run(*GPUModule); 68332837fe3STobias Grosser 68432837fe3STobias Grosser if (DumpKernelIR) 68532837fe3STobias Grosser outs() << *GPUModule << "\n"; 68632837fe3STobias Grosser 6879a18d559STobias Grosser // Optimize module. 6889a18d559STobias Grosser llvm::legacy::PassManager OptPasses; 6899a18d559STobias Grosser PassManagerBuilder PassBuilder; 6909a18d559STobias Grosser PassBuilder.OptLevel = 3; 6919a18d559STobias Grosser PassBuilder.SizeLevel = 0; 6929a18d559STobias Grosser PassBuilder.populateModulePassManager(OptPasses); 6939a18d559STobias Grosser OptPasses.run(*GPUModule); 6949a18d559STobias Grosser 69574dc3cb4STobias Grosser std::string Assembly = createKernelASM(); 69674dc3cb4STobias Grosser 69774dc3cb4STobias Grosser if (DumpKernelASM) 69874dc3cb4STobias Grosser outs() << Assembly << "\n"; 69974dc3cb4STobias Grosser 70032837fe3STobias Grosser GPUModule.release(); 701472f9654STobias Grosser KernelIDs.clear(); 70232837fe3STobias Grosser } 70332837fe3STobias Grosser 7049dfe4e7cSTobias Grosser namespace { 7059dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass { 7069dfe4e7cSTobias Grosser public: 7079dfe4e7cSTobias Grosser static char ID; 7089dfe4e7cSTobias Grosser 709e938517eSTobias Grosser /// The scop that is currently processed. 710e938517eSTobias Grosser Scop *S; 711e938517eSTobias Grosser 71238fc0aedSTobias Grosser LoopInfo *LI; 71338fc0aedSTobias Grosser DominatorTree *DT; 71438fc0aedSTobias Grosser ScalarEvolution *SE; 71538fc0aedSTobias Grosser const DataLayout *DL; 71638fc0aedSTobias Grosser RegionInfo *RI; 71738fc0aedSTobias Grosser 7189dfe4e7cSTobias Grosser PPCGCodeGeneration() : ScopPass(ID) {} 7199dfe4e7cSTobias Grosser 720e938517eSTobias Grosser /// Construct compilation options for PPCG. 721e938517eSTobias Grosser /// 722e938517eSTobias Grosser /// @returns The compilation options. 723e938517eSTobias Grosser ppcg_options *createPPCGOptions() { 724e938517eSTobias Grosser auto DebugOptions = 725e938517eSTobias Grosser (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options)); 726e938517eSTobias Grosser auto Options = (ppcg_options *)malloc(sizeof(ppcg_options)); 727e938517eSTobias Grosser 728e938517eSTobias Grosser DebugOptions->dump_schedule_constraints = false; 729e938517eSTobias Grosser DebugOptions->dump_schedule = false; 730e938517eSTobias Grosser DebugOptions->dump_final_schedule = false; 731e938517eSTobias Grosser DebugOptions->dump_sizes = false; 732e938517eSTobias Grosser 733e938517eSTobias Grosser Options->debug = DebugOptions; 734e938517eSTobias Grosser 735e938517eSTobias Grosser Options->reschedule = true; 736e938517eSTobias Grosser Options->scale_tile_loops = false; 737e938517eSTobias Grosser Options->wrap = false; 738e938517eSTobias Grosser 739e938517eSTobias Grosser Options->non_negative_parameters = false; 740e938517eSTobias Grosser Options->ctx = nullptr; 741e938517eSTobias Grosser Options->sizes = nullptr; 742e938517eSTobias Grosser 7434eaedde5STobias Grosser Options->tile_size = 32; 7444eaedde5STobias Grosser 745e938517eSTobias Grosser Options->use_private_memory = false; 746e938517eSTobias Grosser Options->use_shared_memory = false; 747e938517eSTobias Grosser Options->max_shared_memory = 0; 748e938517eSTobias Grosser 749e938517eSTobias Grosser Options->target = PPCG_TARGET_CUDA; 750e938517eSTobias Grosser Options->openmp = false; 751e938517eSTobias Grosser Options->linearize_device_arrays = true; 752e938517eSTobias Grosser Options->live_range_reordering = false; 753e938517eSTobias Grosser 754e938517eSTobias Grosser Options->opencl_compiler_options = nullptr; 755e938517eSTobias Grosser Options->opencl_use_gpu = false; 756e938517eSTobias Grosser Options->opencl_n_include_file = 0; 757e938517eSTobias Grosser Options->opencl_include_files = nullptr; 758e938517eSTobias Grosser Options->opencl_print_kernel_types = false; 759e938517eSTobias Grosser Options->opencl_embed_kernel_code = false; 760e938517eSTobias Grosser 761e938517eSTobias Grosser Options->save_schedule_file = nullptr; 762e938517eSTobias Grosser Options->load_schedule_file = nullptr; 763e938517eSTobias Grosser 764e938517eSTobias Grosser return Options; 765e938517eSTobias Grosser } 766e938517eSTobias Grosser 767f384594dSTobias Grosser /// Get a tagged access relation containing all accesses of type @p AccessTy. 768f384594dSTobias Grosser /// 769f384594dSTobias Grosser /// Instead of a normal access of the form: 770f384594dSTobias Grosser /// 771f384594dSTobias Grosser /// Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)] 772f384594dSTobias Grosser /// 773f384594dSTobias Grosser /// a tagged access has the form 774f384594dSTobias Grosser /// 775f384594dSTobias Grosser /// [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)] 776f384594dSTobias Grosser /// 777f384594dSTobias Grosser /// where 'id' is an additional space that references the memory access that 778f384594dSTobias Grosser /// triggered the access. 779f384594dSTobias Grosser /// 780f384594dSTobias Grosser /// @param AccessTy The type of the memory accesses to collect. 781f384594dSTobias Grosser /// 782f384594dSTobias Grosser /// @return The relation describing all tagged memory accesses. 783f384594dSTobias Grosser isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) { 784f384594dSTobias Grosser isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace()); 785f384594dSTobias Grosser 786f384594dSTobias Grosser for (auto &Stmt : *S) 787f384594dSTobias Grosser for (auto &Acc : Stmt) 788f384594dSTobias Grosser if (Acc->getType() == AccessTy) { 789f384594dSTobias Grosser isl_map *Relation = Acc->getAccessRelation(); 790f384594dSTobias Grosser Relation = isl_map_intersect_domain(Relation, Stmt.getDomain()); 791f384594dSTobias Grosser 792f384594dSTobias Grosser isl_space *Space = isl_map_get_space(Relation); 793f384594dSTobias Grosser Space = isl_space_range(Space); 794f384594dSTobias Grosser Space = isl_space_from_range(Space); 7956293ba69STobias Grosser Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId()); 796f384594dSTobias Grosser isl_map *Universe = isl_map_universe(Space); 797f384594dSTobias Grosser Relation = isl_map_domain_product(Relation, Universe); 798f384594dSTobias Grosser Accesses = isl_union_map_add_map(Accesses, Relation); 799f384594dSTobias Grosser } 800f384594dSTobias Grosser 801f384594dSTobias Grosser return Accesses; 802f384594dSTobias Grosser } 803f384594dSTobias Grosser 804f384594dSTobias Grosser /// Get the set of all read accesses, tagged with the access id. 805f384594dSTobias Grosser /// 806f384594dSTobias Grosser /// @see getTaggedAccesses 807f384594dSTobias Grosser isl_union_map *getTaggedReads() { 808f384594dSTobias Grosser return getTaggedAccesses(MemoryAccess::READ); 809f384594dSTobias Grosser } 810f384594dSTobias Grosser 811f384594dSTobias Grosser /// Get the set of all may (and must) accesses, tagged with the access id. 812f384594dSTobias Grosser /// 813f384594dSTobias Grosser /// @see getTaggedAccesses 814f384594dSTobias Grosser isl_union_map *getTaggedMayWrites() { 815f384594dSTobias Grosser return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE), 816f384594dSTobias Grosser getTaggedAccesses(MemoryAccess::MUST_WRITE)); 817f384594dSTobias Grosser } 818f384594dSTobias Grosser 819f384594dSTobias Grosser /// Get the set of all must accesses, tagged with the access id. 820f384594dSTobias Grosser /// 821f384594dSTobias Grosser /// @see getTaggedAccesses 822f384594dSTobias Grosser isl_union_map *getTaggedMustWrites() { 823f384594dSTobias Grosser return getTaggedAccesses(MemoryAccess::MUST_WRITE); 824f384594dSTobias Grosser } 825f384594dSTobias Grosser 826aef5196fSTobias Grosser /// Collect parameter and array names as isl_ids. 827aef5196fSTobias Grosser /// 828aef5196fSTobias Grosser /// To reason about the different parameters and arrays used, ppcg requires 829aef5196fSTobias Grosser /// a list of all isl_ids in use. As PPCG traditionally performs 830aef5196fSTobias Grosser /// source-to-source compilation each of these isl_ids is mapped to the 831aef5196fSTobias Grosser /// expression that represents it. As we do not have a corresponding 832aef5196fSTobias Grosser /// expression in Polly, we just map each id to a 'zero' expression to match 833aef5196fSTobias Grosser /// the data format that ppcg expects. 834aef5196fSTobias Grosser /// 835aef5196fSTobias Grosser /// @returns Retun a map from collected ids to 'zero' ast expressions. 836aef5196fSTobias Grosser __isl_give isl_id_to_ast_expr *getNames() { 837aef5196fSTobias Grosser auto *Names = isl_id_to_ast_expr_alloc( 838bd81a7eeSTobias Grosser S->getIslCtx(), 839bd81a7eeSTobias Grosser S->getNumParams() + std::distance(S->array_begin(), S->array_end())); 840aef5196fSTobias Grosser auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx())); 841aef5196fSTobias Grosser auto *Space = S->getParamSpace(); 842aef5196fSTobias Grosser 843aef5196fSTobias Grosser for (int I = 0, E = S->getNumParams(); I < E; ++I) { 844aef5196fSTobias Grosser isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I); 845aef5196fSTobias Grosser Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 846aef5196fSTobias Grosser } 847aef5196fSTobias Grosser 848aef5196fSTobias Grosser for (auto &Array : S->arrays()) { 849aef5196fSTobias Grosser auto Id = Array.second->getBasePtrId(); 850aef5196fSTobias Grosser Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 851aef5196fSTobias Grosser } 852aef5196fSTobias Grosser 853aef5196fSTobias Grosser isl_space_free(Space); 854aef5196fSTobias Grosser isl_ast_expr_free(Zero); 855aef5196fSTobias Grosser 856aef5196fSTobias Grosser return Names; 857aef5196fSTobias Grosser } 858aef5196fSTobias Grosser 859e938517eSTobias Grosser /// Create a new PPCG scop from the current scop. 860e938517eSTobias Grosser /// 861f384594dSTobias Grosser /// The PPCG scop is initialized with data from the current polly::Scop. From 862f384594dSTobias Grosser /// this initial data, the data-dependences in the PPCG scop are initialized. 863f384594dSTobias Grosser /// We do not use Polly's dependence analysis for now, to ensure we match 864f384594dSTobias Grosser /// the PPCG default behaviour more closely. 865e938517eSTobias Grosser /// 866e938517eSTobias Grosser /// @returns A new ppcg scop. 867e938517eSTobias Grosser ppcg_scop *createPPCGScop() { 868e938517eSTobias Grosser auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop)); 869e938517eSTobias Grosser 870e938517eSTobias Grosser PPCGScop->options = createPPCGOptions(); 871e938517eSTobias Grosser 872e938517eSTobias Grosser PPCGScop->start = 0; 873e938517eSTobias Grosser PPCGScop->end = 0; 874e938517eSTobias Grosser 875f384594dSTobias Grosser PPCGScop->context = S->getContext(); 876f384594dSTobias Grosser PPCGScop->domain = S->getDomains(); 877e938517eSTobias Grosser PPCGScop->call = nullptr; 878f384594dSTobias Grosser PPCGScop->tagged_reads = getTaggedReads(); 879f384594dSTobias Grosser PPCGScop->reads = S->getReads(); 880e938517eSTobias Grosser PPCGScop->live_in = nullptr; 881f384594dSTobias Grosser PPCGScop->tagged_may_writes = getTaggedMayWrites(); 882f384594dSTobias Grosser PPCGScop->may_writes = S->getWrites(); 883f384594dSTobias Grosser PPCGScop->tagged_must_writes = getTaggedMustWrites(); 884f384594dSTobias Grosser PPCGScop->must_writes = S->getMustWrites(); 885e938517eSTobias Grosser PPCGScop->live_out = nullptr; 886f384594dSTobias Grosser PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace()); 887e938517eSTobias Grosser PPCGScop->tagger = nullptr; 888e938517eSTobias Grosser 889e938517eSTobias Grosser PPCGScop->independence = nullptr; 890e938517eSTobias Grosser PPCGScop->dep_flow = nullptr; 891e938517eSTobias Grosser PPCGScop->tagged_dep_flow = nullptr; 892e938517eSTobias Grosser PPCGScop->dep_false = nullptr; 893e938517eSTobias Grosser PPCGScop->dep_forced = nullptr; 894e938517eSTobias Grosser PPCGScop->dep_order = nullptr; 895e938517eSTobias Grosser PPCGScop->tagged_dep_order = nullptr; 896e938517eSTobias Grosser 897f384594dSTobias Grosser PPCGScop->schedule = S->getScheduleTree(); 898aef5196fSTobias Grosser PPCGScop->names = getNames(); 899e938517eSTobias Grosser 900e938517eSTobias Grosser PPCGScop->pet = nullptr; 901e938517eSTobias Grosser 902f384594dSTobias Grosser compute_tagger(PPCGScop); 903f384594dSTobias Grosser compute_dependences(PPCGScop); 904f384594dSTobias Grosser 905e938517eSTobias Grosser return PPCGScop; 906e938517eSTobias Grosser } 907e938517eSTobias Grosser 90860f63b49STobias Grosser /// Collect the array acesses in a statement. 90960f63b49STobias Grosser /// 91060f63b49STobias Grosser /// @param Stmt The statement for which to collect the accesses. 91160f63b49STobias Grosser /// 91260f63b49STobias Grosser /// @returns A list of array accesses. 91360f63b49STobias Grosser gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) { 91460f63b49STobias Grosser gpu_stmt_access *Accesses = nullptr; 91560f63b49STobias Grosser 91660f63b49STobias Grosser for (MemoryAccess *Acc : Stmt) { 91760f63b49STobias Grosser auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access); 91860f63b49STobias Grosser Access->read = Acc->isRead(); 91960f63b49STobias Grosser Access->write = Acc->isWrite(); 92060f63b49STobias Grosser Access->access = Acc->getAccessRelation(); 92160f63b49STobias Grosser isl_space *Space = isl_map_get_space(Access->access); 92260f63b49STobias Grosser Space = isl_space_range(Space); 92360f63b49STobias Grosser Space = isl_space_from_range(Space); 9246293ba69STobias Grosser Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId()); 92560f63b49STobias Grosser isl_map *Universe = isl_map_universe(Space); 92660f63b49STobias Grosser Access->tagged_access = 92760f63b49STobias Grosser isl_map_domain_product(Acc->getAccessRelation(), Universe); 92860f63b49STobias Grosser Access->exact_write = Acc->isWrite(); 92960f63b49STobias Grosser Access->ref_id = Acc->getId(); 93060f63b49STobias Grosser Access->next = Accesses; 93160f63b49STobias Grosser Accesses = Access; 93260f63b49STobias Grosser } 93360f63b49STobias Grosser 93460f63b49STobias Grosser return Accesses; 93560f63b49STobias Grosser } 93660f63b49STobias Grosser 93769b46751STobias Grosser /// Collect the list of GPU statements. 93869b46751STobias Grosser /// 93969b46751STobias Grosser /// Each statement has an id, a pointer to the underlying data structure, 94069b46751STobias Grosser /// as well as a list with all memory accesses. 94169b46751STobias Grosser /// 94269b46751STobias Grosser /// TODO: Initialize the list of memory accesses. 94369b46751STobias Grosser /// 94469b46751STobias Grosser /// @returns A linked-list of statements. 94569b46751STobias Grosser gpu_stmt *getStatements() { 94669b46751STobias Grosser gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt, 94769b46751STobias Grosser std::distance(S->begin(), S->end())); 94869b46751STobias Grosser 94969b46751STobias Grosser int i = 0; 95069b46751STobias Grosser for (auto &Stmt : *S) { 95169b46751STobias Grosser gpu_stmt *GPUStmt = &Stmts[i]; 95269b46751STobias Grosser 95369b46751STobias Grosser GPUStmt->id = Stmt.getDomainId(); 95469b46751STobias Grosser 95569b46751STobias Grosser // We use the pet stmt pointer to keep track of the Polly statements. 95669b46751STobias Grosser GPUStmt->stmt = (pet_stmt *)&Stmt; 95760f63b49STobias Grosser GPUStmt->accesses = getStmtAccesses(Stmt); 95869b46751STobias Grosser i++; 95969b46751STobias Grosser } 96069b46751STobias Grosser 96169b46751STobias Grosser return Stmts; 96269b46751STobias Grosser } 96369b46751STobias Grosser 96460f63b49STobias Grosser /// Derive the extent of an array. 96560f63b49STobias Grosser /// 96660f63b49STobias Grosser /// The extent of an array is defined by the set of memory locations for 96760f63b49STobias Grosser /// which a memory access in the iteration domain exists. 96860f63b49STobias Grosser /// 96960f63b49STobias Grosser /// @param Array The array to derive the extent for. 97060f63b49STobias Grosser /// 97160f63b49STobias Grosser /// @returns An isl_set describing the extent of the array. 97260f63b49STobias Grosser __isl_give isl_set *getExtent(ScopArrayInfo *Array) { 97360f63b49STobias Grosser isl_union_map *Accesses = S->getAccesses(); 97460f63b49STobias Grosser Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains()); 97560f63b49STobias Grosser isl_union_set *AccessUSet = isl_union_map_range(Accesses); 97660f63b49STobias Grosser isl_set *AccessSet = 97760f63b49STobias Grosser isl_union_set_extract_set(AccessUSet, Array->getSpace()); 97860f63b49STobias Grosser isl_union_set_free(AccessUSet); 97960f63b49STobias Grosser 98060f63b49STobias Grosser return AccessSet; 98160f63b49STobias Grosser } 98260f63b49STobias Grosser 98360f63b49STobias Grosser /// Derive the bounds of an array. 98460f63b49STobias Grosser /// 98560f63b49STobias Grosser /// For the first dimension we derive the bound of the array from the extent 98660f63b49STobias Grosser /// of this dimension. For inner dimensions we obtain their size directly from 98760f63b49STobias Grosser /// ScopArrayInfo. 98860f63b49STobias Grosser /// 98960f63b49STobias Grosser /// @param PPCGArray The array to compute bounds for. 99060f63b49STobias Grosser /// @param Array The polly array from which to take the information. 99160f63b49STobias Grosser void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) { 99260f63b49STobias Grosser if (PPCGArray.n_index > 0) { 99360f63b49STobias Grosser isl_set *Dom = isl_set_copy(PPCGArray.extent); 99460f63b49STobias Grosser Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1); 99560f63b49STobias Grosser isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0); 99660f63b49STobias Grosser isl_set_free(Dom); 99760f63b49STobias Grosser Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound)); 99860f63b49STobias Grosser isl_local_space *LS = isl_local_space_from_space(isl_set_get_space(Dom)); 99960f63b49STobias Grosser isl_aff *One = isl_aff_zero_on_domain(LS); 100060f63b49STobias Grosser One = isl_aff_add_constant_si(One, 1); 100160f63b49STobias Grosser Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One)); 100260f63b49STobias Grosser Bound = isl_pw_aff_gist(Bound, S->getContext()); 100360f63b49STobias Grosser PPCGArray.bound[0] = Bound; 100460f63b49STobias Grosser } 100560f63b49STobias Grosser 100660f63b49STobias Grosser for (unsigned i = 1; i < PPCGArray.n_index; ++i) { 100760f63b49STobias Grosser isl_pw_aff *Bound = Array->getDimensionSizePw(i); 100860f63b49STobias Grosser auto LS = isl_pw_aff_get_domain_space(Bound); 100960f63b49STobias Grosser auto Aff = isl_multi_aff_zero(LS); 101060f63b49STobias Grosser Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff); 101160f63b49STobias Grosser PPCGArray.bound[i] = Bound; 101260f63b49STobias Grosser } 101360f63b49STobias Grosser } 101460f63b49STobias Grosser 101560f63b49STobias Grosser /// Create the arrays for @p PPCGProg. 101660f63b49STobias Grosser /// 101760f63b49STobias Grosser /// @param PPCGProg The program to compute the arrays for. 101860f63b49STobias Grosser void createArrays(gpu_prog *PPCGProg) { 101960f63b49STobias Grosser int i = 0; 102060f63b49STobias Grosser for (auto &Element : S->arrays()) { 102160f63b49STobias Grosser ScopArrayInfo *Array = Element.second.get(); 102260f63b49STobias Grosser 102360f63b49STobias Grosser std::string TypeName; 102460f63b49STobias Grosser raw_string_ostream OS(TypeName); 102560f63b49STobias Grosser 102660f63b49STobias Grosser OS << *Array->getElementType(); 102760f63b49STobias Grosser TypeName = OS.str(); 102860f63b49STobias Grosser 102960f63b49STobias Grosser gpu_array_info &PPCGArray = PPCGProg->array[i]; 103060f63b49STobias Grosser 103160f63b49STobias Grosser PPCGArray.space = Array->getSpace(); 103260f63b49STobias Grosser PPCGArray.type = strdup(TypeName.c_str()); 103360f63b49STobias Grosser PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8; 103460f63b49STobias Grosser PPCGArray.name = strdup(Array->getName().c_str()); 103560f63b49STobias Grosser PPCGArray.extent = nullptr; 103660f63b49STobias Grosser PPCGArray.n_index = Array->getNumberOfDimensions(); 103760f63b49STobias Grosser PPCGArray.bound = 103860f63b49STobias Grosser isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index); 103960f63b49STobias Grosser PPCGArray.extent = getExtent(Array); 104060f63b49STobias Grosser PPCGArray.n_ref = 0; 104160f63b49STobias Grosser PPCGArray.refs = nullptr; 104260f63b49STobias Grosser PPCGArray.accessed = true; 104360f63b49STobias Grosser PPCGArray.read_only_scalar = false; 104460f63b49STobias Grosser PPCGArray.has_compound_element = false; 104560f63b49STobias Grosser PPCGArray.local = false; 104660f63b49STobias Grosser PPCGArray.declare_local = false; 104760f63b49STobias Grosser PPCGArray.global = false; 104860f63b49STobias Grosser PPCGArray.linearize = false; 104960f63b49STobias Grosser PPCGArray.dep_order = nullptr; 105060f63b49STobias Grosser 105160f63b49STobias Grosser setArrayBounds(PPCGArray, Array); 10522d010dafSTobias Grosser i++; 1053b9fc860aSTobias Grosser 1054b9fc860aSTobias Grosser collect_references(PPCGProg, &PPCGArray); 105560f63b49STobias Grosser } 105660f63b49STobias Grosser } 105760f63b49STobias Grosser 105860f63b49STobias Grosser /// Create an identity map between the arrays in the scop. 105960f63b49STobias Grosser /// 106060f63b49STobias Grosser /// @returns An identity map between the arrays in the scop. 106160f63b49STobias Grosser isl_union_map *getArrayIdentity() { 106260f63b49STobias Grosser isl_union_map *Maps = isl_union_map_empty(S->getParamSpace()); 106360f63b49STobias Grosser 106460f63b49STobias Grosser for (auto &Item : S->arrays()) { 106560f63b49STobias Grosser ScopArrayInfo *Array = Item.second.get(); 106660f63b49STobias Grosser isl_space *Space = Array->getSpace(); 106760f63b49STobias Grosser Space = isl_space_map_from_set(Space); 106860f63b49STobias Grosser isl_map *Identity = isl_map_identity(Space); 106960f63b49STobias Grosser Maps = isl_union_map_add_map(Maps, Identity); 107060f63b49STobias Grosser } 107160f63b49STobias Grosser 107260f63b49STobias Grosser return Maps; 107360f63b49STobias Grosser } 107460f63b49STobias Grosser 1075e938517eSTobias Grosser /// Create a default-initialized PPCG GPU program. 1076e938517eSTobias Grosser /// 1077e938517eSTobias Grosser /// @returns A new gpu grogram description. 1078e938517eSTobias Grosser gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) { 1079e938517eSTobias Grosser 1080e938517eSTobias Grosser if (!PPCGScop) 1081e938517eSTobias Grosser return nullptr; 1082e938517eSTobias Grosser 1083e938517eSTobias Grosser auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog); 1084e938517eSTobias Grosser 1085e938517eSTobias Grosser PPCGProg->ctx = S->getIslCtx(); 1086e938517eSTobias Grosser PPCGProg->scop = PPCGScop; 1087aef5196fSTobias Grosser PPCGProg->context = isl_set_copy(PPCGScop->context); 108860f63b49STobias Grosser PPCGProg->read = isl_union_map_copy(PPCGScop->reads); 108960f63b49STobias Grosser PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes); 109060f63b49STobias Grosser PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes); 109160f63b49STobias Grosser PPCGProg->tagged_must_kill = 109260f63b49STobias Grosser isl_union_map_copy(PPCGScop->tagged_must_kills); 109360f63b49STobias Grosser PPCGProg->to_inner = getArrayIdentity(); 109460f63b49STobias Grosser PPCGProg->to_outer = getArrayIdentity(); 109560f63b49STobias Grosser PPCGProg->may_persist = compute_may_persist(PPCGProg); 1096e938517eSTobias Grosser PPCGProg->any_to_outer = nullptr; 1097e938517eSTobias Grosser PPCGProg->array_order = nullptr; 109869b46751STobias Grosser PPCGProg->n_stmts = std::distance(S->begin(), S->end()); 109969b46751STobias Grosser PPCGProg->stmts = getStatements(); 110060f63b49STobias Grosser PPCGProg->n_array = std::distance(S->array_begin(), S->array_end()); 110160f63b49STobias Grosser PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info, 110260f63b49STobias Grosser PPCGProg->n_array); 110360f63b49STobias Grosser 110460f63b49STobias Grosser createArrays(PPCGProg); 1105e938517eSTobias Grosser 1106e938517eSTobias Grosser return PPCGProg; 1107e938517eSTobias Grosser } 1108e938517eSTobias Grosser 110969b46751STobias Grosser struct PrintGPUUserData { 111069b46751STobias Grosser struct cuda_info *CudaInfo; 111169b46751STobias Grosser struct gpu_prog *PPCGProg; 111269b46751STobias Grosser std::vector<ppcg_kernel *> Kernels; 111369b46751STobias Grosser }; 111469b46751STobias Grosser 111569b46751STobias Grosser /// Print a user statement node in the host code. 111669b46751STobias Grosser /// 111769b46751STobias Grosser /// We use ppcg's printing facilities to print the actual statement and 111869b46751STobias Grosser /// additionally build up a list of all kernels that are encountered in the 111969b46751STobias Grosser /// host ast. 112069b46751STobias Grosser /// 112169b46751STobias Grosser /// @param P The printer to print to 112269b46751STobias Grosser /// @param Options The printing options to use 112369b46751STobias Grosser /// @param Node The node to print 112469b46751STobias Grosser /// @param User A user pointer to carry additional data. This pointer is 112569b46751STobias Grosser /// expected to be of type PrintGPUUserData. 112669b46751STobias Grosser /// 112769b46751STobias Grosser /// @returns A printer to which the output has been printed. 112869b46751STobias Grosser static __isl_give isl_printer * 112969b46751STobias Grosser printHostUser(__isl_take isl_printer *P, 113069b46751STobias Grosser __isl_take isl_ast_print_options *Options, 113169b46751STobias Grosser __isl_take isl_ast_node *Node, void *User) { 113269b46751STobias Grosser auto Data = (struct PrintGPUUserData *)User; 113369b46751STobias Grosser auto Id = isl_ast_node_get_annotation(Node); 113469b46751STobias Grosser 113569b46751STobias Grosser if (Id) { 113620251734STobias Grosser bool IsUser = !strcmp(isl_id_get_name(Id), "user"); 113720251734STobias Grosser 113820251734STobias Grosser // If this is a user statement, format it ourselves as ppcg would 113920251734STobias Grosser // otherwise try to call pet functionality that is not available in 114020251734STobias Grosser // Polly. 114120251734STobias Grosser if (IsUser) { 114220251734STobias Grosser P = isl_printer_start_line(P); 114320251734STobias Grosser P = isl_printer_print_ast_node(P, Node); 114420251734STobias Grosser P = isl_printer_end_line(P); 114520251734STobias Grosser isl_id_free(Id); 114620251734STobias Grosser isl_ast_print_options_free(Options); 114720251734STobias Grosser return P; 114820251734STobias Grosser } 114920251734STobias Grosser 115069b46751STobias Grosser auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id); 115169b46751STobias Grosser isl_id_free(Id); 115269b46751STobias Grosser Data->Kernels.push_back(Kernel); 115369b46751STobias Grosser } 115469b46751STobias Grosser 115569b46751STobias Grosser return print_host_user(P, Options, Node, User); 115669b46751STobias Grosser } 115769b46751STobias Grosser 115869b46751STobias Grosser /// Print C code corresponding to the control flow in @p Kernel. 115969b46751STobias Grosser /// 116069b46751STobias Grosser /// @param Kernel The kernel to print 116169b46751STobias Grosser void printKernel(ppcg_kernel *Kernel) { 116269b46751STobias Grosser auto *P = isl_printer_to_str(S->getIslCtx()); 116369b46751STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C); 116469b46751STobias Grosser auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 116569b46751STobias Grosser P = isl_ast_node_print(Kernel->tree, P, Options); 116669b46751STobias Grosser char *String = isl_printer_get_str(P); 116769b46751STobias Grosser printf("%s\n", String); 116869b46751STobias Grosser free(String); 116969b46751STobias Grosser isl_printer_free(P); 117069b46751STobias Grosser } 117169b46751STobias Grosser 117269b46751STobias Grosser /// Print C code corresponding to the GPU code described by @p Tree. 117369b46751STobias Grosser /// 117469b46751STobias Grosser /// @param Tree An AST describing GPU code 117569b46751STobias Grosser /// @param PPCGProg The PPCG program from which @Tree has been constructed. 117669b46751STobias Grosser void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) { 117769b46751STobias Grosser auto *P = isl_printer_to_str(S->getIslCtx()); 117869b46751STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C); 117969b46751STobias Grosser 118069b46751STobias Grosser PrintGPUUserData Data; 118169b46751STobias Grosser Data.PPCGProg = PPCGProg; 118269b46751STobias Grosser 118369b46751STobias Grosser auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 118469b46751STobias Grosser Options = 118569b46751STobias Grosser isl_ast_print_options_set_print_user(Options, printHostUser, &Data); 118669b46751STobias Grosser P = isl_ast_node_print(Tree, P, Options); 118769b46751STobias Grosser char *String = isl_printer_get_str(P); 118869b46751STobias Grosser printf("# host\n"); 118969b46751STobias Grosser printf("%s\n", String); 119069b46751STobias Grosser free(String); 119169b46751STobias Grosser isl_printer_free(P); 119269b46751STobias Grosser 119369b46751STobias Grosser for (auto Kernel : Data.Kernels) { 119469b46751STobias Grosser printf("# kernel%d\n", Kernel->id); 119569b46751STobias Grosser printKernel(Kernel); 119669b46751STobias Grosser } 119769b46751STobias Grosser } 119869b46751STobias Grosser 1199f384594dSTobias Grosser // Generate a GPU program using PPCG. 1200f384594dSTobias Grosser // 1201f384594dSTobias Grosser // GPU mapping consists of multiple steps: 1202f384594dSTobias Grosser // 1203f384594dSTobias Grosser // 1) Compute new schedule for the program. 1204f384594dSTobias Grosser // 2) Map schedule to GPU (TODO) 1205f384594dSTobias Grosser // 3) Generate code for new schedule (TODO) 1206f384594dSTobias Grosser // 1207f384594dSTobias Grosser // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer 1208f384594dSTobias Grosser // is mostly CPU specific. Instead, we use PPCG's GPU code generation 1209f384594dSTobias Grosser // strategy directly from this pass. 1210f384594dSTobias Grosser gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) { 1211f384594dSTobias Grosser 1212f384594dSTobias Grosser auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen); 1213f384594dSTobias Grosser 1214f384594dSTobias Grosser PPCGGen->ctx = S->getIslCtx(); 1215f384594dSTobias Grosser PPCGGen->options = PPCGScop->options; 1216f384594dSTobias Grosser PPCGGen->print = nullptr; 1217f384594dSTobias Grosser PPCGGen->print_user = nullptr; 121860c60025STobias Grosser PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt; 1219f384594dSTobias Grosser PPCGGen->prog = PPCGProg; 1220f384594dSTobias Grosser PPCGGen->tree = nullptr; 1221f384594dSTobias Grosser PPCGGen->types.n = 0; 1222f384594dSTobias Grosser PPCGGen->types.name = nullptr; 1223f384594dSTobias Grosser PPCGGen->sizes = nullptr; 1224f384594dSTobias Grosser PPCGGen->used_sizes = nullptr; 1225f384594dSTobias Grosser PPCGGen->kernel_id = 0; 1226f384594dSTobias Grosser 1227f384594dSTobias Grosser // Set scheduling strategy to same strategy PPCG is using. 1228f384594dSTobias Grosser isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true); 1229f384594dSTobias Grosser isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true); 12302341fe9eSTobias Grosser isl_options_set_schedule_whole_component(PPCGGen->ctx, false); 1231f384594dSTobias Grosser 1232f384594dSTobias Grosser isl_schedule *Schedule = get_schedule(PPCGGen); 1233f384594dSTobias Grosser 1234aef5196fSTobias Grosser int has_permutable = has_any_permutable_node(Schedule); 1235aef5196fSTobias Grosser 123669b46751STobias Grosser if (!has_permutable || has_permutable < 0) { 1237aef5196fSTobias Grosser Schedule = isl_schedule_free(Schedule); 123869b46751STobias Grosser } else { 1239aef5196fSTobias Grosser Schedule = map_to_device(PPCGGen, Schedule); 124069b46751STobias Grosser PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule)); 124169b46751STobias Grosser } 1242aef5196fSTobias Grosser 1243f384594dSTobias Grosser if (DumpSchedule) { 1244f384594dSTobias Grosser isl_printer *P = isl_printer_to_str(S->getIslCtx()); 1245f384594dSTobias Grosser P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK); 1246f384594dSTobias Grosser P = isl_printer_print_str(P, "Schedule\n"); 1247f384594dSTobias Grosser P = isl_printer_print_str(P, "========\n"); 1248f384594dSTobias Grosser if (Schedule) 1249f384594dSTobias Grosser P = isl_printer_print_schedule(P, Schedule); 1250f384594dSTobias Grosser else 1251f384594dSTobias Grosser P = isl_printer_print_str(P, "No schedule found\n"); 1252f384594dSTobias Grosser 1253f384594dSTobias Grosser printf("%s\n", isl_printer_get_str(P)); 1254f384594dSTobias Grosser isl_printer_free(P); 1255f384594dSTobias Grosser } 1256f384594dSTobias Grosser 125769b46751STobias Grosser if (DumpCode) { 125869b46751STobias Grosser printf("Code\n"); 125969b46751STobias Grosser printf("====\n"); 126069b46751STobias Grosser if (PPCGGen->tree) 126169b46751STobias Grosser printGPUTree(PPCGGen->tree, PPCGProg); 126269b46751STobias Grosser else 126369b46751STobias Grosser printf("No code generated\n"); 126469b46751STobias Grosser } 126569b46751STobias Grosser 1266f384594dSTobias Grosser isl_schedule_free(Schedule); 1267f384594dSTobias Grosser 1268f384594dSTobias Grosser return PPCGGen; 1269f384594dSTobias Grosser } 1270f384594dSTobias Grosser 1271f384594dSTobias Grosser /// Free gpu_gen structure. 1272f384594dSTobias Grosser /// 1273f384594dSTobias Grosser /// @param PPCGGen The ppcg_gen object to free. 1274f384594dSTobias Grosser void freePPCGGen(gpu_gen *PPCGGen) { 1275f384594dSTobias Grosser isl_ast_node_free(PPCGGen->tree); 1276f384594dSTobias Grosser isl_union_map_free(PPCGGen->sizes); 1277f384594dSTobias Grosser isl_union_map_free(PPCGGen->used_sizes); 1278f384594dSTobias Grosser free(PPCGGen); 1279f384594dSTobias Grosser } 1280f384594dSTobias Grosser 1281b307ed4dSTobias Grosser /// Free the options in the ppcg scop structure. 1282b307ed4dSTobias Grosser /// 1283b307ed4dSTobias Grosser /// ppcg is not freeing these options for us. To avoid leaks we do this 1284b307ed4dSTobias Grosser /// ourselves. 1285b307ed4dSTobias Grosser /// 1286b307ed4dSTobias Grosser /// @param PPCGScop The scop referencing the options to free. 1287b307ed4dSTobias Grosser void freeOptions(ppcg_scop *PPCGScop) { 1288b307ed4dSTobias Grosser free(PPCGScop->options->debug); 1289b307ed4dSTobias Grosser PPCGScop->options->debug = nullptr; 1290b307ed4dSTobias Grosser free(PPCGScop->options); 1291b307ed4dSTobias Grosser PPCGScop->options = nullptr; 1292b307ed4dSTobias Grosser } 1293b307ed4dSTobias Grosser 129438fc0aedSTobias Grosser /// Generate code for a given GPU AST described by @p Root. 129538fc0aedSTobias Grosser /// 129632837fe3STobias Grosser /// @param Root An isl_ast_node pointing to the root of the GPU AST. 129732837fe3STobias Grosser /// @param Prog The GPU Program to generate code for. 129832837fe3STobias Grosser void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) { 129938fc0aedSTobias Grosser ScopAnnotator Annotator; 130038fc0aedSTobias Grosser Annotator.buildAliasScopes(*S); 130138fc0aedSTobias Grosser 130238fc0aedSTobias Grosser Region *R = &S->getRegion(); 130338fc0aedSTobias Grosser 130438fc0aedSTobias Grosser simplifyRegion(R, DT, LI, RI); 130538fc0aedSTobias Grosser 130638fc0aedSTobias Grosser BasicBlock *EnteringBB = R->getEnteringBlock(); 130738fc0aedSTobias Grosser 130838fc0aedSTobias Grosser PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator); 130938fc0aedSTobias Grosser 131032837fe3STobias Grosser GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S, 131132837fe3STobias Grosser Prog); 131238fc0aedSTobias Grosser 131338fc0aedSTobias Grosser // Only build the run-time condition and parameters _after_ having 131438fc0aedSTobias Grosser // introduced the conditional branch. This is important as the conditional 131538fc0aedSTobias Grosser // branch will guard the original scop from new induction variables that 131638fc0aedSTobias Grosser // the SCEVExpander may introduce while code generating the parameters and 131738fc0aedSTobias Grosser // which may introduce scalar dependences that prevent us from correctly 131838fc0aedSTobias Grosser // code generating this scop. 131938fc0aedSTobias Grosser BasicBlock *StartBlock = 132038fc0aedSTobias Grosser executeScopConditionally(*S, this, Builder.getTrue()); 132138fc0aedSTobias Grosser 132238fc0aedSTobias Grosser // TODO: Handle LICM 132338fc0aedSTobias Grosser // TODO: Verify run-time checks 132438fc0aedSTobias Grosser auto SplitBlock = StartBlock->getSinglePredecessor(); 132538fc0aedSTobias Grosser Builder.SetInsertPoint(SplitBlock->getTerminator()); 132638fc0aedSTobias Grosser NodeBuilder.addParameters(S->getContext()); 132738fc0aedSTobias Grosser Builder.SetInsertPoint(&*StartBlock->begin()); 132838fc0aedSTobias Grosser NodeBuilder.create(Root); 1329*8ed5e599STobias Grosser NodeBuilder.finalize(); 133038fc0aedSTobias Grosser } 133138fc0aedSTobias Grosser 1332e938517eSTobias Grosser bool runOnScop(Scop &CurrentScop) override { 1333e938517eSTobias Grosser S = &CurrentScop; 133438fc0aedSTobias Grosser LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 133538fc0aedSTobias Grosser DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 133638fc0aedSTobias Grosser SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 133738fc0aedSTobias Grosser DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout(); 133838fc0aedSTobias Grosser RI = &getAnalysis<RegionInfoPass>().getRegionInfo(); 1339e938517eSTobias Grosser 13402d58a64eSTobias Grosser // We currently do not support scops with invariant loads. 13412d58a64eSTobias Grosser if (S->hasInvariantAccesses()) 13422d58a64eSTobias Grosser return false; 13432d58a64eSTobias Grosser 1344e938517eSTobias Grosser auto PPCGScop = createPPCGScop(); 1345e938517eSTobias Grosser auto PPCGProg = createPPCGProg(PPCGScop); 1346f384594dSTobias Grosser auto PPCGGen = generateGPU(PPCGScop, PPCGProg); 134738fc0aedSTobias Grosser 134838fc0aedSTobias Grosser if (PPCGGen->tree) 134932837fe3STobias Grosser generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg); 135038fc0aedSTobias Grosser 1351b307ed4dSTobias Grosser freeOptions(PPCGScop); 1352f384594dSTobias Grosser freePPCGGen(PPCGGen); 1353e938517eSTobias Grosser gpu_prog_free(PPCGProg); 1354e938517eSTobias Grosser ppcg_scop_free(PPCGScop); 1355e938517eSTobias Grosser 1356e938517eSTobias Grosser return true; 1357e938517eSTobias Grosser } 13589dfe4e7cSTobias Grosser 13599dfe4e7cSTobias Grosser void printScop(raw_ostream &, Scop &) const override {} 13609dfe4e7cSTobias Grosser 13619dfe4e7cSTobias Grosser void getAnalysisUsage(AnalysisUsage &AU) const override { 13629dfe4e7cSTobias Grosser AU.addRequired<DominatorTreeWrapperPass>(); 13639dfe4e7cSTobias Grosser AU.addRequired<RegionInfoPass>(); 13649dfe4e7cSTobias Grosser AU.addRequired<ScalarEvolutionWrapperPass>(); 13659dfe4e7cSTobias Grosser AU.addRequired<ScopDetection>(); 13669dfe4e7cSTobias Grosser AU.addRequired<ScopInfoRegionPass>(); 13679dfe4e7cSTobias Grosser AU.addRequired<LoopInfoWrapperPass>(); 13689dfe4e7cSTobias Grosser 13699dfe4e7cSTobias Grosser AU.addPreserved<AAResultsWrapperPass>(); 13709dfe4e7cSTobias Grosser AU.addPreserved<BasicAAWrapperPass>(); 13719dfe4e7cSTobias Grosser AU.addPreserved<LoopInfoWrapperPass>(); 13729dfe4e7cSTobias Grosser AU.addPreserved<DominatorTreeWrapperPass>(); 13739dfe4e7cSTobias Grosser AU.addPreserved<GlobalsAAWrapperPass>(); 13749dfe4e7cSTobias Grosser AU.addPreserved<PostDominatorTreeWrapperPass>(); 13759dfe4e7cSTobias Grosser AU.addPreserved<ScopDetection>(); 13769dfe4e7cSTobias Grosser AU.addPreserved<ScalarEvolutionWrapperPass>(); 13779dfe4e7cSTobias Grosser AU.addPreserved<SCEVAAWrapperPass>(); 13789dfe4e7cSTobias Grosser 13799dfe4e7cSTobias Grosser // FIXME: We do not yet add regions for the newly generated code to the 13809dfe4e7cSTobias Grosser // region tree. 13819dfe4e7cSTobias Grosser AU.addPreserved<RegionInfoPass>(); 13829dfe4e7cSTobias Grosser AU.addPreserved<ScopInfoRegionPass>(); 13839dfe4e7cSTobias Grosser } 13849dfe4e7cSTobias Grosser }; 13859dfe4e7cSTobias Grosser } 13869dfe4e7cSTobias Grosser 13879dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1; 13889dfe4e7cSTobias Grosser 13899dfe4e7cSTobias Grosser Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); } 13909dfe4e7cSTobias Grosser 13919dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg", 13929dfe4e7cSTobias Grosser "Polly - Apply PPCG translation to SCOP", false, false) 13939dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo); 13949dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 13959dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 13969dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 13979dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 13989dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScopDetection); 13999dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg", 14009dfe4e7cSTobias Grosser "Polly - Apply PPCG translation to SCOP", false, false) 1401