1 //===------ PPCGCodeGeneration.cpp - Polly Accelerator Code Generation. ---===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // Take a scop created by ScopInfo and map it to GPU code using the ppcg 11 // GPU mapping strategy. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "polly/CodeGen/PPCGCodeGeneration.h" 16 #include "polly/CodeGen/IslAst.h" 17 #include "polly/CodeGen/IslNodeBuilder.h" 18 #include "polly/CodeGen/Utils.h" 19 #include "polly/DependenceInfo.h" 20 #include "polly/LinkAllPasses.h" 21 #include "polly/Options.h" 22 #include "polly/ScopDetection.h" 23 #include "polly/ScopInfo.h" 24 #include "polly/Support/SCEVValidator.h" 25 #include "llvm/ADT/PostOrderIterator.h" 26 #include "llvm/Analysis/AliasAnalysis.h" 27 #include "llvm/Analysis/BasicAliasAnalysis.h" 28 #include "llvm/Analysis/GlobalsModRef.h" 29 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 30 #include "llvm/Analysis/TargetLibraryInfo.h" 31 #include "llvm/Analysis/TargetTransformInfo.h" 32 #include "llvm/IR/LegacyPassManager.h" 33 #include "llvm/IR/Verifier.h" 34 #include "llvm/Support/TargetRegistry.h" 35 #include "llvm/Support/TargetSelect.h" 36 #include "llvm/Target/TargetMachine.h" 37 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 38 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 39 40 #include "isl/union_map.h" 41 42 extern "C" { 43 #include "ppcg/cuda.h" 44 #include "ppcg/gpu.h" 45 #include "ppcg/gpu_print.h" 46 #include "ppcg/ppcg.h" 47 #include "ppcg/schedule.h" 48 } 49 50 #include "llvm/Support/Debug.h" 51 52 using namespace polly; 53 using namespace llvm; 54 55 #define DEBUG_TYPE "polly-codegen-ppcg" 56 57 static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule", 58 cl::desc("Dump the computed GPU Schedule"), 59 cl::Hidden, cl::init(false), cl::ZeroOrMore, 60 cl::cat(PollyCategory)); 61 62 static cl::opt<bool> 63 DumpCode("polly-acc-dump-code", 64 cl::desc("Dump C code describing the GPU mapping"), cl::Hidden, 65 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory)); 66 67 static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir", 68 cl::desc("Dump the kernel LLVM-IR"), 69 cl::Hidden, cl::init(false), cl::ZeroOrMore, 70 cl::cat(PollyCategory)); 71 72 static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm", 73 cl::desc("Dump the kernel assembly code"), 74 cl::Hidden, cl::init(false), cl::ZeroOrMore, 75 cl::cat(PollyCategory)); 76 77 static cl::opt<bool> FastMath("polly-acc-fastmath", 78 cl::desc("Allow unsafe math optimizations"), 79 cl::Hidden, cl::init(false), cl::ZeroOrMore, 80 cl::cat(PollyCategory)); 81 static cl::opt<bool> SharedMemory("polly-acc-use-shared", 82 cl::desc("Use shared memory"), cl::Hidden, 83 cl::init(false), cl::ZeroOrMore, 84 cl::cat(PollyCategory)); 85 static cl::opt<bool> PrivateMemory("polly-acc-use-private", 86 cl::desc("Use private memory"), cl::Hidden, 87 cl::init(false), cl::ZeroOrMore, 88 cl::cat(PollyCategory)); 89 90 static cl::opt<bool> ManagedMemory("polly-acc-codegen-managed-memory", 91 cl::desc("Generate Host kernel code assuming" 92 " that all memory has been" 93 " declared as managed memory"), 94 cl::Hidden, cl::init(false), cl::ZeroOrMore, 95 cl::cat(PollyCategory)); 96 97 static cl::opt<bool> 98 FailOnVerifyModuleFailure("polly-acc-fail-on-verify-module-failure", 99 cl::desc("Fail and generate a backtrace if" 100 " verifyModule fails on the GPU " 101 " kernel module."), 102 cl::Hidden, cl::init(false), cl::ZeroOrMore, 103 cl::cat(PollyCategory)); 104 105 static cl::opt<std::string> 106 CudaVersion("polly-acc-cuda-version", 107 cl::desc("The CUDA version to compile for"), cl::Hidden, 108 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory)); 109 110 static cl::opt<int> 111 MinCompute("polly-acc-mincompute", 112 cl::desc("Minimal number of compute statements to run on GPU."), 113 cl::Hidden, cl::init(10 * 512 * 512)); 114 115 /// Used to store information PPCG wants for kills. This information is 116 /// used by live range reordering. 117 /// 118 /// @see computeLiveRangeReordering 119 /// @see GPUNodeBuilder::createPPCGScop 120 /// @see GPUNodeBuilder::createPPCGProg 121 struct MustKillsInfo { 122 /// Collection of all kill statements that will be sequenced at the end of 123 /// PPCGScop->schedule. 124 /// 125 /// The nodes in `KillsSchedule` will be merged using `isl_schedule_set` 126 /// which merges schedules in *arbitrary* order. 127 /// (we don't care about the order of the kills anyway). 128 isl::schedule KillsSchedule; 129 /// Map from kill statement instances to scalars that need to be 130 /// killed. 131 /// 132 /// We currently derive kill information for: 133 /// 1. phi nodes. PHI nodes are not alive outside the scop and can 134 /// consequently all be killed. 135 /// 2. Scalar arrays that are not used outside the Scop. This is 136 /// checked by `isScalarUsesContainedInScop`. 137 /// [params] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] } 138 isl::union_map TaggedMustKills; 139 140 /// Tagged must kills stripped of the tags. 141 /// [params] -> { Stmt_phantom[] -> scalar_to_kill[] } 142 isl::union_map MustKills; 143 144 MustKillsInfo() : KillsSchedule(nullptr) {} 145 }; 146 147 /// Check if SAI's uses are entirely contained within Scop S. 148 /// If a scalar is used only with a Scop, we are free to kill it, as no data 149 /// can flow in/out of the value any more. 150 /// @see computeMustKillsInfo 151 static bool isScalarUsesContainedInScop(const Scop &S, 152 const ScopArrayInfo *SAI) { 153 assert(SAI->isValueKind() && "this function only deals with scalars." 154 " Dealing with arrays required alias analysis"); 155 156 const Region &R = S.getRegion(); 157 for (User *U : SAI->getBasePtr()->users()) { 158 Instruction *I = dyn_cast<Instruction>(U); 159 assert(I && "invalid user of scop array info"); 160 if (!R.contains(I)) 161 return false; 162 } 163 return true; 164 } 165 166 /// Compute must-kills needed to enable live range reordering with PPCG. 167 /// 168 /// @params S The Scop to compute live range reordering information 169 /// @returns live range reordering information that can be used to setup 170 /// PPCG. 171 static MustKillsInfo computeMustKillsInfo(const Scop &S) { 172 const isl::space ParamSpace(isl::manage(S.getParamSpace())); 173 MustKillsInfo Info; 174 175 // 1. Collect all ScopArrayInfo that satisfy *any* of the criteria: 176 // 1.1 phi nodes in scop. 177 // 1.2 scalars that are only used within the scop 178 SmallVector<isl::id, 4> KillMemIds; 179 for (ScopArrayInfo *SAI : S.arrays()) { 180 if (SAI->isPHIKind() || 181 (SAI->isValueKind() && isScalarUsesContainedInScop(S, SAI))) 182 KillMemIds.push_back(isl::manage(SAI->getBasePtrId().release())); 183 } 184 185 Info.TaggedMustKills = isl::union_map::empty(isl::space(ParamSpace)); 186 Info.MustKills = isl::union_map::empty(isl::space(ParamSpace)); 187 188 // Initialising KillsSchedule to `isl_set_empty` creates an empty node in the 189 // schedule: 190 // - filter: "[control] -> { }" 191 // So, we choose to not create this to keep the output a little nicer, 192 // at the cost of some code complexity. 193 Info.KillsSchedule = nullptr; 194 195 for (isl::id &ToKillId : KillMemIds) { 196 isl::id KillStmtId = isl::id::alloc( 197 S.getIslCtx(), 198 std::string("SKill_phantom_").append(ToKillId.get_name()), nullptr); 199 200 // NOTE: construction of tagged_must_kill: 201 // 2. We need to construct a map: 202 // [param] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] } 203 // To construct this, we use `isl_map_domain_product` on 2 maps`: 204 // 2a. StmtToScalar: 205 // [param] -> { Stmt_phantom[] -> scalar_to_kill[] } 206 // 2b. PhantomRefToScalar: 207 // [param] -> { ref_phantom[] -> scalar_to_kill[] } 208 // 209 // Combining these with `isl_map_domain_product` gives us 210 // TaggedMustKill: 211 // [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] } 212 213 // 2a. [param] -> { Stmt[] -> scalar_to_kill[] } 214 isl::map StmtToScalar = isl::map::universe(isl::space(ParamSpace)); 215 StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::in, isl::id(KillStmtId)); 216 StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::out, isl::id(ToKillId)); 217 218 isl::id PhantomRefId = isl::id::alloc( 219 S.getIslCtx(), std::string("ref_phantom") + ToKillId.get_name(), 220 nullptr); 221 222 // 2b. [param] -> { phantom_ref[] -> scalar_to_kill[] } 223 isl::map PhantomRefToScalar = isl::map::universe(isl::space(ParamSpace)); 224 PhantomRefToScalar = 225 PhantomRefToScalar.set_tuple_id(isl::dim::in, PhantomRefId); 226 PhantomRefToScalar = 227 PhantomRefToScalar.set_tuple_id(isl::dim::out, ToKillId); 228 229 // 2. [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] } 230 isl::map TaggedMustKill = StmtToScalar.domain_product(PhantomRefToScalar); 231 Info.TaggedMustKills = Info.TaggedMustKills.unite(TaggedMustKill); 232 233 // 2. [param] -> { Stmt[] -> scalar_to_kill[] } 234 Info.MustKills = Info.TaggedMustKills.domain_factor_domain(); 235 236 // 3. Create the kill schedule of the form: 237 // "[param] -> { Stmt_phantom[] }" 238 // Then add this to Info.KillsSchedule. 239 isl::space KillStmtSpace = ParamSpace; 240 KillStmtSpace = KillStmtSpace.set_tuple_id(isl::dim::set, KillStmtId); 241 isl::union_set KillStmtDomain = isl::set::universe(KillStmtSpace); 242 243 isl::schedule KillSchedule = isl::schedule::from_domain(KillStmtDomain); 244 if (Info.KillsSchedule) 245 Info.KillsSchedule = Info.KillsSchedule.set(KillSchedule); 246 else 247 Info.KillsSchedule = KillSchedule; 248 } 249 250 return Info; 251 } 252 253 /// Create the ast expressions for a ScopStmt. 254 /// 255 /// This function is a callback for to generate the ast expressions for each 256 /// of the scheduled ScopStmts. 257 static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt( 258 void *StmtT, __isl_take isl_ast_build *Build_C, 259 isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA, 260 isl_id *Id, void *User), 261 void *UserIndex, 262 isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User), 263 void *UserExpr) { 264 265 ScopStmt *Stmt = (ScopStmt *)StmtT; 266 267 if (!Stmt || !Build_C) 268 return NULL; 269 270 isl::ast_build Build = isl::manage(isl_ast_build_copy(Build_C)); 271 isl::ctx Ctx = Build.get_ctx(); 272 isl::id_to_ast_expr RefToExpr = isl::id_to_ast_expr::alloc(Ctx, 0); 273 274 for (MemoryAccess *Acc : *Stmt) { 275 isl::map AddrFunc = Acc->getAddressFunction(); 276 AddrFunc = AddrFunc.intersect_domain(isl::manage(Stmt->getDomain())); 277 278 isl::id RefId = Acc->getId(); 279 isl::pw_multi_aff PMA = isl::pw_multi_aff::from_map(AddrFunc); 280 281 isl::multi_pw_aff MPA = isl::multi_pw_aff(PMA); 282 MPA = MPA.coalesce(); 283 MPA = isl::manage(FunctionIndex(MPA.release(), RefId.get(), UserIndex)); 284 285 isl::ast_expr Access = Build.access_from(MPA); 286 Access = isl::manage(FunctionExpr(Access.release(), RefId.get(), UserExpr)); 287 RefToExpr = RefToExpr.set(RefId, Access); 288 } 289 290 return RefToExpr.release(); 291 } 292 293 /// Given a LLVM Type, compute its size in bytes, 294 static int computeSizeInBytes(const Type *T) { 295 int bytes = T->getPrimitiveSizeInBits() / 8; 296 if (bytes == 0) 297 bytes = T->getScalarSizeInBits() / 8; 298 return bytes; 299 } 300 301 /// Generate code for a GPU specific isl AST. 302 /// 303 /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which 304 /// generates code for general-purpose AST nodes, with special functionality 305 /// for generating GPU specific user nodes. 306 /// 307 /// @see GPUNodeBuilder::createUser 308 class GPUNodeBuilder : public IslNodeBuilder { 309 public: 310 GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, 311 const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE, 312 DominatorTree &DT, Scop &S, BasicBlock *StartBlock, 313 gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch) 314 : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock), 315 Prog(Prog), Runtime(Runtime), Arch(Arch) { 316 getExprBuilder().setIDToSAI(&IDToSAI); 317 } 318 319 /// Create after-run-time-check initialization code. 320 void initializeAfterRTH(); 321 322 /// Finalize the generated scop. 323 virtual void finalize(); 324 325 /// Track if the full build process was successful. 326 /// 327 /// This value is set to false, if throughout the build process an error 328 /// occurred which prevents us from generating valid GPU code. 329 bool BuildSuccessful = true; 330 331 /// The maximal number of loops surrounding a sequential kernel. 332 unsigned DeepestSequential = 0; 333 334 /// The maximal number of loops surrounding a parallel kernel. 335 unsigned DeepestParallel = 0; 336 337 /// Return the name to set for the ptx_kernel. 338 std::string getKernelFuncName(int Kernel_id); 339 340 private: 341 /// A vector of array base pointers for which a new ScopArrayInfo was created. 342 /// 343 /// This vector is used to delete the ScopArrayInfo when it is not needed any 344 /// more. 345 std::vector<Value *> LocalArrays; 346 347 /// A map from ScopArrays to their corresponding device allocations. 348 std::map<ScopArrayInfo *, Value *> DeviceAllocations; 349 350 /// The current GPU context. 351 Value *GPUContext; 352 353 /// The set of isl_ids allocated in the kernel 354 std::vector<isl_id *> KernelIds; 355 356 /// A module containing GPU code. 357 /// 358 /// This pointer is only set in case we are currently generating GPU code. 359 std::unique_ptr<Module> GPUModule; 360 361 /// The GPU program we generate code for. 362 gpu_prog *Prog; 363 364 /// The GPU Runtime implementation to use (OpenCL or CUDA). 365 GPURuntime Runtime; 366 367 /// The GPU Architecture to target. 368 GPUArch Arch; 369 370 /// Class to free isl_ids. 371 class IslIdDeleter { 372 public: 373 void operator()(__isl_take isl_id *Id) { isl_id_free(Id); }; 374 }; 375 376 /// A set containing all isl_ids allocated in a GPU kernel. 377 /// 378 /// By releasing this set all isl_ids will be freed. 379 std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs; 380 381 IslExprBuilder::IDToScopArrayInfoTy IDToSAI; 382 383 /// Create code for user-defined AST nodes. 384 /// 385 /// These AST nodes can be of type: 386 /// 387 /// - ScopStmt: A computational statement (TODO) 388 /// - Kernel: A GPU kernel call (TODO) 389 /// - Data-Transfer: A GPU <-> CPU data-transfer 390 /// - In-kernel synchronization 391 /// - In-kernel memory copy statement 392 /// 393 /// @param UserStmt The ast node to generate code for. 394 virtual void createUser(__isl_take isl_ast_node *UserStmt); 395 396 enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST }; 397 398 /// Create code for a data transfer statement 399 /// 400 /// @param TransferStmt The data transfer statement. 401 /// @param Direction The direction in which to transfer data. 402 void createDataTransfer(__isl_take isl_ast_node *TransferStmt, 403 enum DataDirection Direction); 404 405 /// Find llvm::Values referenced in GPU kernel. 406 /// 407 /// @param Kernel The kernel to scan for llvm::Values 408 /// 409 /// @returns A pair, whose first element contains the set of values 410 /// referenced by the kernel, and whose second element contains the 411 /// set of functions referenced by the kernel. All functions in the 412 /// second set satisfy isValidFunctionInKernel. 413 std::pair<SetVector<Value *>, SetVector<Function *>> 414 getReferencesInKernel(ppcg_kernel *Kernel); 415 416 /// Compute the sizes of the execution grid for a given kernel. 417 /// 418 /// @param Kernel The kernel to compute grid sizes for. 419 /// 420 /// @returns A tuple with grid sizes for X and Y dimension 421 std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel); 422 423 /// Creates a array that can be sent to the kernel on the device using a 424 /// host pointer. This is required for managed memory, when we directly send 425 /// host pointers to the device. 426 /// \note 427 /// This is to be used only with managed memory 428 Value *getOrCreateManagedDeviceArray(gpu_array_info *Array, 429 ScopArrayInfo *ArrayInfo); 430 431 /// Compute the sizes of the thread blocks for a given kernel. 432 /// 433 /// @param Kernel The kernel to compute thread block sizes for. 434 /// 435 /// @returns A tuple with thread block sizes for X, Y, and Z dimensions. 436 std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel); 437 438 /// Store a specific kernel launch parameter in the array of kernel launch 439 /// parameters. 440 /// 441 /// @param Parameters The list of parameters in which to store. 442 /// @param Param The kernel launch parameter to store. 443 /// @param Index The index in the parameter list, at which to store the 444 /// parameter. 445 void insertStoreParameter(Instruction *Parameters, Instruction *Param, 446 int Index); 447 448 /// Create kernel launch parameters. 449 /// 450 /// @param Kernel The kernel to create parameters for. 451 /// @param F The kernel function that has been created. 452 /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 453 /// 454 /// @returns A stack allocated array with pointers to the parameter 455 /// values that are passed to the kernel. 456 Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F, 457 SetVector<Value *> SubtreeValues); 458 459 /// Create declarations for kernel variable. 460 /// 461 /// This includes shared memory declarations. 462 /// 463 /// @param Kernel The kernel definition to create variables for. 464 /// @param FN The function into which to generate the variables. 465 void createKernelVariables(ppcg_kernel *Kernel, Function *FN); 466 467 /// Add CUDA annotations to module. 468 /// 469 /// Add a set of CUDA annotations that declares the maximal block dimensions 470 /// that will be used to execute the CUDA kernel. This allows the NVIDIA 471 /// PTX compiler to bound the number of allocated registers to ensure the 472 /// resulting kernel is known to run with up to as many block dimensions 473 /// as specified here. 474 /// 475 /// @param M The module to add the annotations to. 476 /// @param BlockDimX The size of block dimension X. 477 /// @param BlockDimY The size of block dimension Y. 478 /// @param BlockDimZ The size of block dimension Z. 479 void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY, 480 Value *BlockDimZ); 481 482 /// Create GPU kernel. 483 /// 484 /// Code generate the kernel described by @p KernelStmt. 485 /// 486 /// @param KernelStmt The ast node to generate kernel code for. 487 void createKernel(__isl_take isl_ast_node *KernelStmt); 488 489 /// Generate code that computes the size of an array. 490 /// 491 /// @param Array The array for which to compute a size. 492 Value *getArraySize(gpu_array_info *Array); 493 494 /// Generate code to compute the minimal offset at which an array is accessed. 495 /// 496 /// The offset of an array is the minimal array location accessed in a scop. 497 /// 498 /// Example: 499 /// 500 /// for (long i = 0; i < 100; i++) 501 /// A[i + 42] += ... 502 /// 503 /// getArrayOffset(A) results in 42. 504 /// 505 /// @param Array The array for which to compute the offset. 506 /// @returns An llvm::Value that contains the offset of the array. 507 Value *getArrayOffset(gpu_array_info *Array); 508 509 /// Prepare the kernel arguments for kernel code generation 510 /// 511 /// @param Kernel The kernel to generate code for. 512 /// @param FN The function created for the kernel. 513 void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN); 514 515 /// Create kernel function. 516 /// 517 /// Create a kernel function located in a newly created module that can serve 518 /// as target for device code generation. Set the Builder to point to the 519 /// start block of this newly created function. 520 /// 521 /// @param Kernel The kernel to generate code for. 522 /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 523 /// @param SubtreeFunctions The set of llvm::Functions referenced by this 524 /// kernel. 525 void createKernelFunction(ppcg_kernel *Kernel, 526 SetVector<Value *> &SubtreeValues, 527 SetVector<Function *> &SubtreeFunctions); 528 529 /// Create the declaration of a kernel function. 530 /// 531 /// The kernel function takes as arguments: 532 /// 533 /// - One i8 pointer for each external array reference used in the kernel. 534 /// - Host iterators 535 /// - Parameters 536 /// - Other LLVM Value references (TODO) 537 /// 538 /// @param Kernel The kernel to generate the function declaration for. 539 /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 540 /// 541 /// @returns The newly declared function. 542 Function *createKernelFunctionDecl(ppcg_kernel *Kernel, 543 SetVector<Value *> &SubtreeValues); 544 545 /// Insert intrinsic functions to obtain thread and block ids. 546 /// 547 /// @param The kernel to generate the intrinsic functions for. 548 void insertKernelIntrinsics(ppcg_kernel *Kernel); 549 550 /// Insert function calls to retrieve the SPIR group/local ids. 551 /// 552 /// @param The kernel to generate the function calls for. 553 void insertKernelCallsSPIR(ppcg_kernel *Kernel); 554 555 /// Setup the creation of functions referenced by the GPU kernel. 556 /// 557 /// 1. Create new function declarations in GPUModule which are the same as 558 /// SubtreeFunctions. 559 /// 560 /// 2. Populate IslNodeBuilder::ValueMap with mappings from 561 /// old functions (that come from the original module) to new functions 562 /// (that are created within GPUModule). That way, we generate references 563 /// to the correct function (in GPUModule) in BlockGenerator. 564 /// 565 /// @see IslNodeBuilder::ValueMap 566 /// @see BlockGenerator::GlobalMap 567 /// @see BlockGenerator::getNewValue 568 /// @see GPUNodeBuilder::getReferencesInKernel. 569 /// 570 /// @param SubtreeFunctions The set of llvm::Functions referenced by 571 /// this kernel. 572 void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions); 573 574 /// Create a global-to-shared or shared-to-global copy statement. 575 /// 576 /// @param CopyStmt The copy statement to generate code for 577 void createKernelCopy(ppcg_kernel_stmt *CopyStmt); 578 579 /// Create code for a ScopStmt called in @p Expr. 580 /// 581 /// @param Expr The expression containing the call. 582 /// @param KernelStmt The kernel statement referenced in the call. 583 void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt); 584 585 /// Create an in-kernel synchronization call. 586 void createKernelSync(); 587 588 /// Create a PTX assembly string for the current GPU kernel. 589 /// 590 /// @returns A string containing the corresponding PTX assembly code. 591 std::string createKernelASM(); 592 593 /// Remove references from the dominator tree to the kernel function @p F. 594 /// 595 /// @param F The function to remove references to. 596 void clearDominators(Function *F); 597 598 /// Remove references from scalar evolution to the kernel function @p F. 599 /// 600 /// @param F The function to remove references to. 601 void clearScalarEvolution(Function *F); 602 603 /// Remove references from loop info to the kernel function @p F. 604 /// 605 /// @param F The function to remove references to. 606 void clearLoops(Function *F); 607 608 /// Finalize the generation of the kernel function. 609 /// 610 /// Free the LLVM-IR module corresponding to the kernel and -- if requested -- 611 /// dump its IR to stderr. 612 /// 613 /// @returns The Assembly string of the kernel. 614 std::string finalizeKernelFunction(); 615 616 /// Finalize the generation of the kernel arguments. 617 /// 618 /// This function ensures that not-read-only scalars used in a kernel are 619 /// stored back to the global memory location they are backed with before 620 /// the kernel terminates. 621 /// 622 /// @params Kernel The kernel to finalize kernel arguments for. 623 void finalizeKernelArguments(ppcg_kernel *Kernel); 624 625 /// Create code that allocates memory to store arrays on device. 626 void allocateDeviceArrays(); 627 628 /// Free all allocated device arrays. 629 void freeDeviceArrays(); 630 631 /// Create a call to initialize the GPU context. 632 /// 633 /// @returns A pointer to the newly initialized context. 634 Value *createCallInitContext(); 635 636 /// Create a call to get the device pointer for a kernel allocation. 637 /// 638 /// @param Allocation The Polly GPU allocation 639 /// 640 /// @returns The device parameter corresponding to this allocation. 641 Value *createCallGetDevicePtr(Value *Allocation); 642 643 /// Create a call to free the GPU context. 644 /// 645 /// @param Context A pointer to an initialized GPU context. 646 void createCallFreeContext(Value *Context); 647 648 /// Create a call to allocate memory on the device. 649 /// 650 /// @param Size The size of memory to allocate 651 /// 652 /// @returns A pointer that identifies this allocation. 653 Value *createCallAllocateMemoryForDevice(Value *Size); 654 655 /// Create a call to free a device array. 656 /// 657 /// @param Array The device array to free. 658 void createCallFreeDeviceMemory(Value *Array); 659 660 /// Create a call to copy data from host to device. 661 /// 662 /// @param HostPtr A pointer to the host data that should be copied. 663 /// @param DevicePtr A device pointer specifying the location to copy to. 664 void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr, 665 Value *Size); 666 667 /// Create a call to copy data from device to host. 668 /// 669 /// @param DevicePtr A pointer to the device data that should be copied. 670 /// @param HostPtr A host pointer specifying the location to copy to. 671 void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr, 672 Value *Size); 673 674 /// Create a call to synchronize Host & Device. 675 /// \note 676 /// This is to be used only with managed memory. 677 void createCallSynchronizeDevice(); 678 679 /// Create a call to get a kernel from an assembly string. 680 /// 681 /// @param Buffer The string describing the kernel. 682 /// @param Entry The name of the kernel function to call. 683 /// 684 /// @returns A pointer to a kernel object 685 Value *createCallGetKernel(Value *Buffer, Value *Entry); 686 687 /// Create a call to free a GPU kernel. 688 /// 689 /// @param GPUKernel THe kernel to free. 690 void createCallFreeKernel(Value *GPUKernel); 691 692 /// Create a call to launch a GPU kernel. 693 /// 694 /// @param GPUKernel The kernel to launch. 695 /// @param GridDimX The size of the first grid dimension. 696 /// @param GridDimY The size of the second grid dimension. 697 /// @param GridBlockX The size of the first block dimension. 698 /// @param GridBlockY The size of the second block dimension. 699 /// @param GridBlockZ The size of the third block dimension. 700 /// @param Parameters A pointer to an array that contains itself pointers to 701 /// the parameter values passed for each kernel argument. 702 void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 703 Value *GridDimY, Value *BlockDimX, 704 Value *BlockDimY, Value *BlockDimZ, 705 Value *Parameters); 706 }; 707 708 std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) { 709 return "FUNC_" + S.getFunction().getName().str() + "_SCOP_" + 710 std::to_string(S.getID()) + "_KERNEL_" + std::to_string(Kernel_id); 711 } 712 713 void GPUNodeBuilder::initializeAfterRTH() { 714 BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(), 715 &*Builder.GetInsertPoint(), &DT, &LI); 716 NewBB->setName("polly.acc.initialize"); 717 Builder.SetInsertPoint(&NewBB->front()); 718 719 GPUContext = createCallInitContext(); 720 721 if (!ManagedMemory) 722 allocateDeviceArrays(); 723 } 724 725 void GPUNodeBuilder::finalize() { 726 if (!ManagedMemory) 727 freeDeviceArrays(); 728 729 createCallFreeContext(GPUContext); 730 IslNodeBuilder::finalize(); 731 } 732 733 void GPUNodeBuilder::allocateDeviceArrays() { 734 assert(!ManagedMemory && "Managed memory will directly send host pointers " 735 "to the kernel. There is no need for device arrays"); 736 isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 737 738 for (int i = 0; i < Prog->n_array; ++i) { 739 gpu_array_info *Array = &Prog->array[i]; 740 auto *ScopArray = (ScopArrayInfo *)Array->user; 741 std::string DevArrayName("p_dev_array_"); 742 DevArrayName.append(Array->name); 743 744 Value *ArraySize = getArraySize(Array); 745 Value *Offset = getArrayOffset(Array); 746 if (Offset) 747 ArraySize = Builder.CreateSub( 748 ArraySize, 749 Builder.CreateMul(Offset, 750 Builder.getInt64(ScopArray->getElemSizeInBytes()))); 751 Value *DevArray = createCallAllocateMemoryForDevice(ArraySize); 752 DevArray->setName(DevArrayName); 753 DeviceAllocations[ScopArray] = DevArray; 754 } 755 756 isl_ast_build_free(Build); 757 } 758 759 void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX, 760 Value *BlockDimY, Value *BlockDimZ) { 761 auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations"); 762 763 for (auto &F : *M) { 764 if (F.getCallingConv() != CallingConv::PTX_Kernel) 765 continue; 766 767 Value *V[] = {BlockDimX, BlockDimY, BlockDimZ}; 768 769 Metadata *Elements[] = { 770 ValueAsMetadata::get(&F), MDString::get(M->getContext(), "maxntidx"), 771 ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"), 772 ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"), 773 ValueAsMetadata::get(V[2]), 774 }; 775 MDNode *Node = MDNode::get(M->getContext(), Elements); 776 AnnotationNode->addOperand(Node); 777 } 778 } 779 780 void GPUNodeBuilder::freeDeviceArrays() { 781 assert(!ManagedMemory && "Managed memory does not use device arrays"); 782 for (auto &Array : DeviceAllocations) 783 createCallFreeDeviceMemory(Array.second); 784 } 785 786 Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) { 787 const char *Name = "polly_getKernel"; 788 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 789 Function *F = M->getFunction(Name); 790 791 // If F is not available, declare it. 792 if (!F) { 793 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 794 std::vector<Type *> Args; 795 Args.push_back(Builder.getInt8PtrTy()); 796 Args.push_back(Builder.getInt8PtrTy()); 797 FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 798 F = Function::Create(Ty, Linkage, Name, M); 799 } 800 801 return Builder.CreateCall(F, {Buffer, Entry}); 802 } 803 804 Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) { 805 const char *Name = "polly_getDevicePtr"; 806 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 807 Function *F = M->getFunction(Name); 808 809 // If F is not available, declare it. 810 if (!F) { 811 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 812 std::vector<Type *> Args; 813 Args.push_back(Builder.getInt8PtrTy()); 814 FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 815 F = Function::Create(Ty, Linkage, Name, M); 816 } 817 818 return Builder.CreateCall(F, {Allocation}); 819 } 820 821 void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 822 Value *GridDimY, Value *BlockDimX, 823 Value *BlockDimY, Value *BlockDimZ, 824 Value *Parameters) { 825 const char *Name = "polly_launchKernel"; 826 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 827 Function *F = M->getFunction(Name); 828 829 // If F is not available, declare it. 830 if (!F) { 831 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 832 std::vector<Type *> Args; 833 Args.push_back(Builder.getInt8PtrTy()); 834 Args.push_back(Builder.getInt32Ty()); 835 Args.push_back(Builder.getInt32Ty()); 836 Args.push_back(Builder.getInt32Ty()); 837 Args.push_back(Builder.getInt32Ty()); 838 Args.push_back(Builder.getInt32Ty()); 839 Args.push_back(Builder.getInt8PtrTy()); 840 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 841 F = Function::Create(Ty, Linkage, Name, M); 842 } 843 844 Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 845 BlockDimZ, Parameters}); 846 } 847 848 void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) { 849 const char *Name = "polly_freeKernel"; 850 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 851 Function *F = M->getFunction(Name); 852 853 // If F is not available, declare it. 854 if (!F) { 855 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 856 std::vector<Type *> Args; 857 Args.push_back(Builder.getInt8PtrTy()); 858 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 859 F = Function::Create(Ty, Linkage, Name, M); 860 } 861 862 Builder.CreateCall(F, {GPUKernel}); 863 } 864 865 void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) { 866 assert(!ManagedMemory && "Managed memory does not allocate or free memory " 867 "for device"); 868 const char *Name = "polly_freeDeviceMemory"; 869 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 870 Function *F = M->getFunction(Name); 871 872 // If F is not available, declare it. 873 if (!F) { 874 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 875 std::vector<Type *> Args; 876 Args.push_back(Builder.getInt8PtrTy()); 877 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 878 F = Function::Create(Ty, Linkage, Name, M); 879 } 880 881 Builder.CreateCall(F, {Array}); 882 } 883 884 Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) { 885 assert(!ManagedMemory && "Managed memory does not allocate or free memory " 886 "for device"); 887 const char *Name = "polly_allocateMemoryForDevice"; 888 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 889 Function *F = M->getFunction(Name); 890 891 // If F is not available, declare it. 892 if (!F) { 893 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 894 std::vector<Type *> Args; 895 Args.push_back(Builder.getInt64Ty()); 896 FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 897 F = Function::Create(Ty, Linkage, Name, M); 898 } 899 900 return Builder.CreateCall(F, {Size}); 901 } 902 903 void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData, 904 Value *DeviceData, 905 Value *Size) { 906 assert(!ManagedMemory && "Managed memory does not transfer memory between " 907 "device and host"); 908 const char *Name = "polly_copyFromHostToDevice"; 909 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 910 Function *F = M->getFunction(Name); 911 912 // If F is not available, declare it. 913 if (!F) { 914 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 915 std::vector<Type *> Args; 916 Args.push_back(Builder.getInt8PtrTy()); 917 Args.push_back(Builder.getInt8PtrTy()); 918 Args.push_back(Builder.getInt64Ty()); 919 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 920 F = Function::Create(Ty, Linkage, Name, M); 921 } 922 923 Builder.CreateCall(F, {HostData, DeviceData, Size}); 924 } 925 926 void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData, 927 Value *HostData, 928 Value *Size) { 929 assert(!ManagedMemory && "Managed memory does not transfer memory between " 930 "device and host"); 931 const char *Name = "polly_copyFromDeviceToHost"; 932 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 933 Function *F = M->getFunction(Name); 934 935 // If F is not available, declare it. 936 if (!F) { 937 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 938 std::vector<Type *> Args; 939 Args.push_back(Builder.getInt8PtrTy()); 940 Args.push_back(Builder.getInt8PtrTy()); 941 Args.push_back(Builder.getInt64Ty()); 942 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 943 F = Function::Create(Ty, Linkage, Name, M); 944 } 945 946 Builder.CreateCall(F, {DeviceData, HostData, Size}); 947 } 948 949 void GPUNodeBuilder::createCallSynchronizeDevice() { 950 assert(ManagedMemory && "explicit synchronization is only necessary for " 951 "managed memory"); 952 const char *Name = "polly_synchronizeDevice"; 953 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 954 Function *F = M->getFunction(Name); 955 956 // If F is not available, declare it. 957 if (!F) { 958 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 959 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false); 960 F = Function::Create(Ty, Linkage, Name, M); 961 } 962 963 Builder.CreateCall(F); 964 } 965 966 Value *GPUNodeBuilder::createCallInitContext() { 967 const char *Name; 968 969 switch (Runtime) { 970 case GPURuntime::CUDA: 971 Name = "polly_initContextCUDA"; 972 break; 973 case GPURuntime::OpenCL: 974 Name = "polly_initContextCL"; 975 break; 976 } 977 978 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 979 Function *F = M->getFunction(Name); 980 981 // If F is not available, declare it. 982 if (!F) { 983 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 984 std::vector<Type *> Args; 985 FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 986 F = Function::Create(Ty, Linkage, Name, M); 987 } 988 989 return Builder.CreateCall(F, {}); 990 } 991 992 void GPUNodeBuilder::createCallFreeContext(Value *Context) { 993 const char *Name = "polly_freeContext"; 994 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 995 Function *F = M->getFunction(Name); 996 997 // If F is not available, declare it. 998 if (!F) { 999 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 1000 std::vector<Type *> Args; 1001 Args.push_back(Builder.getInt8PtrTy()); 1002 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 1003 F = Function::Create(Ty, Linkage, Name, M); 1004 } 1005 1006 Builder.CreateCall(F, {Context}); 1007 } 1008 1009 /// Check if one string is a prefix of another. 1010 /// 1011 /// @param String The string in which to look for the prefix. 1012 /// @param Prefix The prefix to look for. 1013 static bool isPrefix(std::string String, std::string Prefix) { 1014 return String.find(Prefix) == 0; 1015 } 1016 1017 Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) { 1018 isl::ast_build Build = 1019 isl::ast_build::from_context(isl::manage(S.getContext())); 1020 Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size); 1021 1022 if (!gpu_array_is_scalar(Array)) { 1023 isl::multi_pw_aff ArrayBound = 1024 isl::manage(isl_multi_pw_aff_copy(Array->bound)); 1025 1026 isl::pw_aff OffsetDimZero = ArrayBound.get_pw_aff(0); 1027 isl::ast_expr Res = Build.expr_from(OffsetDimZero); 1028 1029 for (unsigned int i = 1; i < Array->n_index; i++) { 1030 isl::pw_aff Bound_I = ArrayBound.get_pw_aff(i); 1031 isl::ast_expr Expr = Build.expr_from(Bound_I); 1032 Res = Res.mul(Expr); 1033 } 1034 1035 Value *NumElements = ExprBuilder.create(Res.release()); 1036 if (NumElements->getType() != ArraySize->getType()) 1037 NumElements = Builder.CreateSExt(NumElements, ArraySize->getType()); 1038 ArraySize = Builder.CreateMul(ArraySize, NumElements); 1039 } 1040 return ArraySize; 1041 } 1042 1043 Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) { 1044 if (gpu_array_is_scalar(Array)) 1045 return nullptr; 1046 1047 isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 1048 1049 isl_set *Min = isl_set_lexmin(isl_set_copy(Array->extent)); 1050 1051 isl_set *ZeroSet = isl_set_universe(isl_set_get_space(Min)); 1052 1053 for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) 1054 ZeroSet = isl_set_fix_si(ZeroSet, isl_dim_set, i, 0); 1055 1056 if (isl_set_is_subset(Min, ZeroSet)) { 1057 isl_set_free(Min); 1058 isl_set_free(ZeroSet); 1059 isl_ast_build_free(Build); 1060 return nullptr; 1061 } 1062 isl_set_free(ZeroSet); 1063 1064 isl_ast_expr *Result = 1065 isl_ast_expr_from_val(isl_val_int_from_si(isl_set_get_ctx(Min), 0)); 1066 1067 for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) { 1068 if (i > 0) { 1069 isl_pw_aff *Bound_I = isl_multi_pw_aff_get_pw_aff(Array->bound, i - 1); 1070 isl_ast_expr *BExpr = isl_ast_build_expr_from_pw_aff(Build, Bound_I); 1071 Result = isl_ast_expr_mul(Result, BExpr); 1072 } 1073 isl_pw_aff *DimMin = isl_set_dim_min(isl_set_copy(Min), i); 1074 isl_ast_expr *MExpr = isl_ast_build_expr_from_pw_aff(Build, DimMin); 1075 Result = isl_ast_expr_add(Result, MExpr); 1076 } 1077 1078 Value *ResultValue = ExprBuilder.create(Result); 1079 isl_set_free(Min); 1080 isl_ast_build_free(Build); 1081 1082 return ResultValue; 1083 } 1084 1085 Value *GPUNodeBuilder::getOrCreateManagedDeviceArray(gpu_array_info *Array, 1086 ScopArrayInfo *ArrayInfo) { 1087 1088 assert(ManagedMemory && "Only used when you wish to get a host " 1089 "pointer for sending data to the kernel, " 1090 "with managed memory"); 1091 std::map<ScopArrayInfo *, Value *>::iterator it; 1092 if ((it = DeviceAllocations.find(ArrayInfo)) != DeviceAllocations.end()) { 1093 return it->second; 1094 } else { 1095 Value *HostPtr; 1096 1097 if (gpu_array_is_scalar(Array)) 1098 HostPtr = BlockGen.getOrCreateAlloca(ArrayInfo); 1099 else 1100 HostPtr = ArrayInfo->getBasePtr(); 1101 1102 Value *Offset = getArrayOffset(Array); 1103 if (Offset) { 1104 HostPtr = Builder.CreatePointerCast( 1105 HostPtr, ArrayInfo->getElementType()->getPointerTo()); 1106 HostPtr = Builder.CreateGEP(HostPtr, Offset); 1107 } 1108 1109 HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 1110 DeviceAllocations[ArrayInfo] = HostPtr; 1111 return HostPtr; 1112 } 1113 } 1114 1115 void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt, 1116 enum DataDirection Direction) { 1117 assert(!ManagedMemory && "Managed memory needs no data transfers"); 1118 isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt); 1119 isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0); 1120 isl_id *Id = isl_ast_expr_get_id(Arg); 1121 auto Array = (gpu_array_info *)isl_id_get_user(Id); 1122 auto ScopArray = (ScopArrayInfo *)(Array->user); 1123 1124 Value *Size = getArraySize(Array); 1125 Value *Offset = getArrayOffset(Array); 1126 Value *DevPtr = DeviceAllocations[ScopArray]; 1127 1128 Value *HostPtr; 1129 1130 if (gpu_array_is_scalar(Array)) 1131 HostPtr = BlockGen.getOrCreateAlloca(ScopArray); 1132 else 1133 HostPtr = ScopArray->getBasePtr(); 1134 1135 if (Offset) { 1136 HostPtr = Builder.CreatePointerCast( 1137 HostPtr, ScopArray->getElementType()->getPointerTo()); 1138 HostPtr = Builder.CreateGEP(HostPtr, Offset); 1139 } 1140 1141 HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 1142 1143 if (Offset) { 1144 Size = Builder.CreateSub( 1145 Size, Builder.CreateMul( 1146 Offset, Builder.getInt64(ScopArray->getElemSizeInBytes()))); 1147 } 1148 1149 if (Direction == HOST_TO_DEVICE) 1150 createCallCopyFromHostToDevice(HostPtr, DevPtr, Size); 1151 else 1152 createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size); 1153 1154 isl_id_free(Id); 1155 isl_ast_expr_free(Arg); 1156 isl_ast_expr_free(Expr); 1157 isl_ast_node_free(TransferStmt); 1158 } 1159 1160 void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) { 1161 isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt); 1162 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 1163 isl_id *Id = isl_ast_expr_get_id(StmtExpr); 1164 isl_id_free(Id); 1165 isl_ast_expr_free(StmtExpr); 1166 1167 const char *Str = isl_id_get_name(Id); 1168 if (!strcmp(Str, "kernel")) { 1169 createKernel(UserStmt); 1170 isl_ast_expr_free(Expr); 1171 return; 1172 } 1173 if (!strcmp(Str, "init_device")) { 1174 initializeAfterRTH(); 1175 isl_ast_node_free(UserStmt); 1176 isl_ast_expr_free(Expr); 1177 return; 1178 } 1179 if (!strcmp(Str, "clear_device")) { 1180 finalize(); 1181 isl_ast_node_free(UserStmt); 1182 isl_ast_expr_free(Expr); 1183 return; 1184 } 1185 if (isPrefix(Str, "to_device")) { 1186 if (!ManagedMemory) 1187 createDataTransfer(UserStmt, HOST_TO_DEVICE); 1188 else 1189 isl_ast_node_free(UserStmt); 1190 1191 isl_ast_expr_free(Expr); 1192 return; 1193 } 1194 1195 if (isPrefix(Str, "from_device")) { 1196 if (!ManagedMemory) { 1197 createDataTransfer(UserStmt, DEVICE_TO_HOST); 1198 } else { 1199 createCallSynchronizeDevice(); 1200 isl_ast_node_free(UserStmt); 1201 } 1202 isl_ast_expr_free(Expr); 1203 return; 1204 } 1205 1206 isl_id *Anno = isl_ast_node_get_annotation(UserStmt); 1207 struct ppcg_kernel_stmt *KernelStmt = 1208 (struct ppcg_kernel_stmt *)isl_id_get_user(Anno); 1209 isl_id_free(Anno); 1210 1211 switch (KernelStmt->type) { 1212 case ppcg_kernel_domain: 1213 createScopStmt(Expr, KernelStmt); 1214 isl_ast_node_free(UserStmt); 1215 return; 1216 case ppcg_kernel_copy: 1217 createKernelCopy(KernelStmt); 1218 isl_ast_expr_free(Expr); 1219 isl_ast_node_free(UserStmt); 1220 return; 1221 case ppcg_kernel_sync: 1222 createKernelSync(); 1223 isl_ast_expr_free(Expr); 1224 isl_ast_node_free(UserStmt); 1225 return; 1226 } 1227 1228 isl_ast_expr_free(Expr); 1229 isl_ast_node_free(UserStmt); 1230 return; 1231 } 1232 void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) { 1233 isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index); 1234 LocalIndex = isl_ast_expr_address_of(LocalIndex); 1235 Value *LocalAddr = ExprBuilder.create(LocalIndex); 1236 isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index); 1237 Index = isl_ast_expr_address_of(Index); 1238 Value *GlobalAddr = ExprBuilder.create(Index); 1239 1240 if (KernelStmt->u.c.read) { 1241 LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read"); 1242 Builder.CreateStore(Load, LocalAddr); 1243 } else { 1244 LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write"); 1245 Builder.CreateStore(Load, GlobalAddr); 1246 } 1247 } 1248 1249 void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr, 1250 ppcg_kernel_stmt *KernelStmt) { 1251 auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1252 isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr; 1253 1254 LoopToScevMapT LTS; 1255 LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end()); 1256 1257 createSubstitutions(Expr, Stmt, LTS); 1258 1259 if (Stmt->isBlockStmt()) 1260 BlockGen.copyStmt(*Stmt, LTS, Indexes); 1261 else 1262 RegionGen.copyStmt(*Stmt, LTS, Indexes); 1263 } 1264 1265 void GPUNodeBuilder::createKernelSync() { 1266 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1267 const char *SpirName = "__gen_ocl_barrier_global"; 1268 1269 Function *Sync; 1270 1271 switch (Arch) { 1272 case GPUArch::SPIR64: 1273 case GPUArch::SPIR32: 1274 Sync = M->getFunction(SpirName); 1275 1276 // If Sync is not available, declare it. 1277 if (!Sync) { 1278 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 1279 std::vector<Type *> Args; 1280 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 1281 Sync = Function::Create(Ty, Linkage, SpirName, M); 1282 Sync->setCallingConv(CallingConv::SPIR_FUNC); 1283 } 1284 break; 1285 case GPUArch::NVPTX64: 1286 Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0); 1287 break; 1288 } 1289 1290 Builder.CreateCall(Sync, {}); 1291 } 1292 1293 /// Collect llvm::Values referenced from @p Node 1294 /// 1295 /// This function only applies to isl_ast_nodes that are user_nodes referring 1296 /// to a ScopStmt. All other node types are ignore. 1297 /// 1298 /// @param Node The node to collect references for. 1299 /// @param User A user pointer used as storage for the data that is collected. 1300 /// 1301 /// @returns isl_bool_true if data could be collected successfully. 1302 isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) { 1303 if (isl_ast_node_get_type(Node) != isl_ast_node_user) 1304 return isl_bool_true; 1305 1306 isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node); 1307 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 1308 isl_id *Id = isl_ast_expr_get_id(StmtExpr); 1309 const char *Str = isl_id_get_name(Id); 1310 isl_id_free(Id); 1311 isl_ast_expr_free(StmtExpr); 1312 isl_ast_expr_free(Expr); 1313 1314 if (!isPrefix(Str, "Stmt")) 1315 return isl_bool_true; 1316 1317 Id = isl_ast_node_get_annotation(Node); 1318 auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id); 1319 auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1320 isl_id_free(Id); 1321 1322 addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */); 1323 1324 return isl_bool_true; 1325 } 1326 1327 /// Check if F is a function that we can code-generate in a GPU kernel. 1328 static bool isValidFunctionInKernel(llvm::Function *F) { 1329 assert(F && "F is an invalid pointer"); 1330 // We string compare against the name of the function to allow 1331 // all variants of the intrinsic "llvm.sqrt.*", "llvm.fabs", and 1332 // "llvm.copysign". 1333 const StringRef Name = F->getName(); 1334 return F->isIntrinsic() && 1335 (Name.startswith("llvm.sqrt") || Name.startswith("llvm.fabs") || 1336 Name.startswith("llvm.copysign")); 1337 } 1338 1339 /// Do not take `Function` as a subtree value. 1340 /// 1341 /// We try to take the reference of all subtree values and pass them along 1342 /// to the kernel from the host. Taking an address of any function and 1343 /// trying to pass along is nonsensical. Only allow `Value`s that are not 1344 /// `Function`s. 1345 static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); } 1346 1347 /// Return `Function`s from `RawSubtreeValues`. 1348 static SetVector<Function *> 1349 getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues) { 1350 SetVector<Function *> SubtreeFunctions; 1351 for (Value *It : RawSubtreeValues) { 1352 Function *F = dyn_cast<Function>(It); 1353 if (F) { 1354 assert(isValidFunctionInKernel(F) && "Code should have bailed out by " 1355 "this point if an invalid function " 1356 "were present in a kernel."); 1357 SubtreeFunctions.insert(F); 1358 } 1359 } 1360 return SubtreeFunctions; 1361 } 1362 1363 std::pair<SetVector<Value *>, SetVector<Function *>> 1364 GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) { 1365 SetVector<Value *> SubtreeValues; 1366 SetVector<const SCEV *> SCEVs; 1367 SetVector<const Loop *> Loops; 1368 SubtreeReferences References = { 1369 LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()}; 1370 1371 for (const auto &I : IDToValue) 1372 SubtreeValues.insert(I.second); 1373 1374 isl_ast_node_foreach_descendant_top_down( 1375 Kernel->tree, collectReferencesInGPUStmt, &References); 1376 1377 for (const SCEV *Expr : SCEVs) 1378 findValues(Expr, SE, SubtreeValues); 1379 1380 for (auto &SAI : S.arrays()) 1381 SubtreeValues.remove(SAI->getBasePtr()); 1382 1383 isl_space *Space = S.getParamSpace(); 1384 for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) { 1385 isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i); 1386 assert(IDToValue.count(Id)); 1387 Value *Val = IDToValue[Id]; 1388 SubtreeValues.remove(Val); 1389 isl_id_free(Id); 1390 } 1391 isl_space_free(Space); 1392 1393 for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) { 1394 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1395 assert(IDToValue.count(Id)); 1396 Value *Val = IDToValue[Id]; 1397 SubtreeValues.remove(Val); 1398 isl_id_free(Id); 1399 } 1400 1401 // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions 1402 // SubtreeValues. This is important, because we should not lose any 1403 // SubtreeValues in the process of constructing the 1404 // "ValidSubtree{Values, Functions} sets. Nor should the set 1405 // ValidSubtree{Values, Functions} have any common element. 1406 auto ValidSubtreeValuesIt = 1407 make_filter_range(SubtreeValues, isValidSubtreeValue); 1408 SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(), 1409 ValidSubtreeValuesIt.end()); 1410 SetVector<Function *> ValidSubtreeFunctions( 1411 getFunctionsFromRawSubtreeValues(SubtreeValues)); 1412 1413 // @see IslNodeBuilder::getReferencesInSubtree 1414 SetVector<Value *> ReplacedValues; 1415 for (Value *V : ValidSubtreeValues) { 1416 auto It = ValueMap.find(V); 1417 if (It == ValueMap.end()) 1418 ReplacedValues.insert(V); 1419 else 1420 ReplacedValues.insert(It->second); 1421 } 1422 return std::make_pair(ReplacedValues, ValidSubtreeFunctions); 1423 } 1424 1425 void GPUNodeBuilder::clearDominators(Function *F) { 1426 DomTreeNode *N = DT.getNode(&F->getEntryBlock()); 1427 std::vector<BasicBlock *> Nodes; 1428 for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I) 1429 Nodes.push_back(I->getBlock()); 1430 1431 for (BasicBlock *BB : Nodes) 1432 DT.eraseNode(BB); 1433 } 1434 1435 void GPUNodeBuilder::clearScalarEvolution(Function *F) { 1436 for (BasicBlock &BB : *F) { 1437 Loop *L = LI.getLoopFor(&BB); 1438 if (L) 1439 SE.forgetLoop(L); 1440 } 1441 } 1442 1443 void GPUNodeBuilder::clearLoops(Function *F) { 1444 for (BasicBlock &BB : *F) { 1445 Loop *L = LI.getLoopFor(&BB); 1446 if (L) 1447 SE.forgetLoop(L); 1448 LI.removeBlock(&BB); 1449 } 1450 } 1451 1452 std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) { 1453 std::vector<Value *> Sizes; 1454 isl_ast_build *Context = isl_ast_build_from_context(S.getContext()); 1455 1456 for (long i = 0; i < Kernel->n_grid; i++) { 1457 isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i); 1458 isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size); 1459 Value *Res = ExprBuilder.create(GridSize); 1460 Res = Builder.CreateTrunc(Res, Builder.getInt32Ty()); 1461 Sizes.push_back(Res); 1462 } 1463 isl_ast_build_free(Context); 1464 1465 for (long i = Kernel->n_grid; i < 3; i++) 1466 Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 1467 1468 return std::make_tuple(Sizes[0], Sizes[1]); 1469 } 1470 1471 std::tuple<Value *, Value *, Value *> 1472 GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) { 1473 std::vector<Value *> Sizes; 1474 1475 for (long i = 0; i < Kernel->n_block; i++) { 1476 Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]); 1477 Sizes.push_back(Res); 1478 } 1479 1480 for (long i = Kernel->n_block; i < 3; i++) 1481 Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 1482 1483 return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]); 1484 } 1485 1486 void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters, 1487 Instruction *Param, int Index) { 1488 Value *Slot = Builder.CreateGEP( 1489 Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1490 Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 1491 Builder.CreateStore(ParamTyped, Slot); 1492 } 1493 1494 Value * 1495 GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F, 1496 SetVector<Value *> SubtreeValues) { 1497 const int NumArgs = F->arg_size(); 1498 std::vector<int> ArgSizes(NumArgs); 1499 1500 Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs); 1501 1502 BasicBlock *EntryBlock = 1503 &Builder.GetInsertBlock()->getParent()->getEntryBlock(); 1504 auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace(); 1505 std::string Launch = "polly_launch_" + std::to_string(Kernel->id); 1506 Instruction *Parameters = new AllocaInst( 1507 ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator()); 1508 1509 int Index = 0; 1510 for (long i = 0; i < Prog->n_array; i++) { 1511 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 1512 continue; 1513 1514 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1515 const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id)); 1516 1517 ArgSizes[Index] = SAI->getElemSizeInBytes(); 1518 1519 Value *DevArray = nullptr; 1520 if (ManagedMemory) { 1521 DevArray = getOrCreateManagedDeviceArray( 1522 &Prog->array[i], const_cast<ScopArrayInfo *>(SAI)); 1523 } else { 1524 DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)]; 1525 DevArray = createCallGetDevicePtr(DevArray); 1526 } 1527 assert(DevArray != nullptr && "Array to be offloaded to device not " 1528 "initialized"); 1529 Value *Offset = getArrayOffset(&Prog->array[i]); 1530 1531 if (Offset) { 1532 DevArray = Builder.CreatePointerCast( 1533 DevArray, SAI->getElementType()->getPointerTo()); 1534 DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset)); 1535 DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy()); 1536 } 1537 Value *Slot = Builder.CreateGEP( 1538 Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1539 1540 if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1541 Value *ValPtr = nullptr; 1542 if (ManagedMemory) 1543 ValPtr = DevArray; 1544 else 1545 ValPtr = BlockGen.getOrCreateAlloca(SAI); 1546 1547 assert(ValPtr != nullptr && "ValPtr that should point to a valid object" 1548 " to be stored into Parameters"); 1549 Value *ValPtrCast = 1550 Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy()); 1551 Builder.CreateStore(ValPtrCast, Slot); 1552 } else { 1553 Instruction *Param = 1554 new AllocaInst(Builder.getInt8PtrTy(), AddressSpace, 1555 Launch + "_param_" + std::to_string(Index), 1556 EntryBlock->getTerminator()); 1557 Builder.CreateStore(DevArray, Param); 1558 Value *ParamTyped = 1559 Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 1560 Builder.CreateStore(ParamTyped, Slot); 1561 } 1562 Index++; 1563 } 1564 1565 int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1566 1567 for (long i = 0; i < NumHostIters; i++) { 1568 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1569 Value *Val = IDToValue[Id]; 1570 isl_id_free(Id); 1571 1572 ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1573 1574 Instruction *Param = 1575 new AllocaInst(Val->getType(), AddressSpace, 1576 Launch + "_param_" + std::to_string(Index), 1577 EntryBlock->getTerminator()); 1578 Builder.CreateStore(Val, Param); 1579 insertStoreParameter(Parameters, Param, Index); 1580 Index++; 1581 } 1582 1583 int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1584 1585 for (long i = 0; i < NumVars; i++) { 1586 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1587 Value *Val = IDToValue[Id]; 1588 if (ValueMap.count(Val)) 1589 Val = ValueMap[Val]; 1590 isl_id_free(Id); 1591 1592 ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1593 1594 Instruction *Param = 1595 new AllocaInst(Val->getType(), AddressSpace, 1596 Launch + "_param_" + std::to_string(Index), 1597 EntryBlock->getTerminator()); 1598 Builder.CreateStore(Val, Param); 1599 insertStoreParameter(Parameters, Param, Index); 1600 Index++; 1601 } 1602 1603 for (auto Val : SubtreeValues) { 1604 ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1605 1606 Instruction *Param = 1607 new AllocaInst(Val->getType(), AddressSpace, 1608 Launch + "_param_" + std::to_string(Index), 1609 EntryBlock->getTerminator()); 1610 Builder.CreateStore(Val, Param); 1611 insertStoreParameter(Parameters, Param, Index); 1612 Index++; 1613 } 1614 1615 for (int i = 0; i < NumArgs; i++) { 1616 Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]); 1617 Instruction *Param = 1618 new AllocaInst(Builder.getInt32Ty(), AddressSpace, 1619 Launch + "_param_size_" + std::to_string(i), 1620 EntryBlock->getTerminator()); 1621 Builder.CreateStore(Val, Param); 1622 insertStoreParameter(Parameters, Param, Index); 1623 Index++; 1624 } 1625 1626 auto Location = EntryBlock->getTerminator(); 1627 return new BitCastInst(Parameters, Builder.getInt8PtrTy(), 1628 Launch + "_params_i8ptr", Location); 1629 } 1630 1631 void GPUNodeBuilder::setupKernelSubtreeFunctions( 1632 SetVector<Function *> SubtreeFunctions) { 1633 for (auto Fn : SubtreeFunctions) { 1634 const std::string ClonedFnName = Fn->getName(); 1635 Function *Clone = GPUModule->getFunction(ClonedFnName); 1636 if (!Clone) 1637 Clone = 1638 Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage, 1639 ClonedFnName, GPUModule.get()); 1640 assert(Clone && "Expected cloned function to be initialized."); 1641 assert(ValueMap.find(Fn) == ValueMap.end() && 1642 "Fn already present in ValueMap"); 1643 ValueMap[Fn] = Clone; 1644 } 1645 } 1646 void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) { 1647 isl_id *Id = isl_ast_node_get_annotation(KernelStmt); 1648 ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id); 1649 isl_id_free(Id); 1650 isl_ast_node_free(KernelStmt); 1651 1652 if (Kernel->n_grid > 1) 1653 DeepestParallel = 1654 std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set)); 1655 else 1656 DeepestSequential = 1657 std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set)); 1658 1659 Value *BlockDimX, *BlockDimY, *BlockDimZ; 1660 std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel); 1661 1662 SetVector<Value *> SubtreeValues; 1663 SetVector<Function *> SubtreeFunctions; 1664 std::tie(SubtreeValues, SubtreeFunctions) = getReferencesInKernel(Kernel); 1665 1666 assert(Kernel->tree && "Device AST of kernel node is empty"); 1667 1668 Instruction &HostInsertPoint = *Builder.GetInsertPoint(); 1669 IslExprBuilder::IDToValueTy HostIDs = IDToValue; 1670 ValueMapT HostValueMap = ValueMap; 1671 BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap; 1672 ScalarMap.clear(); 1673 1674 SetVector<const Loop *> Loops; 1675 1676 // Create for all loops we depend on values that contain the current loop 1677 // iteration. These values are necessary to generate code for SCEVs that 1678 // depend on such loops. As a result we need to pass them to the subfunction. 1679 for (const Loop *L : Loops) { 1680 const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)), 1681 SE.getUnknown(Builder.getInt64(1)), 1682 L, SCEV::FlagAnyWrap); 1683 Value *V = generateSCEV(OuterLIV); 1684 OutsideLoopIterations[L] = SE.getUnknown(V); 1685 SubtreeValues.insert(V); 1686 } 1687 1688 createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions); 1689 setupKernelSubtreeFunctions(SubtreeFunctions); 1690 1691 create(isl_ast_node_copy(Kernel->tree)); 1692 1693 finalizeKernelArguments(Kernel); 1694 Function *F = Builder.GetInsertBlock()->getParent(); 1695 if (Arch == GPUArch::NVPTX64) 1696 addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ); 1697 clearDominators(F); 1698 clearScalarEvolution(F); 1699 clearLoops(F); 1700 1701 IDToValue = HostIDs; 1702 1703 ValueMap = std::move(HostValueMap); 1704 ScalarMap = std::move(HostScalarMap); 1705 EscapeMap.clear(); 1706 IDToSAI.clear(); 1707 Annotator.resetAlternativeAliasBases(); 1708 for (auto &BasePtr : LocalArrays) 1709 S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array); 1710 LocalArrays.clear(); 1711 1712 std::string ASMString = finalizeKernelFunction(); 1713 Builder.SetInsertPoint(&HostInsertPoint); 1714 Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues); 1715 1716 std::string Name = getKernelFuncName(Kernel->id); 1717 Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name); 1718 Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name"); 1719 Value *GPUKernel = createCallGetKernel(KernelString, NameString); 1720 1721 Value *GridDimX, *GridDimY; 1722 std::tie(GridDimX, GridDimY) = getGridSizes(Kernel); 1723 1724 createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 1725 BlockDimZ, Parameters); 1726 createCallFreeKernel(GPUKernel); 1727 1728 for (auto Id : KernelIds) 1729 isl_id_free(Id); 1730 1731 KernelIds.clear(); 1732 } 1733 1734 /// Compute the DataLayout string for the NVPTX backend. 1735 /// 1736 /// @param is64Bit Are we looking for a 64 bit architecture? 1737 static std::string computeNVPTXDataLayout(bool is64Bit) { 1738 std::string Ret = ""; 1739 1740 if (!is64Bit) { 1741 Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1742 "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1743 "64-v128:128:128-n16:32:64"; 1744 } else { 1745 Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1746 "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1747 "64-v128:128:128-n16:32:64"; 1748 } 1749 1750 return Ret; 1751 } 1752 1753 /// Compute the DataLayout string for a SPIR kernel. 1754 /// 1755 /// @param is64Bit Are we looking for a 64 bit architecture? 1756 static std::string computeSPIRDataLayout(bool is64Bit) { 1757 std::string Ret = ""; 1758 1759 if (!is64Bit) { 1760 Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1761 "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:" 1762 "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:" 1763 "256:256-v256:256:256-v512:512:512-v1024:1024:1024"; 1764 } else { 1765 Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1766 "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:" 1767 "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:" 1768 "256:256-v256:256:256-v512:512:512-v1024:1024:1024"; 1769 } 1770 1771 return Ret; 1772 } 1773 1774 Function * 1775 GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel, 1776 SetVector<Value *> &SubtreeValues) { 1777 std::vector<Type *> Args; 1778 std::string Identifier = getKernelFuncName(Kernel->id); 1779 1780 std::vector<Metadata *> MemoryType; 1781 1782 for (long i = 0; i < Prog->n_array; i++) { 1783 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 1784 continue; 1785 1786 if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1787 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1788 const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id)); 1789 Args.push_back(SAI->getElementType()); 1790 MemoryType.push_back( 1791 ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 1792 } else { 1793 static const int UseGlobalMemory = 1; 1794 Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory)); 1795 MemoryType.push_back( 1796 ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 1))); 1797 } 1798 } 1799 1800 int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1801 1802 for (long i = 0; i < NumHostIters; i++) { 1803 Args.push_back(Builder.getInt64Ty()); 1804 MemoryType.push_back( 1805 ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 1806 } 1807 1808 int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1809 1810 for (long i = 0; i < NumVars; i++) { 1811 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1812 Value *Val = IDToValue[Id]; 1813 isl_id_free(Id); 1814 Args.push_back(Val->getType()); 1815 MemoryType.push_back( 1816 ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 1817 } 1818 1819 for (auto *V : SubtreeValues) { 1820 Args.push_back(V->getType()); 1821 MemoryType.push_back( 1822 ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 1823 } 1824 1825 auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false); 1826 auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier, 1827 GPUModule.get()); 1828 1829 std::vector<Metadata *> EmptyStrings; 1830 1831 for (unsigned int i = 0; i < MemoryType.size(); i++) { 1832 EmptyStrings.push_back(MDString::get(FN->getContext(), "")); 1833 } 1834 1835 if (Arch == GPUArch::SPIR32 || Arch == GPUArch::SPIR64) { 1836 FN->setMetadata("kernel_arg_addr_space", 1837 MDNode::get(FN->getContext(), MemoryType)); 1838 FN->setMetadata("kernel_arg_name", 1839 MDNode::get(FN->getContext(), EmptyStrings)); 1840 FN->setMetadata("kernel_arg_access_qual", 1841 MDNode::get(FN->getContext(), EmptyStrings)); 1842 FN->setMetadata("kernel_arg_type", 1843 MDNode::get(FN->getContext(), EmptyStrings)); 1844 FN->setMetadata("kernel_arg_type_qual", 1845 MDNode::get(FN->getContext(), EmptyStrings)); 1846 FN->setMetadata("kernel_arg_base_type", 1847 MDNode::get(FN->getContext(), EmptyStrings)); 1848 } 1849 1850 switch (Arch) { 1851 case GPUArch::NVPTX64: 1852 FN->setCallingConv(CallingConv::PTX_Kernel); 1853 break; 1854 case GPUArch::SPIR32: 1855 case GPUArch::SPIR64: 1856 FN->setCallingConv(CallingConv::SPIR_KERNEL); 1857 break; 1858 } 1859 1860 auto Arg = FN->arg_begin(); 1861 for (long i = 0; i < Kernel->n_array; i++) { 1862 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 1863 continue; 1864 1865 Arg->setName(Kernel->array[i].array->name); 1866 1867 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1868 const ScopArrayInfo *SAI = 1869 ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id))); 1870 Type *EleTy = SAI->getElementType(); 1871 Value *Val = &*Arg; 1872 SmallVector<const SCEV *, 4> Sizes; 1873 isl_ast_build *Build = 1874 isl_ast_build_from_context(isl_set_copy(Prog->context)); 1875 Sizes.push_back(nullptr); 1876 for (long j = 1; j < Kernel->array[i].array->n_index; j++) { 1877 isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff( 1878 Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j)); 1879 auto V = ExprBuilder.create(DimSize); 1880 Sizes.push_back(SE.getSCEV(V)); 1881 } 1882 const ScopArrayInfo *SAIRep = 1883 S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array); 1884 LocalArrays.push_back(Val); 1885 1886 isl_ast_build_free(Build); 1887 KernelIds.push_back(Id); 1888 IDToSAI[Id] = SAIRep; 1889 Arg++; 1890 } 1891 1892 for (long i = 0; i < NumHostIters; i++) { 1893 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1894 Arg->setName(isl_id_get_name(Id)); 1895 IDToValue[Id] = &*Arg; 1896 KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1897 Arg++; 1898 } 1899 1900 for (long i = 0; i < NumVars; i++) { 1901 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1902 Arg->setName(isl_id_get_name(Id)); 1903 Value *Val = IDToValue[Id]; 1904 ValueMap[Val] = &*Arg; 1905 IDToValue[Id] = &*Arg; 1906 KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1907 Arg++; 1908 } 1909 1910 for (auto *V : SubtreeValues) { 1911 Arg->setName(V->getName()); 1912 ValueMap[V] = &*Arg; 1913 Arg++; 1914 } 1915 1916 return FN; 1917 } 1918 1919 void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) { 1920 Intrinsic::ID IntrinsicsBID[2]; 1921 Intrinsic::ID IntrinsicsTID[3]; 1922 1923 switch (Arch) { 1924 case GPUArch::SPIR64: 1925 case GPUArch::SPIR32: 1926 llvm_unreachable("Cannot generate NVVM intrinsics for SPIR"); 1927 case GPUArch::NVPTX64: 1928 IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x; 1929 IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y; 1930 1931 IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x; 1932 IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y; 1933 IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z; 1934 break; 1935 } 1936 1937 auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable { 1938 std::string Name = isl_id_get_name(Id); 1939 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1940 Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr); 1941 Value *Val = Builder.CreateCall(IntrinsicFn, {}); 1942 Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 1943 IDToValue[Id] = Val; 1944 KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1945 }; 1946 1947 for (int i = 0; i < Kernel->n_grid; ++i) { 1948 isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i); 1949 addId(Id, IntrinsicsBID[i]); 1950 } 1951 1952 for (int i = 0; i < Kernel->n_block; ++i) { 1953 isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i); 1954 addId(Id, IntrinsicsTID[i]); 1955 } 1956 } 1957 1958 void GPUNodeBuilder::insertKernelCallsSPIR(ppcg_kernel *Kernel) { 1959 const char *GroupName[3] = {"__gen_ocl_get_group_id0", 1960 "__gen_ocl_get_group_id1", 1961 "__gen_ocl_get_group_id2"}; 1962 1963 const char *LocalName[3] = {"__gen_ocl_get_local_id0", 1964 "__gen_ocl_get_local_id1", 1965 "__gen_ocl_get_local_id2"}; 1966 1967 auto createFunc = [this](const char *Name, __isl_take isl_id *Id) mutable { 1968 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1969 Function *FN = M->getFunction(Name); 1970 1971 // If FN is not available, declare it. 1972 if (!FN) { 1973 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 1974 std::vector<Type *> Args; 1975 FunctionType *Ty = FunctionType::get(Builder.getInt32Ty(), Args, false); 1976 FN = Function::Create(Ty, Linkage, Name, M); 1977 FN->setCallingConv(CallingConv::SPIR_FUNC); 1978 } 1979 1980 Value *Val = Builder.CreateCall(FN, {}); 1981 Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 1982 IDToValue[Id] = Val; 1983 KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1984 }; 1985 1986 for (int i = 0; i < Kernel->n_grid; ++i) 1987 createFunc(GroupName[i], isl_id_list_get_id(Kernel->block_ids, i)); 1988 1989 for (int i = 0; i < Kernel->n_block; ++i) 1990 createFunc(LocalName[i], isl_id_list_get_id(Kernel->thread_ids, i)); 1991 } 1992 1993 void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) { 1994 auto Arg = FN->arg_begin(); 1995 for (long i = 0; i < Kernel->n_array; i++) { 1996 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 1997 continue; 1998 1999 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 2000 const ScopArrayInfo *SAI = 2001 ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id))); 2002 isl_id_free(Id); 2003 2004 if (SAI->getNumberOfDimensions() > 0) { 2005 Arg++; 2006 continue; 2007 } 2008 2009 Value *Val = &*Arg; 2010 2011 if (!gpu_array_is_read_only_scalar(&Prog->array[i])) { 2012 Type *TypePtr = SAI->getElementType()->getPointerTo(); 2013 Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr); 2014 Val = Builder.CreateLoad(TypedArgPtr); 2015 } 2016 2017 Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 2018 Builder.CreateStore(Val, Alloca); 2019 2020 Arg++; 2021 } 2022 } 2023 2024 void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) { 2025 auto *FN = Builder.GetInsertBlock()->getParent(); 2026 auto Arg = FN->arg_begin(); 2027 2028 bool StoredScalar = false; 2029 for (long i = 0; i < Kernel->n_array; i++) { 2030 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 2031 continue; 2032 2033 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 2034 const ScopArrayInfo *SAI = 2035 ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id))); 2036 isl_id_free(Id); 2037 2038 if (SAI->getNumberOfDimensions() > 0) { 2039 Arg++; 2040 continue; 2041 } 2042 2043 if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 2044 Arg++; 2045 continue; 2046 } 2047 2048 Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 2049 Value *ArgPtr = &*Arg; 2050 Type *TypePtr = SAI->getElementType()->getPointerTo(); 2051 Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr); 2052 Value *Val = Builder.CreateLoad(Alloca); 2053 Builder.CreateStore(Val, TypedArgPtr); 2054 StoredScalar = true; 2055 2056 Arg++; 2057 } 2058 2059 if (StoredScalar) 2060 /// In case more than one thread contains scalar stores, the generated 2061 /// code might be incorrect, if we only store at the end of the kernel. 2062 /// To support this case we need to store these scalars back at each 2063 /// memory store or at least before each kernel barrier. 2064 if (Kernel->n_block != 0 || Kernel->n_grid != 0) 2065 BuildSuccessful = 0; 2066 } 2067 2068 void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) { 2069 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 2070 2071 for (int i = 0; i < Kernel->n_var; ++i) { 2072 struct ppcg_kernel_var &Var = Kernel->var[i]; 2073 isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set); 2074 Type *EleTy = ScopArrayInfo::getFromId(isl::manage(Id))->getElementType(); 2075 2076 Type *ArrayTy = EleTy; 2077 SmallVector<const SCEV *, 4> Sizes; 2078 2079 Sizes.push_back(nullptr); 2080 for (unsigned int j = 1; j < Var.array->n_index; ++j) { 2081 isl_val *Val = isl_vec_get_element_val(Var.size, j); 2082 long Bound = isl_val_get_num_si(Val); 2083 isl_val_free(Val); 2084 Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound)); 2085 } 2086 2087 for (int j = Var.array->n_index - 1; j >= 0; --j) { 2088 isl_val *Val = isl_vec_get_element_val(Var.size, j); 2089 long Bound = isl_val_get_num_si(Val); 2090 isl_val_free(Val); 2091 ArrayTy = ArrayType::get(ArrayTy, Bound); 2092 } 2093 2094 const ScopArrayInfo *SAI; 2095 Value *Allocation; 2096 if (Var.type == ppcg_access_shared) { 2097 auto GlobalVar = new GlobalVariable( 2098 *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name, 2099 nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3); 2100 GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8); 2101 GlobalVar->setInitializer(Constant::getNullValue(ArrayTy)); 2102 2103 Allocation = GlobalVar; 2104 } else if (Var.type == ppcg_access_private) { 2105 Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array"); 2106 } else { 2107 llvm_unreachable("unknown variable type"); 2108 } 2109 SAI = 2110 S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array); 2111 Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr); 2112 IDToValue[Id] = Allocation; 2113 LocalArrays.push_back(Allocation); 2114 KernelIds.push_back(Id); 2115 IDToSAI[Id] = SAI; 2116 } 2117 } 2118 2119 void GPUNodeBuilder::createKernelFunction( 2120 ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues, 2121 SetVector<Function *> &SubtreeFunctions) { 2122 std::string Identifier = getKernelFuncName(Kernel->id); 2123 GPUModule.reset(new Module(Identifier, Builder.getContext())); 2124 2125 switch (Arch) { 2126 case GPUArch::NVPTX64: 2127 if (Runtime == GPURuntime::CUDA) 2128 GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda")); 2129 else if (Runtime == GPURuntime::OpenCL) 2130 GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl")); 2131 GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */)); 2132 break; 2133 case GPUArch::SPIR32: 2134 GPUModule->setTargetTriple(Triple::normalize("spir-unknown-unknown")); 2135 GPUModule->setDataLayout(computeSPIRDataLayout(false /* is64Bit */)); 2136 break; 2137 case GPUArch::SPIR64: 2138 GPUModule->setTargetTriple(Triple::normalize("spir64-unknown-unknown")); 2139 GPUModule->setDataLayout(computeSPIRDataLayout(true /* is64Bit */)); 2140 break; 2141 } 2142 2143 Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues); 2144 2145 BasicBlock *PrevBlock = Builder.GetInsertBlock(); 2146 auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN); 2147 2148 DT.addNewBlock(EntryBlock, PrevBlock); 2149 2150 Builder.SetInsertPoint(EntryBlock); 2151 Builder.CreateRetVoid(); 2152 Builder.SetInsertPoint(EntryBlock, EntryBlock->begin()); 2153 2154 ScopDetection::markFunctionAsInvalid(FN); 2155 2156 prepareKernelArguments(Kernel, FN); 2157 createKernelVariables(Kernel, FN); 2158 2159 switch (Arch) { 2160 case GPUArch::NVPTX64: 2161 insertKernelIntrinsics(Kernel); 2162 break; 2163 case GPUArch::SPIR32: 2164 case GPUArch::SPIR64: 2165 insertKernelCallsSPIR(Kernel); 2166 break; 2167 } 2168 } 2169 2170 std::string GPUNodeBuilder::createKernelASM() { 2171 llvm::Triple GPUTriple; 2172 2173 switch (Arch) { 2174 case GPUArch::NVPTX64: 2175 switch (Runtime) { 2176 case GPURuntime::CUDA: 2177 GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda")); 2178 break; 2179 case GPURuntime::OpenCL: 2180 GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl")); 2181 break; 2182 } 2183 break; 2184 case GPUArch::SPIR64: 2185 case GPUArch::SPIR32: 2186 std::string SPIRAssembly; 2187 raw_string_ostream IROstream(SPIRAssembly); 2188 IROstream << *GPUModule; 2189 IROstream.flush(); 2190 return SPIRAssembly; 2191 } 2192 2193 std::string ErrMsg; 2194 auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg); 2195 2196 if (!GPUTarget) { 2197 errs() << ErrMsg << "\n"; 2198 return ""; 2199 } 2200 2201 TargetOptions Options; 2202 Options.UnsafeFPMath = FastMath; 2203 2204 std::string subtarget; 2205 2206 switch (Arch) { 2207 case GPUArch::NVPTX64: 2208 subtarget = CudaVersion; 2209 break; 2210 case GPUArch::SPIR32: 2211 case GPUArch::SPIR64: 2212 llvm_unreachable("No subtarget for SPIR architecture"); 2213 } 2214 2215 std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine( 2216 GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>())); 2217 2218 SmallString<0> ASMString; 2219 raw_svector_ostream ASMStream(ASMString); 2220 llvm::legacy::PassManager PM; 2221 2222 PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis())); 2223 2224 if (TargetM->addPassesToEmitFile( 2225 PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) { 2226 errs() << "The target does not support generation of this file type!\n"; 2227 return ""; 2228 } 2229 2230 PM.run(*GPUModule); 2231 2232 return ASMStream.str(); 2233 } 2234 2235 std::string GPUNodeBuilder::finalizeKernelFunction() { 2236 2237 if (verifyModule(*GPUModule)) { 2238 DEBUG(dbgs() << "verifyModule failed on module:\n"; 2239 GPUModule->print(dbgs(), nullptr); dbgs() << "\n";); 2240 DEBUG(dbgs() << "verifyModule Error:\n"; 2241 verifyModule(*GPUModule, &dbgs());); 2242 2243 if (FailOnVerifyModuleFailure) 2244 llvm_unreachable("VerifyModule failed."); 2245 2246 BuildSuccessful = false; 2247 return ""; 2248 } 2249 2250 if (DumpKernelIR) 2251 outs() << *GPUModule << "\n"; 2252 2253 if (Arch != GPUArch::SPIR32 && Arch != GPUArch::SPIR64) { 2254 // Optimize module. 2255 llvm::legacy::PassManager OptPasses; 2256 PassManagerBuilder PassBuilder; 2257 PassBuilder.OptLevel = 3; 2258 PassBuilder.SizeLevel = 0; 2259 PassBuilder.populateModulePassManager(OptPasses); 2260 OptPasses.run(*GPUModule); 2261 } 2262 2263 std::string Assembly = createKernelASM(); 2264 2265 if (DumpKernelASM) 2266 outs() << Assembly << "\n"; 2267 2268 GPUModule.release(); 2269 KernelIDs.clear(); 2270 2271 return Assembly; 2272 } 2273 2274 namespace { 2275 class PPCGCodeGeneration : public ScopPass { 2276 public: 2277 static char ID; 2278 2279 GPURuntime Runtime = GPURuntime::CUDA; 2280 2281 GPUArch Architecture = GPUArch::NVPTX64; 2282 2283 /// The scop that is currently processed. 2284 Scop *S; 2285 2286 LoopInfo *LI; 2287 DominatorTree *DT; 2288 ScalarEvolution *SE; 2289 const DataLayout *DL; 2290 RegionInfo *RI; 2291 2292 PPCGCodeGeneration() : ScopPass(ID) {} 2293 2294 /// Construct compilation options for PPCG. 2295 /// 2296 /// @returns The compilation options. 2297 ppcg_options *createPPCGOptions() { 2298 auto DebugOptions = 2299 (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options)); 2300 auto Options = (ppcg_options *)malloc(sizeof(ppcg_options)); 2301 2302 DebugOptions->dump_schedule_constraints = false; 2303 DebugOptions->dump_schedule = false; 2304 DebugOptions->dump_final_schedule = false; 2305 DebugOptions->dump_sizes = false; 2306 DebugOptions->verbose = false; 2307 2308 Options->debug = DebugOptions; 2309 2310 Options->group_chains = false; 2311 Options->reschedule = true; 2312 Options->scale_tile_loops = false; 2313 Options->wrap = false; 2314 2315 Options->non_negative_parameters = false; 2316 Options->ctx = nullptr; 2317 Options->sizes = nullptr; 2318 2319 Options->tile = true; 2320 Options->tile_size = 32; 2321 2322 Options->isolate_full_tiles = false; 2323 2324 Options->use_private_memory = PrivateMemory; 2325 Options->use_shared_memory = SharedMemory; 2326 Options->max_shared_memory = 48 * 1024; 2327 2328 Options->target = PPCG_TARGET_CUDA; 2329 Options->openmp = false; 2330 Options->linearize_device_arrays = true; 2331 Options->allow_gnu_extensions = false; 2332 2333 Options->unroll_copy_shared = false; 2334 Options->unroll_gpu_tile = false; 2335 Options->live_range_reordering = true; 2336 2337 Options->live_range_reordering = true; 2338 Options->hybrid = false; 2339 Options->opencl_compiler_options = nullptr; 2340 Options->opencl_use_gpu = false; 2341 Options->opencl_n_include_file = 0; 2342 Options->opencl_include_files = nullptr; 2343 Options->opencl_print_kernel_types = false; 2344 Options->opencl_embed_kernel_code = false; 2345 2346 Options->save_schedule_file = nullptr; 2347 Options->load_schedule_file = nullptr; 2348 2349 return Options; 2350 } 2351 2352 /// Get a tagged access relation containing all accesses of type @p AccessTy. 2353 /// 2354 /// Instead of a normal access of the form: 2355 /// 2356 /// Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)] 2357 /// 2358 /// a tagged access has the form 2359 /// 2360 /// [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)] 2361 /// 2362 /// where 'id' is an additional space that references the memory access that 2363 /// triggered the access. 2364 /// 2365 /// @param AccessTy The type of the memory accesses to collect. 2366 /// 2367 /// @return The relation describing all tagged memory accesses. 2368 isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) { 2369 isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace()); 2370 2371 for (auto &Stmt : *S) 2372 for (auto &Acc : Stmt) 2373 if (Acc->getType() == AccessTy) { 2374 isl_map *Relation = Acc->getAccessRelation().release(); 2375 Relation = isl_map_intersect_domain(Relation, Stmt.getDomain()); 2376 2377 isl_space *Space = isl_map_get_space(Relation); 2378 Space = isl_space_range(Space); 2379 Space = isl_space_from_range(Space); 2380 Space = 2381 isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release()); 2382 isl_map *Universe = isl_map_universe(Space); 2383 Relation = isl_map_domain_product(Relation, Universe); 2384 Accesses = isl_union_map_add_map(Accesses, Relation); 2385 } 2386 2387 return Accesses; 2388 } 2389 2390 /// Get the set of all read accesses, tagged with the access id. 2391 /// 2392 /// @see getTaggedAccesses 2393 isl_union_map *getTaggedReads() { 2394 return getTaggedAccesses(MemoryAccess::READ); 2395 } 2396 2397 /// Get the set of all may (and must) accesses, tagged with the access id. 2398 /// 2399 /// @see getTaggedAccesses 2400 isl_union_map *getTaggedMayWrites() { 2401 return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE), 2402 getTaggedAccesses(MemoryAccess::MUST_WRITE)); 2403 } 2404 2405 /// Get the set of all must accesses, tagged with the access id. 2406 /// 2407 /// @see getTaggedAccesses 2408 isl_union_map *getTaggedMustWrites() { 2409 return getTaggedAccesses(MemoryAccess::MUST_WRITE); 2410 } 2411 2412 /// Collect parameter and array names as isl_ids. 2413 /// 2414 /// To reason about the different parameters and arrays used, ppcg requires 2415 /// a list of all isl_ids in use. As PPCG traditionally performs 2416 /// source-to-source compilation each of these isl_ids is mapped to the 2417 /// expression that represents it. As we do not have a corresponding 2418 /// expression in Polly, we just map each id to a 'zero' expression to match 2419 /// the data format that ppcg expects. 2420 /// 2421 /// @returns Retun a map from collected ids to 'zero' ast expressions. 2422 __isl_give isl_id_to_ast_expr *getNames() { 2423 auto *Names = isl_id_to_ast_expr_alloc( 2424 S->getIslCtx(), 2425 S->getNumParams() + std::distance(S->array_begin(), S->array_end())); 2426 auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx())); 2427 2428 for (const SCEV *P : S->parameters()) { 2429 isl_id *Id = S->getIdForParam(P); 2430 Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2431 } 2432 2433 for (auto &Array : S->arrays()) { 2434 auto Id = Array->getBasePtrId().release(); 2435 Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2436 } 2437 2438 isl_ast_expr_free(Zero); 2439 2440 return Names; 2441 } 2442 2443 /// Create a new PPCG scop from the current scop. 2444 /// 2445 /// The PPCG scop is initialized with data from the current polly::Scop. From 2446 /// this initial data, the data-dependences in the PPCG scop are initialized. 2447 /// We do not use Polly's dependence analysis for now, to ensure we match 2448 /// the PPCG default behaviour more closely. 2449 /// 2450 /// @returns A new ppcg scop. 2451 ppcg_scop *createPPCGScop() { 2452 MustKillsInfo KillsInfo = computeMustKillsInfo(*S); 2453 2454 auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop)); 2455 2456 PPCGScop->options = createPPCGOptions(); 2457 // enable live range reordering 2458 PPCGScop->options->live_range_reordering = 1; 2459 2460 PPCGScop->start = 0; 2461 PPCGScop->end = 0; 2462 2463 PPCGScop->context = S->getContext(); 2464 PPCGScop->domain = S->getDomains(); 2465 // TODO: investigate this further. PPCG calls collect_call_domains. 2466 PPCGScop->call = isl_union_set_from_set(S->getContext()); 2467 PPCGScop->tagged_reads = getTaggedReads(); 2468 PPCGScop->reads = S->getReads(); 2469 PPCGScop->live_in = nullptr; 2470 PPCGScop->tagged_may_writes = getTaggedMayWrites(); 2471 PPCGScop->may_writes = S->getWrites(); 2472 PPCGScop->tagged_must_writes = getTaggedMustWrites(); 2473 PPCGScop->must_writes = S->getMustWrites(); 2474 PPCGScop->live_out = nullptr; 2475 PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.take(); 2476 PPCGScop->must_kills = KillsInfo.MustKills.take(); 2477 2478 PPCGScop->tagger = nullptr; 2479 PPCGScop->independence = 2480 isl_union_map_empty(isl_set_get_space(PPCGScop->context)); 2481 PPCGScop->dep_flow = nullptr; 2482 PPCGScop->tagged_dep_flow = nullptr; 2483 PPCGScop->dep_false = nullptr; 2484 PPCGScop->dep_forced = nullptr; 2485 PPCGScop->dep_order = nullptr; 2486 PPCGScop->tagged_dep_order = nullptr; 2487 2488 PPCGScop->schedule = S->getScheduleTree(); 2489 // If we have something non-trivial to kill, add it to the schedule 2490 if (KillsInfo.KillsSchedule.get()) 2491 PPCGScop->schedule = isl_schedule_sequence( 2492 PPCGScop->schedule, KillsInfo.KillsSchedule.take()); 2493 2494 PPCGScop->names = getNames(); 2495 PPCGScop->pet = nullptr; 2496 2497 compute_tagger(PPCGScop); 2498 compute_dependences(PPCGScop); 2499 eliminate_dead_code(PPCGScop); 2500 2501 return PPCGScop; 2502 } 2503 2504 /// Collect the array accesses in a statement. 2505 /// 2506 /// @param Stmt The statement for which to collect the accesses. 2507 /// 2508 /// @returns A list of array accesses. 2509 gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) { 2510 gpu_stmt_access *Accesses = nullptr; 2511 2512 for (MemoryAccess *Acc : Stmt) { 2513 auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access); 2514 Access->read = Acc->isRead(); 2515 Access->write = Acc->isWrite(); 2516 Access->access = Acc->getAccessRelation().release(); 2517 isl_space *Space = isl_map_get_space(Access->access); 2518 Space = isl_space_range(Space); 2519 Space = isl_space_from_range(Space); 2520 Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release()); 2521 isl_map *Universe = isl_map_universe(Space); 2522 Access->tagged_access = 2523 isl_map_domain_product(Acc->getAccessRelation().release(), Universe); 2524 Access->exact_write = !Acc->isMayWrite(); 2525 Access->ref_id = Acc->getId().release(); 2526 Access->next = Accesses; 2527 Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions(); 2528 Accesses = Access; 2529 } 2530 2531 return Accesses; 2532 } 2533 2534 /// Collect the list of GPU statements. 2535 /// 2536 /// Each statement has an id, a pointer to the underlying data structure, 2537 /// as well as a list with all memory accesses. 2538 /// 2539 /// TODO: Initialize the list of memory accesses. 2540 /// 2541 /// @returns A linked-list of statements. 2542 gpu_stmt *getStatements() { 2543 gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt, 2544 std::distance(S->begin(), S->end())); 2545 2546 int i = 0; 2547 for (auto &Stmt : *S) { 2548 gpu_stmt *GPUStmt = &Stmts[i]; 2549 2550 GPUStmt->id = Stmt.getDomainId(); 2551 2552 // We use the pet stmt pointer to keep track of the Polly statements. 2553 GPUStmt->stmt = (pet_stmt *)&Stmt; 2554 GPUStmt->accesses = getStmtAccesses(Stmt); 2555 i++; 2556 } 2557 2558 return Stmts; 2559 } 2560 2561 /// Derive the extent of an array. 2562 /// 2563 /// The extent of an array is the set of elements that are within the 2564 /// accessed array. For the inner dimensions, the extent constraints are 2565 /// 0 and the size of the corresponding array dimension. For the first 2566 /// (outermost) dimension, the extent constraints are the minimal and maximal 2567 /// subscript value for the first dimension. 2568 /// 2569 /// @param Array The array to derive the extent for. 2570 /// 2571 /// @returns An isl_set describing the extent of the array. 2572 __isl_give isl_set *getExtent(ScopArrayInfo *Array) { 2573 unsigned NumDims = Array->getNumberOfDimensions(); 2574 isl_union_map *Accesses = S->getAccesses(); 2575 Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains()); 2576 Accesses = isl_union_map_detect_equalities(Accesses); 2577 isl_union_set *AccessUSet = isl_union_map_range(Accesses); 2578 AccessUSet = isl_union_set_coalesce(AccessUSet); 2579 AccessUSet = isl_union_set_detect_equalities(AccessUSet); 2580 AccessUSet = isl_union_set_coalesce(AccessUSet); 2581 2582 if (isl_union_set_is_empty(AccessUSet)) { 2583 isl_union_set_free(AccessUSet); 2584 return isl_set_empty(Array->getSpace().release()); 2585 } 2586 2587 if (Array->getNumberOfDimensions() == 0) { 2588 isl_union_set_free(AccessUSet); 2589 return isl_set_universe(Array->getSpace().release()); 2590 } 2591 2592 isl_set *AccessSet = 2593 isl_union_set_extract_set(AccessUSet, Array->getSpace().release()); 2594 2595 isl_union_set_free(AccessUSet); 2596 isl_local_space *LS = 2597 isl_local_space_from_space(Array->getSpace().release()); 2598 2599 isl_pw_aff *Val = 2600 isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0)); 2601 2602 isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0); 2603 isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0); 2604 OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in, 2605 isl_pw_aff_dim(Val, isl_dim_in)); 2606 OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in, 2607 isl_pw_aff_dim(Val, isl_dim_in)); 2608 OuterMin = isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, 2609 Array->getBasePtrId().release()); 2610 OuterMax = isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, 2611 Array->getBasePtrId().release()); 2612 2613 isl_set *Extent = isl_set_universe(Array->getSpace().release()); 2614 2615 Extent = isl_set_intersect( 2616 Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val))); 2617 Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val)); 2618 2619 for (unsigned i = 1; i < NumDims; ++i) 2620 Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0); 2621 2622 for (unsigned i = 0; i < NumDims; ++i) { 2623 isl_pw_aff *PwAff = 2624 const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i).release()); 2625 2626 // isl_pw_aff can be NULL for zero dimension. Only in the case of a 2627 // Fortran array will we have a legitimate dimension. 2628 if (!PwAff) { 2629 assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension"); 2630 continue; 2631 } 2632 2633 isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain( 2634 isl_local_space_from_space(Array->getSpace().release()), isl_dim_set, 2635 i)); 2636 PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in, 2637 isl_pw_aff_dim(Val, isl_dim_in)); 2638 PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in, 2639 isl_pw_aff_get_tuple_id(Val, isl_dim_in)); 2640 auto *Set = isl_pw_aff_gt_set(PwAff, Val); 2641 Extent = isl_set_intersect(Set, Extent); 2642 } 2643 2644 return Extent; 2645 } 2646 2647 /// Derive the bounds of an array. 2648 /// 2649 /// For the first dimension we derive the bound of the array from the extent 2650 /// of this dimension. For inner dimensions we obtain their size directly from 2651 /// ScopArrayInfo. 2652 /// 2653 /// @param PPCGArray The array to compute bounds for. 2654 /// @param Array The polly array from which to take the information. 2655 void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) { 2656 isl_pw_aff_list *BoundsList = 2657 isl_pw_aff_list_alloc(S->getIslCtx(), PPCGArray.n_index); 2658 std::vector<isl::pw_aff> PwAffs; 2659 2660 isl_space *AlignSpace = S->getParamSpace(); 2661 AlignSpace = isl_space_add_dims(AlignSpace, isl_dim_set, 1); 2662 2663 if (PPCGArray.n_index > 0) { 2664 if (isl_set_is_empty(PPCGArray.extent)) { 2665 isl_set *Dom = isl_set_copy(PPCGArray.extent); 2666 isl_local_space *LS = isl_local_space_from_space( 2667 isl_space_params(isl_set_get_space(Dom))); 2668 isl_set_free(Dom); 2669 isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS)); 2670 Zero = isl_pw_aff_align_params(Zero, isl_space_copy(AlignSpace)); 2671 PwAffs.push_back(isl::manage(isl_pw_aff_copy(Zero))); 2672 BoundsList = isl_pw_aff_list_insert(BoundsList, 0, Zero); 2673 } else { 2674 isl_set *Dom = isl_set_copy(PPCGArray.extent); 2675 Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1); 2676 isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0); 2677 isl_set_free(Dom); 2678 Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound)); 2679 isl_local_space *LS = 2680 isl_local_space_from_space(isl_set_get_space(Dom)); 2681 isl_aff *One = isl_aff_zero_on_domain(LS); 2682 One = isl_aff_add_constant_si(One, 1); 2683 Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One)); 2684 Bound = isl_pw_aff_gist(Bound, S->getContext()); 2685 Bound = isl_pw_aff_align_params(Bound, isl_space_copy(AlignSpace)); 2686 PwAffs.push_back(isl::manage(isl_pw_aff_copy(Bound))); 2687 BoundsList = isl_pw_aff_list_insert(BoundsList, 0, Bound); 2688 } 2689 } 2690 2691 for (unsigned i = 1; i < PPCGArray.n_index; ++i) { 2692 isl_pw_aff *Bound = Array->getDimensionSizePw(i).release(); 2693 auto LS = isl_pw_aff_get_domain_space(Bound); 2694 auto Aff = isl_multi_aff_zero(LS); 2695 Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff); 2696 Bound = isl_pw_aff_align_params(Bound, isl_space_copy(AlignSpace)); 2697 PwAffs.push_back(isl::manage(isl_pw_aff_copy(Bound))); 2698 BoundsList = isl_pw_aff_list_insert(BoundsList, i, Bound); 2699 } 2700 2701 isl_space_free(AlignSpace); 2702 isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent); 2703 2704 assert(BoundsSpace && "Unable to access space of array."); 2705 assert(BoundsList && "Unable to access list of bounds."); 2706 2707 PPCGArray.bound = 2708 isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList); 2709 assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly."); 2710 } 2711 2712 /// Create the arrays for @p PPCGProg. 2713 /// 2714 /// @param PPCGProg The program to compute the arrays for. 2715 void createArrays(gpu_prog *PPCGProg, 2716 const SmallVector<ScopArrayInfo *, 4> &ValidSAIs) { 2717 int i = 0; 2718 for (auto &Array : ValidSAIs) { 2719 std::string TypeName; 2720 raw_string_ostream OS(TypeName); 2721 2722 OS << *Array->getElementType(); 2723 TypeName = OS.str(); 2724 2725 gpu_array_info &PPCGArray = PPCGProg->array[i]; 2726 2727 PPCGArray.space = Array->getSpace().release(); 2728 PPCGArray.type = strdup(TypeName.c_str()); 2729 PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8; 2730 PPCGArray.name = strdup(Array->getName().c_str()); 2731 PPCGArray.extent = nullptr; 2732 PPCGArray.n_index = Array->getNumberOfDimensions(); 2733 PPCGArray.extent = getExtent(Array); 2734 PPCGArray.n_ref = 0; 2735 PPCGArray.refs = nullptr; 2736 PPCGArray.accessed = true; 2737 PPCGArray.read_only_scalar = 2738 Array->isReadOnly() && Array->getNumberOfDimensions() == 0; 2739 PPCGArray.has_compound_element = false; 2740 PPCGArray.local = false; 2741 PPCGArray.declare_local = false; 2742 PPCGArray.global = false; 2743 PPCGArray.linearize = false; 2744 PPCGArray.dep_order = nullptr; 2745 PPCGArray.user = Array; 2746 2747 PPCGArray.bound = nullptr; 2748 setArrayBounds(PPCGArray, Array); 2749 i++; 2750 2751 collect_references(PPCGProg, &PPCGArray); 2752 } 2753 } 2754 2755 /// Create an identity map between the arrays in the scop. 2756 /// 2757 /// @returns An identity map between the arrays in the scop. 2758 isl_union_map *getArrayIdentity() { 2759 isl_union_map *Maps = isl_union_map_empty(S->getParamSpace()); 2760 2761 for (auto &Array : S->arrays()) { 2762 isl_space *Space = Array->getSpace().release(); 2763 Space = isl_space_map_from_set(Space); 2764 isl_map *Identity = isl_map_identity(Space); 2765 Maps = isl_union_map_add_map(Maps, Identity); 2766 } 2767 2768 return Maps; 2769 } 2770 2771 /// Create a default-initialized PPCG GPU program. 2772 /// 2773 /// @returns A new gpu program description. 2774 gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) { 2775 2776 if (!PPCGScop) 2777 return nullptr; 2778 2779 auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog); 2780 2781 PPCGProg->ctx = S->getIslCtx(); 2782 PPCGProg->scop = PPCGScop; 2783 PPCGProg->context = isl_set_copy(PPCGScop->context); 2784 PPCGProg->read = isl_union_map_copy(PPCGScop->reads); 2785 PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes); 2786 PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes); 2787 PPCGProg->tagged_must_kill = 2788 isl_union_map_copy(PPCGScop->tagged_must_kills); 2789 PPCGProg->to_inner = getArrayIdentity(); 2790 PPCGProg->to_outer = getArrayIdentity(); 2791 // TODO: verify that this assignment is correct. 2792 PPCGProg->any_to_outer = nullptr; 2793 2794 // this needs to be set when live range reordering is enabled. 2795 // NOTE: I believe that is conservatively correct. I'm not sure 2796 // what the semantics of this is. 2797 // Quoting PPCG/gpu.h: "Order dependences on non-scalars." 2798 PPCGProg->array_order = 2799 isl_union_map_empty(isl_set_get_space(PPCGScop->context)); 2800 PPCGProg->n_stmts = std::distance(S->begin(), S->end()); 2801 PPCGProg->stmts = getStatements(); 2802 2803 // Only consider arrays that have a non-empty extent. 2804 // Otherwise, this will cause us to consider the following kinds of 2805 // empty arrays: 2806 // 1. Invariant loads that are represented by SAI objects. 2807 // 2. Arrays with statically known zero size. 2808 auto ValidSAIsRange = 2809 make_filter_range(S->arrays(), [this](ScopArrayInfo *SAI) -> bool { 2810 return !isl::manage(getExtent(SAI)).is_empty(); 2811 }); 2812 SmallVector<ScopArrayInfo *, 4> ValidSAIs(ValidSAIsRange.begin(), 2813 ValidSAIsRange.end()); 2814 2815 PPCGProg->n_array = 2816 ValidSAIs.size(); // std::distance(S->array_begin(), S->array_end()); 2817 PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info, 2818 PPCGProg->n_array); 2819 2820 createArrays(PPCGProg, ValidSAIs); 2821 2822 PPCGProg->may_persist = compute_may_persist(PPCGProg); 2823 return PPCGProg; 2824 } 2825 2826 struct PrintGPUUserData { 2827 struct cuda_info *CudaInfo; 2828 struct gpu_prog *PPCGProg; 2829 std::vector<ppcg_kernel *> Kernels; 2830 }; 2831 2832 /// Print a user statement node in the host code. 2833 /// 2834 /// We use ppcg's printing facilities to print the actual statement and 2835 /// additionally build up a list of all kernels that are encountered in the 2836 /// host ast. 2837 /// 2838 /// @param P The printer to print to 2839 /// @param Options The printing options to use 2840 /// @param Node The node to print 2841 /// @param User A user pointer to carry additional data. This pointer is 2842 /// expected to be of type PrintGPUUserData. 2843 /// 2844 /// @returns A printer to which the output has been printed. 2845 static __isl_give isl_printer * 2846 printHostUser(__isl_take isl_printer *P, 2847 __isl_take isl_ast_print_options *Options, 2848 __isl_take isl_ast_node *Node, void *User) { 2849 auto Data = (struct PrintGPUUserData *)User; 2850 auto Id = isl_ast_node_get_annotation(Node); 2851 2852 if (Id) { 2853 bool IsUser = !strcmp(isl_id_get_name(Id), "user"); 2854 2855 // If this is a user statement, format it ourselves as ppcg would 2856 // otherwise try to call pet functionality that is not available in 2857 // Polly. 2858 if (IsUser) { 2859 P = isl_printer_start_line(P); 2860 P = isl_printer_print_ast_node(P, Node); 2861 P = isl_printer_end_line(P); 2862 isl_id_free(Id); 2863 isl_ast_print_options_free(Options); 2864 return P; 2865 } 2866 2867 auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id); 2868 isl_id_free(Id); 2869 Data->Kernels.push_back(Kernel); 2870 } 2871 2872 return print_host_user(P, Options, Node, User); 2873 } 2874 2875 /// Print C code corresponding to the control flow in @p Kernel. 2876 /// 2877 /// @param Kernel The kernel to print 2878 void printKernel(ppcg_kernel *Kernel) { 2879 auto *P = isl_printer_to_str(S->getIslCtx()); 2880 P = isl_printer_set_output_format(P, ISL_FORMAT_C); 2881 auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 2882 P = isl_ast_node_print(Kernel->tree, P, Options); 2883 char *String = isl_printer_get_str(P); 2884 printf("%s\n", String); 2885 free(String); 2886 isl_printer_free(P); 2887 } 2888 2889 /// Print C code corresponding to the GPU code described by @p Tree. 2890 /// 2891 /// @param Tree An AST describing GPU code 2892 /// @param PPCGProg The PPCG program from which @Tree has been constructed. 2893 void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) { 2894 auto *P = isl_printer_to_str(S->getIslCtx()); 2895 P = isl_printer_set_output_format(P, ISL_FORMAT_C); 2896 2897 PrintGPUUserData Data; 2898 Data.PPCGProg = PPCGProg; 2899 2900 auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 2901 Options = 2902 isl_ast_print_options_set_print_user(Options, printHostUser, &Data); 2903 P = isl_ast_node_print(Tree, P, Options); 2904 char *String = isl_printer_get_str(P); 2905 printf("# host\n"); 2906 printf("%s\n", String); 2907 free(String); 2908 isl_printer_free(P); 2909 2910 for (auto Kernel : Data.Kernels) { 2911 printf("# kernel%d\n", Kernel->id); 2912 printKernel(Kernel); 2913 } 2914 } 2915 2916 // Generate a GPU program using PPCG. 2917 // 2918 // GPU mapping consists of multiple steps: 2919 // 2920 // 1) Compute new schedule for the program. 2921 // 2) Map schedule to GPU (TODO) 2922 // 3) Generate code for new schedule (TODO) 2923 // 2924 // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer 2925 // is mostly CPU specific. Instead, we use PPCG's GPU code generation 2926 // strategy directly from this pass. 2927 gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) { 2928 2929 auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen); 2930 2931 PPCGGen->ctx = S->getIslCtx(); 2932 PPCGGen->options = PPCGScop->options; 2933 PPCGGen->print = nullptr; 2934 PPCGGen->print_user = nullptr; 2935 PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt; 2936 PPCGGen->prog = PPCGProg; 2937 PPCGGen->tree = nullptr; 2938 PPCGGen->types.n = 0; 2939 PPCGGen->types.name = nullptr; 2940 PPCGGen->sizes = nullptr; 2941 PPCGGen->used_sizes = nullptr; 2942 PPCGGen->kernel_id = 0; 2943 2944 // Set scheduling strategy to same strategy PPCG is using. 2945 isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true); 2946 isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true); 2947 isl_options_set_schedule_whole_component(PPCGGen->ctx, false); 2948 2949 isl_schedule *Schedule = get_schedule(PPCGGen); 2950 2951 int has_permutable = has_any_permutable_node(Schedule); 2952 2953 if (!has_permutable || has_permutable < 0) { 2954 Schedule = isl_schedule_free(Schedule); 2955 } else { 2956 Schedule = map_to_device(PPCGGen, Schedule); 2957 PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule)); 2958 } 2959 2960 if (DumpSchedule) { 2961 isl_printer *P = isl_printer_to_str(S->getIslCtx()); 2962 P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK); 2963 P = isl_printer_print_str(P, "Schedule\n"); 2964 P = isl_printer_print_str(P, "========\n"); 2965 if (Schedule) 2966 P = isl_printer_print_schedule(P, Schedule); 2967 else 2968 P = isl_printer_print_str(P, "No schedule found\n"); 2969 2970 printf("%s\n", isl_printer_get_str(P)); 2971 isl_printer_free(P); 2972 } 2973 2974 if (DumpCode) { 2975 printf("Code\n"); 2976 printf("====\n"); 2977 if (PPCGGen->tree) 2978 printGPUTree(PPCGGen->tree, PPCGProg); 2979 else 2980 printf("No code generated\n"); 2981 } 2982 2983 isl_schedule_free(Schedule); 2984 2985 return PPCGGen; 2986 } 2987 2988 /// Free gpu_gen structure. 2989 /// 2990 /// @param PPCGGen The ppcg_gen object to free. 2991 void freePPCGGen(gpu_gen *PPCGGen) { 2992 isl_ast_node_free(PPCGGen->tree); 2993 isl_union_map_free(PPCGGen->sizes); 2994 isl_union_map_free(PPCGGen->used_sizes); 2995 free(PPCGGen); 2996 } 2997 2998 /// Free the options in the ppcg scop structure. 2999 /// 3000 /// ppcg is not freeing these options for us. To avoid leaks we do this 3001 /// ourselves. 3002 /// 3003 /// @param PPCGScop The scop referencing the options to free. 3004 void freeOptions(ppcg_scop *PPCGScop) { 3005 free(PPCGScop->options->debug); 3006 PPCGScop->options->debug = nullptr; 3007 free(PPCGScop->options); 3008 PPCGScop->options = nullptr; 3009 } 3010 3011 /// Approximate the number of points in the set. 3012 /// 3013 /// This function returns an ast expression that overapproximates the number 3014 /// of points in an isl set through the rectangular hull surrounding this set. 3015 /// 3016 /// @param Set The set to count. 3017 /// @param Build The isl ast build object to use for creating the ast 3018 /// expression. 3019 /// 3020 /// @returns An approximation of the number of points in the set. 3021 __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set, 3022 __isl_keep isl_ast_build *Build) { 3023 3024 isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1); 3025 auto *Expr = isl_ast_expr_from_val(isl_val_copy(One)); 3026 3027 isl_space *Space = isl_set_get_space(Set); 3028 Space = isl_space_params(Space); 3029 auto *Univ = isl_set_universe(Space); 3030 isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One); 3031 3032 for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) { 3033 isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i); 3034 isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i); 3035 isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min); 3036 DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff)); 3037 auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize); 3038 Expr = isl_ast_expr_mul(Expr, DimSizeExpr); 3039 } 3040 3041 isl_set_free(Set); 3042 isl_pw_aff_free(OneAff); 3043 3044 return Expr; 3045 } 3046 3047 /// Approximate a number of dynamic instructions executed by a given 3048 /// statement. 3049 /// 3050 /// @param Stmt The statement for which to compute the number of dynamic 3051 /// instructions. 3052 /// @param Build The isl ast build object to use for creating the ast 3053 /// expression. 3054 /// @returns An approximation of the number of dynamic instructions executed 3055 /// by @p Stmt. 3056 __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt, 3057 __isl_keep isl_ast_build *Build) { 3058 auto Iterations = approxPointsInSet(Stmt.getDomain(), Build); 3059 3060 long InstCount = 0; 3061 3062 if (Stmt.isBlockStmt()) { 3063 auto *BB = Stmt.getBasicBlock(); 3064 InstCount = std::distance(BB->begin(), BB->end()); 3065 } else { 3066 auto *R = Stmt.getRegion(); 3067 3068 for (auto *BB : R->blocks()) { 3069 InstCount += std::distance(BB->begin(), BB->end()); 3070 } 3071 } 3072 3073 isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount); 3074 auto *InstExpr = isl_ast_expr_from_val(InstVal); 3075 return isl_ast_expr_mul(InstExpr, Iterations); 3076 } 3077 3078 /// Approximate dynamic instructions executed in scop. 3079 /// 3080 /// @param S The scop for which to approximate dynamic instructions. 3081 /// @param Build The isl ast build object to use for creating the ast 3082 /// expression. 3083 /// @returns An approximation of the number of dynamic instructions executed 3084 /// in @p S. 3085 __isl_give isl_ast_expr * 3086 getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) { 3087 isl_ast_expr *Instructions; 3088 3089 isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0); 3090 Instructions = isl_ast_expr_from_val(Zero); 3091 3092 for (ScopStmt &Stmt : S) { 3093 isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build); 3094 Instructions = isl_ast_expr_add(Instructions, StmtInstructions); 3095 } 3096 return Instructions; 3097 } 3098 3099 /// Create a check that ensures sufficient compute in scop. 3100 /// 3101 /// @param S The scop for which to ensure sufficient compute. 3102 /// @param Build The isl ast build object to use for creating the ast 3103 /// expression. 3104 /// @returns An expression that evaluates to TRUE in case of sufficient 3105 /// compute and to FALSE, otherwise. 3106 __isl_give isl_ast_expr * 3107 createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) { 3108 auto Iterations = getNumberOfIterations(S, Build); 3109 auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute); 3110 auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal); 3111 return isl_ast_expr_ge(Iterations, MinComputeExpr); 3112 } 3113 3114 /// Check if the basic block contains a function we cannot codegen for GPU 3115 /// kernels. 3116 /// 3117 /// If this basic block does something with a `Function` other than calling 3118 /// a function that we support in a kernel, return true. 3119 bool containsInvalidKernelFunctionInBlock(const BasicBlock *BB) { 3120 for (const Instruction &Inst : *BB) { 3121 const CallInst *Call = dyn_cast<CallInst>(&Inst); 3122 if (Call && isValidFunctionInKernel(Call->getCalledFunction())) { 3123 continue; 3124 } 3125 3126 for (Value *SrcVal : Inst.operands()) { 3127 PointerType *p = dyn_cast<PointerType>(SrcVal->getType()); 3128 if (!p) 3129 continue; 3130 if (isa<FunctionType>(p->getElementType())) 3131 return true; 3132 } 3133 } 3134 return false; 3135 } 3136 3137 /// Return whether the Scop S uses functions in a way that we do not support. 3138 bool containsInvalidKernelFunction(const Scop &S) { 3139 for (auto &Stmt : S) { 3140 if (Stmt.isBlockStmt()) { 3141 if (containsInvalidKernelFunctionInBlock(Stmt.getBasicBlock())) 3142 return true; 3143 } else { 3144 assert(Stmt.isRegionStmt() && 3145 "Stmt was neither block nor region statement"); 3146 for (const BasicBlock *BB : Stmt.getRegion()->blocks()) 3147 if (containsInvalidKernelFunctionInBlock(BB)) 3148 return true; 3149 } 3150 } 3151 return false; 3152 } 3153 3154 /// Generate code for a given GPU AST described by @p Root. 3155 /// 3156 /// @param Root An isl_ast_node pointing to the root of the GPU AST. 3157 /// @param Prog The GPU Program to generate code for. 3158 void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) { 3159 ScopAnnotator Annotator; 3160 Annotator.buildAliasScopes(*S); 3161 3162 Region *R = &S->getRegion(); 3163 3164 simplifyRegion(R, DT, LI, RI); 3165 3166 BasicBlock *EnteringBB = R->getEnteringBlock(); 3167 3168 PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator); 3169 3170 // Only build the run-time condition and parameters _after_ having 3171 // introduced the conditional branch. This is important as the conditional 3172 // branch will guard the original scop from new induction variables that 3173 // the SCEVExpander may introduce while code generating the parameters and 3174 // which may introduce scalar dependences that prevent us from correctly 3175 // code generating this scop. 3176 BBPair StartExitBlocks; 3177 BranchInst *CondBr = nullptr; 3178 std::tie(StartExitBlocks, CondBr) = 3179 executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI); 3180 BasicBlock *StartBlock = std::get<0>(StartExitBlocks); 3181 3182 assert(CondBr && "CondBr not initialized by executeScopConditionally"); 3183 3184 GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S, 3185 StartBlock, Prog, Runtime, Architecture); 3186 3187 // TODO: Handle LICM 3188 auto SplitBlock = StartBlock->getSinglePredecessor(); 3189 Builder.SetInsertPoint(SplitBlock->getTerminator()); 3190 NodeBuilder.addParameters(S->getContext()); 3191 3192 isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx()); 3193 isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build); 3194 isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build); 3195 Condition = isl_ast_expr_and(Condition, SufficientCompute); 3196 isl_ast_build_free(Build); 3197 3198 // preload invariant loads. Note: This should happen before the RTC 3199 // because the RTC may depend on values that are invariant load hoisted. 3200 if (!NodeBuilder.preloadInvariantLoads()) 3201 report_fatal_error("preloading invariant loads failed in function: " + 3202 S->getFunction().getName() + 3203 " | Scop Region: " + S->getNameStr()); 3204 3205 Value *RTC = NodeBuilder.createRTC(Condition); 3206 Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC); 3207 3208 Builder.SetInsertPoint(&*StartBlock->begin()); 3209 3210 NodeBuilder.create(Root); 3211 3212 /// In case a sequential kernel has more surrounding loops as any parallel 3213 /// kernel, the SCoP is probably mostly sequential. Hence, there is no 3214 /// point in running it on a GPU. 3215 if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel) 3216 CondBr->setOperand(0, Builder.getFalse()); 3217 3218 if (!NodeBuilder.BuildSuccessful) 3219 CondBr->setOperand(0, Builder.getFalse()); 3220 } 3221 3222 bool runOnScop(Scop &CurrentScop) override { 3223 S = &CurrentScop; 3224 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 3225 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 3226 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 3227 DL = &S->getRegion().getEntry()->getModule()->getDataLayout(); 3228 RI = &getAnalysis<RegionInfoPass>().getRegionInfo(); 3229 3230 // We currently do not support functions other than intrinsics inside 3231 // kernels, as code generation will need to offload function calls to the 3232 // kernel. This may lead to a kernel trying to call a function on the host. 3233 // This also allows us to prevent codegen from trying to take the 3234 // address of an intrinsic function to send to the kernel. 3235 if (containsInvalidKernelFunction(CurrentScop)) { 3236 DEBUG( 3237 dbgs() 3238 << "Scop contains function which cannot be materialised in a GPU " 3239 "kernel. Bailing out.\n";); 3240 return false; 3241 } 3242 3243 auto PPCGScop = createPPCGScop(); 3244 auto PPCGProg = createPPCGProg(PPCGScop); 3245 auto PPCGGen = generateGPU(PPCGScop, PPCGProg); 3246 3247 if (PPCGGen->tree) { 3248 generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg); 3249 CurrentScop.markAsToBeSkipped(); 3250 } 3251 3252 freeOptions(PPCGScop); 3253 freePPCGGen(PPCGGen); 3254 gpu_prog_free(PPCGProg); 3255 ppcg_scop_free(PPCGScop); 3256 3257 return true; 3258 } 3259 3260 void printScop(raw_ostream &, Scop &) const override {} 3261 3262 void getAnalysisUsage(AnalysisUsage &AU) const override { 3263 AU.addRequired<DominatorTreeWrapperPass>(); 3264 AU.addRequired<RegionInfoPass>(); 3265 AU.addRequired<ScalarEvolutionWrapperPass>(); 3266 AU.addRequired<ScopDetectionWrapperPass>(); 3267 AU.addRequired<ScopInfoRegionPass>(); 3268 AU.addRequired<LoopInfoWrapperPass>(); 3269 3270 AU.addPreserved<AAResultsWrapperPass>(); 3271 AU.addPreserved<BasicAAWrapperPass>(); 3272 AU.addPreserved<LoopInfoWrapperPass>(); 3273 AU.addPreserved<DominatorTreeWrapperPass>(); 3274 AU.addPreserved<GlobalsAAWrapperPass>(); 3275 AU.addPreserved<ScopDetectionWrapperPass>(); 3276 AU.addPreserved<ScalarEvolutionWrapperPass>(); 3277 AU.addPreserved<SCEVAAWrapperPass>(); 3278 3279 // FIXME: We do not yet add regions for the newly generated code to the 3280 // region tree. 3281 AU.addPreserved<RegionInfoPass>(); 3282 AU.addPreserved<ScopInfoRegionPass>(); 3283 } 3284 }; 3285 } // namespace 3286 3287 char PPCGCodeGeneration::ID = 1; 3288 3289 Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) { 3290 PPCGCodeGeneration *generator = new PPCGCodeGeneration(); 3291 generator->Runtime = Runtime; 3292 generator->Architecture = Arch; 3293 return generator; 3294 } 3295 3296 INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg", 3297 "Polly - Apply PPCG translation to SCOP", false, false) 3298 INITIALIZE_PASS_DEPENDENCY(DependenceInfo); 3299 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 3300 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 3301 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 3302 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 3303 INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass); 3304 INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg", 3305 "Polly - Apply PPCG translation to SCOP", false, false) 3306