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