1 //===-- IPO/OpenMPOpt.cpp - Collection of OpenMP specific optimizations ---===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // OpenMP specific optimizations: 10 // 11 // - Deduplication of runtime calls, e.g., omp_get_thread_num. 12 // - Replacing globalized device memory with stack memory. 13 // - Replacing globalized device memory with shared memory. 14 // - Parallel region merging. 15 // - Transforming generic-mode device kernels to SPMD mode. 16 // - Specializing the state machine for generic-mode device kernels. 17 // 18 //===----------------------------------------------------------------------===// 19 20 #include "llvm/Transforms/IPO/OpenMPOpt.h" 21 22 #include "llvm/ADT/EnumeratedArray.h" 23 #include "llvm/ADT/PostOrderIterator.h" 24 #include "llvm/ADT/SetVector.h" 25 #include "llvm/ADT/Statistic.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/Analysis/CallGraph.h" 28 #include "llvm/Analysis/CallGraphSCCPass.h" 29 #include "llvm/Analysis/MemoryLocation.h" 30 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 31 #include "llvm/Analysis/ValueTracking.h" 32 #include "llvm/Frontend/OpenMP/OMPConstants.h" 33 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 34 #include "llvm/IR/Assumptions.h" 35 #include "llvm/IR/Constants.h" 36 #include "llvm/IR/DiagnosticInfo.h" 37 #include "llvm/IR/GlobalValue.h" 38 #include "llvm/IR/GlobalVariable.h" 39 #include "llvm/IR/Instruction.h" 40 #include "llvm/IR/Instructions.h" 41 #include "llvm/IR/IntrinsicInst.h" 42 #include "llvm/IR/IntrinsicsAMDGPU.h" 43 #include "llvm/IR/IntrinsicsNVPTX.h" 44 #include "llvm/IR/LLVMContext.h" 45 #include "llvm/InitializePasses.h" 46 #include "llvm/Support/CommandLine.h" 47 #include "llvm/Support/Debug.h" 48 #include "llvm/Transforms/IPO.h" 49 #include "llvm/Transforms/IPO/Attributor.h" 50 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 51 #include "llvm/Transforms/Utils/CallGraphUpdater.h" 52 #include "llvm/Transforms/Utils/CodeExtractor.h" 53 54 #include <algorithm> 55 56 using namespace llvm; 57 using namespace omp; 58 59 #define DEBUG_TYPE "openmp-opt" 60 61 static cl::opt<bool> DisableOpenMPOptimizations( 62 "openmp-opt-disable", cl::ZeroOrMore, 63 cl::desc("Disable OpenMP specific optimizations."), cl::Hidden, 64 cl::init(false)); 65 66 static cl::opt<bool> EnableParallelRegionMerging( 67 "openmp-opt-enable-merging", cl::ZeroOrMore, 68 cl::desc("Enable the OpenMP region merging optimization."), cl::Hidden, 69 cl::init(false)); 70 71 static cl::opt<bool> 72 DisableInternalization("openmp-opt-disable-internalization", cl::ZeroOrMore, 73 cl::desc("Disable function internalization."), 74 cl::Hidden, cl::init(false)); 75 76 static cl::opt<bool> PrintICVValues("openmp-print-icv-values", cl::init(false), 77 cl::Hidden); 78 static cl::opt<bool> PrintOpenMPKernels("openmp-print-gpu-kernels", 79 cl::init(false), cl::Hidden); 80 81 static cl::opt<bool> HideMemoryTransferLatency( 82 "openmp-hide-memory-transfer-latency", 83 cl::desc("[WIP] Tries to hide the latency of host to device memory" 84 " transfers"), 85 cl::Hidden, cl::init(false)); 86 87 static cl::opt<bool> DisableOpenMPOptDeglobalization( 88 "openmp-opt-disable-deglobalization", cl::ZeroOrMore, 89 cl::desc("Disable OpenMP optimizations involving deglobalization."), 90 cl::Hidden, cl::init(false)); 91 92 static cl::opt<bool> DisableOpenMPOptSPMDization( 93 "openmp-opt-disable-spmdization", cl::ZeroOrMore, 94 cl::desc("Disable OpenMP optimizations involving SPMD-ization."), 95 cl::Hidden, cl::init(false)); 96 97 static cl::opt<bool> DisableOpenMPOptFolding( 98 "openmp-opt-disable-folding", cl::ZeroOrMore, 99 cl::desc("Disable OpenMP optimizations involving folding."), cl::Hidden, 100 cl::init(false)); 101 102 static cl::opt<bool> DisableOpenMPOptStateMachineRewrite( 103 "openmp-opt-disable-state-machine-rewrite", cl::ZeroOrMore, 104 cl::desc("Disable OpenMP optimizations that replace the state machine."), 105 cl::Hidden, cl::init(false)); 106 107 static cl::opt<bool> DisableOpenMPOptBarrierElimination( 108 "openmp-opt-disable-barrier-elimination", cl::ZeroOrMore, 109 cl::desc("Disable OpenMP optimizations that eliminate barriers."), 110 cl::Hidden, cl::init(false)); 111 112 static cl::opt<bool> PrintModuleAfterOptimizations( 113 "openmp-opt-print-module-after", cl::ZeroOrMore, 114 cl::desc("Print the current module after OpenMP optimizations."), 115 cl::Hidden, cl::init(false)); 116 117 static cl::opt<bool> PrintModuleBeforeOptimizations( 118 "openmp-opt-print-module-before", cl::ZeroOrMore, 119 cl::desc("Print the current module before OpenMP optimizations."), 120 cl::Hidden, cl::init(false)); 121 122 static cl::opt<bool> AlwaysInlineDeviceFunctions( 123 "openmp-opt-inline-device", cl::ZeroOrMore, 124 cl::desc("Inline all applicible functions on the device."), cl::Hidden, 125 cl::init(false)); 126 127 static cl::opt<bool> 128 EnableVerboseRemarks("openmp-opt-verbose-remarks", cl::ZeroOrMore, 129 cl::desc("Enables more verbose remarks."), cl::Hidden, 130 cl::init(false)); 131 132 static cl::opt<unsigned> 133 SetFixpointIterations("openmp-opt-max-iterations", cl::Hidden, 134 cl::desc("Maximal number of attributor iterations."), 135 cl::init(256)); 136 137 static cl::opt<unsigned> 138 SharedMemoryLimit("openmp-opt-shared-limit", cl::Hidden, 139 cl::desc("Maximum amount of shared memory to use."), 140 cl::init(std::numeric_limits<unsigned>::max())); 141 142 STATISTIC(NumOpenMPRuntimeCallsDeduplicated, 143 "Number of OpenMP runtime calls deduplicated"); 144 STATISTIC(NumOpenMPParallelRegionsDeleted, 145 "Number of OpenMP parallel regions deleted"); 146 STATISTIC(NumOpenMPRuntimeFunctionsIdentified, 147 "Number of OpenMP runtime functions identified"); 148 STATISTIC(NumOpenMPRuntimeFunctionUsesIdentified, 149 "Number of OpenMP runtime function uses identified"); 150 STATISTIC(NumOpenMPTargetRegionKernels, 151 "Number of OpenMP target region entry points (=kernels) identified"); 152 STATISTIC(NumOpenMPTargetRegionKernelsSPMD, 153 "Number of OpenMP target region entry points (=kernels) executed in " 154 "SPMD-mode instead of generic-mode"); 155 STATISTIC(NumOpenMPTargetRegionKernelsWithoutStateMachine, 156 "Number of OpenMP target region entry points (=kernels) executed in " 157 "generic-mode without a state machines"); 158 STATISTIC(NumOpenMPTargetRegionKernelsCustomStateMachineWithFallback, 159 "Number of OpenMP target region entry points (=kernels) executed in " 160 "generic-mode with customized state machines with fallback"); 161 STATISTIC(NumOpenMPTargetRegionKernelsCustomStateMachineWithoutFallback, 162 "Number of OpenMP target region entry points (=kernels) executed in " 163 "generic-mode with customized state machines without fallback"); 164 STATISTIC( 165 NumOpenMPParallelRegionsReplacedInGPUStateMachine, 166 "Number of OpenMP parallel regions replaced with ID in GPU state machines"); 167 STATISTIC(NumOpenMPParallelRegionsMerged, 168 "Number of OpenMP parallel regions merged"); 169 STATISTIC(NumBytesMovedToSharedMemory, 170 "Amount of memory pushed to shared memory"); 171 STATISTIC(NumBarriersEliminated, "Number of redundant barriers eliminated"); 172 173 #if !defined(NDEBUG) 174 static constexpr auto TAG = "[" DEBUG_TYPE "]"; 175 #endif 176 177 namespace { 178 179 struct AAHeapToShared; 180 181 struct AAICVTracker; 182 183 /// OpenMP specific information. For now, stores RFIs and ICVs also needed for 184 /// Attributor runs. 185 struct OMPInformationCache : public InformationCache { 186 OMPInformationCache(Module &M, AnalysisGetter &AG, 187 BumpPtrAllocator &Allocator, SetVector<Function *> &CGSCC, 188 KernelSet &Kernels) 189 : InformationCache(M, AG, Allocator, &CGSCC), OMPBuilder(M), 190 Kernels(Kernels) { 191 192 OMPBuilder.initialize(); 193 initializeRuntimeFunctions(); 194 initializeInternalControlVars(); 195 } 196 197 /// Generic information that describes an internal control variable. 198 struct InternalControlVarInfo { 199 /// The kind, as described by InternalControlVar enum. 200 InternalControlVar Kind; 201 202 /// The name of the ICV. 203 StringRef Name; 204 205 /// Environment variable associated with this ICV. 206 StringRef EnvVarName; 207 208 /// Initial value kind. 209 ICVInitValue InitKind; 210 211 /// Initial value. 212 ConstantInt *InitValue; 213 214 /// Setter RTL function associated with this ICV. 215 RuntimeFunction Setter; 216 217 /// Getter RTL function associated with this ICV. 218 RuntimeFunction Getter; 219 220 /// RTL Function corresponding to the override clause of this ICV 221 RuntimeFunction Clause; 222 }; 223 224 /// Generic information that describes a runtime function 225 struct RuntimeFunctionInfo { 226 227 /// The kind, as described by the RuntimeFunction enum. 228 RuntimeFunction Kind; 229 230 /// The name of the function. 231 StringRef Name; 232 233 /// Flag to indicate a variadic function. 234 bool IsVarArg; 235 236 /// The return type of the function. 237 Type *ReturnType; 238 239 /// The argument types of the function. 240 SmallVector<Type *, 8> ArgumentTypes; 241 242 /// The declaration if available. 243 Function *Declaration = nullptr; 244 245 /// Uses of this runtime function per function containing the use. 246 using UseVector = SmallVector<Use *, 16>; 247 248 /// Clear UsesMap for runtime function. 249 void clearUsesMap() { UsesMap.clear(); } 250 251 /// Boolean conversion that is true if the runtime function was found. 252 operator bool() const { return Declaration; } 253 254 /// Return the vector of uses in function \p F. 255 UseVector &getOrCreateUseVector(Function *F) { 256 std::shared_ptr<UseVector> &UV = UsesMap[F]; 257 if (!UV) 258 UV = std::make_shared<UseVector>(); 259 return *UV; 260 } 261 262 /// Return the vector of uses in function \p F or `nullptr` if there are 263 /// none. 264 const UseVector *getUseVector(Function &F) const { 265 auto I = UsesMap.find(&F); 266 if (I != UsesMap.end()) 267 return I->second.get(); 268 return nullptr; 269 } 270 271 /// Return how many functions contain uses of this runtime function. 272 size_t getNumFunctionsWithUses() const { return UsesMap.size(); } 273 274 /// Return the number of arguments (or the minimal number for variadic 275 /// functions). 276 size_t getNumArgs() const { return ArgumentTypes.size(); } 277 278 /// Run the callback \p CB on each use and forget the use if the result is 279 /// true. The callback will be fed the function in which the use was 280 /// encountered as second argument. 281 void foreachUse(SmallVectorImpl<Function *> &SCC, 282 function_ref<bool(Use &, Function &)> CB) { 283 for (Function *F : SCC) 284 foreachUse(CB, F); 285 } 286 287 /// Run the callback \p CB on each use within the function \p F and forget 288 /// the use if the result is true. 289 void foreachUse(function_ref<bool(Use &, Function &)> CB, Function *F) { 290 SmallVector<unsigned, 8> ToBeDeleted; 291 ToBeDeleted.clear(); 292 293 unsigned Idx = 0; 294 UseVector &UV = getOrCreateUseVector(F); 295 296 for (Use *U : UV) { 297 if (CB(*U, *F)) 298 ToBeDeleted.push_back(Idx); 299 ++Idx; 300 } 301 302 // Remove the to-be-deleted indices in reverse order as prior 303 // modifications will not modify the smaller indices. 304 while (!ToBeDeleted.empty()) { 305 unsigned Idx = ToBeDeleted.pop_back_val(); 306 UV[Idx] = UV.back(); 307 UV.pop_back(); 308 } 309 } 310 311 private: 312 /// Map from functions to all uses of this runtime function contained in 313 /// them. 314 DenseMap<Function *, std::shared_ptr<UseVector>> UsesMap; 315 316 public: 317 /// Iterators for the uses of this runtime function. 318 decltype(UsesMap)::iterator begin() { return UsesMap.begin(); } 319 decltype(UsesMap)::iterator end() { return UsesMap.end(); } 320 }; 321 322 /// An OpenMP-IR-Builder instance 323 OpenMPIRBuilder OMPBuilder; 324 325 /// Map from runtime function kind to the runtime function description. 326 EnumeratedArray<RuntimeFunctionInfo, RuntimeFunction, 327 RuntimeFunction::OMPRTL___last> 328 RFIs; 329 330 /// Map from function declarations/definitions to their runtime enum type. 331 DenseMap<Function *, RuntimeFunction> RuntimeFunctionIDMap; 332 333 /// Map from ICV kind to the ICV description. 334 EnumeratedArray<InternalControlVarInfo, InternalControlVar, 335 InternalControlVar::ICV___last> 336 ICVs; 337 338 /// Helper to initialize all internal control variable information for those 339 /// defined in OMPKinds.def. 340 void initializeInternalControlVars() { 341 #define ICV_RT_SET(_Name, RTL) \ 342 { \ 343 auto &ICV = ICVs[_Name]; \ 344 ICV.Setter = RTL; \ 345 } 346 #define ICV_RT_GET(Name, RTL) \ 347 { \ 348 auto &ICV = ICVs[Name]; \ 349 ICV.Getter = RTL; \ 350 } 351 #define ICV_DATA_ENV(Enum, _Name, _EnvVarName, Init) \ 352 { \ 353 auto &ICV = ICVs[Enum]; \ 354 ICV.Name = _Name; \ 355 ICV.Kind = Enum; \ 356 ICV.InitKind = Init; \ 357 ICV.EnvVarName = _EnvVarName; \ 358 switch (ICV.InitKind) { \ 359 case ICV_IMPLEMENTATION_DEFINED: \ 360 ICV.InitValue = nullptr; \ 361 break; \ 362 case ICV_ZERO: \ 363 ICV.InitValue = ConstantInt::get( \ 364 Type::getInt32Ty(OMPBuilder.Int32->getContext()), 0); \ 365 break; \ 366 case ICV_FALSE: \ 367 ICV.InitValue = ConstantInt::getFalse(OMPBuilder.Int1->getContext()); \ 368 break; \ 369 case ICV_LAST: \ 370 break; \ 371 } \ 372 } 373 #include "llvm/Frontend/OpenMP/OMPKinds.def" 374 } 375 376 /// Returns true if the function declaration \p F matches the runtime 377 /// function types, that is, return type \p RTFRetType, and argument types 378 /// \p RTFArgTypes. 379 static bool declMatchesRTFTypes(Function *F, Type *RTFRetType, 380 SmallVector<Type *, 8> &RTFArgTypes) { 381 // TODO: We should output information to the user (under debug output 382 // and via remarks). 383 384 if (!F) 385 return false; 386 if (F->getReturnType() != RTFRetType) 387 return false; 388 if (F->arg_size() != RTFArgTypes.size()) 389 return false; 390 391 auto *RTFTyIt = RTFArgTypes.begin(); 392 for (Argument &Arg : F->args()) { 393 if (Arg.getType() != *RTFTyIt) 394 return false; 395 396 ++RTFTyIt; 397 } 398 399 return true; 400 } 401 402 // Helper to collect all uses of the declaration in the UsesMap. 403 unsigned collectUses(RuntimeFunctionInfo &RFI, bool CollectStats = true) { 404 unsigned NumUses = 0; 405 if (!RFI.Declaration) 406 return NumUses; 407 OMPBuilder.addAttributes(RFI.Kind, *RFI.Declaration); 408 409 if (CollectStats) { 410 NumOpenMPRuntimeFunctionsIdentified += 1; 411 NumOpenMPRuntimeFunctionUsesIdentified += RFI.Declaration->getNumUses(); 412 } 413 414 // TODO: We directly convert uses into proper calls and unknown uses. 415 for (Use &U : RFI.Declaration->uses()) { 416 if (Instruction *UserI = dyn_cast<Instruction>(U.getUser())) { 417 if (ModuleSlice.count(UserI->getFunction())) { 418 RFI.getOrCreateUseVector(UserI->getFunction()).push_back(&U); 419 ++NumUses; 420 } 421 } else { 422 RFI.getOrCreateUseVector(nullptr).push_back(&U); 423 ++NumUses; 424 } 425 } 426 return NumUses; 427 } 428 429 // Helper function to recollect uses of a runtime function. 430 void recollectUsesForFunction(RuntimeFunction RTF) { 431 auto &RFI = RFIs[RTF]; 432 RFI.clearUsesMap(); 433 collectUses(RFI, /*CollectStats*/ false); 434 } 435 436 // Helper function to recollect uses of all runtime functions. 437 void recollectUses() { 438 for (int Idx = 0; Idx < RFIs.size(); ++Idx) 439 recollectUsesForFunction(static_cast<RuntimeFunction>(Idx)); 440 } 441 442 // Helper function to inherit the calling convention of the function callee. 443 void setCallingConvention(FunctionCallee Callee, CallInst *CI) { 444 if (Function *Fn = dyn_cast<Function>(Callee.getCallee())) 445 CI->setCallingConv(Fn->getCallingConv()); 446 } 447 448 /// Helper to initialize all runtime function information for those defined 449 /// in OpenMPKinds.def. 450 void initializeRuntimeFunctions() { 451 Module &M = *((*ModuleSlice.begin())->getParent()); 452 453 // Helper macros for handling __VA_ARGS__ in OMP_RTL 454 #define OMP_TYPE(VarName, ...) \ 455 Type *VarName = OMPBuilder.VarName; \ 456 (void)VarName; 457 458 #define OMP_ARRAY_TYPE(VarName, ...) \ 459 ArrayType *VarName##Ty = OMPBuilder.VarName##Ty; \ 460 (void)VarName##Ty; \ 461 PointerType *VarName##PtrTy = OMPBuilder.VarName##PtrTy; \ 462 (void)VarName##PtrTy; 463 464 #define OMP_FUNCTION_TYPE(VarName, ...) \ 465 FunctionType *VarName = OMPBuilder.VarName; \ 466 (void)VarName; \ 467 PointerType *VarName##Ptr = OMPBuilder.VarName##Ptr; \ 468 (void)VarName##Ptr; 469 470 #define OMP_STRUCT_TYPE(VarName, ...) \ 471 StructType *VarName = OMPBuilder.VarName; \ 472 (void)VarName; \ 473 PointerType *VarName##Ptr = OMPBuilder.VarName##Ptr; \ 474 (void)VarName##Ptr; 475 476 #define OMP_RTL(_Enum, _Name, _IsVarArg, _ReturnType, ...) \ 477 { \ 478 SmallVector<Type *, 8> ArgsTypes({__VA_ARGS__}); \ 479 Function *F = M.getFunction(_Name); \ 480 RTLFunctions.insert(F); \ 481 if (declMatchesRTFTypes(F, OMPBuilder._ReturnType, ArgsTypes)) { \ 482 RuntimeFunctionIDMap[F] = _Enum; \ 483 auto &RFI = RFIs[_Enum]; \ 484 RFI.Kind = _Enum; \ 485 RFI.Name = _Name; \ 486 RFI.IsVarArg = _IsVarArg; \ 487 RFI.ReturnType = OMPBuilder._ReturnType; \ 488 RFI.ArgumentTypes = std::move(ArgsTypes); \ 489 RFI.Declaration = F; \ 490 unsigned NumUses = collectUses(RFI); \ 491 (void)NumUses; \ 492 LLVM_DEBUG({ \ 493 dbgs() << TAG << RFI.Name << (RFI.Declaration ? "" : " not") \ 494 << " found\n"; \ 495 if (RFI.Declaration) \ 496 dbgs() << TAG << "-> got " << NumUses << " uses in " \ 497 << RFI.getNumFunctionsWithUses() \ 498 << " different functions.\n"; \ 499 }); \ 500 } \ 501 } 502 #include "llvm/Frontend/OpenMP/OMPKinds.def" 503 504 // Remove the `noinline` attribute from `__kmpc`, `_OMP::` and `omp_` 505 // functions, except if `optnone` is present. 506 for (Function &F : M) { 507 for (StringRef Prefix : {"__kmpc", "_ZN4_OMP", "omp_"}) 508 if (F.getName().startswith(Prefix) && 509 !F.hasFnAttribute(Attribute::OptimizeNone)) 510 F.removeFnAttr(Attribute::NoInline); 511 } 512 513 // TODO: We should attach the attributes defined in OMPKinds.def. 514 } 515 516 /// Collection of known kernels (\see Kernel) in the module. 517 KernelSet &Kernels; 518 519 /// Collection of known OpenMP runtime functions.. 520 DenseSet<const Function *> RTLFunctions; 521 }; 522 523 template <typename Ty, bool InsertInvalidates = true> 524 struct BooleanStateWithSetVector : public BooleanState { 525 bool contains(const Ty &Elem) const { return Set.contains(Elem); } 526 bool insert(const Ty &Elem) { 527 if (InsertInvalidates) 528 BooleanState::indicatePessimisticFixpoint(); 529 return Set.insert(Elem); 530 } 531 532 const Ty &operator[](int Idx) const { return Set[Idx]; } 533 bool operator==(const BooleanStateWithSetVector &RHS) const { 534 return BooleanState::operator==(RHS) && Set == RHS.Set; 535 } 536 bool operator!=(const BooleanStateWithSetVector &RHS) const { 537 return !(*this == RHS); 538 } 539 540 bool empty() const { return Set.empty(); } 541 size_t size() const { return Set.size(); } 542 543 /// "Clamp" this state with \p RHS. 544 BooleanStateWithSetVector &operator^=(const BooleanStateWithSetVector &RHS) { 545 BooleanState::operator^=(RHS); 546 Set.insert(RHS.Set.begin(), RHS.Set.end()); 547 return *this; 548 } 549 550 private: 551 /// A set to keep track of elements. 552 SetVector<Ty> Set; 553 554 public: 555 typename decltype(Set)::iterator begin() { return Set.begin(); } 556 typename decltype(Set)::iterator end() { return Set.end(); } 557 typename decltype(Set)::const_iterator begin() const { return Set.begin(); } 558 typename decltype(Set)::const_iterator end() const { return Set.end(); } 559 }; 560 561 template <typename Ty, bool InsertInvalidates = true> 562 using BooleanStateWithPtrSetVector = 563 BooleanStateWithSetVector<Ty *, InsertInvalidates>; 564 565 struct KernelInfoState : AbstractState { 566 /// Flag to track if we reached a fixpoint. 567 bool IsAtFixpoint = false; 568 569 /// The parallel regions (identified by the outlined parallel functions) that 570 /// can be reached from the associated function. 571 BooleanStateWithPtrSetVector<Function, /* InsertInvalidates */ false> 572 ReachedKnownParallelRegions; 573 574 /// State to track what parallel region we might reach. 575 BooleanStateWithPtrSetVector<CallBase> ReachedUnknownParallelRegions; 576 577 /// State to track if we are in SPMD-mode, assumed or know, and why we decided 578 /// we cannot be. If it is assumed, then RequiresFullRuntime should also be 579 /// false. 580 BooleanStateWithPtrSetVector<Instruction, false> SPMDCompatibilityTracker; 581 582 /// The __kmpc_target_init call in this kernel, if any. If we find more than 583 /// one we abort as the kernel is malformed. 584 CallBase *KernelInitCB = nullptr; 585 586 /// The __kmpc_target_deinit call in this kernel, if any. If we find more than 587 /// one we abort as the kernel is malformed. 588 CallBase *KernelDeinitCB = nullptr; 589 590 /// Flag to indicate if the associated function is a kernel entry. 591 bool IsKernelEntry = false; 592 593 /// State to track what kernel entries can reach the associated function. 594 BooleanStateWithPtrSetVector<Function, false> ReachingKernelEntries; 595 596 /// State to indicate if we can track parallel level of the associated 597 /// function. We will give up tracking if we encounter unknown caller or the 598 /// caller is __kmpc_parallel_51. 599 BooleanStateWithSetVector<uint8_t> ParallelLevels; 600 601 /// Abstract State interface 602 ///{ 603 604 KernelInfoState() = default; 605 KernelInfoState(bool BestState) { 606 if (!BestState) 607 indicatePessimisticFixpoint(); 608 } 609 610 /// See AbstractState::isValidState(...) 611 bool isValidState() const override { return true; } 612 613 /// See AbstractState::isAtFixpoint(...) 614 bool isAtFixpoint() const override { return IsAtFixpoint; } 615 616 /// See AbstractState::indicatePessimisticFixpoint(...) 617 ChangeStatus indicatePessimisticFixpoint() override { 618 IsAtFixpoint = true; 619 ReachingKernelEntries.indicatePessimisticFixpoint(); 620 SPMDCompatibilityTracker.indicatePessimisticFixpoint(); 621 ReachedKnownParallelRegions.indicatePessimisticFixpoint(); 622 ReachedUnknownParallelRegions.indicatePessimisticFixpoint(); 623 return ChangeStatus::CHANGED; 624 } 625 626 /// See AbstractState::indicateOptimisticFixpoint(...) 627 ChangeStatus indicateOptimisticFixpoint() override { 628 IsAtFixpoint = true; 629 ReachingKernelEntries.indicateOptimisticFixpoint(); 630 SPMDCompatibilityTracker.indicateOptimisticFixpoint(); 631 ReachedKnownParallelRegions.indicateOptimisticFixpoint(); 632 ReachedUnknownParallelRegions.indicateOptimisticFixpoint(); 633 return ChangeStatus::UNCHANGED; 634 } 635 636 /// Return the assumed state 637 KernelInfoState &getAssumed() { return *this; } 638 const KernelInfoState &getAssumed() const { return *this; } 639 640 bool operator==(const KernelInfoState &RHS) const { 641 if (SPMDCompatibilityTracker != RHS.SPMDCompatibilityTracker) 642 return false; 643 if (ReachedKnownParallelRegions != RHS.ReachedKnownParallelRegions) 644 return false; 645 if (ReachedUnknownParallelRegions != RHS.ReachedUnknownParallelRegions) 646 return false; 647 if (ReachingKernelEntries != RHS.ReachingKernelEntries) 648 return false; 649 return true; 650 } 651 652 /// Returns true if this kernel contains any OpenMP parallel regions. 653 bool mayContainParallelRegion() { 654 return !ReachedKnownParallelRegions.empty() || 655 !ReachedUnknownParallelRegions.empty(); 656 } 657 658 /// Return empty set as the best state of potential values. 659 static KernelInfoState getBestState() { return KernelInfoState(true); } 660 661 static KernelInfoState getBestState(KernelInfoState &KIS) { 662 return getBestState(); 663 } 664 665 /// Return full set as the worst state of potential values. 666 static KernelInfoState getWorstState() { return KernelInfoState(false); } 667 668 /// "Clamp" this state with \p KIS. 669 KernelInfoState operator^=(const KernelInfoState &KIS) { 670 // Do not merge two different _init and _deinit call sites. 671 if (KIS.KernelInitCB) { 672 if (KernelInitCB && KernelInitCB != KIS.KernelInitCB) 673 llvm_unreachable("Kernel that calls another kernel violates OpenMP-Opt " 674 "assumptions."); 675 KernelInitCB = KIS.KernelInitCB; 676 } 677 if (KIS.KernelDeinitCB) { 678 if (KernelDeinitCB && KernelDeinitCB != KIS.KernelDeinitCB) 679 llvm_unreachable("Kernel that calls another kernel violates OpenMP-Opt " 680 "assumptions."); 681 KernelDeinitCB = KIS.KernelDeinitCB; 682 } 683 SPMDCompatibilityTracker ^= KIS.SPMDCompatibilityTracker; 684 ReachedKnownParallelRegions ^= KIS.ReachedKnownParallelRegions; 685 ReachedUnknownParallelRegions ^= KIS.ReachedUnknownParallelRegions; 686 return *this; 687 } 688 689 KernelInfoState operator&=(const KernelInfoState &KIS) { 690 return (*this ^= KIS); 691 } 692 693 ///} 694 }; 695 696 /// Used to map the values physically (in the IR) stored in an offload 697 /// array, to a vector in memory. 698 struct OffloadArray { 699 /// Physical array (in the IR). 700 AllocaInst *Array = nullptr; 701 /// Mapped values. 702 SmallVector<Value *, 8> StoredValues; 703 /// Last stores made in the offload array. 704 SmallVector<StoreInst *, 8> LastAccesses; 705 706 OffloadArray() = default; 707 708 /// Initializes the OffloadArray with the values stored in \p Array before 709 /// instruction \p Before is reached. Returns false if the initialization 710 /// fails. 711 /// This MUST be used immediately after the construction of the object. 712 bool initialize(AllocaInst &Array, Instruction &Before) { 713 if (!Array.getAllocatedType()->isArrayTy()) 714 return false; 715 716 if (!getValues(Array, Before)) 717 return false; 718 719 this->Array = &Array; 720 return true; 721 } 722 723 static const unsigned DeviceIDArgNum = 1; 724 static const unsigned BasePtrsArgNum = 3; 725 static const unsigned PtrsArgNum = 4; 726 static const unsigned SizesArgNum = 5; 727 728 private: 729 /// Traverses the BasicBlock where \p Array is, collecting the stores made to 730 /// \p Array, leaving StoredValues with the values stored before the 731 /// instruction \p Before is reached. 732 bool getValues(AllocaInst &Array, Instruction &Before) { 733 // Initialize container. 734 const uint64_t NumValues = Array.getAllocatedType()->getArrayNumElements(); 735 StoredValues.assign(NumValues, nullptr); 736 LastAccesses.assign(NumValues, nullptr); 737 738 // TODO: This assumes the instruction \p Before is in the same 739 // BasicBlock as Array. Make it general, for any control flow graph. 740 BasicBlock *BB = Array.getParent(); 741 if (BB != Before.getParent()) 742 return false; 743 744 const DataLayout &DL = Array.getModule()->getDataLayout(); 745 const unsigned int PointerSize = DL.getPointerSize(); 746 747 for (Instruction &I : *BB) { 748 if (&I == &Before) 749 break; 750 751 if (!isa<StoreInst>(&I)) 752 continue; 753 754 auto *S = cast<StoreInst>(&I); 755 int64_t Offset = -1; 756 auto *Dst = 757 GetPointerBaseWithConstantOffset(S->getPointerOperand(), Offset, DL); 758 if (Dst == &Array) { 759 int64_t Idx = Offset / PointerSize; 760 StoredValues[Idx] = getUnderlyingObject(S->getValueOperand()); 761 LastAccesses[Idx] = S; 762 } 763 } 764 765 return isFilled(); 766 } 767 768 /// Returns true if all values in StoredValues and 769 /// LastAccesses are not nullptrs. 770 bool isFilled() { 771 const unsigned NumValues = StoredValues.size(); 772 for (unsigned I = 0; I < NumValues; ++I) { 773 if (!StoredValues[I] || !LastAccesses[I]) 774 return false; 775 } 776 777 return true; 778 } 779 }; 780 781 struct OpenMPOpt { 782 783 using OptimizationRemarkGetter = 784 function_ref<OptimizationRemarkEmitter &(Function *)>; 785 786 OpenMPOpt(SmallVectorImpl<Function *> &SCC, CallGraphUpdater &CGUpdater, 787 OptimizationRemarkGetter OREGetter, 788 OMPInformationCache &OMPInfoCache, Attributor &A) 789 : M(*(*SCC.begin())->getParent()), SCC(SCC), CGUpdater(CGUpdater), 790 OREGetter(OREGetter), OMPInfoCache(OMPInfoCache), A(A) {} 791 792 /// Check if any remarks are enabled for openmp-opt 793 bool remarksEnabled() { 794 auto &Ctx = M.getContext(); 795 return Ctx.getDiagHandlerPtr()->isAnyRemarkEnabled(DEBUG_TYPE); 796 } 797 798 /// Run all OpenMP optimizations on the underlying SCC/ModuleSlice. 799 bool run(bool IsModulePass) { 800 if (SCC.empty()) 801 return false; 802 803 bool Changed = false; 804 805 LLVM_DEBUG(dbgs() << TAG << "Run on SCC with " << SCC.size() 806 << " functions in a slice with " 807 << OMPInfoCache.ModuleSlice.size() << " functions\n"); 808 809 if (IsModulePass) { 810 Changed |= runAttributor(IsModulePass); 811 812 // Recollect uses, in case Attributor deleted any. 813 OMPInfoCache.recollectUses(); 814 815 // TODO: This should be folded into buildCustomStateMachine. 816 Changed |= rewriteDeviceCodeStateMachine(); 817 818 if (remarksEnabled()) 819 analysisGlobalization(); 820 821 Changed |= eliminateBarriers(); 822 } else { 823 if (PrintICVValues) 824 printICVs(); 825 if (PrintOpenMPKernels) 826 printKernels(); 827 828 Changed |= runAttributor(IsModulePass); 829 830 // Recollect uses, in case Attributor deleted any. 831 OMPInfoCache.recollectUses(); 832 833 Changed |= deleteParallelRegions(); 834 835 if (HideMemoryTransferLatency) 836 Changed |= hideMemTransfersLatency(); 837 Changed |= deduplicateRuntimeCalls(); 838 if (EnableParallelRegionMerging) { 839 if (mergeParallelRegions()) { 840 deduplicateRuntimeCalls(); 841 Changed = true; 842 } 843 } 844 845 Changed |= eliminateBarriers(); 846 } 847 848 return Changed; 849 } 850 851 /// Print initial ICV values for testing. 852 /// FIXME: This should be done from the Attributor once it is added. 853 void printICVs() const { 854 InternalControlVar ICVs[] = {ICV_nthreads, ICV_active_levels, ICV_cancel, 855 ICV_proc_bind}; 856 857 for (Function *F : OMPInfoCache.ModuleSlice) { 858 for (auto ICV : ICVs) { 859 auto ICVInfo = OMPInfoCache.ICVs[ICV]; 860 auto Remark = [&](OptimizationRemarkAnalysis ORA) { 861 return ORA << "OpenMP ICV " << ore::NV("OpenMPICV", ICVInfo.Name) 862 << " Value: " 863 << (ICVInfo.InitValue 864 ? toString(ICVInfo.InitValue->getValue(), 10, true) 865 : "IMPLEMENTATION_DEFINED"); 866 }; 867 868 emitRemark<OptimizationRemarkAnalysis>(F, "OpenMPICVTracker", Remark); 869 } 870 } 871 } 872 873 /// Print OpenMP GPU kernels for testing. 874 void printKernels() const { 875 for (Function *F : SCC) { 876 if (!OMPInfoCache.Kernels.count(F)) 877 continue; 878 879 auto Remark = [&](OptimizationRemarkAnalysis ORA) { 880 return ORA << "OpenMP GPU kernel " 881 << ore::NV("OpenMPGPUKernel", F->getName()) << "\n"; 882 }; 883 884 emitRemark<OptimizationRemarkAnalysis>(F, "OpenMPGPU", Remark); 885 } 886 } 887 888 /// Return the call if \p U is a callee use in a regular call. If \p RFI is 889 /// given it has to be the callee or a nullptr is returned. 890 static CallInst *getCallIfRegularCall( 891 Use &U, OMPInformationCache::RuntimeFunctionInfo *RFI = nullptr) { 892 CallInst *CI = dyn_cast<CallInst>(U.getUser()); 893 if (CI && CI->isCallee(&U) && !CI->hasOperandBundles() && 894 (!RFI || 895 (RFI->Declaration && CI->getCalledFunction() == RFI->Declaration))) 896 return CI; 897 return nullptr; 898 } 899 900 /// Return the call if \p V is a regular call. If \p RFI is given it has to be 901 /// the callee or a nullptr is returned. 902 static CallInst *getCallIfRegularCall( 903 Value &V, OMPInformationCache::RuntimeFunctionInfo *RFI = nullptr) { 904 CallInst *CI = dyn_cast<CallInst>(&V); 905 if (CI && !CI->hasOperandBundles() && 906 (!RFI || 907 (RFI->Declaration && CI->getCalledFunction() == RFI->Declaration))) 908 return CI; 909 return nullptr; 910 } 911 912 private: 913 /// Merge parallel regions when it is safe. 914 bool mergeParallelRegions() { 915 const unsigned CallbackCalleeOperand = 2; 916 const unsigned CallbackFirstArgOperand = 3; 917 using InsertPointTy = OpenMPIRBuilder::InsertPointTy; 918 919 // Check if there are any __kmpc_fork_call calls to merge. 920 OMPInformationCache::RuntimeFunctionInfo &RFI = 921 OMPInfoCache.RFIs[OMPRTL___kmpc_fork_call]; 922 923 if (!RFI.Declaration) 924 return false; 925 926 // Unmergable calls that prevent merging a parallel region. 927 OMPInformationCache::RuntimeFunctionInfo UnmergableCallsInfo[] = { 928 OMPInfoCache.RFIs[OMPRTL___kmpc_push_proc_bind], 929 OMPInfoCache.RFIs[OMPRTL___kmpc_push_num_threads], 930 }; 931 932 bool Changed = false; 933 LoopInfo *LI = nullptr; 934 DominatorTree *DT = nullptr; 935 936 SmallDenseMap<BasicBlock *, SmallPtrSet<Instruction *, 4>> BB2PRMap; 937 938 BasicBlock *StartBB = nullptr, *EndBB = nullptr; 939 auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP, 940 BasicBlock &ContinuationIP) { 941 BasicBlock *CGStartBB = CodeGenIP.getBlock(); 942 BasicBlock *CGEndBB = 943 SplitBlock(CGStartBB, &*CodeGenIP.getPoint(), DT, LI); 944 assert(StartBB != nullptr && "StartBB should not be null"); 945 CGStartBB->getTerminator()->setSuccessor(0, StartBB); 946 assert(EndBB != nullptr && "EndBB should not be null"); 947 EndBB->getTerminator()->setSuccessor(0, CGEndBB); 948 }; 949 950 auto PrivCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP, Value &, 951 Value &Inner, Value *&ReplacementValue) -> InsertPointTy { 952 ReplacementValue = &Inner; 953 return CodeGenIP; 954 }; 955 956 auto FiniCB = [&](InsertPointTy CodeGenIP) {}; 957 958 /// Create a sequential execution region within a merged parallel region, 959 /// encapsulated in a master construct with a barrier for synchronization. 960 auto CreateSequentialRegion = [&](Function *OuterFn, 961 BasicBlock *OuterPredBB, 962 Instruction *SeqStartI, 963 Instruction *SeqEndI) { 964 // Isolate the instructions of the sequential region to a separate 965 // block. 966 BasicBlock *ParentBB = SeqStartI->getParent(); 967 BasicBlock *SeqEndBB = 968 SplitBlock(ParentBB, SeqEndI->getNextNode(), DT, LI); 969 BasicBlock *SeqAfterBB = 970 SplitBlock(SeqEndBB, &*SeqEndBB->getFirstInsertionPt(), DT, LI); 971 BasicBlock *SeqStartBB = 972 SplitBlock(ParentBB, SeqStartI, DT, LI, nullptr, "seq.par.merged"); 973 974 assert(ParentBB->getUniqueSuccessor() == SeqStartBB && 975 "Expected a different CFG"); 976 const DebugLoc DL = ParentBB->getTerminator()->getDebugLoc(); 977 ParentBB->getTerminator()->eraseFromParent(); 978 979 auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP, 980 BasicBlock &ContinuationIP) { 981 BasicBlock *CGStartBB = CodeGenIP.getBlock(); 982 BasicBlock *CGEndBB = 983 SplitBlock(CGStartBB, &*CodeGenIP.getPoint(), DT, LI); 984 assert(SeqStartBB != nullptr && "SeqStartBB should not be null"); 985 CGStartBB->getTerminator()->setSuccessor(0, SeqStartBB); 986 assert(SeqEndBB != nullptr && "SeqEndBB should not be null"); 987 SeqEndBB->getTerminator()->setSuccessor(0, CGEndBB); 988 }; 989 auto FiniCB = [&](InsertPointTy CodeGenIP) {}; 990 991 // Find outputs from the sequential region to outside users and 992 // broadcast their values to them. 993 for (Instruction &I : *SeqStartBB) { 994 SmallPtrSet<Instruction *, 4> OutsideUsers; 995 for (User *Usr : I.users()) { 996 Instruction &UsrI = *cast<Instruction>(Usr); 997 // Ignore outputs to LT intrinsics, code extraction for the merged 998 // parallel region will fix them. 999 if (UsrI.isLifetimeStartOrEnd()) 1000 continue; 1001 1002 if (UsrI.getParent() != SeqStartBB) 1003 OutsideUsers.insert(&UsrI); 1004 } 1005 1006 if (OutsideUsers.empty()) 1007 continue; 1008 1009 // Emit an alloca in the outer region to store the broadcasted 1010 // value. 1011 const DataLayout &DL = M.getDataLayout(); 1012 AllocaInst *AllocaI = new AllocaInst( 1013 I.getType(), DL.getAllocaAddrSpace(), nullptr, 1014 I.getName() + ".seq.output.alloc", &OuterFn->front().front()); 1015 1016 // Emit a store instruction in the sequential BB to update the 1017 // value. 1018 new StoreInst(&I, AllocaI, SeqStartBB->getTerminator()); 1019 1020 // Emit a load instruction and replace the use of the output value 1021 // with it. 1022 for (Instruction *UsrI : OutsideUsers) { 1023 LoadInst *LoadI = new LoadInst( 1024 I.getType(), AllocaI, I.getName() + ".seq.output.load", UsrI); 1025 UsrI->replaceUsesOfWith(&I, LoadI); 1026 } 1027 } 1028 1029 OpenMPIRBuilder::LocationDescription Loc( 1030 InsertPointTy(ParentBB, ParentBB->end()), DL); 1031 InsertPointTy SeqAfterIP = 1032 OMPInfoCache.OMPBuilder.createMaster(Loc, BodyGenCB, FiniCB); 1033 1034 OMPInfoCache.OMPBuilder.createBarrier(SeqAfterIP, OMPD_parallel); 1035 1036 BranchInst::Create(SeqAfterBB, SeqAfterIP.getBlock()); 1037 1038 LLVM_DEBUG(dbgs() << TAG << "After sequential inlining " << *OuterFn 1039 << "\n"); 1040 }; 1041 1042 // Helper to merge the __kmpc_fork_call calls in MergableCIs. They are all 1043 // contained in BB and only separated by instructions that can be 1044 // redundantly executed in parallel. The block BB is split before the first 1045 // call (in MergableCIs) and after the last so the entire region we merge 1046 // into a single parallel region is contained in a single basic block 1047 // without any other instructions. We use the OpenMPIRBuilder to outline 1048 // that block and call the resulting function via __kmpc_fork_call. 1049 auto Merge = [&](const SmallVectorImpl<CallInst *> &MergableCIs, 1050 BasicBlock *BB) { 1051 // TODO: Change the interface to allow single CIs expanded, e.g, to 1052 // include an outer loop. 1053 assert(MergableCIs.size() > 1 && "Assumed multiple mergable CIs"); 1054 1055 auto Remark = [&](OptimizationRemark OR) { 1056 OR << "Parallel region merged with parallel region" 1057 << (MergableCIs.size() > 2 ? "s" : "") << " at "; 1058 for (auto *CI : llvm::drop_begin(MergableCIs)) { 1059 OR << ore::NV("OpenMPParallelMerge", CI->getDebugLoc()); 1060 if (CI != MergableCIs.back()) 1061 OR << ", "; 1062 } 1063 return OR << "."; 1064 }; 1065 1066 emitRemark<OptimizationRemark>(MergableCIs.front(), "OMP150", Remark); 1067 1068 Function *OriginalFn = BB->getParent(); 1069 LLVM_DEBUG(dbgs() << TAG << "Merge " << MergableCIs.size() 1070 << " parallel regions in " << OriginalFn->getName() 1071 << "\n"); 1072 1073 // Isolate the calls to merge in a separate block. 1074 EndBB = SplitBlock(BB, MergableCIs.back()->getNextNode(), DT, LI); 1075 BasicBlock *AfterBB = 1076 SplitBlock(EndBB, &*EndBB->getFirstInsertionPt(), DT, LI); 1077 StartBB = SplitBlock(BB, MergableCIs.front(), DT, LI, nullptr, 1078 "omp.par.merged"); 1079 1080 assert(BB->getUniqueSuccessor() == StartBB && "Expected a different CFG"); 1081 const DebugLoc DL = BB->getTerminator()->getDebugLoc(); 1082 BB->getTerminator()->eraseFromParent(); 1083 1084 // Create sequential regions for sequential instructions that are 1085 // in-between mergable parallel regions. 1086 for (auto *It = MergableCIs.begin(), *End = MergableCIs.end() - 1; 1087 It != End; ++It) { 1088 Instruction *ForkCI = *It; 1089 Instruction *NextForkCI = *(It + 1); 1090 1091 // Continue if there are not in-between instructions. 1092 if (ForkCI->getNextNode() == NextForkCI) 1093 continue; 1094 1095 CreateSequentialRegion(OriginalFn, BB, ForkCI->getNextNode(), 1096 NextForkCI->getPrevNode()); 1097 } 1098 1099 OpenMPIRBuilder::LocationDescription Loc(InsertPointTy(BB, BB->end()), 1100 DL); 1101 IRBuilder<>::InsertPoint AllocaIP( 1102 &OriginalFn->getEntryBlock(), 1103 OriginalFn->getEntryBlock().getFirstInsertionPt()); 1104 // Create the merged parallel region with default proc binding, to 1105 // avoid overriding binding settings, and without explicit cancellation. 1106 InsertPointTy AfterIP = OMPInfoCache.OMPBuilder.createParallel( 1107 Loc, AllocaIP, BodyGenCB, PrivCB, FiniCB, nullptr, nullptr, 1108 OMP_PROC_BIND_default, /* IsCancellable */ false); 1109 BranchInst::Create(AfterBB, AfterIP.getBlock()); 1110 1111 // Perform the actual outlining. 1112 OMPInfoCache.OMPBuilder.finalize(OriginalFn); 1113 1114 Function *OutlinedFn = MergableCIs.front()->getCaller(); 1115 1116 // Replace the __kmpc_fork_call calls with direct calls to the outlined 1117 // callbacks. 1118 SmallVector<Value *, 8> Args; 1119 for (auto *CI : MergableCIs) { 1120 Value *Callee = CI->getArgOperand(CallbackCalleeOperand); 1121 FunctionType *FT = OMPInfoCache.OMPBuilder.ParallelTask; 1122 Args.clear(); 1123 Args.push_back(OutlinedFn->getArg(0)); 1124 Args.push_back(OutlinedFn->getArg(1)); 1125 for (unsigned U = CallbackFirstArgOperand, E = CI->arg_size(); U < E; 1126 ++U) 1127 Args.push_back(CI->getArgOperand(U)); 1128 1129 CallInst *NewCI = CallInst::Create(FT, Callee, Args, "", CI); 1130 if (CI->getDebugLoc()) 1131 NewCI->setDebugLoc(CI->getDebugLoc()); 1132 1133 // Forward parameter attributes from the callback to the callee. 1134 for (unsigned U = CallbackFirstArgOperand, E = CI->arg_size(); U < E; 1135 ++U) 1136 for (const Attribute &A : CI->getAttributes().getParamAttrs(U)) 1137 NewCI->addParamAttr( 1138 U - (CallbackFirstArgOperand - CallbackCalleeOperand), A); 1139 1140 // Emit an explicit barrier to replace the implicit fork-join barrier. 1141 if (CI != MergableCIs.back()) { 1142 // TODO: Remove barrier if the merged parallel region includes the 1143 // 'nowait' clause. 1144 OMPInfoCache.OMPBuilder.createBarrier( 1145 InsertPointTy(NewCI->getParent(), 1146 NewCI->getNextNode()->getIterator()), 1147 OMPD_parallel); 1148 } 1149 1150 CI->eraseFromParent(); 1151 } 1152 1153 assert(OutlinedFn != OriginalFn && "Outlining failed"); 1154 CGUpdater.registerOutlinedFunction(*OriginalFn, *OutlinedFn); 1155 CGUpdater.reanalyzeFunction(*OriginalFn); 1156 1157 NumOpenMPParallelRegionsMerged += MergableCIs.size(); 1158 1159 return true; 1160 }; 1161 1162 // Helper function that identifes sequences of 1163 // __kmpc_fork_call uses in a basic block. 1164 auto DetectPRsCB = [&](Use &U, Function &F) { 1165 CallInst *CI = getCallIfRegularCall(U, &RFI); 1166 BB2PRMap[CI->getParent()].insert(CI); 1167 1168 return false; 1169 }; 1170 1171 BB2PRMap.clear(); 1172 RFI.foreachUse(SCC, DetectPRsCB); 1173 SmallVector<SmallVector<CallInst *, 4>, 4> MergableCIsVector; 1174 // Find mergable parallel regions within a basic block that are 1175 // safe to merge, that is any in-between instructions can safely 1176 // execute in parallel after merging. 1177 // TODO: support merging across basic-blocks. 1178 for (auto &It : BB2PRMap) { 1179 auto &CIs = It.getSecond(); 1180 if (CIs.size() < 2) 1181 continue; 1182 1183 BasicBlock *BB = It.getFirst(); 1184 SmallVector<CallInst *, 4> MergableCIs; 1185 1186 /// Returns true if the instruction is mergable, false otherwise. 1187 /// A terminator instruction is unmergable by definition since merging 1188 /// works within a BB. Instructions before the mergable region are 1189 /// mergable if they are not calls to OpenMP runtime functions that may 1190 /// set different execution parameters for subsequent parallel regions. 1191 /// Instructions in-between parallel regions are mergable if they are not 1192 /// calls to any non-intrinsic function since that may call a non-mergable 1193 /// OpenMP runtime function. 1194 auto IsMergable = [&](Instruction &I, bool IsBeforeMergableRegion) { 1195 // We do not merge across BBs, hence return false (unmergable) if the 1196 // instruction is a terminator. 1197 if (I.isTerminator()) 1198 return false; 1199 1200 if (!isa<CallInst>(&I)) 1201 return true; 1202 1203 CallInst *CI = cast<CallInst>(&I); 1204 if (IsBeforeMergableRegion) { 1205 Function *CalledFunction = CI->getCalledFunction(); 1206 if (!CalledFunction) 1207 return false; 1208 // Return false (unmergable) if the call before the parallel 1209 // region calls an explicit affinity (proc_bind) or number of 1210 // threads (num_threads) compiler-generated function. Those settings 1211 // may be incompatible with following parallel regions. 1212 // TODO: ICV tracking to detect compatibility. 1213 for (const auto &RFI : UnmergableCallsInfo) { 1214 if (CalledFunction == RFI.Declaration) 1215 return false; 1216 } 1217 } else { 1218 // Return false (unmergable) if there is a call instruction 1219 // in-between parallel regions when it is not an intrinsic. It 1220 // may call an unmergable OpenMP runtime function in its callpath. 1221 // TODO: Keep track of possible OpenMP calls in the callpath. 1222 if (!isa<IntrinsicInst>(CI)) 1223 return false; 1224 } 1225 1226 return true; 1227 }; 1228 // Find maximal number of parallel region CIs that are safe to merge. 1229 for (auto It = BB->begin(), End = BB->end(); It != End;) { 1230 Instruction &I = *It; 1231 ++It; 1232 1233 if (CIs.count(&I)) { 1234 MergableCIs.push_back(cast<CallInst>(&I)); 1235 continue; 1236 } 1237 1238 // Continue expanding if the instruction is mergable. 1239 if (IsMergable(I, MergableCIs.empty())) 1240 continue; 1241 1242 // Forward the instruction iterator to skip the next parallel region 1243 // since there is an unmergable instruction which can affect it. 1244 for (; It != End; ++It) { 1245 Instruction &SkipI = *It; 1246 if (CIs.count(&SkipI)) { 1247 LLVM_DEBUG(dbgs() << TAG << "Skip parallel region " << SkipI 1248 << " due to " << I << "\n"); 1249 ++It; 1250 break; 1251 } 1252 } 1253 1254 // Store mergable regions found. 1255 if (MergableCIs.size() > 1) { 1256 MergableCIsVector.push_back(MergableCIs); 1257 LLVM_DEBUG(dbgs() << TAG << "Found " << MergableCIs.size() 1258 << " parallel regions in block " << BB->getName() 1259 << " of function " << BB->getParent()->getName() 1260 << "\n";); 1261 } 1262 1263 MergableCIs.clear(); 1264 } 1265 1266 if (!MergableCIsVector.empty()) { 1267 Changed = true; 1268 1269 for (auto &MergableCIs : MergableCIsVector) 1270 Merge(MergableCIs, BB); 1271 MergableCIsVector.clear(); 1272 } 1273 } 1274 1275 if (Changed) { 1276 /// Re-collect use for fork calls, emitted barrier calls, and 1277 /// any emitted master/end_master calls. 1278 OMPInfoCache.recollectUsesForFunction(OMPRTL___kmpc_fork_call); 1279 OMPInfoCache.recollectUsesForFunction(OMPRTL___kmpc_barrier); 1280 OMPInfoCache.recollectUsesForFunction(OMPRTL___kmpc_master); 1281 OMPInfoCache.recollectUsesForFunction(OMPRTL___kmpc_end_master); 1282 } 1283 1284 return Changed; 1285 } 1286 1287 /// Try to delete parallel regions if possible. 1288 bool deleteParallelRegions() { 1289 const unsigned CallbackCalleeOperand = 2; 1290 1291 OMPInformationCache::RuntimeFunctionInfo &RFI = 1292 OMPInfoCache.RFIs[OMPRTL___kmpc_fork_call]; 1293 1294 if (!RFI.Declaration) 1295 return false; 1296 1297 bool Changed = false; 1298 auto DeleteCallCB = [&](Use &U, Function &) { 1299 CallInst *CI = getCallIfRegularCall(U); 1300 if (!CI) 1301 return false; 1302 auto *Fn = dyn_cast<Function>( 1303 CI->getArgOperand(CallbackCalleeOperand)->stripPointerCasts()); 1304 if (!Fn) 1305 return false; 1306 if (!Fn->onlyReadsMemory()) 1307 return false; 1308 if (!Fn->hasFnAttribute(Attribute::WillReturn)) 1309 return false; 1310 1311 LLVM_DEBUG(dbgs() << TAG << "Delete read-only parallel region in " 1312 << CI->getCaller()->getName() << "\n"); 1313 1314 auto Remark = [&](OptimizationRemark OR) { 1315 return OR << "Removing parallel region with no side-effects."; 1316 }; 1317 emitRemark<OptimizationRemark>(CI, "OMP160", Remark); 1318 1319 CGUpdater.removeCallSite(*CI); 1320 CI->eraseFromParent(); 1321 Changed = true; 1322 ++NumOpenMPParallelRegionsDeleted; 1323 return true; 1324 }; 1325 1326 RFI.foreachUse(SCC, DeleteCallCB); 1327 1328 return Changed; 1329 } 1330 1331 /// Try to eliminate runtime calls by reusing existing ones. 1332 bool deduplicateRuntimeCalls() { 1333 bool Changed = false; 1334 1335 RuntimeFunction DeduplicableRuntimeCallIDs[] = { 1336 OMPRTL_omp_get_num_threads, 1337 OMPRTL_omp_in_parallel, 1338 OMPRTL_omp_get_cancellation, 1339 OMPRTL_omp_get_thread_limit, 1340 OMPRTL_omp_get_supported_active_levels, 1341 OMPRTL_omp_get_level, 1342 OMPRTL_omp_get_ancestor_thread_num, 1343 OMPRTL_omp_get_team_size, 1344 OMPRTL_omp_get_active_level, 1345 OMPRTL_omp_in_final, 1346 OMPRTL_omp_get_proc_bind, 1347 OMPRTL_omp_get_num_places, 1348 OMPRTL_omp_get_num_procs, 1349 OMPRTL_omp_get_place_num, 1350 OMPRTL_omp_get_partition_num_places, 1351 OMPRTL_omp_get_partition_place_nums}; 1352 1353 // Global-tid is handled separately. 1354 SmallSetVector<Value *, 16> GTIdArgs; 1355 collectGlobalThreadIdArguments(GTIdArgs); 1356 LLVM_DEBUG(dbgs() << TAG << "Found " << GTIdArgs.size() 1357 << " global thread ID arguments\n"); 1358 1359 for (Function *F : SCC) { 1360 for (auto DeduplicableRuntimeCallID : DeduplicableRuntimeCallIDs) 1361 Changed |= deduplicateRuntimeCalls( 1362 *F, OMPInfoCache.RFIs[DeduplicableRuntimeCallID]); 1363 1364 // __kmpc_global_thread_num is special as we can replace it with an 1365 // argument in enough cases to make it worth trying. 1366 Value *GTIdArg = nullptr; 1367 for (Argument &Arg : F->args()) 1368 if (GTIdArgs.count(&Arg)) { 1369 GTIdArg = &Arg; 1370 break; 1371 } 1372 Changed |= deduplicateRuntimeCalls( 1373 *F, OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num], GTIdArg); 1374 } 1375 1376 return Changed; 1377 } 1378 1379 /// Tries to hide the latency of runtime calls that involve host to 1380 /// device memory transfers by splitting them into their "issue" and "wait" 1381 /// versions. The "issue" is moved upwards as much as possible. The "wait" is 1382 /// moved downards as much as possible. The "issue" issues the memory transfer 1383 /// asynchronously, returning a handle. The "wait" waits in the returned 1384 /// handle for the memory transfer to finish. 1385 bool hideMemTransfersLatency() { 1386 auto &RFI = OMPInfoCache.RFIs[OMPRTL___tgt_target_data_begin_mapper]; 1387 bool Changed = false; 1388 auto SplitMemTransfers = [&](Use &U, Function &Decl) { 1389 auto *RTCall = getCallIfRegularCall(U, &RFI); 1390 if (!RTCall) 1391 return false; 1392 1393 OffloadArray OffloadArrays[3]; 1394 if (!getValuesInOffloadArrays(*RTCall, OffloadArrays)) 1395 return false; 1396 1397 LLVM_DEBUG(dumpValuesInOffloadArrays(OffloadArrays)); 1398 1399 // TODO: Check if can be moved upwards. 1400 bool WasSplit = false; 1401 Instruction *WaitMovementPoint = canBeMovedDownwards(*RTCall); 1402 if (WaitMovementPoint) 1403 WasSplit = splitTargetDataBeginRTC(*RTCall, *WaitMovementPoint); 1404 1405 Changed |= WasSplit; 1406 return WasSplit; 1407 }; 1408 RFI.foreachUse(SCC, SplitMemTransfers); 1409 1410 return Changed; 1411 } 1412 1413 /// Eliminates redundant, aligned barriers in OpenMP offloaded kernels. 1414 /// TODO: Make this an AA and expand it to work across blocks and functions. 1415 bool eliminateBarriers() { 1416 bool Changed = false; 1417 1418 if (DisableOpenMPOptBarrierElimination) 1419 return /*Changed=*/false; 1420 1421 if (OMPInfoCache.Kernels.empty()) 1422 return /*Changed=*/false; 1423 1424 enum ImplicitBarrierType { IBT_ENTRY, IBT_EXIT }; 1425 1426 class BarrierInfo { 1427 Instruction *I; 1428 enum ImplicitBarrierType Type; 1429 1430 public: 1431 BarrierInfo(enum ImplicitBarrierType Type) : I(nullptr), Type(Type) {} 1432 BarrierInfo(Instruction &I) : I(&I) {} 1433 1434 bool isImplicit() { return !I; } 1435 1436 bool isImplicitEntry() { return isImplicit() && Type == IBT_ENTRY; } 1437 1438 bool isImplicitExit() { return isImplicit() && Type == IBT_EXIT; } 1439 1440 Instruction *getInstruction() { return I; } 1441 }; 1442 1443 for (Function *Kernel : OMPInfoCache.Kernels) { 1444 for (BasicBlock &BB : *Kernel) { 1445 SmallVector<BarrierInfo, 8> BarriersInBlock; 1446 SmallPtrSet<Instruction *, 8> BarriersToBeDeleted; 1447 1448 // Add the kernel entry implicit barrier. 1449 if (&Kernel->getEntryBlock() == &BB) 1450 BarriersInBlock.push_back(IBT_ENTRY); 1451 1452 // Find implicit and explicit aligned barriers in the same basic block. 1453 for (Instruction &I : BB) { 1454 if (isa<ReturnInst>(I)) { 1455 // Add the implicit barrier when exiting the kernel. 1456 BarriersInBlock.push_back(IBT_EXIT); 1457 continue; 1458 } 1459 CallBase *CB = dyn_cast<CallBase>(&I); 1460 if (!CB) 1461 continue; 1462 1463 auto IsAlignBarrierCB = [&](CallBase &CB) { 1464 switch (CB.getIntrinsicID()) { 1465 case Intrinsic::nvvm_barrier0: 1466 case Intrinsic::nvvm_barrier0_and: 1467 case Intrinsic::nvvm_barrier0_or: 1468 case Intrinsic::nvvm_barrier0_popc: 1469 return true; 1470 default: 1471 break; 1472 } 1473 return hasAssumption(CB, 1474 KnownAssumptionString("ompx_aligned_barrier")); 1475 }; 1476 1477 if (IsAlignBarrierCB(*CB)) { 1478 // Add an explicit aligned barrier. 1479 BarriersInBlock.push_back(I); 1480 } 1481 } 1482 1483 if (BarriersInBlock.size() <= 1) 1484 continue; 1485 1486 // A barrier in a barrier pair is removeable if all instructions 1487 // between the barriers in the pair are side-effect free modulo the 1488 // barrier operation. 1489 auto IsBarrierRemoveable = [&Kernel](BarrierInfo *StartBI, 1490 BarrierInfo *EndBI) { 1491 assert( 1492 !StartBI->isImplicitExit() && 1493 "Expected start barrier to be other than a kernel exit barrier"); 1494 assert( 1495 !EndBI->isImplicitEntry() && 1496 "Expected end barrier to be other than a kernel entry barrier"); 1497 // If StarBI instructions is null then this the implicit 1498 // kernel entry barrier, so iterate from the first instruction in the 1499 // entry block. 1500 Instruction *I = (StartBI->isImplicitEntry()) 1501 ? &Kernel->getEntryBlock().front() 1502 : StartBI->getInstruction()->getNextNode(); 1503 assert(I && "Expected non-null start instruction"); 1504 Instruction *E = (EndBI->isImplicitExit()) 1505 ? I->getParent()->getTerminator() 1506 : EndBI->getInstruction(); 1507 assert(E && "Expected non-null end instruction"); 1508 1509 for (; I != E; I = I->getNextNode()) { 1510 if (!I->mayHaveSideEffects() && !I->mayReadFromMemory()) 1511 continue; 1512 1513 auto IsPotentiallyAffectedByBarrier = 1514 [](Optional<MemoryLocation> Loc) { 1515 const Value *Obj = (Loc && Loc->Ptr) 1516 ? getUnderlyingObject(Loc->Ptr) 1517 : nullptr; 1518 if (!Obj) { 1519 LLVM_DEBUG( 1520 dbgs() 1521 << "Access to unknown location requires barriers\n"); 1522 return true; 1523 } 1524 if (isa<UndefValue>(Obj)) 1525 return false; 1526 if (isa<AllocaInst>(Obj)) 1527 return false; 1528 if (auto *GV = dyn_cast<GlobalVariable>(Obj)) { 1529 if (GV->isConstant()) 1530 return false; 1531 if (GV->isThreadLocal()) 1532 return false; 1533 if (GV->getAddressSpace() == (int)AddressSpace::Local) 1534 return false; 1535 if (GV->getAddressSpace() == (int)AddressSpace::Constant) 1536 return false; 1537 } 1538 LLVM_DEBUG(dbgs() << "Access to '" << *Obj 1539 << "' requires barriers\n"); 1540 return true; 1541 }; 1542 1543 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) { 1544 Optional<MemoryLocation> Loc = MemoryLocation::getForDest(MI); 1545 if (IsPotentiallyAffectedByBarrier(Loc)) 1546 return false; 1547 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I)) { 1548 Optional<MemoryLocation> Loc = 1549 MemoryLocation::getForSource(MTI); 1550 if (IsPotentiallyAffectedByBarrier(Loc)) 1551 return false; 1552 } 1553 continue; 1554 } 1555 1556 if (auto *LI = dyn_cast<LoadInst>(I)) 1557 if (LI->hasMetadata(LLVMContext::MD_invariant_load)) 1558 continue; 1559 1560 Optional<MemoryLocation> Loc = MemoryLocation::getOrNone(I); 1561 if (IsPotentiallyAffectedByBarrier(Loc)) 1562 return false; 1563 } 1564 1565 return true; 1566 }; 1567 1568 // Iterate barrier pairs and remove an explicit barrier if analysis 1569 // deems it removeable. 1570 for (auto *It = BarriersInBlock.begin(), 1571 *End = BarriersInBlock.end() - 1; 1572 It != End; ++It) { 1573 1574 BarrierInfo *StartBI = It; 1575 BarrierInfo *EndBI = (It + 1); 1576 1577 // Cannot remove when both are implicit barriers, continue. 1578 if (StartBI->isImplicit() && EndBI->isImplicit()) 1579 continue; 1580 1581 if (!IsBarrierRemoveable(StartBI, EndBI)) 1582 continue; 1583 1584 assert(!(StartBI->isImplicit() && EndBI->isImplicit()) && 1585 "Expected at least one explicit barrier to remove."); 1586 1587 // Remove an explicit barrier, check first, then second. 1588 if (!StartBI->isImplicit()) { 1589 LLVM_DEBUG(dbgs() << "Remove start barrier " 1590 << *StartBI->getInstruction() << "\n"); 1591 BarriersToBeDeleted.insert(StartBI->getInstruction()); 1592 } else { 1593 LLVM_DEBUG(dbgs() << "Remove end barrier " 1594 << *EndBI->getInstruction() << "\n"); 1595 BarriersToBeDeleted.insert(EndBI->getInstruction()); 1596 } 1597 } 1598 1599 if (BarriersToBeDeleted.empty()) 1600 continue; 1601 1602 Changed = true; 1603 for (Instruction *I : BarriersToBeDeleted) { 1604 ++NumBarriersEliminated; 1605 auto Remark = [&](OptimizationRemark OR) { 1606 return OR << "Redundant barrier eliminated."; 1607 }; 1608 1609 if (EnableVerboseRemarks) 1610 emitRemark<OptimizationRemark>(I, "OMP190", Remark); 1611 I->eraseFromParent(); 1612 } 1613 } 1614 } 1615 1616 return Changed; 1617 } 1618 1619 void analysisGlobalization() { 1620 auto &RFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared]; 1621 1622 auto CheckGlobalization = [&](Use &U, Function &Decl) { 1623 if (CallInst *CI = getCallIfRegularCall(U, &RFI)) { 1624 auto Remark = [&](OptimizationRemarkMissed ORM) { 1625 return ORM 1626 << "Found thread data sharing on the GPU. " 1627 << "Expect degraded performance due to data globalization."; 1628 }; 1629 emitRemark<OptimizationRemarkMissed>(CI, "OMP112", Remark); 1630 } 1631 1632 return false; 1633 }; 1634 1635 RFI.foreachUse(SCC, CheckGlobalization); 1636 } 1637 1638 /// Maps the values stored in the offload arrays passed as arguments to 1639 /// \p RuntimeCall into the offload arrays in \p OAs. 1640 bool getValuesInOffloadArrays(CallInst &RuntimeCall, 1641 MutableArrayRef<OffloadArray> OAs) { 1642 assert(OAs.size() == 3 && "Need space for three offload arrays!"); 1643 1644 // A runtime call that involves memory offloading looks something like: 1645 // call void @__tgt_target_data_begin_mapper(arg0, arg1, 1646 // i8** %offload_baseptrs, i8** %offload_ptrs, i64* %offload_sizes, 1647 // ...) 1648 // So, the idea is to access the allocas that allocate space for these 1649 // offload arrays, offload_baseptrs, offload_ptrs, offload_sizes. 1650 // Therefore: 1651 // i8** %offload_baseptrs. 1652 Value *BasePtrsArg = 1653 RuntimeCall.getArgOperand(OffloadArray::BasePtrsArgNum); 1654 // i8** %offload_ptrs. 1655 Value *PtrsArg = RuntimeCall.getArgOperand(OffloadArray::PtrsArgNum); 1656 // i8** %offload_sizes. 1657 Value *SizesArg = RuntimeCall.getArgOperand(OffloadArray::SizesArgNum); 1658 1659 // Get values stored in **offload_baseptrs. 1660 auto *V = getUnderlyingObject(BasePtrsArg); 1661 if (!isa<AllocaInst>(V)) 1662 return false; 1663 auto *BasePtrsArray = cast<AllocaInst>(V); 1664 if (!OAs[0].initialize(*BasePtrsArray, RuntimeCall)) 1665 return false; 1666 1667 // Get values stored in **offload_baseptrs. 1668 V = getUnderlyingObject(PtrsArg); 1669 if (!isa<AllocaInst>(V)) 1670 return false; 1671 auto *PtrsArray = cast<AllocaInst>(V); 1672 if (!OAs[1].initialize(*PtrsArray, RuntimeCall)) 1673 return false; 1674 1675 // Get values stored in **offload_sizes. 1676 V = getUnderlyingObject(SizesArg); 1677 // If it's a [constant] global array don't analyze it. 1678 if (isa<GlobalValue>(V)) 1679 return isa<Constant>(V); 1680 if (!isa<AllocaInst>(V)) 1681 return false; 1682 1683 auto *SizesArray = cast<AllocaInst>(V); 1684 if (!OAs[2].initialize(*SizesArray, RuntimeCall)) 1685 return false; 1686 1687 return true; 1688 } 1689 1690 /// Prints the values in the OffloadArrays \p OAs using LLVM_DEBUG. 1691 /// For now this is a way to test that the function getValuesInOffloadArrays 1692 /// is working properly. 1693 /// TODO: Move this to a unittest when unittests are available for OpenMPOpt. 1694 void dumpValuesInOffloadArrays(ArrayRef<OffloadArray> OAs) { 1695 assert(OAs.size() == 3 && "There are three offload arrays to debug!"); 1696 1697 LLVM_DEBUG(dbgs() << TAG << " Successfully got offload values:\n"); 1698 std::string ValuesStr; 1699 raw_string_ostream Printer(ValuesStr); 1700 std::string Separator = " --- "; 1701 1702 for (auto *BP : OAs[0].StoredValues) { 1703 BP->print(Printer); 1704 Printer << Separator; 1705 } 1706 LLVM_DEBUG(dbgs() << "\t\toffload_baseptrs: " << Printer.str() << "\n"); 1707 ValuesStr.clear(); 1708 1709 for (auto *P : OAs[1].StoredValues) { 1710 P->print(Printer); 1711 Printer << Separator; 1712 } 1713 LLVM_DEBUG(dbgs() << "\t\toffload_ptrs: " << Printer.str() << "\n"); 1714 ValuesStr.clear(); 1715 1716 for (auto *S : OAs[2].StoredValues) { 1717 S->print(Printer); 1718 Printer << Separator; 1719 } 1720 LLVM_DEBUG(dbgs() << "\t\toffload_sizes: " << Printer.str() << "\n"); 1721 } 1722 1723 /// Returns the instruction where the "wait" counterpart \p RuntimeCall can be 1724 /// moved. Returns nullptr if the movement is not possible, or not worth it. 1725 Instruction *canBeMovedDownwards(CallInst &RuntimeCall) { 1726 // FIXME: This traverses only the BasicBlock where RuntimeCall is. 1727 // Make it traverse the CFG. 1728 1729 Instruction *CurrentI = &RuntimeCall; 1730 bool IsWorthIt = false; 1731 while ((CurrentI = CurrentI->getNextNode())) { 1732 1733 // TODO: Once we detect the regions to be offloaded we should use the 1734 // alias analysis manager to check if CurrentI may modify one of 1735 // the offloaded regions. 1736 if (CurrentI->mayHaveSideEffects() || CurrentI->mayReadFromMemory()) { 1737 if (IsWorthIt) 1738 return CurrentI; 1739 1740 return nullptr; 1741 } 1742 1743 // FIXME: For now if we move it over anything without side effect 1744 // is worth it. 1745 IsWorthIt = true; 1746 } 1747 1748 // Return end of BasicBlock. 1749 return RuntimeCall.getParent()->getTerminator(); 1750 } 1751 1752 /// Splits \p RuntimeCall into its "issue" and "wait" counterparts. 1753 bool splitTargetDataBeginRTC(CallInst &RuntimeCall, 1754 Instruction &WaitMovementPoint) { 1755 // Create stack allocated handle (__tgt_async_info) at the beginning of the 1756 // function. Used for storing information of the async transfer, allowing to 1757 // wait on it later. 1758 auto &IRBuilder = OMPInfoCache.OMPBuilder; 1759 auto *F = RuntimeCall.getCaller(); 1760 Instruction *FirstInst = &(F->getEntryBlock().front()); 1761 AllocaInst *Handle = new AllocaInst( 1762 IRBuilder.AsyncInfo, F->getAddressSpace(), "handle", FirstInst); 1763 1764 // Add "issue" runtime call declaration: 1765 // declare %struct.tgt_async_info @__tgt_target_data_begin_issue(i64, i32, 1766 // i8**, i8**, i64*, i64*) 1767 FunctionCallee IssueDecl = IRBuilder.getOrCreateRuntimeFunction( 1768 M, OMPRTL___tgt_target_data_begin_mapper_issue); 1769 1770 // Change RuntimeCall call site for its asynchronous version. 1771 SmallVector<Value *, 16> Args; 1772 for (auto &Arg : RuntimeCall.args()) 1773 Args.push_back(Arg.get()); 1774 Args.push_back(Handle); 1775 1776 CallInst *IssueCallsite = 1777 CallInst::Create(IssueDecl, Args, /*NameStr=*/"", &RuntimeCall); 1778 OMPInfoCache.setCallingConvention(IssueDecl, IssueCallsite); 1779 RuntimeCall.eraseFromParent(); 1780 1781 // Add "wait" runtime call declaration: 1782 // declare void @__tgt_target_data_begin_wait(i64, %struct.__tgt_async_info) 1783 FunctionCallee WaitDecl = IRBuilder.getOrCreateRuntimeFunction( 1784 M, OMPRTL___tgt_target_data_begin_mapper_wait); 1785 1786 Value *WaitParams[2] = { 1787 IssueCallsite->getArgOperand( 1788 OffloadArray::DeviceIDArgNum), // device_id. 1789 Handle // handle to wait on. 1790 }; 1791 CallInst *WaitCallsite = CallInst::Create( 1792 WaitDecl, WaitParams, /*NameStr=*/"", &WaitMovementPoint); 1793 OMPInfoCache.setCallingConvention(WaitDecl, WaitCallsite); 1794 1795 return true; 1796 } 1797 1798 static Value *combinedIdentStruct(Value *CurrentIdent, Value *NextIdent, 1799 bool GlobalOnly, bool &SingleChoice) { 1800 if (CurrentIdent == NextIdent) 1801 return CurrentIdent; 1802 1803 // TODO: Figure out how to actually combine multiple debug locations. For 1804 // now we just keep an existing one if there is a single choice. 1805 if (!GlobalOnly || isa<GlobalValue>(NextIdent)) { 1806 SingleChoice = !CurrentIdent; 1807 return NextIdent; 1808 } 1809 return nullptr; 1810 } 1811 1812 /// Return an `struct ident_t*` value that represents the ones used in the 1813 /// calls of \p RFI inside of \p F. If \p GlobalOnly is true, we will not 1814 /// return a local `struct ident_t*`. For now, if we cannot find a suitable 1815 /// return value we create one from scratch. We also do not yet combine 1816 /// information, e.g., the source locations, see combinedIdentStruct. 1817 Value * 1818 getCombinedIdentFromCallUsesIn(OMPInformationCache::RuntimeFunctionInfo &RFI, 1819 Function &F, bool GlobalOnly) { 1820 bool SingleChoice = true; 1821 Value *Ident = nullptr; 1822 auto CombineIdentStruct = [&](Use &U, Function &Caller) { 1823 CallInst *CI = getCallIfRegularCall(U, &RFI); 1824 if (!CI || &F != &Caller) 1825 return false; 1826 Ident = combinedIdentStruct(Ident, CI->getArgOperand(0), 1827 /* GlobalOnly */ true, SingleChoice); 1828 return false; 1829 }; 1830 RFI.foreachUse(SCC, CombineIdentStruct); 1831 1832 if (!Ident || !SingleChoice) { 1833 // The IRBuilder uses the insertion block to get to the module, this is 1834 // unfortunate but we work around it for now. 1835 if (!OMPInfoCache.OMPBuilder.getInsertionPoint().getBlock()) 1836 OMPInfoCache.OMPBuilder.updateToLocation(OpenMPIRBuilder::InsertPointTy( 1837 &F.getEntryBlock(), F.getEntryBlock().begin())); 1838 // Create a fallback location if non was found. 1839 // TODO: Use the debug locations of the calls instead. 1840 uint32_t SrcLocStrSize; 1841 Constant *Loc = 1842 OMPInfoCache.OMPBuilder.getOrCreateDefaultSrcLocStr(SrcLocStrSize); 1843 Ident = OMPInfoCache.OMPBuilder.getOrCreateIdent(Loc, SrcLocStrSize); 1844 } 1845 return Ident; 1846 } 1847 1848 /// Try to eliminate calls of \p RFI in \p F by reusing an existing one or 1849 /// \p ReplVal if given. 1850 bool deduplicateRuntimeCalls(Function &F, 1851 OMPInformationCache::RuntimeFunctionInfo &RFI, 1852 Value *ReplVal = nullptr) { 1853 auto *UV = RFI.getUseVector(F); 1854 if (!UV || UV->size() + (ReplVal != nullptr) < 2) 1855 return false; 1856 1857 LLVM_DEBUG( 1858 dbgs() << TAG << "Deduplicate " << UV->size() << " uses of " << RFI.Name 1859 << (ReplVal ? " with an existing value\n" : "\n") << "\n"); 1860 1861 assert((!ReplVal || (isa<Argument>(ReplVal) && 1862 cast<Argument>(ReplVal)->getParent() == &F)) && 1863 "Unexpected replacement value!"); 1864 1865 // TODO: Use dominance to find a good position instead. 1866 auto CanBeMoved = [this](CallBase &CB) { 1867 unsigned NumArgs = CB.arg_size(); 1868 if (NumArgs == 0) 1869 return true; 1870 if (CB.getArgOperand(0)->getType() != OMPInfoCache.OMPBuilder.IdentPtr) 1871 return false; 1872 for (unsigned U = 1; U < NumArgs; ++U) 1873 if (isa<Instruction>(CB.getArgOperand(U))) 1874 return false; 1875 return true; 1876 }; 1877 1878 if (!ReplVal) { 1879 for (Use *U : *UV) 1880 if (CallInst *CI = getCallIfRegularCall(*U, &RFI)) { 1881 if (!CanBeMoved(*CI)) 1882 continue; 1883 1884 // If the function is a kernel, dedup will move 1885 // the runtime call right after the kernel init callsite. Otherwise, 1886 // it will move it to the beginning of the caller function. 1887 if (isKernel(F)) { 1888 auto &KernelInitRFI = OMPInfoCache.RFIs[OMPRTL___kmpc_target_init]; 1889 auto *KernelInitUV = KernelInitRFI.getUseVector(F); 1890 1891 if (KernelInitUV->empty()) 1892 continue; 1893 1894 assert(KernelInitUV->size() == 1 && 1895 "Expected a single __kmpc_target_init in kernel\n"); 1896 1897 CallInst *KernelInitCI = 1898 getCallIfRegularCall(*KernelInitUV->front(), &KernelInitRFI); 1899 assert(KernelInitCI && 1900 "Expected a call to __kmpc_target_init in kernel\n"); 1901 1902 CI->moveAfter(KernelInitCI); 1903 } else 1904 CI->moveBefore(&*F.getEntryBlock().getFirstInsertionPt()); 1905 ReplVal = CI; 1906 break; 1907 } 1908 if (!ReplVal) 1909 return false; 1910 } 1911 1912 // If we use a call as a replacement value we need to make sure the ident is 1913 // valid at the new location. For now we just pick a global one, either 1914 // existing and used by one of the calls, or created from scratch. 1915 if (CallBase *CI = dyn_cast<CallBase>(ReplVal)) { 1916 if (!CI->arg_empty() && 1917 CI->getArgOperand(0)->getType() == OMPInfoCache.OMPBuilder.IdentPtr) { 1918 Value *Ident = getCombinedIdentFromCallUsesIn(RFI, F, 1919 /* GlobalOnly */ true); 1920 CI->setArgOperand(0, Ident); 1921 } 1922 } 1923 1924 bool Changed = false; 1925 auto ReplaceAndDeleteCB = [&](Use &U, Function &Caller) { 1926 CallInst *CI = getCallIfRegularCall(U, &RFI); 1927 if (!CI || CI == ReplVal || &F != &Caller) 1928 return false; 1929 assert(CI->getCaller() == &F && "Unexpected call!"); 1930 1931 auto Remark = [&](OptimizationRemark OR) { 1932 return OR << "OpenMP runtime call " 1933 << ore::NV("OpenMPOptRuntime", RFI.Name) << " deduplicated."; 1934 }; 1935 if (CI->getDebugLoc()) 1936 emitRemark<OptimizationRemark>(CI, "OMP170", Remark); 1937 else 1938 emitRemark<OptimizationRemark>(&F, "OMP170", Remark); 1939 1940 CGUpdater.removeCallSite(*CI); 1941 CI->replaceAllUsesWith(ReplVal); 1942 CI->eraseFromParent(); 1943 ++NumOpenMPRuntimeCallsDeduplicated; 1944 Changed = true; 1945 return true; 1946 }; 1947 RFI.foreachUse(SCC, ReplaceAndDeleteCB); 1948 1949 return Changed; 1950 } 1951 1952 /// Collect arguments that represent the global thread id in \p GTIdArgs. 1953 void collectGlobalThreadIdArguments(SmallSetVector<Value *, 16> >IdArgs) { 1954 // TODO: Below we basically perform a fixpoint iteration with a pessimistic 1955 // initialization. We could define an AbstractAttribute instead and 1956 // run the Attributor here once it can be run as an SCC pass. 1957 1958 // Helper to check the argument \p ArgNo at all call sites of \p F for 1959 // a GTId. 1960 auto CallArgOpIsGTId = [&](Function &F, unsigned ArgNo, CallInst &RefCI) { 1961 if (!F.hasLocalLinkage()) 1962 return false; 1963 for (Use &U : F.uses()) { 1964 if (CallInst *CI = getCallIfRegularCall(U)) { 1965 Value *ArgOp = CI->getArgOperand(ArgNo); 1966 if (CI == &RefCI || GTIdArgs.count(ArgOp) || 1967 getCallIfRegularCall( 1968 *ArgOp, &OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num])) 1969 continue; 1970 } 1971 return false; 1972 } 1973 return true; 1974 }; 1975 1976 // Helper to identify uses of a GTId as GTId arguments. 1977 auto AddUserArgs = [&](Value >Id) { 1978 for (Use &U : GTId.uses()) 1979 if (CallInst *CI = dyn_cast<CallInst>(U.getUser())) 1980 if (CI->isArgOperand(&U)) 1981 if (Function *Callee = CI->getCalledFunction()) 1982 if (CallArgOpIsGTId(*Callee, U.getOperandNo(), *CI)) 1983 GTIdArgs.insert(Callee->getArg(U.getOperandNo())); 1984 }; 1985 1986 // The argument users of __kmpc_global_thread_num calls are GTIds. 1987 OMPInformationCache::RuntimeFunctionInfo &GlobThreadNumRFI = 1988 OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num]; 1989 1990 GlobThreadNumRFI.foreachUse(SCC, [&](Use &U, Function &F) { 1991 if (CallInst *CI = getCallIfRegularCall(U, &GlobThreadNumRFI)) 1992 AddUserArgs(*CI); 1993 return false; 1994 }); 1995 1996 // Transitively search for more arguments by looking at the users of the 1997 // ones we know already. During the search the GTIdArgs vector is extended 1998 // so we cannot cache the size nor can we use a range based for. 1999 for (unsigned U = 0; U < GTIdArgs.size(); ++U) 2000 AddUserArgs(*GTIdArgs[U]); 2001 } 2002 2003 /// Kernel (=GPU) optimizations and utility functions 2004 /// 2005 ///{{ 2006 2007 /// Check if \p F is a kernel, hence entry point for target offloading. 2008 bool isKernel(Function &F) { return OMPInfoCache.Kernels.count(&F); } 2009 2010 /// Cache to remember the unique kernel for a function. 2011 DenseMap<Function *, Optional<Kernel>> UniqueKernelMap; 2012 2013 /// Find the unique kernel that will execute \p F, if any. 2014 Kernel getUniqueKernelFor(Function &F); 2015 2016 /// Find the unique kernel that will execute \p I, if any. 2017 Kernel getUniqueKernelFor(Instruction &I) { 2018 return getUniqueKernelFor(*I.getFunction()); 2019 } 2020 2021 /// Rewrite the device (=GPU) code state machine create in non-SPMD mode in 2022 /// the cases we can avoid taking the address of a function. 2023 bool rewriteDeviceCodeStateMachine(); 2024 2025 /// 2026 ///}} 2027 2028 /// Emit a remark generically 2029 /// 2030 /// This template function can be used to generically emit a remark. The 2031 /// RemarkKind should be one of the following: 2032 /// - OptimizationRemark to indicate a successful optimization attempt 2033 /// - OptimizationRemarkMissed to report a failed optimization attempt 2034 /// - OptimizationRemarkAnalysis to provide additional information about an 2035 /// optimization attempt 2036 /// 2037 /// The remark is built using a callback function provided by the caller that 2038 /// takes a RemarkKind as input and returns a RemarkKind. 2039 template <typename RemarkKind, typename RemarkCallBack> 2040 void emitRemark(Instruction *I, StringRef RemarkName, 2041 RemarkCallBack &&RemarkCB) const { 2042 Function *F = I->getParent()->getParent(); 2043 auto &ORE = OREGetter(F); 2044 2045 if (RemarkName.startswith("OMP")) 2046 ORE.emit([&]() { 2047 return RemarkCB(RemarkKind(DEBUG_TYPE, RemarkName, I)) 2048 << " [" << RemarkName << "]"; 2049 }); 2050 else 2051 ORE.emit( 2052 [&]() { return RemarkCB(RemarkKind(DEBUG_TYPE, RemarkName, I)); }); 2053 } 2054 2055 /// Emit a remark on a function. 2056 template <typename RemarkKind, typename RemarkCallBack> 2057 void emitRemark(Function *F, StringRef RemarkName, 2058 RemarkCallBack &&RemarkCB) const { 2059 auto &ORE = OREGetter(F); 2060 2061 if (RemarkName.startswith("OMP")) 2062 ORE.emit([&]() { 2063 return RemarkCB(RemarkKind(DEBUG_TYPE, RemarkName, F)) 2064 << " [" << RemarkName << "]"; 2065 }); 2066 else 2067 ORE.emit( 2068 [&]() { return RemarkCB(RemarkKind(DEBUG_TYPE, RemarkName, F)); }); 2069 } 2070 2071 /// RAII struct to temporarily change an RTL function's linkage to external. 2072 /// This prevents it from being mistakenly removed by other optimizations. 2073 struct ExternalizationRAII { 2074 ExternalizationRAII(OMPInformationCache &OMPInfoCache, 2075 RuntimeFunction RFKind) 2076 : Declaration(OMPInfoCache.RFIs[RFKind].Declaration) { 2077 if (!Declaration) 2078 return; 2079 2080 LinkageType = Declaration->getLinkage(); 2081 Declaration->setLinkage(GlobalValue::ExternalLinkage); 2082 } 2083 2084 ~ExternalizationRAII() { 2085 if (!Declaration) 2086 return; 2087 2088 Declaration->setLinkage(LinkageType); 2089 } 2090 2091 Function *Declaration; 2092 GlobalValue::LinkageTypes LinkageType; 2093 }; 2094 2095 /// The underlying module. 2096 Module &M; 2097 2098 /// The SCC we are operating on. 2099 SmallVectorImpl<Function *> &SCC; 2100 2101 /// Callback to update the call graph, the first argument is a removed call, 2102 /// the second an optional replacement call. 2103 CallGraphUpdater &CGUpdater; 2104 2105 /// Callback to get an OptimizationRemarkEmitter from a Function * 2106 OptimizationRemarkGetter OREGetter; 2107 2108 /// OpenMP-specific information cache. Also Used for Attributor runs. 2109 OMPInformationCache &OMPInfoCache; 2110 2111 /// Attributor instance. 2112 Attributor &A; 2113 2114 /// Helper function to run Attributor on SCC. 2115 bool runAttributor(bool IsModulePass) { 2116 if (SCC.empty()) 2117 return false; 2118 2119 // Temporarily make these function have external linkage so the Attributor 2120 // doesn't remove them when we try to look them up later. 2121 ExternalizationRAII Parallel(OMPInfoCache, OMPRTL___kmpc_kernel_parallel); 2122 ExternalizationRAII EndParallel(OMPInfoCache, 2123 OMPRTL___kmpc_kernel_end_parallel); 2124 ExternalizationRAII BarrierSPMD(OMPInfoCache, 2125 OMPRTL___kmpc_barrier_simple_spmd); 2126 ExternalizationRAII BarrierGeneric(OMPInfoCache, 2127 OMPRTL___kmpc_barrier_simple_generic); 2128 ExternalizationRAII ThreadId(OMPInfoCache, 2129 OMPRTL___kmpc_get_hardware_thread_id_in_block); 2130 ExternalizationRAII NumThreads( 2131 OMPInfoCache, OMPRTL___kmpc_get_hardware_num_threads_in_block); 2132 ExternalizationRAII WarpSize(OMPInfoCache, OMPRTL___kmpc_get_warp_size); 2133 2134 registerAAs(IsModulePass); 2135 2136 ChangeStatus Changed = A.run(); 2137 2138 LLVM_DEBUG(dbgs() << "[Attributor] Done with " << SCC.size() 2139 << " functions, result: " << Changed << ".\n"); 2140 2141 return Changed == ChangeStatus::CHANGED; 2142 } 2143 2144 void registerFoldRuntimeCall(RuntimeFunction RF); 2145 2146 /// Populate the Attributor with abstract attribute opportunities in the 2147 /// function. 2148 void registerAAs(bool IsModulePass); 2149 }; 2150 2151 Kernel OpenMPOpt::getUniqueKernelFor(Function &F) { 2152 if (!OMPInfoCache.ModuleSlice.count(&F)) 2153 return nullptr; 2154 2155 // Use a scope to keep the lifetime of the CachedKernel short. 2156 { 2157 Optional<Kernel> &CachedKernel = UniqueKernelMap[&F]; 2158 if (CachedKernel) 2159 return *CachedKernel; 2160 2161 // TODO: We should use an AA to create an (optimistic and callback 2162 // call-aware) call graph. For now we stick to simple patterns that 2163 // are less powerful, basically the worst fixpoint. 2164 if (isKernel(F)) { 2165 CachedKernel = Kernel(&F); 2166 return *CachedKernel; 2167 } 2168 2169 CachedKernel = nullptr; 2170 if (!F.hasLocalLinkage()) { 2171 2172 // See https://openmp.llvm.org/remarks/OptimizationRemarks.html 2173 auto Remark = [&](OptimizationRemarkAnalysis ORA) { 2174 return ORA << "Potentially unknown OpenMP target region caller."; 2175 }; 2176 emitRemark<OptimizationRemarkAnalysis>(&F, "OMP100", Remark); 2177 2178 return nullptr; 2179 } 2180 } 2181 2182 auto GetUniqueKernelForUse = [&](const Use &U) -> Kernel { 2183 if (auto *Cmp = dyn_cast<ICmpInst>(U.getUser())) { 2184 // Allow use in equality comparisons. 2185 if (Cmp->isEquality()) 2186 return getUniqueKernelFor(*Cmp); 2187 return nullptr; 2188 } 2189 if (auto *CB = dyn_cast<CallBase>(U.getUser())) { 2190 // Allow direct calls. 2191 if (CB->isCallee(&U)) 2192 return getUniqueKernelFor(*CB); 2193 2194 OMPInformationCache::RuntimeFunctionInfo &KernelParallelRFI = 2195 OMPInfoCache.RFIs[OMPRTL___kmpc_parallel_51]; 2196 // Allow the use in __kmpc_parallel_51 calls. 2197 if (OpenMPOpt::getCallIfRegularCall(*U.getUser(), &KernelParallelRFI)) 2198 return getUniqueKernelFor(*CB); 2199 return nullptr; 2200 } 2201 // Disallow every other use. 2202 return nullptr; 2203 }; 2204 2205 // TODO: In the future we want to track more than just a unique kernel. 2206 SmallPtrSet<Kernel, 2> PotentialKernels; 2207 OMPInformationCache::foreachUse(F, [&](const Use &U) { 2208 PotentialKernels.insert(GetUniqueKernelForUse(U)); 2209 }); 2210 2211 Kernel K = nullptr; 2212 if (PotentialKernels.size() == 1) 2213 K = *PotentialKernels.begin(); 2214 2215 // Cache the result. 2216 UniqueKernelMap[&F] = K; 2217 2218 return K; 2219 } 2220 2221 bool OpenMPOpt::rewriteDeviceCodeStateMachine() { 2222 OMPInformationCache::RuntimeFunctionInfo &KernelParallelRFI = 2223 OMPInfoCache.RFIs[OMPRTL___kmpc_parallel_51]; 2224 2225 bool Changed = false; 2226 if (!KernelParallelRFI) 2227 return Changed; 2228 2229 // If we have disabled state machine changes, exit 2230 if (DisableOpenMPOptStateMachineRewrite) 2231 return Changed; 2232 2233 for (Function *F : SCC) { 2234 2235 // Check if the function is a use in a __kmpc_parallel_51 call at 2236 // all. 2237 bool UnknownUse = false; 2238 bool KernelParallelUse = false; 2239 unsigned NumDirectCalls = 0; 2240 2241 SmallVector<Use *, 2> ToBeReplacedStateMachineUses; 2242 OMPInformationCache::foreachUse(*F, [&](Use &U) { 2243 if (auto *CB = dyn_cast<CallBase>(U.getUser())) 2244 if (CB->isCallee(&U)) { 2245 ++NumDirectCalls; 2246 return; 2247 } 2248 2249 if (isa<ICmpInst>(U.getUser())) { 2250 ToBeReplacedStateMachineUses.push_back(&U); 2251 return; 2252 } 2253 2254 // Find wrapper functions that represent parallel kernels. 2255 CallInst *CI = 2256 OpenMPOpt::getCallIfRegularCall(*U.getUser(), &KernelParallelRFI); 2257 const unsigned int WrapperFunctionArgNo = 6; 2258 if (!KernelParallelUse && CI && 2259 CI->getArgOperandNo(&U) == WrapperFunctionArgNo) { 2260 KernelParallelUse = true; 2261 ToBeReplacedStateMachineUses.push_back(&U); 2262 return; 2263 } 2264 UnknownUse = true; 2265 }); 2266 2267 // Do not emit a remark if we haven't seen a __kmpc_parallel_51 2268 // use. 2269 if (!KernelParallelUse) 2270 continue; 2271 2272 // If this ever hits, we should investigate. 2273 // TODO: Checking the number of uses is not a necessary restriction and 2274 // should be lifted. 2275 if (UnknownUse || NumDirectCalls != 1 || 2276 ToBeReplacedStateMachineUses.size() > 2) { 2277 auto Remark = [&](OptimizationRemarkAnalysis ORA) { 2278 return ORA << "Parallel region is used in " 2279 << (UnknownUse ? "unknown" : "unexpected") 2280 << " ways. Will not attempt to rewrite the state machine."; 2281 }; 2282 emitRemark<OptimizationRemarkAnalysis>(F, "OMP101", Remark); 2283 continue; 2284 } 2285 2286 // Even if we have __kmpc_parallel_51 calls, we (for now) give 2287 // up if the function is not called from a unique kernel. 2288 Kernel K = getUniqueKernelFor(*F); 2289 if (!K) { 2290 auto Remark = [&](OptimizationRemarkAnalysis ORA) { 2291 return ORA << "Parallel region is not called from a unique kernel. " 2292 "Will not attempt to rewrite the state machine."; 2293 }; 2294 emitRemark<OptimizationRemarkAnalysis>(F, "OMP102", Remark); 2295 continue; 2296 } 2297 2298 // We now know F is a parallel body function called only from the kernel K. 2299 // We also identified the state machine uses in which we replace the 2300 // function pointer by a new global symbol for identification purposes. This 2301 // ensures only direct calls to the function are left. 2302 2303 Module &M = *F->getParent(); 2304 Type *Int8Ty = Type::getInt8Ty(M.getContext()); 2305 2306 auto *ID = new GlobalVariable( 2307 M, Int8Ty, /* isConstant */ true, GlobalValue::PrivateLinkage, 2308 UndefValue::get(Int8Ty), F->getName() + ".ID"); 2309 2310 for (Use *U : ToBeReplacedStateMachineUses) 2311 U->set(ConstantExpr::getPointerBitCastOrAddrSpaceCast( 2312 ID, U->get()->getType())); 2313 2314 ++NumOpenMPParallelRegionsReplacedInGPUStateMachine; 2315 2316 Changed = true; 2317 } 2318 2319 return Changed; 2320 } 2321 2322 /// Abstract Attribute for tracking ICV values. 2323 struct AAICVTracker : public StateWrapper<BooleanState, AbstractAttribute> { 2324 using Base = StateWrapper<BooleanState, AbstractAttribute>; 2325 AAICVTracker(const IRPosition &IRP, Attributor &A) : Base(IRP) {} 2326 2327 void initialize(Attributor &A) override { 2328 Function *F = getAnchorScope(); 2329 if (!F || !A.isFunctionIPOAmendable(*F)) 2330 indicatePessimisticFixpoint(); 2331 } 2332 2333 /// Returns true if value is assumed to be tracked. 2334 bool isAssumedTracked() const { return getAssumed(); } 2335 2336 /// Returns true if value is known to be tracked. 2337 bool isKnownTracked() const { return getAssumed(); } 2338 2339 /// Create an abstract attribute biew for the position \p IRP. 2340 static AAICVTracker &createForPosition(const IRPosition &IRP, Attributor &A); 2341 2342 /// Return the value with which \p I can be replaced for specific \p ICV. 2343 virtual Optional<Value *> getReplacementValue(InternalControlVar ICV, 2344 const Instruction *I, 2345 Attributor &A) const { 2346 return None; 2347 } 2348 2349 /// Return an assumed unique ICV value if a single candidate is found. If 2350 /// there cannot be one, return a nullptr. If it is not clear yet, return the 2351 /// Optional::NoneType. 2352 virtual Optional<Value *> 2353 getUniqueReplacementValue(InternalControlVar ICV) const = 0; 2354 2355 // Currently only nthreads is being tracked. 2356 // this array will only grow with time. 2357 InternalControlVar TrackableICVs[1] = {ICV_nthreads}; 2358 2359 /// See AbstractAttribute::getName() 2360 const std::string getName() const override { return "AAICVTracker"; } 2361 2362 /// See AbstractAttribute::getIdAddr() 2363 const char *getIdAddr() const override { return &ID; } 2364 2365 /// This function should return true if the type of the \p AA is AAICVTracker 2366 static bool classof(const AbstractAttribute *AA) { 2367 return (AA->getIdAddr() == &ID); 2368 } 2369 2370 static const char ID; 2371 }; 2372 2373 struct AAICVTrackerFunction : public AAICVTracker { 2374 AAICVTrackerFunction(const IRPosition &IRP, Attributor &A) 2375 : AAICVTracker(IRP, A) {} 2376 2377 // FIXME: come up with better string. 2378 const std::string getAsStr() const override { return "ICVTrackerFunction"; } 2379 2380 // FIXME: come up with some stats. 2381 void trackStatistics() const override {} 2382 2383 /// We don't manifest anything for this AA. 2384 ChangeStatus manifest(Attributor &A) override { 2385 return ChangeStatus::UNCHANGED; 2386 } 2387 2388 // Map of ICV to their values at specific program point. 2389 EnumeratedArray<DenseMap<Instruction *, Value *>, InternalControlVar, 2390 InternalControlVar::ICV___last> 2391 ICVReplacementValuesMap; 2392 2393 ChangeStatus updateImpl(Attributor &A) override { 2394 ChangeStatus HasChanged = ChangeStatus::UNCHANGED; 2395 2396 Function *F = getAnchorScope(); 2397 2398 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 2399 2400 for (InternalControlVar ICV : TrackableICVs) { 2401 auto &SetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Setter]; 2402 2403 auto &ValuesMap = ICVReplacementValuesMap[ICV]; 2404 auto TrackValues = [&](Use &U, Function &) { 2405 CallInst *CI = OpenMPOpt::getCallIfRegularCall(U); 2406 if (!CI) 2407 return false; 2408 2409 // FIXME: handle setters with more that 1 arguments. 2410 /// Track new value. 2411 if (ValuesMap.insert(std::make_pair(CI, CI->getArgOperand(0))).second) 2412 HasChanged = ChangeStatus::CHANGED; 2413 2414 return false; 2415 }; 2416 2417 auto CallCheck = [&](Instruction &I) { 2418 Optional<Value *> ReplVal = getValueForCall(A, I, ICV); 2419 if (ReplVal.hasValue() && 2420 ValuesMap.insert(std::make_pair(&I, *ReplVal)).second) 2421 HasChanged = ChangeStatus::CHANGED; 2422 2423 return true; 2424 }; 2425 2426 // Track all changes of an ICV. 2427 SetterRFI.foreachUse(TrackValues, F); 2428 2429 bool UsedAssumedInformation = false; 2430 A.checkForAllInstructions(CallCheck, *this, {Instruction::Call}, 2431 UsedAssumedInformation, 2432 /* CheckBBLivenessOnly */ true); 2433 2434 /// TODO: Figure out a way to avoid adding entry in 2435 /// ICVReplacementValuesMap 2436 Instruction *Entry = &F->getEntryBlock().front(); 2437 if (HasChanged == ChangeStatus::CHANGED && !ValuesMap.count(Entry)) 2438 ValuesMap.insert(std::make_pair(Entry, nullptr)); 2439 } 2440 2441 return HasChanged; 2442 } 2443 2444 /// Helper to check if \p I is a call and get the value for it if it is 2445 /// unique. 2446 Optional<Value *> getValueForCall(Attributor &A, const Instruction &I, 2447 InternalControlVar &ICV) const { 2448 2449 const auto *CB = dyn_cast<CallBase>(&I); 2450 if (!CB || CB->hasFnAttr("no_openmp") || 2451 CB->hasFnAttr("no_openmp_routines")) 2452 return None; 2453 2454 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 2455 auto &GetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Getter]; 2456 auto &SetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Setter]; 2457 Function *CalledFunction = CB->getCalledFunction(); 2458 2459 // Indirect call, assume ICV changes. 2460 if (CalledFunction == nullptr) 2461 return nullptr; 2462 if (CalledFunction == GetterRFI.Declaration) 2463 return None; 2464 if (CalledFunction == SetterRFI.Declaration) { 2465 if (ICVReplacementValuesMap[ICV].count(&I)) 2466 return ICVReplacementValuesMap[ICV].lookup(&I); 2467 2468 return nullptr; 2469 } 2470 2471 // Since we don't know, assume it changes the ICV. 2472 if (CalledFunction->isDeclaration()) 2473 return nullptr; 2474 2475 const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>( 2476 *this, IRPosition::callsite_returned(*CB), DepClassTy::REQUIRED); 2477 2478 if (ICVTrackingAA.isAssumedTracked()) { 2479 Optional<Value *> URV = ICVTrackingAA.getUniqueReplacementValue(ICV); 2480 if (!URV || (*URV && AA::isValidAtPosition(**URV, I, OMPInfoCache))) 2481 return URV; 2482 } 2483 2484 // If we don't know, assume it changes. 2485 return nullptr; 2486 } 2487 2488 // We don't check unique value for a function, so return None. 2489 Optional<Value *> 2490 getUniqueReplacementValue(InternalControlVar ICV) const override { 2491 return None; 2492 } 2493 2494 /// Return the value with which \p I can be replaced for specific \p ICV. 2495 Optional<Value *> getReplacementValue(InternalControlVar ICV, 2496 const Instruction *I, 2497 Attributor &A) const override { 2498 const auto &ValuesMap = ICVReplacementValuesMap[ICV]; 2499 if (ValuesMap.count(I)) 2500 return ValuesMap.lookup(I); 2501 2502 SmallVector<const Instruction *, 16> Worklist; 2503 SmallPtrSet<const Instruction *, 16> Visited; 2504 Worklist.push_back(I); 2505 2506 Optional<Value *> ReplVal; 2507 2508 while (!Worklist.empty()) { 2509 const Instruction *CurrInst = Worklist.pop_back_val(); 2510 if (!Visited.insert(CurrInst).second) 2511 continue; 2512 2513 const BasicBlock *CurrBB = CurrInst->getParent(); 2514 2515 // Go up and look for all potential setters/calls that might change the 2516 // ICV. 2517 while ((CurrInst = CurrInst->getPrevNode())) { 2518 if (ValuesMap.count(CurrInst)) { 2519 Optional<Value *> NewReplVal = ValuesMap.lookup(CurrInst); 2520 // Unknown value, track new. 2521 if (!ReplVal.hasValue()) { 2522 ReplVal = NewReplVal; 2523 break; 2524 } 2525 2526 // If we found a new value, we can't know the icv value anymore. 2527 if (NewReplVal.hasValue()) 2528 if (ReplVal != NewReplVal) 2529 return nullptr; 2530 2531 break; 2532 } 2533 2534 Optional<Value *> NewReplVal = getValueForCall(A, *CurrInst, ICV); 2535 if (!NewReplVal.hasValue()) 2536 continue; 2537 2538 // Unknown value, track new. 2539 if (!ReplVal.hasValue()) { 2540 ReplVal = NewReplVal; 2541 break; 2542 } 2543 2544 // if (NewReplVal.hasValue()) 2545 // We found a new value, we can't know the icv value anymore. 2546 if (ReplVal != NewReplVal) 2547 return nullptr; 2548 } 2549 2550 // If we are in the same BB and we have a value, we are done. 2551 if (CurrBB == I->getParent() && ReplVal.hasValue()) 2552 return ReplVal; 2553 2554 // Go through all predecessors and add terminators for analysis. 2555 for (const BasicBlock *Pred : predecessors(CurrBB)) 2556 if (const Instruction *Terminator = Pred->getTerminator()) 2557 Worklist.push_back(Terminator); 2558 } 2559 2560 return ReplVal; 2561 } 2562 }; 2563 2564 struct AAICVTrackerFunctionReturned : AAICVTracker { 2565 AAICVTrackerFunctionReturned(const IRPosition &IRP, Attributor &A) 2566 : AAICVTracker(IRP, A) {} 2567 2568 // FIXME: come up with better string. 2569 const std::string getAsStr() const override { 2570 return "ICVTrackerFunctionReturned"; 2571 } 2572 2573 // FIXME: come up with some stats. 2574 void trackStatistics() const override {} 2575 2576 /// We don't manifest anything for this AA. 2577 ChangeStatus manifest(Attributor &A) override { 2578 return ChangeStatus::UNCHANGED; 2579 } 2580 2581 // Map of ICV to their values at specific program point. 2582 EnumeratedArray<Optional<Value *>, InternalControlVar, 2583 InternalControlVar::ICV___last> 2584 ICVReplacementValuesMap; 2585 2586 /// Return the value with which \p I can be replaced for specific \p ICV. 2587 Optional<Value *> 2588 getUniqueReplacementValue(InternalControlVar ICV) const override { 2589 return ICVReplacementValuesMap[ICV]; 2590 } 2591 2592 ChangeStatus updateImpl(Attributor &A) override { 2593 ChangeStatus Changed = ChangeStatus::UNCHANGED; 2594 const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>( 2595 *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED); 2596 2597 if (!ICVTrackingAA.isAssumedTracked()) 2598 return indicatePessimisticFixpoint(); 2599 2600 for (InternalControlVar ICV : TrackableICVs) { 2601 Optional<Value *> &ReplVal = ICVReplacementValuesMap[ICV]; 2602 Optional<Value *> UniqueICVValue; 2603 2604 auto CheckReturnInst = [&](Instruction &I) { 2605 Optional<Value *> NewReplVal = 2606 ICVTrackingAA.getReplacementValue(ICV, &I, A); 2607 2608 // If we found a second ICV value there is no unique returned value. 2609 if (UniqueICVValue.hasValue() && UniqueICVValue != NewReplVal) 2610 return false; 2611 2612 UniqueICVValue = NewReplVal; 2613 2614 return true; 2615 }; 2616 2617 bool UsedAssumedInformation = false; 2618 if (!A.checkForAllInstructions(CheckReturnInst, *this, {Instruction::Ret}, 2619 UsedAssumedInformation, 2620 /* CheckBBLivenessOnly */ true)) 2621 UniqueICVValue = nullptr; 2622 2623 if (UniqueICVValue == ReplVal) 2624 continue; 2625 2626 ReplVal = UniqueICVValue; 2627 Changed = ChangeStatus::CHANGED; 2628 } 2629 2630 return Changed; 2631 } 2632 }; 2633 2634 struct AAICVTrackerCallSite : AAICVTracker { 2635 AAICVTrackerCallSite(const IRPosition &IRP, Attributor &A) 2636 : AAICVTracker(IRP, A) {} 2637 2638 void initialize(Attributor &A) override { 2639 Function *F = getAnchorScope(); 2640 if (!F || !A.isFunctionIPOAmendable(*F)) 2641 indicatePessimisticFixpoint(); 2642 2643 // We only initialize this AA for getters, so we need to know which ICV it 2644 // gets. 2645 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 2646 for (InternalControlVar ICV : TrackableICVs) { 2647 auto ICVInfo = OMPInfoCache.ICVs[ICV]; 2648 auto &Getter = OMPInfoCache.RFIs[ICVInfo.Getter]; 2649 if (Getter.Declaration == getAssociatedFunction()) { 2650 AssociatedICV = ICVInfo.Kind; 2651 return; 2652 } 2653 } 2654 2655 /// Unknown ICV. 2656 indicatePessimisticFixpoint(); 2657 } 2658 2659 ChangeStatus manifest(Attributor &A) override { 2660 if (!ReplVal.hasValue() || !ReplVal.getValue()) 2661 return ChangeStatus::UNCHANGED; 2662 2663 A.changeValueAfterManifest(*getCtxI(), **ReplVal); 2664 A.deleteAfterManifest(*getCtxI()); 2665 2666 return ChangeStatus::CHANGED; 2667 } 2668 2669 // FIXME: come up with better string. 2670 const std::string getAsStr() const override { return "ICVTrackerCallSite"; } 2671 2672 // FIXME: come up with some stats. 2673 void trackStatistics() const override {} 2674 2675 InternalControlVar AssociatedICV; 2676 Optional<Value *> ReplVal; 2677 2678 ChangeStatus updateImpl(Attributor &A) override { 2679 const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>( 2680 *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED); 2681 2682 // We don't have any information, so we assume it changes the ICV. 2683 if (!ICVTrackingAA.isAssumedTracked()) 2684 return indicatePessimisticFixpoint(); 2685 2686 Optional<Value *> NewReplVal = 2687 ICVTrackingAA.getReplacementValue(AssociatedICV, getCtxI(), A); 2688 2689 if (ReplVal == NewReplVal) 2690 return ChangeStatus::UNCHANGED; 2691 2692 ReplVal = NewReplVal; 2693 return ChangeStatus::CHANGED; 2694 } 2695 2696 // Return the value with which associated value can be replaced for specific 2697 // \p ICV. 2698 Optional<Value *> 2699 getUniqueReplacementValue(InternalControlVar ICV) const override { 2700 return ReplVal; 2701 } 2702 }; 2703 2704 struct AAICVTrackerCallSiteReturned : AAICVTracker { 2705 AAICVTrackerCallSiteReturned(const IRPosition &IRP, Attributor &A) 2706 : AAICVTracker(IRP, A) {} 2707 2708 // FIXME: come up with better string. 2709 const std::string getAsStr() const override { 2710 return "ICVTrackerCallSiteReturned"; 2711 } 2712 2713 // FIXME: come up with some stats. 2714 void trackStatistics() const override {} 2715 2716 /// We don't manifest anything for this AA. 2717 ChangeStatus manifest(Attributor &A) override { 2718 return ChangeStatus::UNCHANGED; 2719 } 2720 2721 // Map of ICV to their values at specific program point. 2722 EnumeratedArray<Optional<Value *>, InternalControlVar, 2723 InternalControlVar::ICV___last> 2724 ICVReplacementValuesMap; 2725 2726 /// Return the value with which associated value can be replaced for specific 2727 /// \p ICV. 2728 Optional<Value *> 2729 getUniqueReplacementValue(InternalControlVar ICV) const override { 2730 return ICVReplacementValuesMap[ICV]; 2731 } 2732 2733 ChangeStatus updateImpl(Attributor &A) override { 2734 ChangeStatus Changed = ChangeStatus::UNCHANGED; 2735 const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>( 2736 *this, IRPosition::returned(*getAssociatedFunction()), 2737 DepClassTy::REQUIRED); 2738 2739 // We don't have any information, so we assume it changes the ICV. 2740 if (!ICVTrackingAA.isAssumedTracked()) 2741 return indicatePessimisticFixpoint(); 2742 2743 for (InternalControlVar ICV : TrackableICVs) { 2744 Optional<Value *> &ReplVal = ICVReplacementValuesMap[ICV]; 2745 Optional<Value *> NewReplVal = 2746 ICVTrackingAA.getUniqueReplacementValue(ICV); 2747 2748 if (ReplVal == NewReplVal) 2749 continue; 2750 2751 ReplVal = NewReplVal; 2752 Changed = ChangeStatus::CHANGED; 2753 } 2754 return Changed; 2755 } 2756 }; 2757 2758 struct AAExecutionDomainFunction : public AAExecutionDomain { 2759 AAExecutionDomainFunction(const IRPosition &IRP, Attributor &A) 2760 : AAExecutionDomain(IRP, A) {} 2761 2762 const std::string getAsStr() const override { 2763 return "[AAExecutionDomain] " + std::to_string(SingleThreadedBBs.size()) + 2764 "/" + std::to_string(NumBBs) + " BBs thread 0 only."; 2765 } 2766 2767 /// See AbstractAttribute::trackStatistics(). 2768 void trackStatistics() const override {} 2769 2770 void initialize(Attributor &A) override { 2771 Function *F = getAnchorScope(); 2772 for (const auto &BB : *F) 2773 SingleThreadedBBs.insert(&BB); 2774 NumBBs = SingleThreadedBBs.size(); 2775 } 2776 2777 ChangeStatus manifest(Attributor &A) override { 2778 LLVM_DEBUG({ 2779 for (const BasicBlock *BB : SingleThreadedBBs) 2780 dbgs() << TAG << " Basic block @" << getAnchorScope()->getName() << " " 2781 << BB->getName() << " is executed by a single thread.\n"; 2782 }); 2783 return ChangeStatus::UNCHANGED; 2784 } 2785 2786 ChangeStatus updateImpl(Attributor &A) override; 2787 2788 /// Check if an instruction is executed by a single thread. 2789 bool isExecutedByInitialThreadOnly(const Instruction &I) const override { 2790 return isExecutedByInitialThreadOnly(*I.getParent()); 2791 } 2792 2793 bool isExecutedByInitialThreadOnly(const BasicBlock &BB) const override { 2794 return isValidState() && SingleThreadedBBs.contains(&BB); 2795 } 2796 2797 /// Set of basic blocks that are executed by a single thread. 2798 SmallSetVector<const BasicBlock *, 16> SingleThreadedBBs; 2799 2800 /// Total number of basic blocks in this function. 2801 long unsigned NumBBs = 0; 2802 }; 2803 2804 ChangeStatus AAExecutionDomainFunction::updateImpl(Attributor &A) { 2805 Function *F = getAnchorScope(); 2806 ReversePostOrderTraversal<Function *> RPOT(F); 2807 auto NumSingleThreadedBBs = SingleThreadedBBs.size(); 2808 2809 bool AllCallSitesKnown; 2810 auto PredForCallSite = [&](AbstractCallSite ACS) { 2811 const auto &ExecutionDomainAA = A.getAAFor<AAExecutionDomain>( 2812 *this, IRPosition::function(*ACS.getInstruction()->getFunction()), 2813 DepClassTy::REQUIRED); 2814 return ACS.isDirectCall() && 2815 ExecutionDomainAA.isExecutedByInitialThreadOnly( 2816 *ACS.getInstruction()); 2817 }; 2818 2819 if (!A.checkForAllCallSites(PredForCallSite, *this, 2820 /* RequiresAllCallSites */ true, 2821 AllCallSitesKnown)) 2822 SingleThreadedBBs.remove(&F->getEntryBlock()); 2823 2824 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 2825 auto &RFI = OMPInfoCache.RFIs[OMPRTL___kmpc_target_init]; 2826 2827 // Check if the edge into the successor block contains a condition that only 2828 // lets the main thread execute it. 2829 auto IsInitialThreadOnly = [&](BranchInst *Edge, BasicBlock *SuccessorBB) { 2830 if (!Edge || !Edge->isConditional()) 2831 return false; 2832 if (Edge->getSuccessor(0) != SuccessorBB) 2833 return false; 2834 2835 auto *Cmp = dyn_cast<CmpInst>(Edge->getCondition()); 2836 if (!Cmp || !Cmp->isTrueWhenEqual() || !Cmp->isEquality()) 2837 return false; 2838 2839 ConstantInt *C = dyn_cast<ConstantInt>(Cmp->getOperand(1)); 2840 if (!C) 2841 return false; 2842 2843 // Match: -1 == __kmpc_target_init (for non-SPMD kernels only!) 2844 if (C->isAllOnesValue()) { 2845 auto *CB = dyn_cast<CallBase>(Cmp->getOperand(0)); 2846 CB = CB ? OpenMPOpt::getCallIfRegularCall(*CB, &RFI) : nullptr; 2847 if (!CB) 2848 return false; 2849 const int InitModeArgNo = 1; 2850 auto *ModeCI = dyn_cast<ConstantInt>(CB->getOperand(InitModeArgNo)); 2851 return ModeCI && (ModeCI->getSExtValue() & OMP_TGT_EXEC_MODE_GENERIC); 2852 } 2853 2854 if (C->isZero()) { 2855 // Match: 0 == llvm.nvvm.read.ptx.sreg.tid.x() 2856 if (auto *II = dyn_cast<IntrinsicInst>(Cmp->getOperand(0))) 2857 if (II->getIntrinsicID() == Intrinsic::nvvm_read_ptx_sreg_tid_x) 2858 return true; 2859 2860 // Match: 0 == llvm.amdgcn.workitem.id.x() 2861 if (auto *II = dyn_cast<IntrinsicInst>(Cmp->getOperand(0))) 2862 if (II->getIntrinsicID() == Intrinsic::amdgcn_workitem_id_x) 2863 return true; 2864 } 2865 2866 return false; 2867 }; 2868 2869 // Merge all the predecessor states into the current basic block. A basic 2870 // block is executed by a single thread if all of its predecessors are. 2871 auto MergePredecessorStates = [&](BasicBlock *BB) { 2872 if (pred_empty(BB)) 2873 return SingleThreadedBBs.contains(BB); 2874 2875 bool IsInitialThread = true; 2876 for (BasicBlock *PredBB : predecessors(BB)) { 2877 if (!IsInitialThreadOnly(dyn_cast<BranchInst>(PredBB->getTerminator()), 2878 BB)) 2879 IsInitialThread &= SingleThreadedBBs.contains(PredBB); 2880 } 2881 2882 return IsInitialThread; 2883 }; 2884 2885 for (auto *BB : RPOT) { 2886 if (!MergePredecessorStates(BB)) 2887 SingleThreadedBBs.remove(BB); 2888 } 2889 2890 return (NumSingleThreadedBBs == SingleThreadedBBs.size()) 2891 ? ChangeStatus::UNCHANGED 2892 : ChangeStatus::CHANGED; 2893 } 2894 2895 /// Try to replace memory allocation calls called by a single thread with a 2896 /// static buffer of shared memory. 2897 struct AAHeapToShared : public StateWrapper<BooleanState, AbstractAttribute> { 2898 using Base = StateWrapper<BooleanState, AbstractAttribute>; 2899 AAHeapToShared(const IRPosition &IRP, Attributor &A) : Base(IRP) {} 2900 2901 /// Create an abstract attribute view for the position \p IRP. 2902 static AAHeapToShared &createForPosition(const IRPosition &IRP, 2903 Attributor &A); 2904 2905 /// Returns true if HeapToShared conversion is assumed to be possible. 2906 virtual bool isAssumedHeapToShared(CallBase &CB) const = 0; 2907 2908 /// Returns true if HeapToShared conversion is assumed and the CB is a 2909 /// callsite to a free operation to be removed. 2910 virtual bool isAssumedHeapToSharedRemovedFree(CallBase &CB) const = 0; 2911 2912 /// See AbstractAttribute::getName(). 2913 const std::string getName() const override { return "AAHeapToShared"; } 2914 2915 /// See AbstractAttribute::getIdAddr(). 2916 const char *getIdAddr() const override { return &ID; } 2917 2918 /// This function should return true if the type of the \p AA is 2919 /// AAHeapToShared. 2920 static bool classof(const AbstractAttribute *AA) { 2921 return (AA->getIdAddr() == &ID); 2922 } 2923 2924 /// Unique ID (due to the unique address) 2925 static const char ID; 2926 }; 2927 2928 struct AAHeapToSharedFunction : public AAHeapToShared { 2929 AAHeapToSharedFunction(const IRPosition &IRP, Attributor &A) 2930 : AAHeapToShared(IRP, A) {} 2931 2932 const std::string getAsStr() const override { 2933 return "[AAHeapToShared] " + std::to_string(MallocCalls.size()) + 2934 " malloc calls eligible."; 2935 } 2936 2937 /// See AbstractAttribute::trackStatistics(). 2938 void trackStatistics() const override {} 2939 2940 /// This functions finds free calls that will be removed by the 2941 /// HeapToShared transformation. 2942 void findPotentialRemovedFreeCalls(Attributor &A) { 2943 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 2944 auto &FreeRFI = OMPInfoCache.RFIs[OMPRTL___kmpc_free_shared]; 2945 2946 PotentialRemovedFreeCalls.clear(); 2947 // Update free call users of found malloc calls. 2948 for (CallBase *CB : MallocCalls) { 2949 SmallVector<CallBase *, 4> FreeCalls; 2950 for (auto *U : CB->users()) { 2951 CallBase *C = dyn_cast<CallBase>(U); 2952 if (C && C->getCalledFunction() == FreeRFI.Declaration) 2953 FreeCalls.push_back(C); 2954 } 2955 2956 if (FreeCalls.size() != 1) 2957 continue; 2958 2959 PotentialRemovedFreeCalls.insert(FreeCalls.front()); 2960 } 2961 } 2962 2963 void initialize(Attributor &A) override { 2964 if (DisableOpenMPOptDeglobalization) { 2965 indicatePessimisticFixpoint(); 2966 return; 2967 } 2968 2969 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 2970 auto &RFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared]; 2971 2972 Attributor::SimplifictionCallbackTy SCB = 2973 [](const IRPosition &, const AbstractAttribute *, 2974 bool &) -> Optional<Value *> { return nullptr; }; 2975 for (User *U : RFI.Declaration->users()) 2976 if (CallBase *CB = dyn_cast<CallBase>(U)) { 2977 MallocCalls.insert(CB); 2978 A.registerSimplificationCallback(IRPosition::callsite_returned(*CB), 2979 SCB); 2980 } 2981 2982 findPotentialRemovedFreeCalls(A); 2983 } 2984 2985 bool isAssumedHeapToShared(CallBase &CB) const override { 2986 return isValidState() && MallocCalls.count(&CB); 2987 } 2988 2989 bool isAssumedHeapToSharedRemovedFree(CallBase &CB) const override { 2990 return isValidState() && PotentialRemovedFreeCalls.count(&CB); 2991 } 2992 2993 ChangeStatus manifest(Attributor &A) override { 2994 if (MallocCalls.empty()) 2995 return ChangeStatus::UNCHANGED; 2996 2997 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 2998 auto &FreeCall = OMPInfoCache.RFIs[OMPRTL___kmpc_free_shared]; 2999 3000 Function *F = getAnchorScope(); 3001 auto *HS = A.lookupAAFor<AAHeapToStack>(IRPosition::function(*F), this, 3002 DepClassTy::OPTIONAL); 3003 3004 ChangeStatus Changed = ChangeStatus::UNCHANGED; 3005 for (CallBase *CB : MallocCalls) { 3006 // Skip replacing this if HeapToStack has already claimed it. 3007 if (HS && HS->isAssumedHeapToStack(*CB)) 3008 continue; 3009 3010 // Find the unique free call to remove it. 3011 SmallVector<CallBase *, 4> FreeCalls; 3012 for (auto *U : CB->users()) { 3013 CallBase *C = dyn_cast<CallBase>(U); 3014 if (C && C->getCalledFunction() == FreeCall.Declaration) 3015 FreeCalls.push_back(C); 3016 } 3017 if (FreeCalls.size() != 1) 3018 continue; 3019 3020 auto *AllocSize = cast<ConstantInt>(CB->getArgOperand(0)); 3021 3022 if (AllocSize->getZExtValue() + SharedMemoryUsed > SharedMemoryLimit) { 3023 LLVM_DEBUG(dbgs() << TAG << "Cannot replace call " << *CB 3024 << " with shared memory." 3025 << " Shared memory usage is limited to " 3026 << SharedMemoryLimit << " bytes\n"); 3027 continue; 3028 } 3029 3030 LLVM_DEBUG(dbgs() << TAG << "Replace globalization call " << *CB 3031 << " with " << AllocSize->getZExtValue() 3032 << " bytes of shared memory\n"); 3033 3034 // Create a new shared memory buffer of the same size as the allocation 3035 // and replace all the uses of the original allocation with it. 3036 Module *M = CB->getModule(); 3037 Type *Int8Ty = Type::getInt8Ty(M->getContext()); 3038 Type *Int8ArrTy = ArrayType::get(Int8Ty, AllocSize->getZExtValue()); 3039 auto *SharedMem = new GlobalVariable( 3040 *M, Int8ArrTy, /* IsConstant */ false, GlobalValue::InternalLinkage, 3041 UndefValue::get(Int8ArrTy), CB->getName() + "_shared", nullptr, 3042 GlobalValue::NotThreadLocal, 3043 static_cast<unsigned>(AddressSpace::Shared)); 3044 auto *NewBuffer = 3045 ConstantExpr::getPointerCast(SharedMem, Int8Ty->getPointerTo()); 3046 3047 auto Remark = [&](OptimizationRemark OR) { 3048 return OR << "Replaced globalized variable with " 3049 << ore::NV("SharedMemory", AllocSize->getZExtValue()) 3050 << ((AllocSize->getZExtValue() != 1) ? " bytes " : " byte ") 3051 << "of shared memory."; 3052 }; 3053 A.emitRemark<OptimizationRemark>(CB, "OMP111", Remark); 3054 3055 MaybeAlign Alignment = CB->getRetAlign(); 3056 assert(Alignment && 3057 "HeapToShared on allocation without alignment attribute"); 3058 SharedMem->setAlignment(MaybeAlign(Alignment)); 3059 3060 A.changeValueAfterManifest(*CB, *NewBuffer); 3061 A.deleteAfterManifest(*CB); 3062 A.deleteAfterManifest(*FreeCalls.front()); 3063 3064 SharedMemoryUsed += AllocSize->getZExtValue(); 3065 NumBytesMovedToSharedMemory = SharedMemoryUsed; 3066 Changed = ChangeStatus::CHANGED; 3067 } 3068 3069 return Changed; 3070 } 3071 3072 ChangeStatus updateImpl(Attributor &A) override { 3073 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 3074 auto &RFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared]; 3075 Function *F = getAnchorScope(); 3076 3077 auto NumMallocCalls = MallocCalls.size(); 3078 3079 // Only consider malloc calls executed by a single thread with a constant. 3080 for (User *U : RFI.Declaration->users()) { 3081 const auto &ED = A.getAAFor<AAExecutionDomain>( 3082 *this, IRPosition::function(*F), DepClassTy::REQUIRED); 3083 if (CallBase *CB = dyn_cast<CallBase>(U)) 3084 if (!isa<ConstantInt>(CB->getArgOperand(0)) || 3085 !ED.isExecutedByInitialThreadOnly(*CB)) 3086 MallocCalls.remove(CB); 3087 } 3088 3089 findPotentialRemovedFreeCalls(A); 3090 3091 if (NumMallocCalls != MallocCalls.size()) 3092 return ChangeStatus::CHANGED; 3093 3094 return ChangeStatus::UNCHANGED; 3095 } 3096 3097 /// Collection of all malloc calls in a function. 3098 SmallSetVector<CallBase *, 4> MallocCalls; 3099 /// Collection of potentially removed free calls in a function. 3100 SmallPtrSet<CallBase *, 4> PotentialRemovedFreeCalls; 3101 /// The total amount of shared memory that has been used for HeapToShared. 3102 unsigned SharedMemoryUsed = 0; 3103 }; 3104 3105 struct AAKernelInfo : public StateWrapper<KernelInfoState, AbstractAttribute> { 3106 using Base = StateWrapper<KernelInfoState, AbstractAttribute>; 3107 AAKernelInfo(const IRPosition &IRP, Attributor &A) : Base(IRP) {} 3108 3109 /// Statistics are tracked as part of manifest for now. 3110 void trackStatistics() const override {} 3111 3112 /// See AbstractAttribute::getAsStr() 3113 const std::string getAsStr() const override { 3114 if (!isValidState()) 3115 return "<invalid>"; 3116 return std::string(SPMDCompatibilityTracker.isAssumed() ? "SPMD" 3117 : "generic") + 3118 std::string(SPMDCompatibilityTracker.isAtFixpoint() ? " [FIX]" 3119 : "") + 3120 std::string(" #PRs: ") + 3121 (ReachedKnownParallelRegions.isValidState() 3122 ? std::to_string(ReachedKnownParallelRegions.size()) 3123 : "<invalid>") + 3124 ", #Unknown PRs: " + 3125 (ReachedUnknownParallelRegions.isValidState() 3126 ? std::to_string(ReachedUnknownParallelRegions.size()) 3127 : "<invalid>") + 3128 ", #Reaching Kernels: " + 3129 (ReachingKernelEntries.isValidState() 3130 ? std::to_string(ReachingKernelEntries.size()) 3131 : "<invalid>"); 3132 } 3133 3134 /// Create an abstract attribute biew for the position \p IRP. 3135 static AAKernelInfo &createForPosition(const IRPosition &IRP, Attributor &A); 3136 3137 /// See AbstractAttribute::getName() 3138 const std::string getName() const override { return "AAKernelInfo"; } 3139 3140 /// See AbstractAttribute::getIdAddr() 3141 const char *getIdAddr() const override { return &ID; } 3142 3143 /// This function should return true if the type of the \p AA is AAKernelInfo 3144 static bool classof(const AbstractAttribute *AA) { 3145 return (AA->getIdAddr() == &ID); 3146 } 3147 3148 static const char ID; 3149 }; 3150 3151 /// The function kernel info abstract attribute, basically, what can we say 3152 /// about a function with regards to the KernelInfoState. 3153 struct AAKernelInfoFunction : AAKernelInfo { 3154 AAKernelInfoFunction(const IRPosition &IRP, Attributor &A) 3155 : AAKernelInfo(IRP, A) {} 3156 3157 SmallPtrSet<Instruction *, 4> GuardedInstructions; 3158 3159 SmallPtrSetImpl<Instruction *> &getGuardedInstructions() { 3160 return GuardedInstructions; 3161 } 3162 3163 /// See AbstractAttribute::initialize(...). 3164 void initialize(Attributor &A) override { 3165 // This is a high-level transform that might change the constant arguments 3166 // of the init and dinit calls. We need to tell the Attributor about this 3167 // to avoid other parts using the current constant value for simpliication. 3168 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 3169 3170 Function *Fn = getAnchorScope(); 3171 3172 OMPInformationCache::RuntimeFunctionInfo &InitRFI = 3173 OMPInfoCache.RFIs[OMPRTL___kmpc_target_init]; 3174 OMPInformationCache::RuntimeFunctionInfo &DeinitRFI = 3175 OMPInfoCache.RFIs[OMPRTL___kmpc_target_deinit]; 3176 3177 // For kernels we perform more initialization work, first we find the init 3178 // and deinit calls. 3179 auto StoreCallBase = [](Use &U, 3180 OMPInformationCache::RuntimeFunctionInfo &RFI, 3181 CallBase *&Storage) { 3182 CallBase *CB = OpenMPOpt::getCallIfRegularCall(U, &RFI); 3183 assert(CB && 3184 "Unexpected use of __kmpc_target_init or __kmpc_target_deinit!"); 3185 assert(!Storage && 3186 "Multiple uses of __kmpc_target_init or __kmpc_target_deinit!"); 3187 Storage = CB; 3188 return false; 3189 }; 3190 InitRFI.foreachUse( 3191 [&](Use &U, Function &) { 3192 StoreCallBase(U, InitRFI, KernelInitCB); 3193 return false; 3194 }, 3195 Fn); 3196 DeinitRFI.foreachUse( 3197 [&](Use &U, Function &) { 3198 StoreCallBase(U, DeinitRFI, KernelDeinitCB); 3199 return false; 3200 }, 3201 Fn); 3202 3203 // Ignore kernels without initializers such as global constructors. 3204 if (!KernelInitCB || !KernelDeinitCB) 3205 return; 3206 3207 // Add itself to the reaching kernel and set IsKernelEntry. 3208 ReachingKernelEntries.insert(Fn); 3209 IsKernelEntry = true; 3210 3211 // For kernels we might need to initialize/finalize the IsSPMD state and 3212 // we need to register a simplification callback so that the Attributor 3213 // knows the constant arguments to __kmpc_target_init and 3214 // __kmpc_target_deinit might actually change. 3215 3216 Attributor::SimplifictionCallbackTy StateMachineSimplifyCB = 3217 [&](const IRPosition &IRP, const AbstractAttribute *AA, 3218 bool &UsedAssumedInformation) -> Optional<Value *> { 3219 // IRP represents the "use generic state machine" argument of an 3220 // __kmpc_target_init call. We will answer this one with the internal 3221 // state. As long as we are not in an invalid state, we will create a 3222 // custom state machine so the value should be a `i1 false`. If we are 3223 // in an invalid state, we won't change the value that is in the IR. 3224 if (!ReachedKnownParallelRegions.isValidState()) 3225 return nullptr; 3226 // If we have disabled state machine rewrites, don't make a custom one. 3227 if (DisableOpenMPOptStateMachineRewrite) 3228 return nullptr; 3229 if (AA) 3230 A.recordDependence(*this, *AA, DepClassTy::OPTIONAL); 3231 UsedAssumedInformation = !isAtFixpoint(); 3232 auto *FalseVal = 3233 ConstantInt::getBool(IRP.getAnchorValue().getContext(), false); 3234 return FalseVal; 3235 }; 3236 3237 Attributor::SimplifictionCallbackTy ModeSimplifyCB = 3238 [&](const IRPosition &IRP, const AbstractAttribute *AA, 3239 bool &UsedAssumedInformation) -> Optional<Value *> { 3240 // IRP represents the "SPMDCompatibilityTracker" argument of an 3241 // __kmpc_target_init or 3242 // __kmpc_target_deinit call. We will answer this one with the internal 3243 // state. 3244 if (!SPMDCompatibilityTracker.isValidState()) 3245 return nullptr; 3246 if (!SPMDCompatibilityTracker.isAtFixpoint()) { 3247 if (AA) 3248 A.recordDependence(*this, *AA, DepClassTy::OPTIONAL); 3249 UsedAssumedInformation = true; 3250 } else { 3251 UsedAssumedInformation = false; 3252 } 3253 auto *Val = ConstantInt::getSigned( 3254 IntegerType::getInt8Ty(IRP.getAnchorValue().getContext()), 3255 SPMDCompatibilityTracker.isAssumed() ? OMP_TGT_EXEC_MODE_SPMD 3256 : OMP_TGT_EXEC_MODE_GENERIC); 3257 return Val; 3258 }; 3259 3260 Attributor::SimplifictionCallbackTy IsGenericModeSimplifyCB = 3261 [&](const IRPosition &IRP, const AbstractAttribute *AA, 3262 bool &UsedAssumedInformation) -> Optional<Value *> { 3263 // IRP represents the "RequiresFullRuntime" argument of an 3264 // __kmpc_target_init or __kmpc_target_deinit call. We will answer this 3265 // one with the internal state of the SPMDCompatibilityTracker, so if 3266 // generic then true, if SPMD then false. 3267 if (!SPMDCompatibilityTracker.isValidState()) 3268 return nullptr; 3269 if (!SPMDCompatibilityTracker.isAtFixpoint()) { 3270 if (AA) 3271 A.recordDependence(*this, *AA, DepClassTy::OPTIONAL); 3272 UsedAssumedInformation = true; 3273 } else { 3274 UsedAssumedInformation = false; 3275 } 3276 auto *Val = ConstantInt::getBool(IRP.getAnchorValue().getContext(), 3277 !SPMDCompatibilityTracker.isAssumed()); 3278 return Val; 3279 }; 3280 3281 constexpr const int InitModeArgNo = 1; 3282 constexpr const int DeinitModeArgNo = 1; 3283 constexpr const int InitUseStateMachineArgNo = 2; 3284 constexpr const int InitRequiresFullRuntimeArgNo = 3; 3285 constexpr const int DeinitRequiresFullRuntimeArgNo = 2; 3286 A.registerSimplificationCallback( 3287 IRPosition::callsite_argument(*KernelInitCB, InitUseStateMachineArgNo), 3288 StateMachineSimplifyCB); 3289 A.registerSimplificationCallback( 3290 IRPosition::callsite_argument(*KernelInitCB, InitModeArgNo), 3291 ModeSimplifyCB); 3292 A.registerSimplificationCallback( 3293 IRPosition::callsite_argument(*KernelDeinitCB, DeinitModeArgNo), 3294 ModeSimplifyCB); 3295 A.registerSimplificationCallback( 3296 IRPosition::callsite_argument(*KernelInitCB, 3297 InitRequiresFullRuntimeArgNo), 3298 IsGenericModeSimplifyCB); 3299 A.registerSimplificationCallback( 3300 IRPosition::callsite_argument(*KernelDeinitCB, 3301 DeinitRequiresFullRuntimeArgNo), 3302 IsGenericModeSimplifyCB); 3303 3304 // Check if we know we are in SPMD-mode already. 3305 ConstantInt *ModeArg = 3306 dyn_cast<ConstantInt>(KernelInitCB->getArgOperand(InitModeArgNo)); 3307 if (ModeArg && (ModeArg->getSExtValue() & OMP_TGT_EXEC_MODE_SPMD)) 3308 SPMDCompatibilityTracker.indicateOptimisticFixpoint(); 3309 // This is a generic region but SPMDization is disabled so stop tracking. 3310 else if (DisableOpenMPOptSPMDization) 3311 SPMDCompatibilityTracker.indicatePessimisticFixpoint(); 3312 } 3313 3314 /// Sanitize the string \p S such that it is a suitable global symbol name. 3315 static std::string sanitizeForGlobalName(std::string S) { 3316 std::replace_if( 3317 S.begin(), S.end(), 3318 [](const char C) { 3319 return !((C >= 'a' && C <= 'z') || (C >= 'A' && C <= 'Z') || 3320 (C >= '0' && C <= '9') || C == '_'); 3321 }, 3322 '.'); 3323 return S; 3324 } 3325 3326 /// Modify the IR based on the KernelInfoState as the fixpoint iteration is 3327 /// finished now. 3328 ChangeStatus manifest(Attributor &A) override { 3329 // If we are not looking at a kernel with __kmpc_target_init and 3330 // __kmpc_target_deinit call we cannot actually manifest the information. 3331 if (!KernelInitCB || !KernelDeinitCB) 3332 return ChangeStatus::UNCHANGED; 3333 3334 // If we can we change the execution mode to SPMD-mode otherwise we build a 3335 // custom state machine. 3336 ChangeStatus Changed = ChangeStatus::UNCHANGED; 3337 if (!changeToSPMDMode(A, Changed)) 3338 return buildCustomStateMachine(A); 3339 3340 return Changed; 3341 } 3342 3343 bool changeToSPMDMode(Attributor &A, ChangeStatus &Changed) { 3344 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 3345 3346 if (!SPMDCompatibilityTracker.isAssumed()) { 3347 for (Instruction *NonCompatibleI : SPMDCompatibilityTracker) { 3348 if (!NonCompatibleI) 3349 continue; 3350 3351 // Skip diagnostics on calls to known OpenMP runtime functions for now. 3352 if (auto *CB = dyn_cast<CallBase>(NonCompatibleI)) 3353 if (OMPInfoCache.RTLFunctions.contains(CB->getCalledFunction())) 3354 continue; 3355 3356 auto Remark = [&](OptimizationRemarkAnalysis ORA) { 3357 ORA << "Value has potential side effects preventing SPMD-mode " 3358 "execution"; 3359 if (isa<CallBase>(NonCompatibleI)) { 3360 ORA << ". Add `__attribute__((assume(\"ompx_spmd_amenable\")))` to " 3361 "the called function to override"; 3362 } 3363 return ORA << "."; 3364 }; 3365 A.emitRemark<OptimizationRemarkAnalysis>(NonCompatibleI, "OMP121", 3366 Remark); 3367 3368 LLVM_DEBUG(dbgs() << TAG << "SPMD-incompatible side-effect: " 3369 << *NonCompatibleI << "\n"); 3370 } 3371 3372 return false; 3373 } 3374 3375 // Get the actual kernel, could be the caller of the anchor scope if we have 3376 // a debug wrapper. 3377 Function *Kernel = getAnchorScope(); 3378 if (Kernel->hasLocalLinkage()) { 3379 assert(Kernel->hasOneUse() && "Unexpected use of debug kernel wrapper."); 3380 auto *CB = cast<CallBase>(Kernel->user_back()); 3381 Kernel = CB->getCaller(); 3382 } 3383 assert(OMPInfoCache.Kernels.count(Kernel) && "Expected kernel function!"); 3384 3385 // Check if the kernel is already in SPMD mode, if so, return success. 3386 GlobalVariable *ExecMode = Kernel->getParent()->getGlobalVariable( 3387 (Kernel->getName() + "_exec_mode").str()); 3388 assert(ExecMode && "Kernel without exec mode?"); 3389 assert(ExecMode->getInitializer() && "ExecMode doesn't have initializer!"); 3390 3391 // Set the global exec mode flag to indicate SPMD-Generic mode. 3392 assert(isa<ConstantInt>(ExecMode->getInitializer()) && 3393 "ExecMode is not an integer!"); 3394 const int8_t ExecModeVal = 3395 cast<ConstantInt>(ExecMode->getInitializer())->getSExtValue(); 3396 if (ExecModeVal != OMP_TGT_EXEC_MODE_GENERIC) 3397 return true; 3398 3399 // We will now unconditionally modify the IR, indicate a change. 3400 Changed = ChangeStatus::CHANGED; 3401 3402 auto CreateGuardedRegion = [&](Instruction *RegionStartI, 3403 Instruction *RegionEndI) { 3404 LoopInfo *LI = nullptr; 3405 DominatorTree *DT = nullptr; 3406 MemorySSAUpdater *MSU = nullptr; 3407 using InsertPointTy = OpenMPIRBuilder::InsertPointTy; 3408 3409 BasicBlock *ParentBB = RegionStartI->getParent(); 3410 Function *Fn = ParentBB->getParent(); 3411 Module &M = *Fn->getParent(); 3412 3413 // Create all the blocks and logic. 3414 // ParentBB: 3415 // goto RegionCheckTidBB 3416 // RegionCheckTidBB: 3417 // Tid = __kmpc_hardware_thread_id() 3418 // if (Tid != 0) 3419 // goto RegionBarrierBB 3420 // RegionStartBB: 3421 // <execute instructions guarded> 3422 // goto RegionEndBB 3423 // RegionEndBB: 3424 // <store escaping values to shared mem> 3425 // goto RegionBarrierBB 3426 // RegionBarrierBB: 3427 // __kmpc_simple_barrier_spmd() 3428 // // second barrier is omitted if lacking escaping values. 3429 // <load escaping values from shared mem> 3430 // __kmpc_simple_barrier_spmd() 3431 // goto RegionExitBB 3432 // RegionExitBB: 3433 // <execute rest of instructions> 3434 3435 BasicBlock *RegionEndBB = SplitBlock(ParentBB, RegionEndI->getNextNode(), 3436 DT, LI, MSU, "region.guarded.end"); 3437 BasicBlock *RegionBarrierBB = 3438 SplitBlock(RegionEndBB, &*RegionEndBB->getFirstInsertionPt(), DT, LI, 3439 MSU, "region.barrier"); 3440 BasicBlock *RegionExitBB = 3441 SplitBlock(RegionBarrierBB, &*RegionBarrierBB->getFirstInsertionPt(), 3442 DT, LI, MSU, "region.exit"); 3443 BasicBlock *RegionStartBB = 3444 SplitBlock(ParentBB, RegionStartI, DT, LI, MSU, "region.guarded"); 3445 3446 assert(ParentBB->getUniqueSuccessor() == RegionStartBB && 3447 "Expected a different CFG"); 3448 3449 BasicBlock *RegionCheckTidBB = SplitBlock( 3450 ParentBB, ParentBB->getTerminator(), DT, LI, MSU, "region.check.tid"); 3451 3452 // Register basic blocks with the Attributor. 3453 A.registerManifestAddedBasicBlock(*RegionEndBB); 3454 A.registerManifestAddedBasicBlock(*RegionBarrierBB); 3455 A.registerManifestAddedBasicBlock(*RegionExitBB); 3456 A.registerManifestAddedBasicBlock(*RegionStartBB); 3457 A.registerManifestAddedBasicBlock(*RegionCheckTidBB); 3458 3459 bool HasBroadcastValues = false; 3460 // Find escaping outputs from the guarded region to outside users and 3461 // broadcast their values to them. 3462 for (Instruction &I : *RegionStartBB) { 3463 SmallPtrSet<Instruction *, 4> OutsideUsers; 3464 for (User *Usr : I.users()) { 3465 Instruction &UsrI = *cast<Instruction>(Usr); 3466 if (UsrI.getParent() != RegionStartBB) 3467 OutsideUsers.insert(&UsrI); 3468 } 3469 3470 if (OutsideUsers.empty()) 3471 continue; 3472 3473 HasBroadcastValues = true; 3474 3475 // Emit a global variable in shared memory to store the broadcasted 3476 // value. 3477 auto *SharedMem = new GlobalVariable( 3478 M, I.getType(), /* IsConstant */ false, 3479 GlobalValue::InternalLinkage, UndefValue::get(I.getType()), 3480 sanitizeForGlobalName( 3481 (I.getName() + ".guarded.output.alloc").str()), 3482 nullptr, GlobalValue::NotThreadLocal, 3483 static_cast<unsigned>(AddressSpace::Shared)); 3484 3485 // Emit a store instruction to update the value. 3486 new StoreInst(&I, SharedMem, RegionEndBB->getTerminator()); 3487 3488 LoadInst *LoadI = new LoadInst(I.getType(), SharedMem, 3489 I.getName() + ".guarded.output.load", 3490 RegionBarrierBB->getTerminator()); 3491 3492 // Emit a load instruction and replace uses of the output value. 3493 for (Instruction *UsrI : OutsideUsers) 3494 UsrI->replaceUsesOfWith(&I, LoadI); 3495 } 3496 3497 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 3498 3499 // Go to tid check BB in ParentBB. 3500 const DebugLoc DL = ParentBB->getTerminator()->getDebugLoc(); 3501 ParentBB->getTerminator()->eraseFromParent(); 3502 OpenMPIRBuilder::LocationDescription Loc( 3503 InsertPointTy(ParentBB, ParentBB->end()), DL); 3504 OMPInfoCache.OMPBuilder.updateToLocation(Loc); 3505 uint32_t SrcLocStrSize; 3506 auto *SrcLocStr = 3507 OMPInfoCache.OMPBuilder.getOrCreateSrcLocStr(Loc, SrcLocStrSize); 3508 Value *Ident = 3509 OMPInfoCache.OMPBuilder.getOrCreateIdent(SrcLocStr, SrcLocStrSize); 3510 BranchInst::Create(RegionCheckTidBB, ParentBB)->setDebugLoc(DL); 3511 3512 // Add check for Tid in RegionCheckTidBB 3513 RegionCheckTidBB->getTerminator()->eraseFromParent(); 3514 OpenMPIRBuilder::LocationDescription LocRegionCheckTid( 3515 InsertPointTy(RegionCheckTidBB, RegionCheckTidBB->end()), DL); 3516 OMPInfoCache.OMPBuilder.updateToLocation(LocRegionCheckTid); 3517 FunctionCallee HardwareTidFn = 3518 OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction( 3519 M, OMPRTL___kmpc_get_hardware_thread_id_in_block); 3520 CallInst *Tid = 3521 OMPInfoCache.OMPBuilder.Builder.CreateCall(HardwareTidFn, {}); 3522 Tid->setDebugLoc(DL); 3523 OMPInfoCache.setCallingConvention(HardwareTidFn, Tid); 3524 Value *TidCheck = OMPInfoCache.OMPBuilder.Builder.CreateIsNull(Tid); 3525 OMPInfoCache.OMPBuilder.Builder 3526 .CreateCondBr(TidCheck, RegionStartBB, RegionBarrierBB) 3527 ->setDebugLoc(DL); 3528 3529 // First barrier for synchronization, ensures main thread has updated 3530 // values. 3531 FunctionCallee BarrierFn = 3532 OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction( 3533 M, OMPRTL___kmpc_barrier_simple_spmd); 3534 OMPInfoCache.OMPBuilder.updateToLocation(InsertPointTy( 3535 RegionBarrierBB, RegionBarrierBB->getFirstInsertionPt())); 3536 CallInst *Barrier = 3537 OMPInfoCache.OMPBuilder.Builder.CreateCall(BarrierFn, {Ident, Tid}); 3538 Barrier->setDebugLoc(DL); 3539 OMPInfoCache.setCallingConvention(BarrierFn, Barrier); 3540 3541 // Second barrier ensures workers have read broadcast values. 3542 if (HasBroadcastValues) { 3543 CallInst *Barrier = CallInst::Create(BarrierFn, {Ident, Tid}, "", 3544 RegionBarrierBB->getTerminator()); 3545 Barrier->setDebugLoc(DL); 3546 OMPInfoCache.setCallingConvention(BarrierFn, Barrier); 3547 } 3548 }; 3549 3550 auto &AllocSharedRFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared]; 3551 SmallPtrSet<BasicBlock *, 8> Visited; 3552 for (Instruction *GuardedI : SPMDCompatibilityTracker) { 3553 BasicBlock *BB = GuardedI->getParent(); 3554 if (!Visited.insert(BB).second) 3555 continue; 3556 3557 SmallVector<std::pair<Instruction *, Instruction *>> Reorders; 3558 Instruction *LastEffect = nullptr; 3559 BasicBlock::reverse_iterator IP = BB->rbegin(), IPEnd = BB->rend(); 3560 while (++IP != IPEnd) { 3561 if (!IP->mayHaveSideEffects() && !IP->mayReadFromMemory()) 3562 continue; 3563 Instruction *I = &*IP; 3564 if (OpenMPOpt::getCallIfRegularCall(*I, &AllocSharedRFI)) 3565 continue; 3566 if (!I->user_empty() || !SPMDCompatibilityTracker.contains(I)) { 3567 LastEffect = nullptr; 3568 continue; 3569 } 3570 if (LastEffect) 3571 Reorders.push_back({I, LastEffect}); 3572 LastEffect = &*IP; 3573 } 3574 for (auto &Reorder : Reorders) 3575 Reorder.first->moveBefore(Reorder.second); 3576 } 3577 3578 SmallVector<std::pair<Instruction *, Instruction *>, 4> GuardedRegions; 3579 3580 for (Instruction *GuardedI : SPMDCompatibilityTracker) { 3581 BasicBlock *BB = GuardedI->getParent(); 3582 auto *CalleeAA = A.lookupAAFor<AAKernelInfo>( 3583 IRPosition::function(*GuardedI->getFunction()), nullptr, 3584 DepClassTy::NONE); 3585 assert(CalleeAA != nullptr && "Expected Callee AAKernelInfo"); 3586 auto &CalleeAAFunction = *cast<AAKernelInfoFunction>(CalleeAA); 3587 // Continue if instruction is already guarded. 3588 if (CalleeAAFunction.getGuardedInstructions().contains(GuardedI)) 3589 continue; 3590 3591 Instruction *GuardedRegionStart = nullptr, *GuardedRegionEnd = nullptr; 3592 for (Instruction &I : *BB) { 3593 // If instruction I needs to be guarded update the guarded region 3594 // bounds. 3595 if (SPMDCompatibilityTracker.contains(&I)) { 3596 CalleeAAFunction.getGuardedInstructions().insert(&I); 3597 if (GuardedRegionStart) 3598 GuardedRegionEnd = &I; 3599 else 3600 GuardedRegionStart = GuardedRegionEnd = &I; 3601 3602 continue; 3603 } 3604 3605 // Instruction I does not need guarding, store 3606 // any region found and reset bounds. 3607 if (GuardedRegionStart) { 3608 GuardedRegions.push_back( 3609 std::make_pair(GuardedRegionStart, GuardedRegionEnd)); 3610 GuardedRegionStart = nullptr; 3611 GuardedRegionEnd = nullptr; 3612 } 3613 } 3614 } 3615 3616 for (auto &GR : GuardedRegions) 3617 CreateGuardedRegion(GR.first, GR.second); 3618 3619 // Adjust the global exec mode flag that tells the runtime what mode this 3620 // kernel is executed in. 3621 assert(ExecModeVal == OMP_TGT_EXEC_MODE_GENERIC && 3622 "Initially non-SPMD kernel has SPMD exec mode!"); 3623 ExecMode->setInitializer( 3624 ConstantInt::get(ExecMode->getInitializer()->getType(), 3625 ExecModeVal | OMP_TGT_EXEC_MODE_GENERIC_SPMD)); 3626 3627 // Next rewrite the init and deinit calls to indicate we use SPMD-mode now. 3628 const int InitModeArgNo = 1; 3629 const int DeinitModeArgNo = 1; 3630 const int InitUseStateMachineArgNo = 2; 3631 const int InitRequiresFullRuntimeArgNo = 3; 3632 const int DeinitRequiresFullRuntimeArgNo = 2; 3633 3634 auto &Ctx = getAnchorValue().getContext(); 3635 A.changeUseAfterManifest( 3636 KernelInitCB->getArgOperandUse(InitModeArgNo), 3637 *ConstantInt::getSigned(IntegerType::getInt8Ty(Ctx), 3638 OMP_TGT_EXEC_MODE_SPMD)); 3639 A.changeUseAfterManifest( 3640 KernelInitCB->getArgOperandUse(InitUseStateMachineArgNo), 3641 *ConstantInt::getBool(Ctx, false)); 3642 A.changeUseAfterManifest( 3643 KernelDeinitCB->getArgOperandUse(DeinitModeArgNo), 3644 *ConstantInt::getSigned(IntegerType::getInt8Ty(Ctx), 3645 OMP_TGT_EXEC_MODE_SPMD)); 3646 A.changeUseAfterManifest( 3647 KernelInitCB->getArgOperandUse(InitRequiresFullRuntimeArgNo), 3648 *ConstantInt::getBool(Ctx, false)); 3649 A.changeUseAfterManifest( 3650 KernelDeinitCB->getArgOperandUse(DeinitRequiresFullRuntimeArgNo), 3651 *ConstantInt::getBool(Ctx, false)); 3652 3653 ++NumOpenMPTargetRegionKernelsSPMD; 3654 3655 auto Remark = [&](OptimizationRemark OR) { 3656 return OR << "Transformed generic-mode kernel to SPMD-mode."; 3657 }; 3658 A.emitRemark<OptimizationRemark>(KernelInitCB, "OMP120", Remark); 3659 return true; 3660 }; 3661 3662 ChangeStatus buildCustomStateMachine(Attributor &A) { 3663 // If we have disabled state machine rewrites, don't make a custom one 3664 if (DisableOpenMPOptStateMachineRewrite) 3665 return ChangeStatus::UNCHANGED; 3666 3667 // Don't rewrite the state machine if we are not in a valid state. 3668 if (!ReachedKnownParallelRegions.isValidState()) 3669 return ChangeStatus::UNCHANGED; 3670 3671 const int InitModeArgNo = 1; 3672 const int InitUseStateMachineArgNo = 2; 3673 3674 // Check if the current configuration is non-SPMD and generic state machine. 3675 // If we already have SPMD mode or a custom state machine we do not need to 3676 // go any further. If it is anything but a constant something is weird and 3677 // we give up. 3678 ConstantInt *UseStateMachine = dyn_cast<ConstantInt>( 3679 KernelInitCB->getArgOperand(InitUseStateMachineArgNo)); 3680 ConstantInt *Mode = 3681 dyn_cast<ConstantInt>(KernelInitCB->getArgOperand(InitModeArgNo)); 3682 3683 // If we are stuck with generic mode, try to create a custom device (=GPU) 3684 // state machine which is specialized for the parallel regions that are 3685 // reachable by the kernel. 3686 if (!UseStateMachine || UseStateMachine->isZero() || !Mode || 3687 (Mode->getSExtValue() & OMP_TGT_EXEC_MODE_SPMD)) 3688 return ChangeStatus::UNCHANGED; 3689 3690 // If not SPMD mode, indicate we use a custom state machine now. 3691 auto &Ctx = getAnchorValue().getContext(); 3692 auto *FalseVal = ConstantInt::getBool(Ctx, false); 3693 A.changeUseAfterManifest( 3694 KernelInitCB->getArgOperandUse(InitUseStateMachineArgNo), *FalseVal); 3695 3696 // If we don't actually need a state machine we are done here. This can 3697 // happen if there simply are no parallel regions. In the resulting kernel 3698 // all worker threads will simply exit right away, leaving the main thread 3699 // to do the work alone. 3700 if (!mayContainParallelRegion()) { 3701 ++NumOpenMPTargetRegionKernelsWithoutStateMachine; 3702 3703 auto Remark = [&](OptimizationRemark OR) { 3704 return OR << "Removing unused state machine from generic-mode kernel."; 3705 }; 3706 A.emitRemark<OptimizationRemark>(KernelInitCB, "OMP130", Remark); 3707 3708 return ChangeStatus::CHANGED; 3709 } 3710 3711 // Keep track in the statistics of our new shiny custom state machine. 3712 if (ReachedUnknownParallelRegions.empty()) { 3713 ++NumOpenMPTargetRegionKernelsCustomStateMachineWithoutFallback; 3714 3715 auto Remark = [&](OptimizationRemark OR) { 3716 return OR << "Rewriting generic-mode kernel with a customized state " 3717 "machine."; 3718 }; 3719 A.emitRemark<OptimizationRemark>(KernelInitCB, "OMP131", Remark); 3720 } else { 3721 ++NumOpenMPTargetRegionKernelsCustomStateMachineWithFallback; 3722 3723 auto Remark = [&](OptimizationRemarkAnalysis OR) { 3724 return OR << "Generic-mode kernel is executed with a customized state " 3725 "machine that requires a fallback."; 3726 }; 3727 A.emitRemark<OptimizationRemarkAnalysis>(KernelInitCB, "OMP132", Remark); 3728 3729 // Tell the user why we ended up with a fallback. 3730 for (CallBase *UnknownParallelRegionCB : ReachedUnknownParallelRegions) { 3731 if (!UnknownParallelRegionCB) 3732 continue; 3733 auto Remark = [&](OptimizationRemarkAnalysis ORA) { 3734 return ORA << "Call may contain unknown parallel regions. Use " 3735 << "`__attribute__((assume(\"omp_no_parallelism\")))` to " 3736 "override."; 3737 }; 3738 A.emitRemark<OptimizationRemarkAnalysis>(UnknownParallelRegionCB, 3739 "OMP133", Remark); 3740 } 3741 } 3742 3743 // Create all the blocks: 3744 // 3745 // InitCB = __kmpc_target_init(...) 3746 // BlockHwSize = 3747 // __kmpc_get_hardware_num_threads_in_block(); 3748 // WarpSize = __kmpc_get_warp_size(); 3749 // BlockSize = BlockHwSize - WarpSize; 3750 // IsWorkerCheckBB: bool IsWorker = InitCB != -1; 3751 // if (IsWorker) { 3752 // if (InitCB >= BlockSize) return; 3753 // SMBeginBB: __kmpc_barrier_simple_generic(...); 3754 // void *WorkFn; 3755 // bool Active = __kmpc_kernel_parallel(&WorkFn); 3756 // if (!WorkFn) return; 3757 // SMIsActiveCheckBB: if (Active) { 3758 // SMIfCascadeCurrentBB: if (WorkFn == <ParFn0>) 3759 // ParFn0(...); 3760 // SMIfCascadeCurrentBB: else if (WorkFn == <ParFn1>) 3761 // ParFn1(...); 3762 // ... 3763 // SMIfCascadeCurrentBB: else 3764 // ((WorkFnTy*)WorkFn)(...); 3765 // SMEndParallelBB: __kmpc_kernel_end_parallel(...); 3766 // } 3767 // SMDoneBB: __kmpc_barrier_simple_generic(...); 3768 // goto SMBeginBB; 3769 // } 3770 // UserCodeEntryBB: // user code 3771 // __kmpc_target_deinit(...) 3772 // 3773 Function *Kernel = getAssociatedFunction(); 3774 assert(Kernel && "Expected an associated function!"); 3775 3776 BasicBlock *InitBB = KernelInitCB->getParent(); 3777 BasicBlock *UserCodeEntryBB = InitBB->splitBasicBlock( 3778 KernelInitCB->getNextNode(), "thread.user_code.check"); 3779 BasicBlock *IsWorkerCheckBB = 3780 BasicBlock::Create(Ctx, "is_worker_check", Kernel, UserCodeEntryBB); 3781 BasicBlock *StateMachineBeginBB = BasicBlock::Create( 3782 Ctx, "worker_state_machine.begin", Kernel, UserCodeEntryBB); 3783 BasicBlock *StateMachineFinishedBB = BasicBlock::Create( 3784 Ctx, "worker_state_machine.finished", Kernel, UserCodeEntryBB); 3785 BasicBlock *StateMachineIsActiveCheckBB = BasicBlock::Create( 3786 Ctx, "worker_state_machine.is_active.check", Kernel, UserCodeEntryBB); 3787 BasicBlock *StateMachineIfCascadeCurrentBB = 3788 BasicBlock::Create(Ctx, "worker_state_machine.parallel_region.check", 3789 Kernel, UserCodeEntryBB); 3790 BasicBlock *StateMachineEndParallelBB = 3791 BasicBlock::Create(Ctx, "worker_state_machine.parallel_region.end", 3792 Kernel, UserCodeEntryBB); 3793 BasicBlock *StateMachineDoneBarrierBB = BasicBlock::Create( 3794 Ctx, "worker_state_machine.done.barrier", Kernel, UserCodeEntryBB); 3795 A.registerManifestAddedBasicBlock(*InitBB); 3796 A.registerManifestAddedBasicBlock(*UserCodeEntryBB); 3797 A.registerManifestAddedBasicBlock(*IsWorkerCheckBB); 3798 A.registerManifestAddedBasicBlock(*StateMachineBeginBB); 3799 A.registerManifestAddedBasicBlock(*StateMachineFinishedBB); 3800 A.registerManifestAddedBasicBlock(*StateMachineIsActiveCheckBB); 3801 A.registerManifestAddedBasicBlock(*StateMachineIfCascadeCurrentBB); 3802 A.registerManifestAddedBasicBlock(*StateMachineEndParallelBB); 3803 A.registerManifestAddedBasicBlock(*StateMachineDoneBarrierBB); 3804 3805 const DebugLoc &DLoc = KernelInitCB->getDebugLoc(); 3806 ReturnInst::Create(Ctx, StateMachineFinishedBB)->setDebugLoc(DLoc); 3807 InitBB->getTerminator()->eraseFromParent(); 3808 3809 Instruction *IsWorker = 3810 ICmpInst::Create(ICmpInst::ICmp, llvm::CmpInst::ICMP_NE, KernelInitCB, 3811 ConstantInt::get(KernelInitCB->getType(), -1), 3812 "thread.is_worker", InitBB); 3813 IsWorker->setDebugLoc(DLoc); 3814 BranchInst::Create(IsWorkerCheckBB, UserCodeEntryBB, IsWorker, InitBB); 3815 3816 Module &M = *Kernel->getParent(); 3817 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 3818 FunctionCallee BlockHwSizeFn = 3819 OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction( 3820 M, OMPRTL___kmpc_get_hardware_num_threads_in_block); 3821 FunctionCallee WarpSizeFn = 3822 OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction( 3823 M, OMPRTL___kmpc_get_warp_size); 3824 CallInst *BlockHwSize = 3825 CallInst::Create(BlockHwSizeFn, "block.hw_size", IsWorkerCheckBB); 3826 OMPInfoCache.setCallingConvention(BlockHwSizeFn, BlockHwSize); 3827 BlockHwSize->setDebugLoc(DLoc); 3828 CallInst *WarpSize = 3829 CallInst::Create(WarpSizeFn, "warp.size", IsWorkerCheckBB); 3830 OMPInfoCache.setCallingConvention(WarpSizeFn, WarpSize); 3831 WarpSize->setDebugLoc(DLoc); 3832 Instruction *BlockSize = BinaryOperator::CreateSub( 3833 BlockHwSize, WarpSize, "block.size", IsWorkerCheckBB); 3834 BlockSize->setDebugLoc(DLoc); 3835 Instruction *IsMainOrWorker = ICmpInst::Create( 3836 ICmpInst::ICmp, llvm::CmpInst::ICMP_SLT, KernelInitCB, BlockSize, 3837 "thread.is_main_or_worker", IsWorkerCheckBB); 3838 IsMainOrWorker->setDebugLoc(DLoc); 3839 BranchInst::Create(StateMachineBeginBB, StateMachineFinishedBB, 3840 IsMainOrWorker, IsWorkerCheckBB); 3841 3842 // Create local storage for the work function pointer. 3843 const DataLayout &DL = M.getDataLayout(); 3844 Type *VoidPtrTy = Type::getInt8PtrTy(Ctx); 3845 Instruction *WorkFnAI = 3846 new AllocaInst(VoidPtrTy, DL.getAllocaAddrSpace(), nullptr, 3847 "worker.work_fn.addr", &Kernel->getEntryBlock().front()); 3848 WorkFnAI->setDebugLoc(DLoc); 3849 3850 OMPInfoCache.OMPBuilder.updateToLocation( 3851 OpenMPIRBuilder::LocationDescription( 3852 IRBuilder<>::InsertPoint(StateMachineBeginBB, 3853 StateMachineBeginBB->end()), 3854 DLoc)); 3855 3856 Value *Ident = KernelInitCB->getArgOperand(0); 3857 Value *GTid = KernelInitCB; 3858 3859 FunctionCallee BarrierFn = 3860 OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction( 3861 M, OMPRTL___kmpc_barrier_simple_generic); 3862 CallInst *Barrier = 3863 CallInst::Create(BarrierFn, {Ident, GTid}, "", StateMachineBeginBB); 3864 OMPInfoCache.setCallingConvention(BarrierFn, Barrier); 3865 Barrier->setDebugLoc(DLoc); 3866 3867 if (WorkFnAI->getType()->getPointerAddressSpace() != 3868 (unsigned int)AddressSpace::Generic) { 3869 WorkFnAI = new AddrSpaceCastInst( 3870 WorkFnAI, 3871 PointerType::getWithSamePointeeType( 3872 cast<PointerType>(WorkFnAI->getType()), 3873 (unsigned int)AddressSpace::Generic), 3874 WorkFnAI->getName() + ".generic", StateMachineBeginBB); 3875 WorkFnAI->setDebugLoc(DLoc); 3876 } 3877 3878 FunctionCallee KernelParallelFn = 3879 OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction( 3880 M, OMPRTL___kmpc_kernel_parallel); 3881 CallInst *IsActiveWorker = CallInst::Create( 3882 KernelParallelFn, {WorkFnAI}, "worker.is_active", StateMachineBeginBB); 3883 OMPInfoCache.setCallingConvention(KernelParallelFn, IsActiveWorker); 3884 IsActiveWorker->setDebugLoc(DLoc); 3885 Instruction *WorkFn = new LoadInst(VoidPtrTy, WorkFnAI, "worker.work_fn", 3886 StateMachineBeginBB); 3887 WorkFn->setDebugLoc(DLoc); 3888 3889 FunctionType *ParallelRegionFnTy = FunctionType::get( 3890 Type::getVoidTy(Ctx), {Type::getInt16Ty(Ctx), Type::getInt32Ty(Ctx)}, 3891 false); 3892 Value *WorkFnCast = BitCastInst::CreatePointerBitCastOrAddrSpaceCast( 3893 WorkFn, ParallelRegionFnTy->getPointerTo(), "worker.work_fn.addr_cast", 3894 StateMachineBeginBB); 3895 3896 Instruction *IsDone = 3897 ICmpInst::Create(ICmpInst::ICmp, llvm::CmpInst::ICMP_EQ, WorkFn, 3898 Constant::getNullValue(VoidPtrTy), "worker.is_done", 3899 StateMachineBeginBB); 3900 IsDone->setDebugLoc(DLoc); 3901 BranchInst::Create(StateMachineFinishedBB, StateMachineIsActiveCheckBB, 3902 IsDone, StateMachineBeginBB) 3903 ->setDebugLoc(DLoc); 3904 3905 BranchInst::Create(StateMachineIfCascadeCurrentBB, 3906 StateMachineDoneBarrierBB, IsActiveWorker, 3907 StateMachineIsActiveCheckBB) 3908 ->setDebugLoc(DLoc); 3909 3910 Value *ZeroArg = 3911 Constant::getNullValue(ParallelRegionFnTy->getParamType(0)); 3912 3913 // Now that we have most of the CFG skeleton it is time for the if-cascade 3914 // that checks the function pointer we got from the runtime against the 3915 // parallel regions we expect, if there are any. 3916 for (int I = 0, E = ReachedKnownParallelRegions.size(); I < E; ++I) { 3917 auto *ParallelRegion = ReachedKnownParallelRegions[I]; 3918 BasicBlock *PRExecuteBB = BasicBlock::Create( 3919 Ctx, "worker_state_machine.parallel_region.execute", Kernel, 3920 StateMachineEndParallelBB); 3921 CallInst::Create(ParallelRegion, {ZeroArg, GTid}, "", PRExecuteBB) 3922 ->setDebugLoc(DLoc); 3923 BranchInst::Create(StateMachineEndParallelBB, PRExecuteBB) 3924 ->setDebugLoc(DLoc); 3925 3926 BasicBlock *PRNextBB = 3927 BasicBlock::Create(Ctx, "worker_state_machine.parallel_region.check", 3928 Kernel, StateMachineEndParallelBB); 3929 3930 // Check if we need to compare the pointer at all or if we can just 3931 // call the parallel region function. 3932 Value *IsPR; 3933 if (I + 1 < E || !ReachedUnknownParallelRegions.empty()) { 3934 Instruction *CmpI = ICmpInst::Create( 3935 ICmpInst::ICmp, llvm::CmpInst::ICMP_EQ, WorkFnCast, ParallelRegion, 3936 "worker.check_parallel_region", StateMachineIfCascadeCurrentBB); 3937 CmpI->setDebugLoc(DLoc); 3938 IsPR = CmpI; 3939 } else { 3940 IsPR = ConstantInt::getTrue(Ctx); 3941 } 3942 3943 BranchInst::Create(PRExecuteBB, PRNextBB, IsPR, 3944 StateMachineIfCascadeCurrentBB) 3945 ->setDebugLoc(DLoc); 3946 StateMachineIfCascadeCurrentBB = PRNextBB; 3947 } 3948 3949 // At the end of the if-cascade we place the indirect function pointer call 3950 // in case we might need it, that is if there can be parallel regions we 3951 // have not handled in the if-cascade above. 3952 if (!ReachedUnknownParallelRegions.empty()) { 3953 StateMachineIfCascadeCurrentBB->setName( 3954 "worker_state_machine.parallel_region.fallback.execute"); 3955 CallInst::Create(ParallelRegionFnTy, WorkFnCast, {ZeroArg, GTid}, "", 3956 StateMachineIfCascadeCurrentBB) 3957 ->setDebugLoc(DLoc); 3958 } 3959 BranchInst::Create(StateMachineEndParallelBB, 3960 StateMachineIfCascadeCurrentBB) 3961 ->setDebugLoc(DLoc); 3962 3963 FunctionCallee EndParallelFn = 3964 OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction( 3965 M, OMPRTL___kmpc_kernel_end_parallel); 3966 CallInst *EndParallel = 3967 CallInst::Create(EndParallelFn, {}, "", StateMachineEndParallelBB); 3968 OMPInfoCache.setCallingConvention(EndParallelFn, EndParallel); 3969 EndParallel->setDebugLoc(DLoc); 3970 BranchInst::Create(StateMachineDoneBarrierBB, StateMachineEndParallelBB) 3971 ->setDebugLoc(DLoc); 3972 3973 CallInst::Create(BarrierFn, {Ident, GTid}, "", StateMachineDoneBarrierBB) 3974 ->setDebugLoc(DLoc); 3975 BranchInst::Create(StateMachineBeginBB, StateMachineDoneBarrierBB) 3976 ->setDebugLoc(DLoc); 3977 3978 return ChangeStatus::CHANGED; 3979 } 3980 3981 /// Fixpoint iteration update function. Will be called every time a dependence 3982 /// changed its state (and in the beginning). 3983 ChangeStatus updateImpl(Attributor &A) override { 3984 KernelInfoState StateBefore = getState(); 3985 3986 // Callback to check a read/write instruction. 3987 auto CheckRWInst = [&](Instruction &I) { 3988 // We handle calls later. 3989 if (isa<CallBase>(I)) 3990 return true; 3991 // We only care about write effects. 3992 if (!I.mayWriteToMemory()) 3993 return true; 3994 if (auto *SI = dyn_cast<StoreInst>(&I)) { 3995 SmallVector<const Value *> Objects; 3996 getUnderlyingObjects(SI->getPointerOperand(), Objects); 3997 if (llvm::all_of(Objects, 3998 [](const Value *Obj) { return isa<AllocaInst>(Obj); })) 3999 return true; 4000 // Check for AAHeapToStack moved objects which must not be guarded. 4001 auto &HS = A.getAAFor<AAHeapToStack>( 4002 *this, IRPosition::function(*I.getFunction()), 4003 DepClassTy::OPTIONAL); 4004 if (llvm::all_of(Objects, [&HS](const Value *Obj) { 4005 auto *CB = dyn_cast<CallBase>(Obj); 4006 if (!CB) 4007 return false; 4008 return HS.isAssumedHeapToStack(*CB); 4009 })) { 4010 return true; 4011 } 4012 } 4013 4014 // Insert instruction that needs guarding. 4015 SPMDCompatibilityTracker.insert(&I); 4016 return true; 4017 }; 4018 4019 bool UsedAssumedInformationInCheckRWInst = false; 4020 if (!SPMDCompatibilityTracker.isAtFixpoint()) 4021 if (!A.checkForAllReadWriteInstructions( 4022 CheckRWInst, *this, UsedAssumedInformationInCheckRWInst)) 4023 SPMDCompatibilityTracker.indicatePessimisticFixpoint(); 4024 4025 bool UsedAssumedInformationFromReachingKernels = false; 4026 if (!IsKernelEntry) { 4027 updateParallelLevels(A); 4028 4029 bool AllReachingKernelsKnown = true; 4030 updateReachingKernelEntries(A, AllReachingKernelsKnown); 4031 UsedAssumedInformationFromReachingKernels = !AllReachingKernelsKnown; 4032 4033 if (!ParallelLevels.isValidState()) 4034 SPMDCompatibilityTracker.indicatePessimisticFixpoint(); 4035 else if (!ReachingKernelEntries.isValidState()) 4036 SPMDCompatibilityTracker.indicatePessimisticFixpoint(); 4037 else if (!SPMDCompatibilityTracker.empty()) { 4038 // Check if all reaching kernels agree on the mode as we can otherwise 4039 // not guard instructions. We might not be sure about the mode so we 4040 // we cannot fix the internal spmd-zation state either. 4041 int SPMD = 0, Generic = 0; 4042 for (auto *Kernel : ReachingKernelEntries) { 4043 auto &CBAA = A.getAAFor<AAKernelInfo>( 4044 *this, IRPosition::function(*Kernel), DepClassTy::OPTIONAL); 4045 if (CBAA.SPMDCompatibilityTracker.isValidState() && 4046 CBAA.SPMDCompatibilityTracker.isAssumed()) 4047 ++SPMD; 4048 else 4049 ++Generic; 4050 if (!CBAA.SPMDCompatibilityTracker.isAtFixpoint()) 4051 UsedAssumedInformationFromReachingKernels = true; 4052 } 4053 if (SPMD != 0 && Generic != 0) 4054 SPMDCompatibilityTracker.indicatePessimisticFixpoint(); 4055 } 4056 } 4057 4058 // Callback to check a call instruction. 4059 bool AllParallelRegionStatesWereFixed = true; 4060 bool AllSPMDStatesWereFixed = true; 4061 auto CheckCallInst = [&](Instruction &I) { 4062 auto &CB = cast<CallBase>(I); 4063 auto &CBAA = A.getAAFor<AAKernelInfo>( 4064 *this, IRPosition::callsite_function(CB), DepClassTy::OPTIONAL); 4065 getState() ^= CBAA.getState(); 4066 AllSPMDStatesWereFixed &= CBAA.SPMDCompatibilityTracker.isAtFixpoint(); 4067 AllParallelRegionStatesWereFixed &= 4068 CBAA.ReachedKnownParallelRegions.isAtFixpoint(); 4069 AllParallelRegionStatesWereFixed &= 4070 CBAA.ReachedUnknownParallelRegions.isAtFixpoint(); 4071 return true; 4072 }; 4073 4074 bool UsedAssumedInformationInCheckCallInst = false; 4075 if (!A.checkForAllCallLikeInstructions( 4076 CheckCallInst, *this, UsedAssumedInformationInCheckCallInst)) { 4077 LLVM_DEBUG(dbgs() << TAG 4078 << "Failed to visit all call-like instructions!\n";); 4079 return indicatePessimisticFixpoint(); 4080 } 4081 4082 // If we haven't used any assumed information for the reached parallel 4083 // region states we can fix it. 4084 if (!UsedAssumedInformationInCheckCallInst && 4085 AllParallelRegionStatesWereFixed) { 4086 ReachedKnownParallelRegions.indicateOptimisticFixpoint(); 4087 ReachedUnknownParallelRegions.indicateOptimisticFixpoint(); 4088 } 4089 4090 // If we are sure there are no parallel regions in the kernel we do not 4091 // want SPMD mode. 4092 if (IsKernelEntry && ReachedUnknownParallelRegions.isAtFixpoint() && 4093 ReachedKnownParallelRegions.isAtFixpoint() && 4094 ReachedUnknownParallelRegions.isValidState() && 4095 ReachedKnownParallelRegions.isValidState() && 4096 !mayContainParallelRegion()) 4097 SPMDCompatibilityTracker.indicatePessimisticFixpoint(); 4098 4099 // If we haven't used any assumed information for the SPMD state we can fix 4100 // it. 4101 if (!UsedAssumedInformationInCheckRWInst && 4102 !UsedAssumedInformationInCheckCallInst && 4103 !UsedAssumedInformationFromReachingKernels && AllSPMDStatesWereFixed) 4104 SPMDCompatibilityTracker.indicateOptimisticFixpoint(); 4105 4106 return StateBefore == getState() ? ChangeStatus::UNCHANGED 4107 : ChangeStatus::CHANGED; 4108 } 4109 4110 private: 4111 /// Update info regarding reaching kernels. 4112 void updateReachingKernelEntries(Attributor &A, 4113 bool &AllReachingKernelsKnown) { 4114 auto PredCallSite = [&](AbstractCallSite ACS) { 4115 Function *Caller = ACS.getInstruction()->getFunction(); 4116 4117 assert(Caller && "Caller is nullptr"); 4118 4119 auto &CAA = A.getOrCreateAAFor<AAKernelInfo>( 4120 IRPosition::function(*Caller), this, DepClassTy::REQUIRED); 4121 if (CAA.ReachingKernelEntries.isValidState()) { 4122 ReachingKernelEntries ^= CAA.ReachingKernelEntries; 4123 return true; 4124 } 4125 4126 // We lost track of the caller of the associated function, any kernel 4127 // could reach now. 4128 ReachingKernelEntries.indicatePessimisticFixpoint(); 4129 4130 return true; 4131 }; 4132 4133 if (!A.checkForAllCallSites(PredCallSite, *this, 4134 true /* RequireAllCallSites */, 4135 AllReachingKernelsKnown)) 4136 ReachingKernelEntries.indicatePessimisticFixpoint(); 4137 } 4138 4139 /// Update info regarding parallel levels. 4140 void updateParallelLevels(Attributor &A) { 4141 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 4142 OMPInformationCache::RuntimeFunctionInfo &Parallel51RFI = 4143 OMPInfoCache.RFIs[OMPRTL___kmpc_parallel_51]; 4144 4145 auto PredCallSite = [&](AbstractCallSite ACS) { 4146 Function *Caller = ACS.getInstruction()->getFunction(); 4147 4148 assert(Caller && "Caller is nullptr"); 4149 4150 auto &CAA = 4151 A.getOrCreateAAFor<AAKernelInfo>(IRPosition::function(*Caller)); 4152 if (CAA.ParallelLevels.isValidState()) { 4153 // Any function that is called by `__kmpc_parallel_51` will not be 4154 // folded as the parallel level in the function is updated. In order to 4155 // get it right, all the analysis would depend on the implentation. That 4156 // said, if in the future any change to the implementation, the analysis 4157 // could be wrong. As a consequence, we are just conservative here. 4158 if (Caller == Parallel51RFI.Declaration) { 4159 ParallelLevels.indicatePessimisticFixpoint(); 4160 return true; 4161 } 4162 4163 ParallelLevels ^= CAA.ParallelLevels; 4164 4165 return true; 4166 } 4167 4168 // We lost track of the caller of the associated function, any kernel 4169 // could reach now. 4170 ParallelLevels.indicatePessimisticFixpoint(); 4171 4172 return true; 4173 }; 4174 4175 bool AllCallSitesKnown = true; 4176 if (!A.checkForAllCallSites(PredCallSite, *this, 4177 true /* RequireAllCallSites */, 4178 AllCallSitesKnown)) 4179 ParallelLevels.indicatePessimisticFixpoint(); 4180 } 4181 }; 4182 4183 /// The call site kernel info abstract attribute, basically, what can we say 4184 /// about a call site with regards to the KernelInfoState. For now this simply 4185 /// forwards the information from the callee. 4186 struct AAKernelInfoCallSite : AAKernelInfo { 4187 AAKernelInfoCallSite(const IRPosition &IRP, Attributor &A) 4188 : AAKernelInfo(IRP, A) {} 4189 4190 /// See AbstractAttribute::initialize(...). 4191 void initialize(Attributor &A) override { 4192 AAKernelInfo::initialize(A); 4193 4194 CallBase &CB = cast<CallBase>(getAssociatedValue()); 4195 Function *Callee = getAssociatedFunction(); 4196 4197 auto &AssumptionAA = A.getAAFor<AAAssumptionInfo>( 4198 *this, IRPosition::callsite_function(CB), DepClassTy::OPTIONAL); 4199 4200 // Check for SPMD-mode assumptions. 4201 if (AssumptionAA.hasAssumption("ompx_spmd_amenable")) { 4202 SPMDCompatibilityTracker.indicateOptimisticFixpoint(); 4203 indicateOptimisticFixpoint(); 4204 } 4205 4206 // First weed out calls we do not care about, that is readonly/readnone 4207 // calls, intrinsics, and "no_openmp" calls. Neither of these can reach a 4208 // parallel region or anything else we are looking for. 4209 if (!CB.mayWriteToMemory() || isa<IntrinsicInst>(CB)) { 4210 indicateOptimisticFixpoint(); 4211 return; 4212 } 4213 4214 // Next we check if we know the callee. If it is a known OpenMP function 4215 // we will handle them explicitly in the switch below. If it is not, we 4216 // will use an AAKernelInfo object on the callee to gather information and 4217 // merge that into the current state. The latter happens in the updateImpl. 4218 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 4219 const auto &It = OMPInfoCache.RuntimeFunctionIDMap.find(Callee); 4220 if (It == OMPInfoCache.RuntimeFunctionIDMap.end()) { 4221 // Unknown caller or declarations are not analyzable, we give up. 4222 if (!Callee || !A.isFunctionIPOAmendable(*Callee)) { 4223 4224 // Unknown callees might contain parallel regions, except if they have 4225 // an appropriate assumption attached. 4226 if (!(AssumptionAA.hasAssumption("omp_no_openmp") || 4227 AssumptionAA.hasAssumption("omp_no_parallelism"))) 4228 ReachedUnknownParallelRegions.insert(&CB); 4229 4230 // If SPMDCompatibilityTracker is not fixed, we need to give up on the 4231 // idea we can run something unknown in SPMD-mode. 4232 if (!SPMDCompatibilityTracker.isAtFixpoint()) { 4233 SPMDCompatibilityTracker.indicatePessimisticFixpoint(); 4234 SPMDCompatibilityTracker.insert(&CB); 4235 } 4236 4237 // We have updated the state for this unknown call properly, there won't 4238 // be any change so we indicate a fixpoint. 4239 indicateOptimisticFixpoint(); 4240 } 4241 // If the callee is known and can be used in IPO, we will update the state 4242 // based on the callee state in updateImpl. 4243 return; 4244 } 4245 4246 const unsigned int WrapperFunctionArgNo = 6; 4247 RuntimeFunction RF = It->getSecond(); 4248 switch (RF) { 4249 // All the functions we know are compatible with SPMD mode. 4250 case OMPRTL___kmpc_is_spmd_exec_mode: 4251 case OMPRTL___kmpc_distribute_static_fini: 4252 case OMPRTL___kmpc_for_static_fini: 4253 case OMPRTL___kmpc_global_thread_num: 4254 case OMPRTL___kmpc_get_hardware_num_threads_in_block: 4255 case OMPRTL___kmpc_get_hardware_num_blocks: 4256 case OMPRTL___kmpc_single: 4257 case OMPRTL___kmpc_end_single: 4258 case OMPRTL___kmpc_master: 4259 case OMPRTL___kmpc_end_master: 4260 case OMPRTL___kmpc_barrier: 4261 case OMPRTL___kmpc_nvptx_parallel_reduce_nowait_v2: 4262 case OMPRTL___kmpc_nvptx_teams_reduce_nowait_v2: 4263 case OMPRTL___kmpc_nvptx_end_reduce_nowait: 4264 break; 4265 case OMPRTL___kmpc_distribute_static_init_4: 4266 case OMPRTL___kmpc_distribute_static_init_4u: 4267 case OMPRTL___kmpc_distribute_static_init_8: 4268 case OMPRTL___kmpc_distribute_static_init_8u: 4269 case OMPRTL___kmpc_for_static_init_4: 4270 case OMPRTL___kmpc_for_static_init_4u: 4271 case OMPRTL___kmpc_for_static_init_8: 4272 case OMPRTL___kmpc_for_static_init_8u: { 4273 // Check the schedule and allow static schedule in SPMD mode. 4274 unsigned ScheduleArgOpNo = 2; 4275 auto *ScheduleTypeCI = 4276 dyn_cast<ConstantInt>(CB.getArgOperand(ScheduleArgOpNo)); 4277 unsigned ScheduleTypeVal = 4278 ScheduleTypeCI ? ScheduleTypeCI->getZExtValue() : 0; 4279 switch (OMPScheduleType(ScheduleTypeVal)) { 4280 case OMPScheduleType::Static: 4281 case OMPScheduleType::StaticChunked: 4282 case OMPScheduleType::Distribute: 4283 case OMPScheduleType::DistributeChunked: 4284 break; 4285 default: 4286 SPMDCompatibilityTracker.indicatePessimisticFixpoint(); 4287 SPMDCompatibilityTracker.insert(&CB); 4288 break; 4289 }; 4290 } break; 4291 case OMPRTL___kmpc_target_init: 4292 KernelInitCB = &CB; 4293 break; 4294 case OMPRTL___kmpc_target_deinit: 4295 KernelDeinitCB = &CB; 4296 break; 4297 case OMPRTL___kmpc_parallel_51: 4298 if (auto *ParallelRegion = dyn_cast<Function>( 4299 CB.getArgOperand(WrapperFunctionArgNo)->stripPointerCasts())) { 4300 ReachedKnownParallelRegions.insert(ParallelRegion); 4301 break; 4302 } 4303 // The condition above should usually get the parallel region function 4304 // pointer and record it. In the off chance it doesn't we assume the 4305 // worst. 4306 ReachedUnknownParallelRegions.insert(&CB); 4307 break; 4308 case OMPRTL___kmpc_omp_task: 4309 // We do not look into tasks right now, just give up. 4310 SPMDCompatibilityTracker.indicatePessimisticFixpoint(); 4311 SPMDCompatibilityTracker.insert(&CB); 4312 ReachedUnknownParallelRegions.insert(&CB); 4313 break; 4314 case OMPRTL___kmpc_alloc_shared: 4315 case OMPRTL___kmpc_free_shared: 4316 // Return without setting a fixpoint, to be resolved in updateImpl. 4317 return; 4318 default: 4319 // Unknown OpenMP runtime calls cannot be executed in SPMD-mode, 4320 // generally. However, they do not hide parallel regions. 4321 SPMDCompatibilityTracker.indicatePessimisticFixpoint(); 4322 SPMDCompatibilityTracker.insert(&CB); 4323 break; 4324 } 4325 // All other OpenMP runtime calls will not reach parallel regions so they 4326 // can be safely ignored for now. Since it is a known OpenMP runtime call we 4327 // have now modeled all effects and there is no need for any update. 4328 indicateOptimisticFixpoint(); 4329 } 4330 4331 ChangeStatus updateImpl(Attributor &A) override { 4332 // TODO: Once we have call site specific value information we can provide 4333 // call site specific liveness information and then it makes 4334 // sense to specialize attributes for call sites arguments instead of 4335 // redirecting requests to the callee argument. 4336 Function *F = getAssociatedFunction(); 4337 4338 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 4339 const auto &It = OMPInfoCache.RuntimeFunctionIDMap.find(F); 4340 4341 // If F is not a runtime function, propagate the AAKernelInfo of the callee. 4342 if (It == OMPInfoCache.RuntimeFunctionIDMap.end()) { 4343 const IRPosition &FnPos = IRPosition::function(*F); 4344 auto &FnAA = A.getAAFor<AAKernelInfo>(*this, FnPos, DepClassTy::REQUIRED); 4345 if (getState() == FnAA.getState()) 4346 return ChangeStatus::UNCHANGED; 4347 getState() = FnAA.getState(); 4348 return ChangeStatus::CHANGED; 4349 } 4350 4351 // F is a runtime function that allocates or frees memory, check 4352 // AAHeapToStack and AAHeapToShared. 4353 KernelInfoState StateBefore = getState(); 4354 assert((It->getSecond() == OMPRTL___kmpc_alloc_shared || 4355 It->getSecond() == OMPRTL___kmpc_free_shared) && 4356 "Expected a __kmpc_alloc_shared or __kmpc_free_shared runtime call"); 4357 4358 CallBase &CB = cast<CallBase>(getAssociatedValue()); 4359 4360 auto &HeapToStackAA = A.getAAFor<AAHeapToStack>( 4361 *this, IRPosition::function(*CB.getCaller()), DepClassTy::OPTIONAL); 4362 auto &HeapToSharedAA = A.getAAFor<AAHeapToShared>( 4363 *this, IRPosition::function(*CB.getCaller()), DepClassTy::OPTIONAL); 4364 4365 RuntimeFunction RF = It->getSecond(); 4366 4367 switch (RF) { 4368 // If neither HeapToStack nor HeapToShared assume the call is removed, 4369 // assume SPMD incompatibility. 4370 case OMPRTL___kmpc_alloc_shared: 4371 if (!HeapToStackAA.isAssumedHeapToStack(CB) && 4372 !HeapToSharedAA.isAssumedHeapToShared(CB)) 4373 SPMDCompatibilityTracker.insert(&CB); 4374 break; 4375 case OMPRTL___kmpc_free_shared: 4376 if (!HeapToStackAA.isAssumedHeapToStackRemovedFree(CB) && 4377 !HeapToSharedAA.isAssumedHeapToSharedRemovedFree(CB)) 4378 SPMDCompatibilityTracker.insert(&CB); 4379 break; 4380 default: 4381 SPMDCompatibilityTracker.indicatePessimisticFixpoint(); 4382 SPMDCompatibilityTracker.insert(&CB); 4383 } 4384 4385 return StateBefore == getState() ? ChangeStatus::UNCHANGED 4386 : ChangeStatus::CHANGED; 4387 } 4388 }; 4389 4390 struct AAFoldRuntimeCall 4391 : public StateWrapper<BooleanState, AbstractAttribute> { 4392 using Base = StateWrapper<BooleanState, AbstractAttribute>; 4393 4394 AAFoldRuntimeCall(const IRPosition &IRP, Attributor &A) : Base(IRP) {} 4395 4396 /// Statistics are tracked as part of manifest for now. 4397 void trackStatistics() const override {} 4398 4399 /// Create an abstract attribute biew for the position \p IRP. 4400 static AAFoldRuntimeCall &createForPosition(const IRPosition &IRP, 4401 Attributor &A); 4402 4403 /// See AbstractAttribute::getName() 4404 const std::string getName() const override { return "AAFoldRuntimeCall"; } 4405 4406 /// See AbstractAttribute::getIdAddr() 4407 const char *getIdAddr() const override { return &ID; } 4408 4409 /// This function should return true if the type of the \p AA is 4410 /// AAFoldRuntimeCall 4411 static bool classof(const AbstractAttribute *AA) { 4412 return (AA->getIdAddr() == &ID); 4413 } 4414 4415 static const char ID; 4416 }; 4417 4418 struct AAFoldRuntimeCallCallSiteReturned : AAFoldRuntimeCall { 4419 AAFoldRuntimeCallCallSiteReturned(const IRPosition &IRP, Attributor &A) 4420 : AAFoldRuntimeCall(IRP, A) {} 4421 4422 /// See AbstractAttribute::getAsStr() 4423 const std::string getAsStr() const override { 4424 if (!isValidState()) 4425 return "<invalid>"; 4426 4427 std::string Str("simplified value: "); 4428 4429 if (!SimplifiedValue.hasValue()) 4430 return Str + std::string("none"); 4431 4432 if (!SimplifiedValue.getValue()) 4433 return Str + std::string("nullptr"); 4434 4435 if (ConstantInt *CI = dyn_cast<ConstantInt>(SimplifiedValue.getValue())) 4436 return Str + std::to_string(CI->getSExtValue()); 4437 4438 return Str + std::string("unknown"); 4439 } 4440 4441 void initialize(Attributor &A) override { 4442 if (DisableOpenMPOptFolding) 4443 indicatePessimisticFixpoint(); 4444 4445 Function *Callee = getAssociatedFunction(); 4446 4447 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 4448 const auto &It = OMPInfoCache.RuntimeFunctionIDMap.find(Callee); 4449 assert(It != OMPInfoCache.RuntimeFunctionIDMap.end() && 4450 "Expected a known OpenMP runtime function"); 4451 4452 RFKind = It->getSecond(); 4453 4454 CallBase &CB = cast<CallBase>(getAssociatedValue()); 4455 A.registerSimplificationCallback( 4456 IRPosition::callsite_returned(CB), 4457 [&](const IRPosition &IRP, const AbstractAttribute *AA, 4458 bool &UsedAssumedInformation) -> Optional<Value *> { 4459 assert((isValidState() || (SimplifiedValue.hasValue() && 4460 SimplifiedValue.getValue() == nullptr)) && 4461 "Unexpected invalid state!"); 4462 4463 if (!isAtFixpoint()) { 4464 UsedAssumedInformation = true; 4465 if (AA) 4466 A.recordDependence(*this, *AA, DepClassTy::OPTIONAL); 4467 } 4468 return SimplifiedValue; 4469 }); 4470 } 4471 4472 ChangeStatus updateImpl(Attributor &A) override { 4473 ChangeStatus Changed = ChangeStatus::UNCHANGED; 4474 switch (RFKind) { 4475 case OMPRTL___kmpc_is_spmd_exec_mode: 4476 Changed |= foldIsSPMDExecMode(A); 4477 break; 4478 case OMPRTL___kmpc_is_generic_main_thread_id: 4479 Changed |= foldIsGenericMainThread(A); 4480 break; 4481 case OMPRTL___kmpc_parallel_level: 4482 Changed |= foldParallelLevel(A); 4483 break; 4484 case OMPRTL___kmpc_get_hardware_num_threads_in_block: 4485 Changed = Changed | foldKernelFnAttribute(A, "omp_target_thread_limit"); 4486 break; 4487 case OMPRTL___kmpc_get_hardware_num_blocks: 4488 Changed = Changed | foldKernelFnAttribute(A, "omp_target_num_teams"); 4489 break; 4490 default: 4491 llvm_unreachable("Unhandled OpenMP runtime function!"); 4492 } 4493 4494 return Changed; 4495 } 4496 4497 ChangeStatus manifest(Attributor &A) override { 4498 ChangeStatus Changed = ChangeStatus::UNCHANGED; 4499 4500 if (SimplifiedValue.hasValue() && SimplifiedValue.getValue()) { 4501 Instruction &I = *getCtxI(); 4502 A.changeValueAfterManifest(I, **SimplifiedValue); 4503 A.deleteAfterManifest(I); 4504 4505 CallBase *CB = dyn_cast<CallBase>(&I); 4506 auto Remark = [&](OptimizationRemark OR) { 4507 if (auto *C = dyn_cast<ConstantInt>(*SimplifiedValue)) 4508 return OR << "Replacing OpenMP runtime call " 4509 << CB->getCalledFunction()->getName() << " with " 4510 << ore::NV("FoldedValue", C->getZExtValue()) << "."; 4511 return OR << "Replacing OpenMP runtime call " 4512 << CB->getCalledFunction()->getName() << "."; 4513 }; 4514 4515 if (CB && EnableVerboseRemarks) 4516 A.emitRemark<OptimizationRemark>(CB, "OMP180", Remark); 4517 4518 LLVM_DEBUG(dbgs() << TAG << "Replacing runtime call: " << I << " with " 4519 << **SimplifiedValue << "\n"); 4520 4521 Changed = ChangeStatus::CHANGED; 4522 } 4523 4524 return Changed; 4525 } 4526 4527 ChangeStatus indicatePessimisticFixpoint() override { 4528 SimplifiedValue = nullptr; 4529 return AAFoldRuntimeCall::indicatePessimisticFixpoint(); 4530 } 4531 4532 private: 4533 /// Fold __kmpc_is_spmd_exec_mode into a constant if possible. 4534 ChangeStatus foldIsSPMDExecMode(Attributor &A) { 4535 Optional<Value *> SimplifiedValueBefore = SimplifiedValue; 4536 4537 unsigned AssumedSPMDCount = 0, KnownSPMDCount = 0; 4538 unsigned AssumedNonSPMDCount = 0, KnownNonSPMDCount = 0; 4539 auto &CallerKernelInfoAA = A.getAAFor<AAKernelInfo>( 4540 *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED); 4541 4542 if (!CallerKernelInfoAA.ReachingKernelEntries.isValidState()) 4543 return indicatePessimisticFixpoint(); 4544 4545 for (Kernel K : CallerKernelInfoAA.ReachingKernelEntries) { 4546 auto &AA = A.getAAFor<AAKernelInfo>(*this, IRPosition::function(*K), 4547 DepClassTy::REQUIRED); 4548 4549 if (!AA.isValidState()) { 4550 SimplifiedValue = nullptr; 4551 return indicatePessimisticFixpoint(); 4552 } 4553 4554 if (AA.SPMDCompatibilityTracker.isAssumed()) { 4555 if (AA.SPMDCompatibilityTracker.isAtFixpoint()) 4556 ++KnownSPMDCount; 4557 else 4558 ++AssumedSPMDCount; 4559 } else { 4560 if (AA.SPMDCompatibilityTracker.isAtFixpoint()) 4561 ++KnownNonSPMDCount; 4562 else 4563 ++AssumedNonSPMDCount; 4564 } 4565 } 4566 4567 if ((AssumedSPMDCount + KnownSPMDCount) && 4568 (AssumedNonSPMDCount + KnownNonSPMDCount)) 4569 return indicatePessimisticFixpoint(); 4570 4571 auto &Ctx = getAnchorValue().getContext(); 4572 if (KnownSPMDCount || AssumedSPMDCount) { 4573 assert(KnownNonSPMDCount == 0 && AssumedNonSPMDCount == 0 && 4574 "Expected only SPMD kernels!"); 4575 // All reaching kernels are in SPMD mode. Update all function calls to 4576 // __kmpc_is_spmd_exec_mode to 1. 4577 SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), true); 4578 } else if (KnownNonSPMDCount || AssumedNonSPMDCount) { 4579 assert(KnownSPMDCount == 0 && AssumedSPMDCount == 0 && 4580 "Expected only non-SPMD kernels!"); 4581 // All reaching kernels are in non-SPMD mode. Update all function 4582 // calls to __kmpc_is_spmd_exec_mode to 0. 4583 SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), false); 4584 } else { 4585 // We have empty reaching kernels, therefore we cannot tell if the 4586 // associated call site can be folded. At this moment, SimplifiedValue 4587 // must be none. 4588 assert(!SimplifiedValue.hasValue() && "SimplifiedValue should be none"); 4589 } 4590 4591 return SimplifiedValue == SimplifiedValueBefore ? ChangeStatus::UNCHANGED 4592 : ChangeStatus::CHANGED; 4593 } 4594 4595 /// Fold __kmpc_is_generic_main_thread_id into a constant if possible. 4596 ChangeStatus foldIsGenericMainThread(Attributor &A) { 4597 Optional<Value *> SimplifiedValueBefore = SimplifiedValue; 4598 4599 CallBase &CB = cast<CallBase>(getAssociatedValue()); 4600 Function *F = CB.getFunction(); 4601 const auto &ExecutionDomainAA = A.getAAFor<AAExecutionDomain>( 4602 *this, IRPosition::function(*F), DepClassTy::REQUIRED); 4603 4604 if (!ExecutionDomainAA.isValidState()) 4605 return indicatePessimisticFixpoint(); 4606 4607 auto &Ctx = getAnchorValue().getContext(); 4608 if (ExecutionDomainAA.isExecutedByInitialThreadOnly(CB)) 4609 SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), true); 4610 else 4611 return indicatePessimisticFixpoint(); 4612 4613 return SimplifiedValue == SimplifiedValueBefore ? ChangeStatus::UNCHANGED 4614 : ChangeStatus::CHANGED; 4615 } 4616 4617 /// Fold __kmpc_parallel_level into a constant if possible. 4618 ChangeStatus foldParallelLevel(Attributor &A) { 4619 Optional<Value *> SimplifiedValueBefore = SimplifiedValue; 4620 4621 auto &CallerKernelInfoAA = A.getAAFor<AAKernelInfo>( 4622 *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED); 4623 4624 if (!CallerKernelInfoAA.ParallelLevels.isValidState()) 4625 return indicatePessimisticFixpoint(); 4626 4627 if (!CallerKernelInfoAA.ReachingKernelEntries.isValidState()) 4628 return indicatePessimisticFixpoint(); 4629 4630 if (CallerKernelInfoAA.ReachingKernelEntries.empty()) { 4631 assert(!SimplifiedValue.hasValue() && 4632 "SimplifiedValue should keep none at this point"); 4633 return ChangeStatus::UNCHANGED; 4634 } 4635 4636 unsigned AssumedSPMDCount = 0, KnownSPMDCount = 0; 4637 unsigned AssumedNonSPMDCount = 0, KnownNonSPMDCount = 0; 4638 for (Kernel K : CallerKernelInfoAA.ReachingKernelEntries) { 4639 auto &AA = A.getAAFor<AAKernelInfo>(*this, IRPosition::function(*K), 4640 DepClassTy::REQUIRED); 4641 if (!AA.SPMDCompatibilityTracker.isValidState()) 4642 return indicatePessimisticFixpoint(); 4643 4644 if (AA.SPMDCompatibilityTracker.isAssumed()) { 4645 if (AA.SPMDCompatibilityTracker.isAtFixpoint()) 4646 ++KnownSPMDCount; 4647 else 4648 ++AssumedSPMDCount; 4649 } else { 4650 if (AA.SPMDCompatibilityTracker.isAtFixpoint()) 4651 ++KnownNonSPMDCount; 4652 else 4653 ++AssumedNonSPMDCount; 4654 } 4655 } 4656 4657 if ((AssumedSPMDCount + KnownSPMDCount) && 4658 (AssumedNonSPMDCount + KnownNonSPMDCount)) 4659 return indicatePessimisticFixpoint(); 4660 4661 auto &Ctx = getAnchorValue().getContext(); 4662 // If the caller can only be reached by SPMD kernel entries, the parallel 4663 // level is 1. Similarly, if the caller can only be reached by non-SPMD 4664 // kernel entries, it is 0. 4665 if (AssumedSPMDCount || KnownSPMDCount) { 4666 assert(KnownNonSPMDCount == 0 && AssumedNonSPMDCount == 0 && 4667 "Expected only SPMD kernels!"); 4668 SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), 1); 4669 } else { 4670 assert(KnownSPMDCount == 0 && AssumedSPMDCount == 0 && 4671 "Expected only non-SPMD kernels!"); 4672 SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), 0); 4673 } 4674 return SimplifiedValue == SimplifiedValueBefore ? ChangeStatus::UNCHANGED 4675 : ChangeStatus::CHANGED; 4676 } 4677 4678 ChangeStatus foldKernelFnAttribute(Attributor &A, llvm::StringRef Attr) { 4679 // Specialize only if all the calls agree with the attribute constant value 4680 int32_t CurrentAttrValue = -1; 4681 Optional<Value *> SimplifiedValueBefore = SimplifiedValue; 4682 4683 auto &CallerKernelInfoAA = A.getAAFor<AAKernelInfo>( 4684 *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED); 4685 4686 if (!CallerKernelInfoAA.ReachingKernelEntries.isValidState()) 4687 return indicatePessimisticFixpoint(); 4688 4689 // Iterate over the kernels that reach this function 4690 for (Kernel K : CallerKernelInfoAA.ReachingKernelEntries) { 4691 int32_t NextAttrVal = -1; 4692 if (K->hasFnAttribute(Attr)) 4693 NextAttrVal = 4694 std::stoi(K->getFnAttribute(Attr).getValueAsString().str()); 4695 4696 if (NextAttrVal == -1 || 4697 (CurrentAttrValue != -1 && CurrentAttrValue != NextAttrVal)) 4698 return indicatePessimisticFixpoint(); 4699 CurrentAttrValue = NextAttrVal; 4700 } 4701 4702 if (CurrentAttrValue != -1) { 4703 auto &Ctx = getAnchorValue().getContext(); 4704 SimplifiedValue = 4705 ConstantInt::get(Type::getInt32Ty(Ctx), CurrentAttrValue); 4706 } 4707 return SimplifiedValue == SimplifiedValueBefore ? ChangeStatus::UNCHANGED 4708 : ChangeStatus::CHANGED; 4709 } 4710 4711 /// An optional value the associated value is assumed to fold to. That is, we 4712 /// assume the associated value (which is a call) can be replaced by this 4713 /// simplified value. 4714 Optional<Value *> SimplifiedValue; 4715 4716 /// The runtime function kind of the callee of the associated call site. 4717 RuntimeFunction RFKind; 4718 }; 4719 4720 } // namespace 4721 4722 /// Register folding callsite 4723 void OpenMPOpt::registerFoldRuntimeCall(RuntimeFunction RF) { 4724 auto &RFI = OMPInfoCache.RFIs[RF]; 4725 RFI.foreachUse(SCC, [&](Use &U, Function &F) { 4726 CallInst *CI = OpenMPOpt::getCallIfRegularCall(U, &RFI); 4727 if (!CI) 4728 return false; 4729 A.getOrCreateAAFor<AAFoldRuntimeCall>( 4730 IRPosition::callsite_returned(*CI), /* QueryingAA */ nullptr, 4731 DepClassTy::NONE, /* ForceUpdate */ false, 4732 /* UpdateAfterInit */ false); 4733 return false; 4734 }); 4735 } 4736 4737 void OpenMPOpt::registerAAs(bool IsModulePass) { 4738 if (SCC.empty()) 4739 return; 4740 4741 if (IsModulePass) { 4742 // Ensure we create the AAKernelInfo AAs first and without triggering an 4743 // update. This will make sure we register all value simplification 4744 // callbacks before any other AA has the chance to create an AAValueSimplify 4745 // or similar. 4746 auto CreateKernelInfoCB = [&](Use &, Function &Kernel) { 4747 A.getOrCreateAAFor<AAKernelInfo>( 4748 IRPosition::function(Kernel), /* QueryingAA */ nullptr, 4749 DepClassTy::NONE, /* ForceUpdate */ false, 4750 /* UpdateAfterInit */ false); 4751 return false; 4752 }; 4753 OMPInformationCache::RuntimeFunctionInfo &InitRFI = 4754 OMPInfoCache.RFIs[OMPRTL___kmpc_target_init]; 4755 InitRFI.foreachUse(SCC, CreateKernelInfoCB); 4756 4757 registerFoldRuntimeCall(OMPRTL___kmpc_is_generic_main_thread_id); 4758 registerFoldRuntimeCall(OMPRTL___kmpc_is_spmd_exec_mode); 4759 registerFoldRuntimeCall(OMPRTL___kmpc_parallel_level); 4760 registerFoldRuntimeCall(OMPRTL___kmpc_get_hardware_num_threads_in_block); 4761 registerFoldRuntimeCall(OMPRTL___kmpc_get_hardware_num_blocks); 4762 } 4763 4764 // Create CallSite AA for all Getters. 4765 for (int Idx = 0; Idx < OMPInfoCache.ICVs.size() - 1; ++Idx) { 4766 auto ICVInfo = OMPInfoCache.ICVs[static_cast<InternalControlVar>(Idx)]; 4767 4768 auto &GetterRFI = OMPInfoCache.RFIs[ICVInfo.Getter]; 4769 4770 auto CreateAA = [&](Use &U, Function &Caller) { 4771 CallInst *CI = OpenMPOpt::getCallIfRegularCall(U, &GetterRFI); 4772 if (!CI) 4773 return false; 4774 4775 auto &CB = cast<CallBase>(*CI); 4776 4777 IRPosition CBPos = IRPosition::callsite_function(CB); 4778 A.getOrCreateAAFor<AAICVTracker>(CBPos); 4779 return false; 4780 }; 4781 4782 GetterRFI.foreachUse(SCC, CreateAA); 4783 } 4784 auto &GlobalizationRFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared]; 4785 auto CreateAA = [&](Use &U, Function &F) { 4786 A.getOrCreateAAFor<AAHeapToShared>(IRPosition::function(F)); 4787 return false; 4788 }; 4789 if (!DisableOpenMPOptDeglobalization) 4790 GlobalizationRFI.foreachUse(SCC, CreateAA); 4791 4792 // Create an ExecutionDomain AA for every function and a HeapToStack AA for 4793 // every function if there is a device kernel. 4794 if (!isOpenMPDevice(M)) 4795 return; 4796 4797 for (auto *F : SCC) { 4798 if (F->isDeclaration()) 4799 continue; 4800 4801 A.getOrCreateAAFor<AAExecutionDomain>(IRPosition::function(*F)); 4802 if (!DisableOpenMPOptDeglobalization) 4803 A.getOrCreateAAFor<AAHeapToStack>(IRPosition::function(*F)); 4804 4805 for (auto &I : instructions(*F)) { 4806 if (auto *LI = dyn_cast<LoadInst>(&I)) { 4807 bool UsedAssumedInformation = false; 4808 A.getAssumedSimplified(IRPosition::value(*LI), /* AA */ nullptr, 4809 UsedAssumedInformation); 4810 } else if (auto *SI = dyn_cast<StoreInst>(&I)) { 4811 A.getOrCreateAAFor<AAIsDead>(IRPosition::value(*SI)); 4812 } 4813 } 4814 } 4815 } 4816 4817 const char AAICVTracker::ID = 0; 4818 const char AAKernelInfo::ID = 0; 4819 const char AAExecutionDomain::ID = 0; 4820 const char AAHeapToShared::ID = 0; 4821 const char AAFoldRuntimeCall::ID = 0; 4822 4823 AAICVTracker &AAICVTracker::createForPosition(const IRPosition &IRP, 4824 Attributor &A) { 4825 AAICVTracker *AA = nullptr; 4826 switch (IRP.getPositionKind()) { 4827 case IRPosition::IRP_INVALID: 4828 case IRPosition::IRP_FLOAT: 4829 case IRPosition::IRP_ARGUMENT: 4830 case IRPosition::IRP_CALL_SITE_ARGUMENT: 4831 llvm_unreachable("ICVTracker can only be created for function position!"); 4832 case IRPosition::IRP_RETURNED: 4833 AA = new (A.Allocator) AAICVTrackerFunctionReturned(IRP, A); 4834 break; 4835 case IRPosition::IRP_CALL_SITE_RETURNED: 4836 AA = new (A.Allocator) AAICVTrackerCallSiteReturned(IRP, A); 4837 break; 4838 case IRPosition::IRP_CALL_SITE: 4839 AA = new (A.Allocator) AAICVTrackerCallSite(IRP, A); 4840 break; 4841 case IRPosition::IRP_FUNCTION: 4842 AA = new (A.Allocator) AAICVTrackerFunction(IRP, A); 4843 break; 4844 } 4845 4846 return *AA; 4847 } 4848 4849 AAExecutionDomain &AAExecutionDomain::createForPosition(const IRPosition &IRP, 4850 Attributor &A) { 4851 AAExecutionDomainFunction *AA = nullptr; 4852 switch (IRP.getPositionKind()) { 4853 case IRPosition::IRP_INVALID: 4854 case IRPosition::IRP_FLOAT: 4855 case IRPosition::IRP_ARGUMENT: 4856 case IRPosition::IRP_CALL_SITE_ARGUMENT: 4857 case IRPosition::IRP_RETURNED: 4858 case IRPosition::IRP_CALL_SITE_RETURNED: 4859 case IRPosition::IRP_CALL_SITE: 4860 llvm_unreachable( 4861 "AAExecutionDomain can only be created for function position!"); 4862 case IRPosition::IRP_FUNCTION: 4863 AA = new (A.Allocator) AAExecutionDomainFunction(IRP, A); 4864 break; 4865 } 4866 4867 return *AA; 4868 } 4869 4870 AAHeapToShared &AAHeapToShared::createForPosition(const IRPosition &IRP, 4871 Attributor &A) { 4872 AAHeapToSharedFunction *AA = nullptr; 4873 switch (IRP.getPositionKind()) { 4874 case IRPosition::IRP_INVALID: 4875 case IRPosition::IRP_FLOAT: 4876 case IRPosition::IRP_ARGUMENT: 4877 case IRPosition::IRP_CALL_SITE_ARGUMENT: 4878 case IRPosition::IRP_RETURNED: 4879 case IRPosition::IRP_CALL_SITE_RETURNED: 4880 case IRPosition::IRP_CALL_SITE: 4881 llvm_unreachable( 4882 "AAHeapToShared can only be created for function position!"); 4883 case IRPosition::IRP_FUNCTION: 4884 AA = new (A.Allocator) AAHeapToSharedFunction(IRP, A); 4885 break; 4886 } 4887 4888 return *AA; 4889 } 4890 4891 AAKernelInfo &AAKernelInfo::createForPosition(const IRPosition &IRP, 4892 Attributor &A) { 4893 AAKernelInfo *AA = nullptr; 4894 switch (IRP.getPositionKind()) { 4895 case IRPosition::IRP_INVALID: 4896 case IRPosition::IRP_FLOAT: 4897 case IRPosition::IRP_ARGUMENT: 4898 case IRPosition::IRP_RETURNED: 4899 case IRPosition::IRP_CALL_SITE_RETURNED: 4900 case IRPosition::IRP_CALL_SITE_ARGUMENT: 4901 llvm_unreachable("KernelInfo can only be created for function position!"); 4902 case IRPosition::IRP_CALL_SITE: 4903 AA = new (A.Allocator) AAKernelInfoCallSite(IRP, A); 4904 break; 4905 case IRPosition::IRP_FUNCTION: 4906 AA = new (A.Allocator) AAKernelInfoFunction(IRP, A); 4907 break; 4908 } 4909 4910 return *AA; 4911 } 4912 4913 AAFoldRuntimeCall &AAFoldRuntimeCall::createForPosition(const IRPosition &IRP, 4914 Attributor &A) { 4915 AAFoldRuntimeCall *AA = nullptr; 4916 switch (IRP.getPositionKind()) { 4917 case IRPosition::IRP_INVALID: 4918 case IRPosition::IRP_FLOAT: 4919 case IRPosition::IRP_ARGUMENT: 4920 case IRPosition::IRP_RETURNED: 4921 case IRPosition::IRP_FUNCTION: 4922 case IRPosition::IRP_CALL_SITE: 4923 case IRPosition::IRP_CALL_SITE_ARGUMENT: 4924 llvm_unreachable("KernelInfo can only be created for call site position!"); 4925 case IRPosition::IRP_CALL_SITE_RETURNED: 4926 AA = new (A.Allocator) AAFoldRuntimeCallCallSiteReturned(IRP, A); 4927 break; 4928 } 4929 4930 return *AA; 4931 } 4932 4933 PreservedAnalyses OpenMPOptPass::run(Module &M, ModuleAnalysisManager &AM) { 4934 if (!containsOpenMP(M)) 4935 return PreservedAnalyses::all(); 4936 if (DisableOpenMPOptimizations) 4937 return PreservedAnalyses::all(); 4938 4939 FunctionAnalysisManager &FAM = 4940 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 4941 KernelSet Kernels = getDeviceKernels(M); 4942 4943 if (PrintModuleBeforeOptimizations) 4944 LLVM_DEBUG(dbgs() << TAG << "Module before OpenMPOpt Module Pass:\n" << M); 4945 4946 auto IsCalled = [&](Function &F) { 4947 if (Kernels.contains(&F)) 4948 return true; 4949 for (const User *U : F.users()) 4950 if (!isa<BlockAddress>(U)) 4951 return true; 4952 return false; 4953 }; 4954 4955 auto EmitRemark = [&](Function &F) { 4956 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F); 4957 ORE.emit([&]() { 4958 OptimizationRemarkAnalysis ORA(DEBUG_TYPE, "OMP140", &F); 4959 return ORA << "Could not internalize function. " 4960 << "Some optimizations may not be possible. [OMP140]"; 4961 }); 4962 }; 4963 4964 // Create internal copies of each function if this is a kernel Module. This 4965 // allows iterprocedural passes to see every call edge. 4966 DenseMap<Function *, Function *> InternalizedMap; 4967 if (isOpenMPDevice(M)) { 4968 SmallPtrSet<Function *, 16> InternalizeFns; 4969 for (Function &F : M) 4970 if (!F.isDeclaration() && !Kernels.contains(&F) && IsCalled(F) && 4971 !DisableInternalization) { 4972 if (Attributor::isInternalizable(F)) { 4973 InternalizeFns.insert(&F); 4974 } else if (!F.hasLocalLinkage() && !F.hasFnAttribute(Attribute::Cold)) { 4975 EmitRemark(F); 4976 } 4977 } 4978 4979 Attributor::internalizeFunctions(InternalizeFns, InternalizedMap); 4980 } 4981 4982 // Look at every function in the Module unless it was internalized. 4983 SmallVector<Function *, 16> SCC; 4984 for (Function &F : M) 4985 if (!F.isDeclaration() && !InternalizedMap.lookup(&F)) 4986 SCC.push_back(&F); 4987 4988 if (SCC.empty()) 4989 return PreservedAnalyses::all(); 4990 4991 AnalysisGetter AG(FAM); 4992 4993 auto OREGetter = [&FAM](Function *F) -> OptimizationRemarkEmitter & { 4994 return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F); 4995 }; 4996 4997 BumpPtrAllocator Allocator; 4998 CallGraphUpdater CGUpdater; 4999 5000 SetVector<Function *> Functions(SCC.begin(), SCC.end()); 5001 OMPInformationCache InfoCache(M, AG, Allocator, /*CGSCC*/ Functions, Kernels); 5002 5003 unsigned MaxFixpointIterations = 5004 (isOpenMPDevice(M)) ? SetFixpointIterations : 32; 5005 Attributor A(Functions, InfoCache, CGUpdater, nullptr, true, false, 5006 MaxFixpointIterations, OREGetter, DEBUG_TYPE); 5007 5008 OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A); 5009 bool Changed = OMPOpt.run(true); 5010 5011 // Optionally inline device functions for potentially better performance. 5012 if (AlwaysInlineDeviceFunctions && isOpenMPDevice(M)) 5013 for (Function &F : M) 5014 if (!F.isDeclaration() && !Kernels.contains(&F) && 5015 !F.hasFnAttribute(Attribute::NoInline)) 5016 F.addFnAttr(Attribute::AlwaysInline); 5017 5018 if (PrintModuleAfterOptimizations) 5019 LLVM_DEBUG(dbgs() << TAG << "Module after OpenMPOpt Module Pass:\n" << M); 5020 5021 if (Changed) 5022 return PreservedAnalyses::none(); 5023 5024 return PreservedAnalyses::all(); 5025 } 5026 5027 PreservedAnalyses OpenMPOptCGSCCPass::run(LazyCallGraph::SCC &C, 5028 CGSCCAnalysisManager &AM, 5029 LazyCallGraph &CG, 5030 CGSCCUpdateResult &UR) { 5031 if (!containsOpenMP(*C.begin()->getFunction().getParent())) 5032 return PreservedAnalyses::all(); 5033 if (DisableOpenMPOptimizations) 5034 return PreservedAnalyses::all(); 5035 5036 SmallVector<Function *, 16> SCC; 5037 // If there are kernels in the module, we have to run on all SCC's. 5038 for (LazyCallGraph::Node &N : C) { 5039 Function *Fn = &N.getFunction(); 5040 SCC.push_back(Fn); 5041 } 5042 5043 if (SCC.empty()) 5044 return PreservedAnalyses::all(); 5045 5046 Module &M = *C.begin()->getFunction().getParent(); 5047 5048 if (PrintModuleBeforeOptimizations) 5049 LLVM_DEBUG(dbgs() << TAG << "Module before OpenMPOpt CGSCC Pass:\n" << M); 5050 5051 KernelSet Kernels = getDeviceKernels(M); 5052 5053 FunctionAnalysisManager &FAM = 5054 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager(); 5055 5056 AnalysisGetter AG(FAM); 5057 5058 auto OREGetter = [&FAM](Function *F) -> OptimizationRemarkEmitter & { 5059 return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F); 5060 }; 5061 5062 BumpPtrAllocator Allocator; 5063 CallGraphUpdater CGUpdater; 5064 CGUpdater.initialize(CG, C, AM, UR); 5065 5066 SetVector<Function *> Functions(SCC.begin(), SCC.end()); 5067 OMPInformationCache InfoCache(*(Functions.back()->getParent()), AG, Allocator, 5068 /*CGSCC*/ Functions, Kernels); 5069 5070 unsigned MaxFixpointIterations = 5071 (isOpenMPDevice(M)) ? SetFixpointIterations : 32; 5072 Attributor A(Functions, InfoCache, CGUpdater, nullptr, false, true, 5073 MaxFixpointIterations, OREGetter, DEBUG_TYPE); 5074 5075 OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A); 5076 bool Changed = OMPOpt.run(false); 5077 5078 if (PrintModuleAfterOptimizations) 5079 LLVM_DEBUG(dbgs() << TAG << "Module after OpenMPOpt CGSCC Pass:\n" << M); 5080 5081 if (Changed) 5082 return PreservedAnalyses::none(); 5083 5084 return PreservedAnalyses::all(); 5085 } 5086 5087 namespace { 5088 5089 struct OpenMPOptCGSCCLegacyPass : public CallGraphSCCPass { 5090 CallGraphUpdater CGUpdater; 5091 static char ID; 5092 5093 OpenMPOptCGSCCLegacyPass() : CallGraphSCCPass(ID) { 5094 initializeOpenMPOptCGSCCLegacyPassPass(*PassRegistry::getPassRegistry()); 5095 } 5096 5097 void getAnalysisUsage(AnalysisUsage &AU) const override { 5098 CallGraphSCCPass::getAnalysisUsage(AU); 5099 } 5100 5101 bool runOnSCC(CallGraphSCC &CGSCC) override { 5102 if (!containsOpenMP(CGSCC.getCallGraph().getModule())) 5103 return false; 5104 if (DisableOpenMPOptimizations || skipSCC(CGSCC)) 5105 return false; 5106 5107 SmallVector<Function *, 16> SCC; 5108 // If there are kernels in the module, we have to run on all SCC's. 5109 for (CallGraphNode *CGN : CGSCC) { 5110 Function *Fn = CGN->getFunction(); 5111 if (!Fn || Fn->isDeclaration()) 5112 continue; 5113 SCC.push_back(Fn); 5114 } 5115 5116 if (SCC.empty()) 5117 return false; 5118 5119 Module &M = CGSCC.getCallGraph().getModule(); 5120 KernelSet Kernels = getDeviceKernels(M); 5121 5122 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph(); 5123 CGUpdater.initialize(CG, CGSCC); 5124 5125 // Maintain a map of functions to avoid rebuilding the ORE 5126 DenseMap<Function *, std::unique_ptr<OptimizationRemarkEmitter>> OREMap; 5127 auto OREGetter = [&OREMap](Function *F) -> OptimizationRemarkEmitter & { 5128 std::unique_ptr<OptimizationRemarkEmitter> &ORE = OREMap[F]; 5129 if (!ORE) 5130 ORE = std::make_unique<OptimizationRemarkEmitter>(F); 5131 return *ORE; 5132 }; 5133 5134 AnalysisGetter AG; 5135 SetVector<Function *> Functions(SCC.begin(), SCC.end()); 5136 BumpPtrAllocator Allocator; 5137 OMPInformationCache InfoCache(*(Functions.back()->getParent()), AG, 5138 Allocator, 5139 /*CGSCC*/ Functions, Kernels); 5140 5141 unsigned MaxFixpointIterations = 5142 (isOpenMPDevice(M)) ? SetFixpointIterations : 32; 5143 Attributor A(Functions, InfoCache, CGUpdater, nullptr, false, true, 5144 MaxFixpointIterations, OREGetter, DEBUG_TYPE); 5145 5146 OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A); 5147 bool Result = OMPOpt.run(false); 5148 5149 if (PrintModuleAfterOptimizations) 5150 LLVM_DEBUG(dbgs() << TAG << "Module after OpenMPOpt CGSCC Pass:\n" << M); 5151 5152 return Result; 5153 } 5154 5155 bool doFinalization(CallGraph &CG) override { return CGUpdater.finalize(); } 5156 }; 5157 5158 } // end anonymous namespace 5159 5160 KernelSet llvm::omp::getDeviceKernels(Module &M) { 5161 // TODO: Create a more cross-platform way of determining device kernels. 5162 NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations"); 5163 KernelSet Kernels; 5164 5165 if (!MD) 5166 return Kernels; 5167 5168 for (auto *Op : MD->operands()) { 5169 if (Op->getNumOperands() < 2) 5170 continue; 5171 MDString *KindID = dyn_cast<MDString>(Op->getOperand(1)); 5172 if (!KindID || KindID->getString() != "kernel") 5173 continue; 5174 5175 Function *KernelFn = 5176 mdconst::dyn_extract_or_null<Function>(Op->getOperand(0)); 5177 if (!KernelFn) 5178 continue; 5179 5180 ++NumOpenMPTargetRegionKernels; 5181 5182 Kernels.insert(KernelFn); 5183 } 5184 5185 return Kernels; 5186 } 5187 5188 bool llvm::omp::containsOpenMP(Module &M) { 5189 Metadata *MD = M.getModuleFlag("openmp"); 5190 if (!MD) 5191 return false; 5192 5193 return true; 5194 } 5195 5196 bool llvm::omp::isOpenMPDevice(Module &M) { 5197 Metadata *MD = M.getModuleFlag("openmp-device"); 5198 if (!MD) 5199 return false; 5200 5201 return true; 5202 } 5203 5204 char OpenMPOptCGSCCLegacyPass::ID = 0; 5205 5206 INITIALIZE_PASS_BEGIN(OpenMPOptCGSCCLegacyPass, "openmp-opt-cgscc", 5207 "OpenMP specific optimizations", false, false) 5208 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass) 5209 INITIALIZE_PASS_END(OpenMPOptCGSCCLegacyPass, "openmp-opt-cgscc", 5210 "OpenMP specific optimizations", false, false) 5211 5212 Pass *llvm::createOpenMPOptCGSCCLegacyPass() { 5213 return new OpenMPOptCGSCCLegacyPass(); 5214 } 5215